synched with trunk at revision 36569
[blender.git] / source / gameengine / Converter / BL_BlenderDataConversion.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Convert blender data to ketsji
29  */
30
31 /** \file gameengine/Converter/BL_BlenderDataConversion.cpp
32  *  \ingroup bgeconv
33  */
34
35
36 #if defined(WIN32) && !defined(FREE_WINDOWS)
37 #pragma warning (disable : 4786)
38 #endif
39
40 #include <math.h>
41
42 #include "BL_BlenderDataConversion.h"
43 #include "KX_BlenderGL.h"
44 #include "KX_BlenderScalarInterpolator.h"
45
46 #include "RAS_IPolygonMaterial.h"
47 #include "KX_PolygonMaterial.h"
48
49 // Expressions
50 #include "ListValue.h"
51 #include "IntValue.h"
52 // Collision & Fuzzics LTD
53
54 #include "PHY_Pro.h"
55
56
57 #include "KX_Scene.h"
58 #include "KX_GameObject.h"
59 #include "RAS_FramingManager.h"
60 #include "RAS_MeshObject.h"
61
62 #include "KX_ConvertActuators.h"
63 #include "KX_ConvertControllers.h"
64 #include "KX_ConvertSensors.h"
65
66 #include "SCA_LogicManager.h"
67 #include "SCA_EventManager.h"
68 #include "SCA_TimeEventManager.h"
69 #include "KX_Light.h"
70 #include "KX_Camera.h"
71 #include "KX_EmptyObject.h"
72 #include "KX_FontObject.h"
73 #include "MT_Point3.h"
74 #include "MT_Transform.h"
75 #include "MT_MinMax.h"
76 #include "SCA_IInputDevice.h"
77 #include "RAS_TexMatrix.h"
78 #include "RAS_ICanvas.h"
79 #include "RAS_MaterialBucket.h"
80 //#include "KX_BlenderPolyMaterial.h"
81 #include "RAS_Polygon.h"
82 #include "RAS_TexVert.h"
83 #include "RAS_BucketManager.h"
84 #include "RAS_IRenderTools.h"
85 #include "BL_Material.h"
86 #include "KX_BlenderMaterial.h"
87 #include "BL_Texture.h"
88
89 #include "DNA_action_types.h"
90 #include "BKE_main.h"
91 #include "BKE_global.h"
92 #include "BKE_object.h"
93 #include "BL_ModifierDeformer.h"
94 #include "BL_ShapeDeformer.h"
95 #include "BL_SkinDeformer.h"
96 #include "BL_MeshDeformer.h"
97 #include "KX_SoftBodyDeformer.h"
98 //#include "BL_ArmatureController.h"
99 #include "BLI_utildefines.h"
100 #include "BlenderWorldInfo.h"
101
102 #include "KX_KetsjiEngine.h"
103 #include "KX_BlenderSceneConverter.h"
104
105 /* This little block needed for linking to Blender... */
106 #ifdef WIN32
107 #include "BLI_winstuff.h"
108 #endif
109
110 /* This list includes only data type definitions */
111 #include "DNA_object_types.h"
112 #include "DNA_material_types.h"
113 #include "DNA_texture_types.h"
114 #include "DNA_image_types.h"
115 #include "DNA_lamp_types.h"
116 #include "DNA_group_types.h"
117 #include "DNA_scene_types.h"
118 #include "DNA_camera_types.h"
119 #include "DNA_property_types.h"
120 #include "DNA_text_types.h"
121 #include "DNA_sensor_types.h"
122 #include "DNA_controller_types.h"
123 #include "DNA_actuator_types.h"
124 #include "DNA_mesh_types.h"
125 #include "DNA_meshdata_types.h"
126 #include "DNA_view3d_types.h"
127 #include "DNA_world_types.h"
128 #include "DNA_sound_types.h"
129 #include "DNA_key_types.h"
130 #include "DNA_armature_types.h"
131 #include "DNA_object_force.h"
132
133 #include "MEM_guardedalloc.h"
134
135 #include "BKE_key.h"
136 #include "BKE_mesh.h"
137 #include "MT_Point3.h"
138
139 #include "BLI_math.h"
140
141 extern "C" {
142 #include "BKE_scene.h"
143 #include "BKE_customdata.h"
144 #include "BKE_cdderivedmesh.h"
145 #include "BKE_DerivedMesh.h"
146 }
147
148 #include "BKE_material.h" /* give_current_material */
149 /* end of blender include block */
150
151 #include "KX_BlenderInputDevice.h"
152 #include "KX_ConvertProperties.h"
153 #include "KX_HashedPtr.h"
154
155
156 #include "KX_ScalarInterpolator.h"
157
158 #include "KX_IpoConvert.h"
159 #include "BL_System.h"
160
161 #include "SG_Node.h"
162 #include "SG_BBox.h"
163 #include "SG_Tree.h"
164
165 #include "KX_ConvertPhysicsObject.h"
166 #ifdef USE_BULLET
167 #include "CcdPhysicsEnvironment.h"
168 #include "CcdGraphicController.h"
169 #endif
170 #include "KX_MotionState.h"
171
172 // This file defines relationships between parents and children
173 // in the game engine.
174
175 #include "KX_SG_NodeRelationships.h"
176 #include "KX_SG_BoneParentNodeRelationship.h"
177
178 #include "BL_ArmatureObject.h"
179 #include "BL_DeformableGameObject.h"
180
181 #include "KX_NavMeshObject.h"
182 #include "KX_ObstacleSimulation.h"
183
184 #ifdef __cplusplus
185 extern "C" {
186 #endif
187 //XXX #include "BSE_headerbuttons.h"
188 //XXX void update_for_newframe();
189 //void scene_update_for_newframe(struct Scene *sce, unsigned int lay);
190 //#include "BKE_ipo.h"
191 //void do_all_data_ipos(void);
192 #ifdef __cplusplus
193 }
194 #endif
195
196 static int default_face_mode = TF_DYNAMIC;
197
198 static unsigned int KX_rgbaint2uint_new(unsigned int icol)
199 {
200         union
201         {
202                 unsigned int integer;
203                 unsigned char cp[4];
204         } out_color, in_color;
205         
206         in_color.integer = icol;
207         out_color.cp[0] = in_color.cp[3]; // red
208         out_color.cp[1] = in_color.cp[2]; // green
209         out_color.cp[2] = in_color.cp[1]; // blue
210         out_color.cp[3] = in_color.cp[0]; // alpha
211         
212         return out_color.integer;
213 }
214
215 /* Now the real converting starts... */
216 static unsigned int KX_Mcol2uint_new(MCol col)
217 {
218         /* color has to be converted without endian sensitivity. So no shifting! */
219         union
220         {
221                 MCol col;
222                 unsigned int integer;
223                 unsigned char cp[4];
224         } out_color, in_color;
225
226         in_color.col = col;
227         out_color.cp[0] = in_color.cp[3]; // red
228         out_color.cp[1] = in_color.cp[2]; // green
229         out_color.cp[2] = in_color.cp[1]; // blue
230         out_color.cp[3] = in_color.cp[0]; // alpha
231         
232         return out_color.integer;
233 }
234
235 static void SetDefaultFaceType(Scene* scene)
236 {
237         default_face_mode = TF_DYNAMIC;
238         Scene *sce_iter;
239         Base *base;
240
241         for(SETLOOPER(scene, sce_iter, base))
242         {
243                 if (base->object->type == OB_LAMP)
244                 {
245                         default_face_mode = TF_DYNAMIC|TF_LIGHT;
246                         return;
247                 }
248         }
249 }
250
251
252 // --
253 static void GetRGB(short type,
254         MFace* mface,
255         MCol* mmcol,
256         Material *mat,
257         unsigned int &c0, 
258         unsigned int &c1, 
259         unsigned int &c2, 
260         unsigned int &c3)
261 {
262         unsigned int color = 0xFFFFFFFFL;
263         switch(type)
264         {
265                 case 0: // vertex colors
266                 {
267                         if(mmcol) {
268                                 c0 = KX_Mcol2uint_new(mmcol[0]);
269                                 c1 = KX_Mcol2uint_new(mmcol[1]);
270                                 c2 = KX_Mcol2uint_new(mmcol[2]);
271                                 if (mface->v4)
272                                         c3 = KX_Mcol2uint_new(mmcol[3]);
273                         }else // backup white
274                         {
275                                 c0 = KX_rgbaint2uint_new(color);
276                                 c1 = KX_rgbaint2uint_new(color);
277                                 c2 = KX_rgbaint2uint_new(color);        
278                                 if (mface->v4)
279                                         c3 = KX_rgbaint2uint_new( color );
280                         }
281                 } break;
282                 
283         
284                 case 1: // material rgba
285                 {
286                         if (mat) {
287                                 union {
288                                         unsigned char cp[4];
289                                         unsigned int integer;
290                                 } col_converter;
291                                 col_converter.cp[3] = (unsigned char) (mat->r*255.0);
292                                 col_converter.cp[2] = (unsigned char) (mat->g*255.0);
293                                 col_converter.cp[1] = (unsigned char) (mat->b*255.0);
294                                 col_converter.cp[0] = (unsigned char) (mat->alpha*255.0);
295                                 color = col_converter.integer;
296                         }
297                         c0 = KX_rgbaint2uint_new(color);
298                         c1 = KX_rgbaint2uint_new(color);
299                         c2 = KX_rgbaint2uint_new(color);        
300                         if (mface->v4)
301                                 c3 = KX_rgbaint2uint_new(color);
302                 } break;
303                 
304                 default: // white
305                 {
306                         c0 = KX_rgbaint2uint_new(color);
307                         c1 = KX_rgbaint2uint_new(color);
308                         c2 = KX_rgbaint2uint_new(color);        
309                         if (mface->v4)
310                                 c3 = KX_rgbaint2uint_new(color);
311                 } break;
312         }
313 }
314
315 typedef struct MTF_localLayer
316 {
317         MTFace *face;
318         const char *name;
319 }MTF_localLayer;
320
321 // ------------------------------------
322 bool ConvertMaterial(
323         BL_Material *material,
324         Material *mat, 
325         MTFace* tface,  
326         const char *tfaceName,
327         MFace* mface, 
328         MCol* mmcol,
329         MTF_localLayer *layers,
330         bool glslmat)
331 {
332         material->Initialize();
333         int numchan =   -1, texalpha = 0;
334         bool validmat   = (mat!=0);
335         bool validface  = (tface!=0);
336         
337         short type = 0;
338         if( validmat )
339                 type = 1; // material color 
340         
341         material->IdMode = DEFAULT_BLENDER;
342         material->glslmat = (validmat)? glslmat: false;
343         material->materialindex = mface->mat_nr;
344
345         // --------------------------------
346         if(validmat) {
347
348                 // use vertex colors by explicitly setting
349                 if(mat->mode &MA_VERTEXCOLP || glslmat)
350                         type = 0;
351
352                 // use lighting?
353                 material->ras_mode |= ( mat->mode & MA_SHLESS )?0:USE_LIGHT;
354                 MTex *mttmp = 0;
355                 numchan = getNumTexChannels(mat);
356                 int valid_index = 0;
357                 
358                 // use the face texture if
359                 // 1) it is set in the buttons
360                 // 2) we have a face texture and a material but no valid texture in slot 1
361                 bool facetex = false;
362                 if(validface && mat->mode &MA_FACETEXTURE) 
363                         facetex = true;
364                 if(validface && !mat->mtex[0])
365                         facetex = true;
366                 if(validface && mat->mtex[0]) {
367                         MTex *tmp = mat->mtex[0];
368                         if(!tmp->tex || (tmp->tex && !tmp->tex->ima))
369                                 facetex = true;
370                 }
371                 numchan = numchan>MAXTEX?MAXTEX:numchan;
372         
373                 // foreach MTex
374                 for(int i=0; i<numchan; i++) {
375                         // use face tex
376
377                         if(i==0 && facetex ) {
378                                 Image*tmp = (Image*)(tface->tpage);
379
380                                 if(tmp) {
381                                         material->img[i] = tmp;
382                                         material->texname[i] = material->img[i]->id.name;
383                                         material->flag[i] |= ( tface->transp  &TF_ALPHA )?USEALPHA:0;
384                                         material->flag[i] |= ( tface->transp  &TF_ADD   )?CALCALPHA:0;
385                                         material->flag[i] |= MIPMAP;
386
387                                         if(material->img[i]->flag & IMA_REFLECT)
388                                                 material->mapping[i].mapping |= USEREFL;
389                                         else
390                                         {
391                                                 mttmp = getImageFromMaterial( mat, i );
392                                                 if(mttmp && mttmp->texco &TEXCO_UV)
393                                                 {
394                                                         STR_String uvName = mttmp->uvname;
395
396                                                         if (!uvName.IsEmpty())
397                                                                 material->mapping[i].uvCoName = mttmp->uvname;
398                                                         else
399                                                                 material->mapping[i].uvCoName = "";
400                                                 }
401                                                 material->mapping[i].mapping |= USEUV;
402                                         }
403
404                                         if(material->ras_mode & USE_LIGHT)
405                                                 material->ras_mode &= ~USE_LIGHT;
406                                         if(tface->mode & TF_LIGHT)
407                                                 material->ras_mode |= USE_LIGHT;
408
409                                         valid_index++;
410                                 }
411                                 else {
412                                         material->img[i] = 0;
413                                         material->texname[i] = "";
414                                 }
415                                 continue;
416                         }
417
418                         mttmp = getImageFromMaterial( mat, i );
419                         if( mttmp ) {
420                                 if( mttmp->tex ) {
421                                         if( mttmp->tex->type == TEX_IMAGE ) {
422                                                 material->mtexname[i] = mttmp->tex->id.name;
423                                                 material->img[i] = mttmp->tex->ima;
424                                                 if( material->img[i] ) {
425
426                                                         material->texname[i] = material->img[i]->id.name;
427                                                         material->flag[i] |= ( mttmp->tex->imaflag &TEX_MIPMAP )?MIPMAP:0;
428                                                         // -----------------------
429                                                         if( mttmp->tex->imaflag &TEX_USEALPHA ) {
430                                                                 material->flag[i]       |= USEALPHA;
431                                                         }
432                                                         // -----------------------
433                                                         else if( mttmp->tex->imaflag &TEX_CALCALPHA ) {
434                                                                 material->flag[i]       |= CALCALPHA;
435                                                         }
436                                                         else if(mttmp->tex->flag &TEX_NEGALPHA) {
437                                                                 material->flag[i]       |= USENEGALPHA;
438                                                         }
439
440                                                         material->color_blend[i] = mttmp->colfac;
441                                                         material->flag[i] |= ( mttmp->mapto  & MAP_ALPHA                )?TEXALPHA:0;
442                                                         material->flag[i] |= ( mttmp->texflag& MTEX_NEGATIVE    )?TEXNEG:0;
443
444                                                         if(!glslmat && (material->flag[i] & TEXALPHA))
445                                                                 texalpha = 1;
446                                                 }
447                                         }
448                                         else if(mttmp->tex->type == TEX_ENVMAP) {
449                                                 if( mttmp->tex->env->stype == ENV_LOAD ) {
450                                         
451                                                         material->mtexname[i]     = mttmp->tex->id.name;
452                                                         EnvMap *env = mttmp->tex->env;
453                                                         env->ima = mttmp->tex->ima;
454                                                         material->cubemap[i] = env;
455
456                                                         if (material->cubemap[i])
457                                                         {
458                                                                 if (!material->cubemap[i]->cube[0])
459                                                                         BL_Texture::SplitEnvMap(material->cubemap[i]);
460
461                                                                 material->texname[i]= material->cubemap[i]->ima->id.name;
462                                                                 material->mapping[i].mapping |= USEENV;
463                                                         }
464                                                 }
465                                         }
466                                         material->flag[i] |= (mat->ipo!=0)?HASIPO:0;
467                                         /// --------------------------------
468                                         // mapping methods
469                                         material->mapping[i].mapping |= ( mttmp->texco  & TEXCO_REFL    )?USEREFL:0;
470                                         
471                                         if(mttmp->texco & TEXCO_OBJECT) {
472                                                 material->mapping[i].mapping |= USEOBJ;
473                                                 if(mttmp->object)
474                                                         material->mapping[i].objconame = mttmp->object->id.name;
475                                         }
476                                         else if(mttmp->texco &TEXCO_REFL)
477                                                 material->mapping[i].mapping |= USEREFL;
478                                         else if(mttmp->texco &(TEXCO_ORCO|TEXCO_GLOB))
479                                                 material->mapping[i].mapping |= USEORCO;
480                                         else if(mttmp->texco &TEXCO_UV)
481                                         {
482                                                 STR_String uvName = mttmp->uvname;
483
484                                                 if (!uvName.IsEmpty())
485                                                         material->mapping[i].uvCoName = mttmp->uvname;
486                                                 else
487                                                         material->mapping[i].uvCoName = "";
488                                                 material->mapping[i].mapping |= USEUV;
489                                         }
490                                         else if(mttmp->texco &TEXCO_NORM)
491                                                 material->mapping[i].mapping |= USENORM;
492                                         else if(mttmp->texco &TEXCO_TANGENT)
493                                                 material->mapping[i].mapping |= USETANG;
494                                         else
495                                                 material->mapping[i].mapping |= DISABLE;
496                                         
497                                         material->mapping[i].scale[0] = mttmp->size[0];
498                                         material->mapping[i].scale[1] = mttmp->size[1];
499                                         material->mapping[i].scale[2] = mttmp->size[2];
500                                         material->mapping[i].offsets[0] = mttmp->ofs[0];
501                                         material->mapping[i].offsets[1] = mttmp->ofs[1];
502                                         material->mapping[i].offsets[2] = mttmp->ofs[2];
503
504                                         material->mapping[i].projplane[0] = mttmp->projx;
505                                         material->mapping[i].projplane[1] = mttmp->projy;
506                                         material->mapping[i].projplane[2] = mttmp->projz;
507                                         /// --------------------------------
508                                         
509                                         switch( mttmp->blendtype ) {
510                                         case MTEX_BLEND:
511                                                 material->blend_mode[i] = BLEND_MIX;
512                                                 break;
513                                         case MTEX_MUL:
514                                                 material->blend_mode[i] = BLEND_MUL;
515                                                 break;
516                                         case MTEX_ADD:
517                                                 material->blend_mode[i] = BLEND_ADD;
518                                                 break;
519                                         case MTEX_SUB:
520                                                 material->blend_mode[i] = BLEND_SUB;
521                                                 break;
522                                         case MTEX_SCREEN:
523                                                 material->blend_mode[i] = BLEND_SCR;
524                                                 break;
525                                         }
526                                         valid_index++;
527                                 }
528                         }
529                 }
530
531                 // above one tex the switches here
532                 // are not used
533                 switch(valid_index) {
534                 case 0:
535                         material->IdMode = DEFAULT_BLENDER;
536                         break;
537                 case 1:
538                         material->IdMode = ONETEX;
539                         break;
540                 default:
541                         material->IdMode = GREATERTHAN2;
542                         break;
543                 }
544                 material->SetUsers(mat->id.us);
545
546                 material->num_enabled = valid_index;
547
548                 material->speccolor[0]  = mat->specr;
549                 material->speccolor[1]  = mat->specg;
550                 material->speccolor[2]  = mat->specb;
551                 material->hard                  = (float)mat->har/4.0f;
552                 material->matcolor[0]   = mat->r;
553                 material->matcolor[1]   = mat->g;
554                 material->matcolor[2]   = mat->b;
555                 material->matcolor[3]   = mat->alpha;
556                 material->alpha                 = mat->alpha;
557                 material->emit                  = mat->emit;
558                 material->spec_f                = mat->spec;
559                 material->ref                   = mat->ref;
560                 material->amb                   = mat->amb;
561
562                 material->ras_mode |= (mat->material_type == MA_TYPE_WIRE)? WIRE: 0;
563         }
564         else {
565                 int valid = 0;
566
567                 // check for tface tex to fallback on
568                 if( validface ){
569
570                         // no light bugfix
571                         if(tface->mode) material->ras_mode |= USE_LIGHT;
572
573                         material->img[0] = (Image*)(tface->tpage);
574                         // ------------------------
575                         if(material->img[0]) {
576                                 material->texname[0] = material->img[0]->id.name;
577                                 material->mapping[0].mapping |= ( (material->img[0]->flag & IMA_REFLECT)!=0 )?USEREFL:0;
578                                 material->flag[0] |= ( tface->transp  &TF_ALPHA )?USEALPHA:0;
579                                 material->flag[0] |= ( tface->transp  &TF_ADD   )?CALCALPHA:0;
580                                 valid++;
581                         }
582                 }
583                 material->SetUsers(-1);
584                 material->num_enabled   = valid;
585                 material->IdMode                = TEXFACE;
586                 material->speccolor[0]  = 1.f;
587                 material->speccolor[1]  = 1.f;
588                 material->speccolor[2]  = 1.f;
589                 material->hard                  = 35.f;
590                 material->matcolor[0]   = 0.5f;
591                 material->matcolor[1]   = 0.5f;
592                 material->matcolor[2]   = 0.5f;
593                 material->spec_f                = 0.5f;
594                 material->ref                   = 0.8f;
595         }
596         MT_Point2 uv[4];
597         MT_Point2 uv2[4];
598         const char *uvName = "", *uv2Name = "";
599
600         
601         uv2[0]= uv2[1]= uv2[2]= uv2[3]= MT_Point2(0.0f, 0.0f);
602
603         if( validface ) {
604
605                 material->ras_mode |= (tface->mode & TF_INVISIBLE)?0:POLY_VIS;
606
607                 material->transp = tface->transp;
608                 material->tile  = tface->tile;
609                 material->mode  = tface->mode;
610                         
611                 uv[0].setValue(tface->uv[0]);
612                 uv[1].setValue(tface->uv[1]);
613                 uv[2].setValue(tface->uv[2]);
614
615                 if (mface->v4) 
616                         uv[3].setValue(tface->uv[3]);
617
618                 uvName = tfaceName;
619         } 
620         else {
621                 // nothing at all
622                 material->ras_mode |= (POLY_VIS| (validmat?0:USE_LIGHT));
623                 material->mode          = default_face_mode;    
624                 material->transp        = TF_SOLID;
625                 material->tile          = 0;
626                 
627                 uv[0]= uv[1]= uv[2]= uv[3]= MT_Point2(0.0f, 0.0f);
628         }
629
630         // with ztransp enabled, enforce alpha blending mode
631         if(validmat && (mat->mode & MA_TRANSP) && (mat->mode & MA_ZTRANSP) && (material->transp == TF_SOLID))
632                 material->transp = TF_ALPHA;
633
634         // always zsort alpha + add
635         if((material->transp == TF_ALPHA || material->transp == TF_ADD || texalpha) && (material->transp != TF_CLIP)) {
636                 material->ras_mode |= ALPHA;
637                 material->ras_mode |= (material->mode & TF_ALPHASORT)? ZSORT: 0;
638         }
639
640         // collider or not?
641         material->ras_mode |= (material->mode & TF_DYNAMIC)? COLLIDER: 0;
642
643         // these flags are irrelevant at this point, remove so they
644         // don't hurt material bucketing 
645         material->mode &= ~(TF_DYNAMIC|TF_ALPHASORT|TF_TEX);
646
647         // get uv sets
648         if(validmat) 
649         {
650                 bool isFirstSet = true;
651
652                 // only two sets implemented, but any of the eight 
653                 // sets can make up the two layers
654                 for (int vind = 0; vind<material->num_enabled; vind++)
655                 {
656                         BL_Mapping &map = material->mapping[vind];
657
658                         if (map.uvCoName.IsEmpty())
659                                 isFirstSet = false;
660                         else
661                         {
662                                 for (int lay=0; lay<MAX_MTFACE; lay++)
663                                 {
664                                         MTF_localLayer& layer = layers[lay];
665                                         if (layer.face == 0) break;
666
667                                         if (strcmp(map.uvCoName.ReadPtr(), layer.name)==0)
668                                         {
669                                                 MT_Point2 uvSet[4];
670
671                                                 uvSet[0].setValue(layer.face->uv[0]);
672                                                 uvSet[1].setValue(layer.face->uv[1]);
673                                                 uvSet[2].setValue(layer.face->uv[2]);
674
675                                                 if (mface->v4) 
676                                                         uvSet[3].setValue(layer.face->uv[3]);
677                                                 else
678                                                         uvSet[3].setValue(0.0f, 0.0f);
679
680                                                 if (isFirstSet)
681                                                 {
682                                                         uv[0] = uvSet[0]; uv[1] = uvSet[1];
683                                                         uv[2] = uvSet[2]; uv[3] = uvSet[3];
684                                                         isFirstSet = false;
685                                                         uvName = layer.name;
686                                                 }
687                                                 else if(strcmp(layer.name, uvName) != 0)
688                                                 {
689                                                         uv2[0] = uvSet[0]; uv2[1] = uvSet[1];
690                                                         uv2[2] = uvSet[2]; uv2[3] = uvSet[3];
691                                                         map.mapping |= USECUSTOMUV;
692                                                         uv2Name = layer.name;
693                                                 }
694                                         }
695                                 }
696                         }
697                 }
698         }
699
700         unsigned int rgb[4];
701         GetRGB(type,mface,mmcol,mat,rgb[0],rgb[1],rgb[2], rgb[3]);
702
703         // swap the material color, so MCol on TF_BMFONT works
704         if (validmat && type==1 && (tface && tface->mode & TF_BMFONT))
705         {
706                 rgb[0] = KX_rgbaint2uint_new(rgb[0]);
707                 rgb[1] = KX_rgbaint2uint_new(rgb[1]);
708                 rgb[2] = KX_rgbaint2uint_new(rgb[2]);
709                 rgb[3] = KX_rgbaint2uint_new(rgb[3]);
710         }
711
712         material->SetConversionRGB(rgb);
713         material->SetConversionUV(uvName, uv);
714         material->SetConversionUV2(uv2Name, uv2);
715
716         if(validmat)
717                 material->matname       =(mat->id.name);
718
719         material->tface         = tface;
720         material->material      = mat;
721         return true;
722 }
723
724 /* blenderobj can be NULL, make sure its checked for */
725 RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, KX_Scene* scene, KX_BlenderSceneConverter *converter)
726 {
727         RAS_MeshObject *meshobj;
728         int lightlayer = blenderobj ? blenderobj->lay:(1<<20)-1; // all layers if no object.
729
730         if ((meshobj = converter->FindGameMesh(mesh/*, ob->lay*/)) != NULL)
731                 return meshobj;
732         // Get DerivedMesh data
733         DerivedMesh *dm = CDDM_from_mesh(mesh, blenderobj);
734
735         MVert *mvert = dm->getVertArray(dm);
736         int totvert = dm->getNumVerts(dm);
737
738         MFace *mface = dm->getFaceArray(dm);
739         MTFace *tface = static_cast<MTFace*>(dm->getFaceDataArray(dm, CD_MTFACE));
740         MCol *mcol = static_cast<MCol*>(dm->getFaceDataArray(dm, CD_MCOL));
741         float (*tangent)[4] = NULL;
742         int totface = dm->getNumFaces(dm);
743         const char *tfaceName = "";
744
745         if(tface) {
746                 DM_add_tangent_layer(dm);
747                 tangent = (float(*)[4])dm->getFaceDataArray(dm, CD_TANGENT);
748         }
749
750         meshobj = new RAS_MeshObject(mesh);
751
752         // Extract avaiable layers
753         MTF_localLayer *layers =  new MTF_localLayer[MAX_MTFACE];
754         for (int lay=0; lay<MAX_MTFACE; lay++) {
755                 layers[lay].face = 0;
756                 layers[lay].name = "";
757         }
758
759         int validLayers = 0;
760         for (int i=0; i<dm->faceData.totlayer; i++)
761         {
762                 if (dm->faceData.layers[i].type == CD_MTFACE)
763                 {
764                         assert(validLayers <= 8);
765
766                         layers[validLayers].face = (MTFace*)(dm->faceData.layers[i].data);
767                         layers[validLayers].name = dm->faceData.layers[i].name;
768                         if(tface == layers[validLayers].face)
769                                 tfaceName = layers[validLayers].name;
770                         validLayers++;
771                 }
772         }
773
774         meshobj->SetName(mesh->id.name + 2);
775         meshobj->m_sharedvertex_map.resize(totvert);
776         RAS_IPolyMaterial* polymat = NULL;
777         STR_String imastr;
778         // These pointers will hold persistent material structure during the conversion
779         // to avoid countless allocation/deallocation of memory.
780         BL_Material* bl_mat = NULL;
781         KX_BlenderMaterial* kx_blmat = NULL;
782         KX_PolygonMaterial* kx_polymat = NULL;
783
784         for (int f=0;f<totface;f++,mface++)
785         {
786                 Material* ma = 0;
787                 bool collider = true;
788                 MT_Point2 uv0(0.0,0.0),uv1(0.0,0.0),uv2(0.0,0.0),uv3(0.0,0.0);
789                 MT_Point2 uv20(0.0,0.0),uv21(0.0,0.0),uv22(0.0,0.0),uv23(0.0,0.0);
790                 unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
791
792                 MT_Point3 pt0, pt1, pt2, pt3;
793                 MT_Vector3 no0(0,0,0), no1(0,0,0), no2(0,0,0), no3(0,0,0);
794                 MT_Vector4 tan0(0,0,0,0), tan1(0,0,0,0), tan2(0,0,0,0), tan3(0,0,0,0);
795
796                 /* get coordinates, normals and tangents */
797                 pt0.setValue(mvert[mface->v1].co);
798                 pt1.setValue(mvert[mface->v2].co);
799                 pt2.setValue(mvert[mface->v3].co);
800                 if (mface->v4) pt3.setValue(mvert[mface->v4].co);
801
802                 if(mface->flag & ME_SMOOTH) {
803                         float n0[3], n1[3], n2[3], n3[3];
804
805                         normal_short_to_float_v3(n0, mvert[mface->v1].no);
806                         normal_short_to_float_v3(n1, mvert[mface->v2].no);
807                         normal_short_to_float_v3(n2, mvert[mface->v3].no);
808                         no0 = n0;
809                         no1 = n1;
810                         no2 = n2;
811
812                         if(mface->v4) {
813                                 normal_short_to_float_v3(n3, mvert[mface->v4].no);
814                                 no3 = n3;
815                         }
816                 }
817                 else {
818                         float fno[3];
819
820                         if(mface->v4)
821                                 normal_quad_v3( fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
822                         else
823                                 normal_tri_v3( fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
824
825                         no0 = no1 = no2 = no3 = MT_Vector3(fno);
826                 }
827
828                 if(tangent) {
829                         tan0 = tangent[f*4 + 0];
830                         tan1 = tangent[f*4 + 1];
831                         tan2 = tangent[f*4 + 2];
832
833                         if (mface->v4)
834                                 tan3 = tangent[f*4 + 3];
835                 }
836                 if(blenderobj)
837                         ma = give_current_material(blenderobj, mface->mat_nr+1);
838                 else
839                         ma = mesh->mat ? mesh->mat[mface->mat_nr]:NULL;
840
841                 {
842                         bool visible = true;
843                         bool twoside = false;
844
845                         if(converter->GetMaterials()) {
846                                 /* do Blender Multitexture and Blender GLSL materials */
847                                 unsigned int rgb[4];
848                                 MT_Point2 uv[4];
849
850                                 /* first is the BL_Material */
851                                 if (!bl_mat)
852                                         bl_mat = new BL_Material();
853                                 ConvertMaterial(bl_mat, ma, tface, tfaceName, mface, mcol,
854                                         layers, converter->GetGLSLMaterials());
855
856                                 visible = ((bl_mat->ras_mode & POLY_VIS)!=0);
857                                 collider = ((bl_mat->ras_mode & COLLIDER)!=0);
858                                 twoside = ((bl_mat->mode & TF_TWOSIDE)!=0);
859
860                                 /* vertex colors and uv's were stored in bl_mat temporarily */
861                                 bl_mat->GetConversionRGB(rgb);
862                                 rgb0 = rgb[0]; rgb1 = rgb[1];
863                                 rgb2 = rgb[2]; rgb3 = rgb[3];
864
865                                 bl_mat->GetConversionUV(uv);
866                                 uv0 = uv[0]; uv1 = uv[1];
867                                 uv2 = uv[2]; uv3 = uv[3];
868
869                                 bl_mat->GetConversionUV2(uv);
870                                 uv20 = uv[0]; uv21 = uv[1];
871                                 uv22 = uv[2]; uv23 = uv[3];
872                                 
873                                 /* then the KX_BlenderMaterial */
874                                 if (kx_blmat == NULL)
875                                         kx_blmat = new KX_BlenderMaterial();
876
877                                 kx_blmat->Initialize(scene, bl_mat);
878                                 polymat = static_cast<RAS_IPolyMaterial*>(kx_blmat);
879                         }
880                         else {
881                                 /* do Texture Face materials */
882                                 Image* bima = (tface)? (Image*)tface->tpage: NULL;
883                                 imastr =  (tface)? (bima? (bima)->id.name : "" ) : "";
884                 
885                                 char transp=0;
886                                 short mode=0, tile=0;
887                                 int     tilexrep=4,tileyrep = 4;
888                                 
889                                 if (bima) {
890                                         tilexrep = bima->xrep;
891                                         tileyrep = bima->yrep;
892                                 }
893
894                                 /* get tface properties if available */
895                                 if(tface) {
896                                         /* TF_DYNAMIC means the polygon is a collision face */
897                                         collider = ((tface->mode & TF_DYNAMIC) != 0);
898                                         transp = tface->transp;
899                                         tile = tface->tile;
900                                         mode = tface->mode;
901                                         
902                                         visible = !(tface->mode & TF_INVISIBLE);
903                                         twoside = ((tface->mode & TF_TWOSIDE)!=0);
904                                         
905                                         uv0.setValue(tface->uv[0]);
906                                         uv1.setValue(tface->uv[1]);
907                                         uv2.setValue(tface->uv[2]);
908         
909                                         if (mface->v4)
910                                                 uv3.setValue(tface->uv[3]);
911                                 } 
912                                 else {
913                                         /* no texfaces, set COLLSION true and everything else FALSE */
914                                         mode = default_face_mode;       
915                                         transp = TF_SOLID;
916                                         tile = 0;
917                                 }
918
919                                 /* get vertex colors */
920                                 if (mcol) {
921                                         /* we have vertex colors */
922                                         rgb0 = KX_Mcol2uint_new(mcol[0]);
923                                         rgb1 = KX_Mcol2uint_new(mcol[1]);
924                                         rgb2 = KX_Mcol2uint_new(mcol[2]);
925                                         
926                                         if (mface->v4)
927                                                 rgb3 = KX_Mcol2uint_new(mcol[3]);
928                                 }
929                                 else {
930                                         /* no vertex colors, take from material, otherwise white */
931                                         unsigned int color = 0xFFFFFFFFL;
932
933                                         if (ma)
934                                         {
935                                                 union
936                                                 {
937                                                         unsigned char cp[4];
938                                                         unsigned int integer;
939                                                 } col_converter;
940                                                 
941                                                 col_converter.cp[3] = (unsigned char) (ma->r*255.0);
942                                                 col_converter.cp[2] = (unsigned char) (ma->g*255.0);
943                                                 col_converter.cp[1] = (unsigned char) (ma->b*255.0);
944                                                 col_converter.cp[0] = (unsigned char) (ma->alpha*255.0);
945                                                 
946                                                 color = col_converter.integer;
947                                         }
948
949                                         rgb0 = KX_rgbaint2uint_new(color);
950                                         rgb1 = KX_rgbaint2uint_new(color);
951                                         rgb2 = KX_rgbaint2uint_new(color);      
952                                         
953                                         if (mface->v4)
954                                                 rgb3 = KX_rgbaint2uint_new(color);
955                                 }
956                                 
957                                 // only zsort alpha + add
958                                 bool alpha = (transp == TF_ALPHA || transp == TF_ADD);
959                                 bool zsort = (mode & TF_ALPHASORT)? alpha: 0;
960
961                                 if (kx_polymat == NULL)
962                                         kx_polymat = new KX_PolygonMaterial();
963                                 kx_polymat->Initialize(imastr, ma, (int)mface->mat_nr,
964                                         tile, tilexrep, tileyrep, 
965                                         mode, transp, alpha, zsort, lightlayer, tface, (unsigned int*)mcol);
966                                 polymat = static_cast<RAS_IPolyMaterial*>(kx_polymat);
967         
968                                 if (ma) {
969                                         polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
970                                         polymat->m_shininess = (float)ma->har/4.0f; // 0 < ma->har <= 512
971                                         polymat->m_diffuse = MT_Vector3(ma->r, ma->g, ma->b)*(ma->emit + ma->ref);
972                                 }
973                                 else {
974                                         polymat->m_specular.setValue(0.0f,0.0f,0.0f);
975                                         polymat->m_shininess = 35.0;
976                                 }
977                         }
978
979                         /* mark face as flat, so vertices are split */
980                         bool flat = (mface->flag & ME_SMOOTH) == 0;
981
982                         // see if a bucket was reused or a new one was created
983                         // this way only one KX_BlenderMaterial object has to exist per bucket
984                         bool bucketCreated; 
985                         RAS_MaterialBucket* bucket = scene->FindBucket(polymat, bucketCreated);
986                         if (bucketCreated) {
987                                 // this is needed to free up memory afterwards
988                                 converter->RegisterPolyMaterial(polymat);
989                                 if(converter->GetMaterials()) {
990                                         converter->RegisterBlenderMaterial(bl_mat);
991                                         // the poly material has been stored in the bucket, next time we must create a new one
992                                         bl_mat = NULL;
993                                         kx_blmat = NULL;
994                                 } else {
995                                         // the poly material has been stored in the bucket, next time we must create a new one
996                                         kx_polymat = NULL;
997                                 }
998                         } else {
999                                 // from now on, use the polygon material from the material bucket
1000                                 polymat = bucket->GetPolyMaterial();
1001                                 // keep the material pointers, they will be reused for next face
1002                         }
1003                                                  
1004                         int nverts = (mface->v4)? 4: 3;
1005                         RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts);
1006
1007                         poly->SetVisible(visible);
1008                         poly->SetCollider(collider);
1009                         poly->SetTwoside(twoside);
1010                         //poly->SetEdgeCode(mface->edcode);
1011
1012                         meshobj->AddVertex(poly,0,pt0,uv0,uv20,tan0,rgb0,no0,flat,mface->v1);
1013                         meshobj->AddVertex(poly,1,pt1,uv1,uv21,tan1,rgb1,no1,flat,mface->v2);
1014                         meshobj->AddVertex(poly,2,pt2,uv2,uv22,tan2,rgb2,no2,flat,mface->v3);
1015
1016                         if (nverts==4)
1017                                 meshobj->AddVertex(poly,3,pt3,uv3,uv23,tan3,rgb3,no3,flat,mface->v4);
1018                 }
1019
1020                 if (tface) 
1021                         tface++;
1022                 if (mcol)
1023                         mcol+=4;
1024
1025                 for (int lay=0; lay<MAX_MTFACE; lay++)
1026                 {
1027                         MTF_localLayer &layer = layers[lay];
1028                         if (layer.face == 0) break;
1029
1030                         layer.face++;
1031                 }
1032         }
1033         // keep meshobj->m_sharedvertex_map for reinstance phys mesh.
1034         // 2.49a and before it did: meshobj->m_sharedvertex_map.clear();
1035         // but this didnt save much ram. - Campbell
1036         meshobj->EndConversion();
1037
1038         // pre calculate texture generation
1039         for(list<RAS_MeshMaterial>::iterator mit = meshobj->GetFirstMaterial();
1040                 mit != meshobj->GetLastMaterial(); ++ mit) {
1041                 mit->m_bucket->GetPolyMaterial()->OnConstruction(lightlayer);
1042         }
1043
1044         if (layers)
1045                 delete []layers;
1046         
1047         dm->release(dm);
1048         // cleanup material
1049         if (bl_mat)
1050                 delete bl_mat;
1051         if (kx_blmat)
1052                 delete kx_blmat;
1053         if (kx_polymat)
1054                 delete kx_polymat;
1055         converter->RegisterGameMesh(meshobj, mesh);
1056         return meshobj;
1057 }
1058
1059         
1060         
1061 static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject)
1062 {
1063         PHY_MaterialProps *materialProps = new PHY_MaterialProps;
1064         
1065         MT_assert(materialProps && "Create physics material properties failed");
1066                 
1067         Material* blendermat = give_current_material(blenderobject, 0);
1068                 
1069         if (blendermat)
1070         {
1071                 MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f);
1072         
1073                 materialProps->m_restitution = blendermat->reflect;
1074                 materialProps->m_friction = blendermat->friction;
1075                 materialProps->m_fh_spring = blendermat->fh;
1076                 materialProps->m_fh_damping = blendermat->xyfrict;
1077                 materialProps->m_fh_distance = blendermat->fhdist;
1078                 materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0;
1079         }
1080         else {
1081                 //give some defaults
1082                 materialProps->m_restitution = 0.f;
1083                 materialProps->m_friction = 0.5;
1084                 materialProps->m_fh_spring = 0.f;
1085                 materialProps->m_fh_damping = 0.f;
1086                 materialProps->m_fh_distance = 0.f;
1087                 materialProps->m_fh_normal = false;
1088
1089         }
1090         
1091         return materialProps;
1092 }
1093
1094 static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject)
1095 {
1096         PHY_ShapeProps *shapeProps = new PHY_ShapeProps;
1097         
1098         MT_assert(shapeProps);
1099                 
1100         shapeProps->m_mass = blenderobject->mass;
1101         
1102 //  This needs to be fixed in blender. For now, we use:
1103         
1104 // in Blender, inertia stands for the size value which is equivalent to
1105 // the sphere radius
1106         shapeProps->m_inertia = blenderobject->formfactor;
1107         
1108         MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f);
1109         MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f);
1110         
1111         shapeProps->m_lin_drag = 1.0 - blenderobject->damping;
1112         shapeProps->m_ang_drag = 1.0 - blenderobject->rdamping;
1113         
1114         shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0]; 
1115         shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1];
1116         shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2];
1117         shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0);
1118         
1119         shapeProps->m_do_fh     = (blenderobject->gameflag & OB_DO_FH) != 0; 
1120         shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0;
1121         
1122 //      velocity clamping XXX
1123         shapeProps->m_clamp_vel_min = blenderobject->min_vel;
1124         shapeProps->m_clamp_vel_max = blenderobject->max_vel;
1125         
1126         return shapeProps;
1127 }
1128
1129         
1130         
1131         
1132                 
1133 //////////////////////////////////////////////////////////
1134         
1135
1136
1137 static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
1138 {
1139         MVert *mvert;
1140         BoundBox *bb;
1141         float min[3], max[3];
1142         float mloc[3], msize[3];
1143         float radius=0.0f, vert_radius, *co;
1144         int a;
1145         
1146         if(me->bb==0) me->bb= (struct BoundBox *)MEM_callocN(sizeof(BoundBox), "boundbox");
1147         bb= me->bb;
1148         
1149         INIT_MINMAX(min, max);
1150
1151         if (!loc) loc= mloc;
1152         if (!size) size= msize;
1153         
1154         mvert= me->mvert;
1155         for(a=0; a<me->totvert; a++, mvert++) {
1156                 co= mvert->co;
1157                 
1158                 /* bounds */
1159                 DO_MINMAX(co, min, max);
1160                 
1161                 /* radius */
1162                 vert_radius= co[0]*co[0] + co[1]*co[1] + co[2]*co[2];
1163                 if (vert_radius > radius)
1164                         radius= vert_radius;
1165         }
1166                 
1167         if(me->totvert) {
1168                 loc[0]= (min[0]+max[0])/2.0f;
1169                 loc[1]= (min[1]+max[1])/2.0f;
1170                 loc[2]= (min[2]+max[2])/2.0f;
1171                 
1172                 size[0]= (max[0]-min[0])/2.0f;
1173                 size[1]= (max[1]-min[1])/2.0f;
1174                 size[2]= (max[2]-min[2])/2.0f;
1175         }
1176         else {
1177                 loc[0]= loc[1]= loc[2]= 0.0f;
1178                 size[0]= size[1]= size[2]= 0.0f;
1179         }
1180                 
1181         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= loc[0]-size[0];
1182         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= loc[0]+size[0];
1183                 
1184         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= loc[1]-size[1];
1185         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= loc[1]+size[1];
1186
1187         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= loc[2]-size[2];
1188         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= loc[2]+size[2];
1189
1190         return sqrt(radius);
1191 }
1192                 
1193
1194
1195
1196 static void my_tex_space_mesh(Mesh *me)
1197                 {
1198         KeyBlock *kb;
1199         float *fp, loc[3], size[3], min[3], max[3];
1200         int a;
1201
1202         my_boundbox_mesh(me, loc, size);
1203         
1204         if(me->texflag & AUTOSPACE) {
1205                 if(me->key) {
1206                         kb= me->key->refkey;
1207                         if (kb) {
1208         
1209                                 INIT_MINMAX(min, max);
1210                 
1211                                 fp= (float *)kb->data;
1212                                 for(a=0; a<kb->totelem; a++, fp+=3) {   
1213                                         DO_MINMAX(fp, min, max);
1214                                 }
1215                                 if(kb->totelem) {
1216                                         loc[0]= (min[0]+max[0])/2.0f; loc[1]= (min[1]+max[1])/2.0f; loc[2]= (min[2]+max[2])/2.0f;
1217                                         size[0]= (max[0]-min[0])/2.0f; size[1]= (max[1]-min[1])/2.0f; size[2]= (max[2]-min[2])/2.0f;
1218         } 
1219         else {
1220                                         loc[0]= loc[1]= loc[2]= 0.0;
1221                                         size[0]= size[1]= size[2]= 0.0;
1222                                 }
1223                                 
1224                         }
1225                                 }
1226         
1227                 VECCOPY(me->loc, loc);
1228                 VECCOPY(me->size, size);
1229                 me->rot[0]= me->rot[1]= me->rot[2]= 0.0f;
1230         
1231                 if(me->size[0]==0.0) me->size[0]= 1.0f;
1232                 else if(me->size[0]>0.0 && me->size[0]< 0.00001f) me->size[0]= 0.00001f;
1233                 else if(me->size[0]<0.0 && me->size[0]> -0.00001f) me->size[0]= -0.00001f;
1234         
1235                 if(me->size[1]==0.0) me->size[1]= 1.0f;
1236                 else if(me->size[1]>0.0 && me->size[1]< 0.00001f) me->size[1]= 0.00001f;
1237                 else if(me->size[1]<0.0 && me->size[1]> -0.00001f) me->size[1]= -0.00001f;
1238                                                 
1239                 if(me->size[2]==0.0) me->size[2]= 1.0f;
1240                 else if(me->size[2]>0.0 && me->size[2]< 0.00001f) me->size[2]= 0.00001f;
1241                 else if(me->size[2]<0.0 && me->size[2]> -0.00001f) me->size[2]= -0.00001f;
1242         }
1243         
1244 }
1245
1246 static void my_get_local_bounds(Object *ob, DerivedMesh *dm, float *center, float *size)
1247 {
1248         BoundBox *bb= NULL;
1249         /* uses boundbox, function used by Ketsji */
1250         switch (ob->type)
1251         {
1252                 case OB_MESH:
1253                         if (dm)
1254                         {
1255                                 float min_r[3], max_r[3];
1256                                 INIT_MINMAX(min_r, max_r);
1257                                 dm->getMinMax(dm, min_r, max_r);
1258                                 size[0]= 0.5f*fabsf(max_r[0] - min_r[0]);
1259                                 size[1]= 0.5f*fabsf(max_r[1] - min_r[1]);
1260                                 size[2]= 0.5f*fabsf(max_r[2] - min_r[2]);
1261                                         
1262                                 center[0]= 0.5f*(max_r[0] + min_r[0]);
1263                                 center[1]= 0.5f*(max_r[1] + min_r[1]);
1264                                 center[2]= 0.5f*(max_r[2] + min_r[2]);
1265                                 return;
1266                         } else
1267                         {
1268                                 bb= ( (Mesh *)ob->data )->bb;
1269                                 if(bb==0) 
1270                                 {
1271                                         my_tex_space_mesh((struct Mesh *)ob->data);
1272                                         bb= ( (Mesh *)ob->data )->bb;
1273                                 }
1274                         }
1275                         break;
1276                 case OB_CURVE:
1277                 case OB_SURF:
1278                         center[0]= center[1]= center[2]= 0.0;
1279                         size[0]  = size[1]=size[2]=0.0;
1280                         break;
1281                 case OB_FONT:
1282                         center[0]= center[1]= center[2]= 0.0;
1283                         size[0]  = size[1]=size[2]=1.0;
1284                         break;
1285                 case OB_MBALL:
1286                         bb= ob->bb;
1287                         break;
1288         }
1289         
1290         if(bb==NULL) 
1291         {
1292                 center[0]= center[1]= center[2]= 0.0;
1293                 size[0] = size[1]=size[2]=1.0;
1294         }
1295         else 
1296         {
1297                 size[0]= 0.5f*fabs(bb->vec[0][0] - bb->vec[4][0]);
1298                 size[1]= 0.5f*fabs(bb->vec[0][1] - bb->vec[2][1]);
1299                 size[2]= 0.5f*fabs(bb->vec[0][2] - bb->vec[1][2]);
1300                                         
1301                 center[0]= 0.5f*(bb->vec[0][0] + bb->vec[4][0]);
1302                 center[1]= 0.5f*(bb->vec[0][1] + bb->vec[2][1]);
1303                 center[2]= 0.5f*(bb->vec[0][2] + bb->vec[1][2]);
1304         }
1305 }
1306         
1307
1308
1309
1310 //////////////////////////////////////////////////////
1311
1312
1313 void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
1314                                                            const MT_Point3& localAabbMin,
1315                                                            const MT_Point3& localAabbMax,
1316                                                            KX_Scene* kxscene,
1317                                                            bool isActive,
1318                                                            e_PhysicsEngine physics_engine)
1319 {
1320         if (gameobj->GetMeshCount() > 0) 
1321         {
1322                 switch (physics_engine)
1323                 {
1324 #ifdef USE_BULLET
1325                 case UseBullet:
1326                         {
1327                                 CcdPhysicsEnvironment* env = (CcdPhysicsEnvironment*)kxscene->GetPhysicsEnvironment();
1328                                 assert(env);
1329                                 PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
1330                                 CcdGraphicController* ctrl = new CcdGraphicController(env, motionstate);
1331                                 gameobj->SetGraphicController(ctrl);
1332                                 ctrl->setNewClientInfo(gameobj->getClientInfo());
1333                                 ctrl->setLocalAabb(localAabbMin, localAabbMax);
1334                                 if (isActive) {
1335                                         // add first, this will create the proxy handle, only if the object is visible
1336                                         if (gameobj->GetVisible())
1337                                                 env->addCcdGraphicController(ctrl);
1338                                         // update the mesh if there is a deformer, this will also update the bounding box for modifiers
1339                                         RAS_Deformer* deformer = gameobj->GetDeformer();
1340                                         if (deformer)
1341                                                 deformer->UpdateBuckets();
1342                                 }
1343                         }
1344                         break;
1345 #endif
1346                 default:
1347                         break;
1348                 }
1349         }
1350 }
1351
1352 void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
1353                                                  struct Object* blenderobject,
1354                                                  RAS_MeshObject* meshobj,
1355                                                  KX_Scene* kxscene,
1356                                                  int activeLayerBitInfo,
1357                                                  e_PhysicsEngine        physics_engine,
1358                                                  KX_BlenderSceneConverter *converter,
1359                                                  bool processCompoundChildren
1360                                                  )
1361                                         
1362 {
1363         //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
1364         //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
1365         //bool bRigidBody = (userigidbody == 0);
1366
1367         // object has physics representation?
1368         if (!(blenderobject->gameflag & OB_COLLISION))
1369                 return;
1370
1371         // get Root Parent of blenderobject
1372         struct Object* parent= blenderobject->parent;
1373         while(parent && parent->parent) {
1374                 parent= parent->parent;
1375         }
1376
1377         bool isCompoundChild = false;
1378         bool hasCompoundChildren = !parent && (blenderobject->gameflag & OB_CHILD);
1379
1380         /* When the parent is not OB_DYNAMIC and has no OB_COLLISION then it gets no bullet controller
1381          * and cant be apart of the parents compound shape */
1382         if (parent && (parent->gameflag & (OB_DYNAMIC | OB_COLLISION))) {
1383                 
1384                 if ((parent->gameflag & OB_CHILD) != 0 && (blenderobject->gameflag & OB_CHILD))
1385                 {
1386                         isCompoundChild = true;
1387                 } 
1388         }
1389         if (processCompoundChildren != isCompoundChild)
1390                 return;
1391
1392
1393         PHY_ShapeProps* shapeprops =
1394                         CreateShapePropsFromBlenderObject(blenderobject);
1395
1396         
1397         PHY_MaterialProps* smmaterial = 
1398                 CreateMaterialFromBlenderObject(blenderobject);
1399                                         
1400         KX_ObjectProperties objprop;
1401         objprop.m_lockXaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_AXIS) !=0;
1402         objprop.m_lockYaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_AXIS) !=0;
1403         objprop.m_lockZaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_AXIS) !=0;
1404         objprop.m_lockXRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_ROT_AXIS) !=0;
1405         objprop.m_lockYRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_ROT_AXIS) !=0;
1406         objprop.m_lockZRotaxis = (blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_ROT_AXIS) !=0;
1407
1408         objprop.m_isCompoundChild = isCompoundChild;
1409         objprop.m_hasCompoundChildren = hasCompoundChildren;
1410         objprop.m_margin = blenderobject->margin;
1411         
1412         // ACTOR is now a separate feature
1413         objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0;
1414         objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
1415         objprop.m_softbody = (blenderobject->gameflag & OB_SOFT_BODY) != 0;
1416         objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
1417         
1418         ///contact processing threshold is only for rigid bodies and static geometry, not 'dynamic'
1419         if (objprop.m_angular_rigidbody || !objprop.m_dyna )
1420         {
1421                 objprop.m_contactProcessingThreshold = blenderobject->m_contactProcessingThreshold;
1422         } else
1423         {
1424                 objprop.m_contactProcessingThreshold = 0.f;
1425         }
1426
1427         objprop.m_sensor = (blenderobject->gameflag & OB_SENSOR) != 0;
1428         
1429         if (objprop.m_softbody)
1430         {
1431                 ///for game soft bodies
1432                 if (blenderobject->bsoft)
1433                 {
1434                         objprop.m_gamesoftFlag = blenderobject->bsoft->flag;
1435                                         ///////////////////
1436                         objprop.m_soft_linStiff = blenderobject->bsoft->linStiff;
1437                         objprop.m_soft_angStiff = blenderobject->bsoft->angStiff;               /* angular stiffness 0..1 */
1438                         objprop.m_soft_volume= blenderobject->bsoft->volume;                    /* volume preservation 0..1 */
1439
1440                         objprop.m_soft_viterations= blenderobject->bsoft->viterations;          /* Velocities solver iterations */
1441                         objprop.m_soft_piterations= blenderobject->bsoft->piterations;          /* Positions solver iterations */
1442                         objprop.m_soft_diterations= blenderobject->bsoft->diterations;          /* Drift solver iterations */
1443                         objprop.m_soft_citerations= blenderobject->bsoft->citerations;          /* Cluster solver iterations */
1444
1445                         objprop.m_soft_kSRHR_CL= blenderobject->bsoft->kSRHR_CL;                /* Soft vs rigid hardness [0,1] (cluster only) */
1446                         objprop.m_soft_kSKHR_CL= blenderobject->bsoft->kSKHR_CL;                /* Soft vs kinetic hardness [0,1] (cluster only) */
1447                         objprop.m_soft_kSSHR_CL= blenderobject->bsoft->kSSHR_CL;                /* Soft vs soft hardness [0,1] (cluster only) */
1448                         objprop.m_soft_kSR_SPLT_CL= blenderobject->bsoft->kSR_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1449
1450                         objprop.m_soft_kSK_SPLT_CL= blenderobject->bsoft->kSK_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1451                         objprop.m_soft_kSS_SPLT_CL= blenderobject->bsoft->kSS_SPLT_CL;  /* Soft vs rigid impulse split [0,1] (cluster only) */
1452                         objprop.m_soft_kVCF= blenderobject->bsoft->kVCF;                        /* Velocities correction factor (Baumgarte) */
1453                         objprop.m_soft_kDP= blenderobject->bsoft->kDP;                  /* Damping coefficient [0,1] */
1454
1455                         objprop.m_soft_kDG= blenderobject->bsoft->kDG;                  /* Drag coefficient [0,+inf] */
1456                         objprop.m_soft_kLF= blenderobject->bsoft->kLF;                  /* Lift coefficient [0,+inf] */
1457                         objprop.m_soft_kPR= blenderobject->bsoft->kPR;                  /* Pressure coefficient [-inf,+inf] */
1458                         objprop.m_soft_kVC= blenderobject->bsoft->kVC;                  /* Volume conversation coefficient [0,+inf] */
1459
1460                         objprop.m_soft_kDF= blenderobject->bsoft->kDF;                  /* Dynamic friction coefficient [0,1] */
1461                         objprop.m_soft_kMT= blenderobject->bsoft->kMT;                  /* Pose matching coefficient [0,1] */
1462                         objprop.m_soft_kCHR= blenderobject->bsoft->kCHR;                        /* Rigid contacts hardness [0,1] */
1463                         objprop.m_soft_kKHR= blenderobject->bsoft->kKHR;                        /* Kinetic contacts hardness [0,1] */
1464
1465                         objprop.m_soft_kSHR= blenderobject->bsoft->kSHR;                        /* Soft contacts hardness [0,1] */
1466                         objprop.m_soft_kAHR= blenderobject->bsoft->kAHR;                        /* Anchors hardness [0,1] */
1467                         objprop.m_soft_collisionflags= blenderobject->bsoft->collisionflags;    /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
1468                         objprop.m_soft_numclusteriterations= blenderobject->bsoft->numclusteriterations;        /* number of iterations to refine collision clusters*/
1469                         //objprop.m_soft_welding = blenderobject->bsoft->welding;               /* welding */
1470                         /* disable welding: it doesn't bring any additional stability and it breaks the relation between soft body collision shape and graphic mesh */
1471                         objprop.m_soft_welding = 0.f;           
1472                         objprop.m_margin = blenderobject->bsoft->margin;
1473                         objprop.m_contactProcessingThreshold = 0.f;
1474                 } else
1475                 {
1476                         objprop.m_gamesoftFlag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT;
1477                         
1478                         objprop.m_soft_linStiff = 0.5;;
1479                         objprop.m_soft_angStiff = 1.f;          /* angular stiffness 0..1 */
1480                         objprop.m_soft_volume= 1.f;                     /* volume preservation 0..1 */
1481
1482
1483                         objprop.m_soft_viterations= 0;
1484                         objprop.m_soft_piterations= 1;
1485                         objprop.m_soft_diterations= 0;
1486                         objprop.m_soft_citerations= 4;
1487
1488                         objprop.m_soft_kSRHR_CL= 0.1f;
1489                         objprop.m_soft_kSKHR_CL= 1.f;
1490                         objprop.m_soft_kSSHR_CL= 0.5;
1491                         objprop.m_soft_kSR_SPLT_CL= 0.5f;
1492
1493                         objprop.m_soft_kSK_SPLT_CL= 0.5f;
1494                         objprop.m_soft_kSS_SPLT_CL= 0.5f;
1495                         objprop.m_soft_kVCF=  1;
1496                         objprop.m_soft_kDP= 0;
1497
1498                         objprop.m_soft_kDG= 0;
1499                         objprop.m_soft_kLF= 0;
1500                         objprop.m_soft_kPR= 0;
1501                         objprop.m_soft_kVC= 0;
1502
1503                         objprop.m_soft_kDF= 0.2f;
1504                         objprop.m_soft_kMT= 0.05f;
1505                         objprop.m_soft_kCHR= 1.0f;
1506                         objprop.m_soft_kKHR= 0.1f;
1507
1508                         objprop.m_soft_kSHR= 1.f;
1509                         objprop.m_soft_kAHR= 0.7f;
1510                         objprop.m_soft_collisionflags= OB_BSB_COL_SDF_RS + OB_BSB_COL_VF_SS;
1511                         objprop.m_soft_numclusteriterations= 16;
1512                         objprop.m_soft_welding = 0.f;
1513                         objprop.m_margin = 0.f;
1514                         objprop.m_contactProcessingThreshold = 0.f;
1515                 }
1516         }
1517
1518         objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
1519         objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
1520         //mmm, for now, taks this for the size of the dynamicobject
1521         // Blender uses inertia for radius of dynamic object
1522         objprop.m_radius = blenderobject->inertia;
1523         objprop.m_in_active_layer = (blenderobject->lay & activeLayerBitInfo) != 0;
1524         objprop.m_dynamic_parent=NULL;
1525         objprop.m_isdeformable = ((blenderobject->gameflag2 & 2)) != 0;
1526         objprop.m_boundclass = objprop.m_dyna?KX_BOUNDSPHERE:KX_BOUNDMESH;
1527         
1528         if ((blenderobject->gameflag & OB_SOFT_BODY) && !(blenderobject->gameflag & OB_BOUNDS))
1529         {
1530                 objprop.m_boundclass = KX_BOUNDMESH;
1531         }
1532
1533         KX_BoxBounds bb;
1534         DerivedMesh* dm = NULL;
1535         if (gameobj->GetDeformer())
1536                 dm = gameobj->GetDeformer()->GetPhysicsMesh();
1537         my_get_local_bounds(blenderobject,dm,objprop.m_boundobject.box.m_center,bb.m_extends);
1538         if (blenderobject->gameflag & OB_BOUNDS)
1539         {
1540                 switch (blenderobject->boundtype)
1541                 {
1542                         case OB_BOUND_BOX:
1543                                 objprop.m_boundclass = KX_BOUNDBOX;
1544                                 //mmm, has to be divided by 2 to be proper extends
1545                                 objprop.m_boundobject.box.m_extends[0]=2.f*bb.m_extends[0];
1546                                 objprop.m_boundobject.box.m_extends[1]=2.f*bb.m_extends[1];
1547                                 objprop.m_boundobject.box.m_extends[2]=2.f*bb.m_extends[2];
1548                                 break;
1549                         case OB_BOUND_POLYT:
1550                                 if (blenderobject->type == OB_MESH)
1551                                 {
1552                                         objprop.m_boundclass = KX_BOUNDPOLYTOPE;
1553                                         break;
1554                                 }
1555                                 // Object is not a mesh... fall through OB_BOUND_POLYH to 
1556                                 // OB_BOUND_SPHERE
1557                         case OB_BOUND_POLYH:
1558                                 if (blenderobject->type == OB_MESH)
1559                                 {
1560                                         objprop.m_boundclass = KX_BOUNDMESH;
1561                                         break;
1562                                 }
1563                                 // Object is not a mesh... can't use polyhedron.
1564                                 // Fall through and become a sphere.
1565                         case OB_BOUND_SPHERE:
1566                         {
1567                                 objprop.m_boundclass = KX_BOUNDSPHERE;
1568                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], MT_max(bb.m_extends[1], bb.m_extends[2]));
1569                                 break;
1570                         }
1571                         case OB_BOUND_CYLINDER:
1572                         {
1573                                 objprop.m_boundclass = KX_BOUNDCYLINDER;
1574                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1575                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1576                                 break;
1577                         }
1578                         case OB_BOUND_CONE:
1579                         {
1580                                 objprop.m_boundclass = KX_BOUNDCONE;
1581                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1582                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1583                                 break;
1584                         }
1585                         case OB_BOUND_CAPSULE:
1586                         {
1587                                 objprop.m_boundclass = KX_BOUNDCAPSULE;
1588                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1589                                 objprop.m_boundobject.c.m_height = 2.f*(bb.m_extends[2]-objprop.m_boundobject.c.m_radius);
1590                                 if (objprop.m_boundobject.c.m_height < 0.f)
1591                                         objprop.m_boundobject.c.m_height = 0.f;
1592                                 break;
1593                         }
1594                 }
1595         }
1596
1597         
1598         if (parent/* && (parent->gameflag & OB_DYNAMIC)*/) {
1599                 // parented object cannot be dynamic
1600                 KX_GameObject *parentgameobject = converter->FindGameObject(parent);
1601                 objprop.m_dynamic_parent = parentgameobject;
1602                 //cannot be dynamic:
1603                 objprop.m_dyna = false;
1604                 objprop.m_softbody = false;
1605                 shapeprops->m_mass = 0.f;
1606         }
1607
1608         
1609         objprop.m_concave = (blenderobject->boundtype & 4) != 0;
1610         
1611         switch (physics_engine)
1612         {
1613 #ifdef USE_BULLET
1614                 case UseBullet:
1615                         KX_ConvertBulletObject(gameobj, meshobj, dm, kxscene, shapeprops, smmaterial, &objprop);
1616                         break;
1617
1618 #endif
1619                 case UseDynamo:
1620                         //KX_ConvertDynamoObject(gameobj,meshobj,kxscene,shapeprops,    smmaterial,     &objprop);
1621                         break;
1622                         
1623                 case UseNone:
1624                 default:
1625                         break;
1626         }
1627         delete shapeprops;
1628         delete smmaterial;
1629         if (dm) {
1630                 dm->needsFree = 1;
1631                 dm->release(dm);
1632         }
1633 }
1634
1635
1636
1637
1638
1639 static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRenderTools *rendertools, KX_BlenderSceneConverter *converter) {
1640         RAS_LightObject lightobj;
1641         KX_LightObject *gamelight;
1642         
1643         lightobj.m_att1 = la->att1;
1644         lightobj.m_att2 = (la->mode & LA_QUAD) ? la->att2 : 0.0f;
1645         lightobj.m_red = la->r;
1646         lightobj.m_green = la->g;
1647         lightobj.m_blue = la->b;
1648         lightobj.m_distance = la->dist;
1649         lightobj.m_energy = la->energy;
1650         lightobj.m_layer = layerflag;
1651         lightobj.m_spotblend = la->spotblend;
1652         lightobj.m_spotsize = la->spotsize;
1653         
1654         lightobj.m_nodiffuse = (la->mode & LA_NO_DIFF) != 0;
1655         lightobj.m_nospecular = (la->mode & LA_NO_SPEC) != 0;
1656         
1657         bool glslmat = converter->GetGLSLMaterials();
1658
1659         // in GLSL NEGATIVE LAMP is handled inside the lamp update function
1660         if(glslmat==0) {
1661                 if (la->mode & LA_NEG)
1662                 {
1663                         lightobj.m_red = -lightobj.m_red;
1664                         lightobj.m_green = -lightobj.m_green;
1665                         lightobj.m_blue = -lightobj.m_blue;
1666                 }
1667         }
1668                 
1669         if (la->type==LA_SUN) {
1670                 lightobj.m_type = RAS_LightObject::LIGHT_SUN;
1671         } else if (la->type==LA_SPOT) {
1672                 lightobj.m_type = RAS_LightObject::LIGHT_SPOT;
1673         } else {
1674                 lightobj.m_type = RAS_LightObject::LIGHT_NORMAL;
1675         }
1676
1677         gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools,
1678                 lightobj, glslmat);
1679
1680         BL_ConvertLampIpos(la, gamelight, converter);
1681         
1682         return gamelight;
1683 }
1684
1685 static KX_Camera *gamecamera_from_bcamera(Object *ob, KX_Scene *kxscene, KX_BlenderSceneConverter *converter) {
1686         Camera* ca = static_cast<Camera*>(ob->data);
1687         RAS_CameraData camdata(ca->lens, ca->ortho_scale, ca->clipsta, ca->clipend, ca->type == CAM_PERSP, ca->YF_dofdist);
1688         KX_Camera *gamecamera;
1689         
1690         gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
1691         gamecamera->SetName(ca->id.name + 2);
1692         
1693         BL_ConvertCameraIpos(ca, gamecamera, converter);
1694         
1695         return gamecamera;
1696 }
1697
1698 static KX_GameObject *gameobject_from_blenderobject(
1699                                                                 Object *ob, 
1700                                                                 KX_Scene *kxscene, 
1701                                                                 RAS_IRenderTools *rendertools, 
1702                                                                 KX_BlenderSceneConverter *converter) 
1703 {
1704         KX_GameObject *gameobj = NULL;
1705         
1706         switch(ob->type)
1707         {
1708         case OB_LAMP:
1709         {
1710                 KX_LightObject* gamelight= gamelight_from_blamp(ob, static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
1711                 gameobj = gamelight;
1712                 
1713                 gamelight->AddRef();
1714                 kxscene->GetLightList()->Add(gamelight);
1715
1716                 break;
1717         }
1718         
1719         case OB_CAMERA:
1720         {
1721                 KX_Camera* gamecamera = gamecamera_from_bcamera(ob, kxscene, converter);
1722                 gameobj = gamecamera;
1723                 
1724                 //don't add a reference: the camera list in kxscene->m_cameras is not released at the end
1725                 //gamecamera->AddRef();
1726                 kxscene->AddCamera(gamecamera);
1727                 
1728                 break;
1729         }
1730         
1731         case OB_MESH:
1732         {
1733                 Mesh* mesh = static_cast<Mesh*>(ob->data);
1734                 float center[3], extents[3];
1735                 float radius = my_boundbox_mesh((Mesh*) ob->data, center, extents);
1736                 RAS_MeshObject* meshobj = BL_ConvertMesh(mesh,ob,kxscene,converter);
1737                 
1738                 // needed for python scripting
1739                 kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1740
1741                 if (ob->gameflag & OB_NAVMESH)
1742                 {
1743                         gameobj = new KX_NavMeshObject(kxscene,KX_Scene::m_callbacks);
1744                         gameobj->AddMesh(meshobj);
1745                         break;
1746                 }
1747
1748                 gameobj = new BL_DeformableGameObject(ob,kxscene,KX_Scene::m_callbacks);
1749         
1750                 // set transformation
1751                 gameobj->AddMesh(meshobj);
1752         
1753                 // for all objects: check whether they want to
1754                 // respond to updates
1755                 bool ignoreActivityCulling =  
1756                         ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
1757                 gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
1758                 gameobj->SetOccluder((ob->gameflag & OB_OCCLUDER) != 0, false);
1759         
1760                 // two options exists for deform: shape keys and armature
1761                 // only support relative shape key
1762                 bool bHasShapeKey = mesh->key != NULL && mesh->key->type==KEY_RELATIVE;
1763                 bool bHasDvert = mesh->dvert != NULL && ob->defbase.first;
1764                 bool bHasArmature = (BL_ModifierDeformer::HasArmatureDeformer(ob) && ob->parent && ob->parent->type == OB_ARMATURE && bHasDvert);
1765                 bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(ob);
1766 #ifdef USE_BULLET
1767                 bool bHasSoftBody = (!ob->parent && (ob->gameflag & OB_SOFT_BODY));
1768 #endif
1769                 if (bHasModifier) {
1770                         BL_ModifierDeformer *dcont = new BL_ModifierDeformer((BL_DeformableGameObject *)gameobj,
1771                                                                                                                                 kxscene->GetBlenderScene(), ob, meshobj);
1772                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1773                         if (bHasShapeKey && bHasArmature)
1774                                 dcont->LoadShapeDrivers(ob->parent);
1775                 } else if (bHasShapeKey) {
1776                         // not that we can have shape keys without dvert! 
1777                         BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj, 
1778                                                                                                                         ob, meshobj);
1779                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1780                         if (bHasArmature)
1781                                 dcont->LoadShapeDrivers(ob->parent);
1782                 } else if (bHasArmature) {
1783                         BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj,
1784                                                                                                                         ob, meshobj);
1785                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1786                 } else if (bHasDvert) {
1787                         // this case correspond to a mesh that can potentially deform but not with the
1788                         // object to which it is attached for the moment. A skin mesh was created in
1789                         // BL_ConvertMesh() so must create a deformer too!
1790                         BL_MeshDeformer *dcont = new BL_MeshDeformer((BL_DeformableGameObject*)gameobj,
1791                                                                                                                   ob, meshobj);
1792                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1793 #ifdef USE_BULLET
1794                 } else if (bHasSoftBody) {
1795                         KX_SoftBodyDeformer *dcont = new KX_SoftBodyDeformer(meshobj, (BL_DeformableGameObject*)gameobj);
1796                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1797 #endif
1798                 }
1799                 
1800                 MT_Point3 min = MT_Point3(center) - MT_Vector3(extents);
1801                 MT_Point3 max = MT_Point3(center) + MT_Vector3(extents);
1802                 SG_BBox bbox = SG_BBox(min, max);
1803                 gameobj->GetSGNode()->SetBBox(bbox);
1804                 gameobj->GetSGNode()->SetRadius(radius);
1805         
1806                 break;
1807         }
1808         
1809         case OB_ARMATURE:
1810         {
1811                 gameobj = new BL_ArmatureObject(
1812                         kxscene,
1813                         KX_Scene::m_callbacks,
1814                         ob,
1815                         kxscene->GetBlenderScene() // handle
1816                 );
1817                 /* Get the current pose from the armature object and apply it as the rest pose */
1818                 break;
1819         }
1820         
1821         case OB_EMPTY:
1822         {
1823                 gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks);
1824                 // set transformation
1825                 break;
1826         }
1827
1828         case OB_FONT:
1829         {
1830                 /* font objects have no bounding box */
1831                 gameobj = new KX_FontObject(kxscene,KX_Scene::m_callbacks, rendertools, ob);
1832
1833                 /* add to the list only the visible fonts */
1834                 if((ob->lay & kxscene->GetBlenderScene()->lay) != 0)
1835                         kxscene->AddFont(static_cast<KX_FontObject*>(gameobj));
1836                 break;
1837         }
1838
1839         }
1840         if (gameobj) 
1841         {
1842                 gameobj->SetLayer(ob->lay);
1843                 gameobj->SetBlenderObject(ob);
1844                 gameobj->SetObjectColor(ob->col);
1845                 /* set the visibility state based on the objects render option in the outliner */
1846                 if(ob->restrictflag & OB_RESTRICT_RENDER) gameobj->SetVisible(0, 0);
1847         }
1848         return gameobj;
1849 }
1850
1851 struct parentChildLink {
1852         struct Object* m_blenderchild;
1853         SG_Node* m_gamechildnode;
1854 };
1855
1856 #include "DNA_constraint_types.h"
1857 //XXX #include "BIF_editconstraint.h"
1858
1859 bPoseChannel *get_active_posechannel2 (Object *ob)
1860 {
1861         bArmature *arm= (bArmature*)ob->data;
1862         bPoseChannel *pchan;
1863         
1864         /* find active */
1865         for(pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1866                 if(pchan->bone && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
1867                         return pchan;
1868         }
1869         
1870         return NULL;
1871 }
1872
1873 ListBase *get_active_constraints2(Object *ob)
1874 {
1875         if (!ob)
1876                 return NULL;
1877
1878   // XXX - shouldnt we care about the pose data and not the mode???
1879         if (ob->mode & OB_MODE_POSE) { 
1880                 bPoseChannel *pchan;
1881
1882                 pchan = get_active_posechannel2(ob);
1883                 if (pchan)
1884                         return &pchan->constraints;
1885         }
1886         else 
1887                 return &ob->constraints;
1888
1889         return NULL;
1890 }
1891
1892
1893 void RBJconstraints(Object *ob)//not used
1894 {
1895         ListBase *conlist;
1896         bConstraint *curcon;
1897
1898         conlist = get_active_constraints2(ob);
1899
1900         if (conlist) {
1901                 for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
1902
1903                         printf("%i\n",curcon->type);
1904                 }
1905
1906
1907         }
1908 }
1909
1910 #include "PHY_IPhysicsEnvironment.h"
1911 #include "KX_IPhysicsController.h"
1912 #include "PHY_DynamicTypes.h"
1913
1914 KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc){//not used
1915
1916     for (int j=0;j<sumolist->GetCount();j++)
1917         {
1918             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1919             if (gameobje->GetName()==busc)
1920             return gameobje->GetPhysicsController();
1921         }
1922
1923         return 0;
1924
1925 }
1926
1927 KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist){
1928
1929     for (int j=0;j<sumolist->GetCount();j++)
1930         {
1931             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1932             if (gameobje->GetName()==busc)
1933             return gameobje;
1934         }
1935         
1936         return 0;
1937
1938 }
1939
1940 // convert blender objects into ketsji gameobjects
1941 void BL_ConvertBlenderObjects(struct Main* maggie,
1942                                                           KX_Scene* kxscene,
1943                                                           KX_KetsjiEngine* ketsjiEngine,
1944                                                           e_PhysicsEngine       physics_engine,
1945                                                           RAS_IRenderTools* rendertools,
1946                                                           RAS_ICanvas* canvas,
1947                                                           KX_BlenderSceneConverter* converter,
1948                                                           bool alwaysUseExpandFraming
1949                                                           )
1950 {       
1951
1952         Scene *blenderscene = kxscene->GetBlenderScene();
1953         // for SETLOOPER
1954         Scene *sce_iter;
1955         Base *base;
1956
1957         // Get the frame settings of the canvas.
1958         // Get the aspect ratio of the canvas as designed by the user.
1959
1960         RAS_FrameSettings::RAS_FrameType frame_type;
1961         int aspect_width;
1962         int aspect_height;
1963         vector<MT_Vector3> inivel,iniang;
1964         set<Group*> grouplist;  // list of groups to be converted
1965         set<Object*> allblobj;  // all objects converted
1966         set<Object*> groupobj;  // objects from groups (never in active layer)
1967
1968         if (alwaysUseExpandFraming) {
1969                 frame_type = RAS_FrameSettings::e_frame_extend;
1970                 aspect_width = canvas->GetWidth();
1971                 aspect_height = canvas->GetHeight();
1972         } else {
1973                 if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_BARS) {
1974                         frame_type = RAS_FrameSettings::e_frame_bars;
1975                 } else if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_EXTEND) {
1976                         frame_type = RAS_FrameSettings::e_frame_extend;
1977                 } else {
1978                         frame_type = RAS_FrameSettings::e_frame_scale;
1979                 }
1980                 
1981                 aspect_width = blenderscene->gm.xsch;
1982                 aspect_height = blenderscene->gm.ysch;
1983         }
1984         
1985         RAS_FrameSettings frame_settings(
1986                 frame_type,
1987                 blenderscene->gm.framing.col[0],
1988                 blenderscene->gm.framing.col[1],
1989                 blenderscene->gm.framing.col[2],
1990                 aspect_width,
1991                 aspect_height
1992         );
1993         kxscene->SetFramingType(frame_settings);
1994
1995         kxscene->SetGravity(MT_Vector3(0,0, -blenderscene->gm.gravity));
1996         
1997         /* set activity culling parameters */
1998         kxscene->SetActivityCulling( (blenderscene->gm.mode & WO_ACTIVITY_CULLING) != 0);
1999         kxscene->SetActivityCullingRadius(blenderscene->gm.activityBoxRadius);
2000         kxscene->SetDbvtCulling((blenderscene->gm.mode & WO_DBVT_CULLING) != 0);
2001         
2002         // no occlusion culling by default
2003         kxscene->SetDbvtOcclusionRes(0);
2004
2005         int activeLayerBitInfo = blenderscene->lay;
2006         
2007         // list of all object converted, active and inactive
2008         CListValue*     sumolist = new CListValue();
2009         
2010         vector<parentChildLink> vec_parent_child;
2011         
2012         CListValue* objectlist = kxscene->GetObjectList();
2013         CListValue* inactivelist = kxscene->GetInactiveList();
2014         CListValue* parentlist = kxscene->GetRootParentList();
2015         
2016         SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
2017         SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager();
2018         
2019         CListValue* logicbrick_conversionlist = new CListValue();
2020         
2021         //SG_TreeFactory tf;
2022         
2023         // Convert actions to actionmap
2024         bAction *curAct;
2025         for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next)
2026         {
2027                 logicmgr->RegisterActionName(curAct->id.name + 2, curAct);
2028         }
2029
2030         SetDefaultFaceType(blenderscene);
2031         // Let's support scene set.
2032         // Beware of name conflict in linked data, it will not crash but will create confusion
2033         // in Python scripting and in certain actuators (replace mesh). Linked scene *should* have
2034         // no conflicting name for Object, Object data and Action.
2035         for (SETLOOPER(blenderscene, sce_iter, base))
2036         {
2037                 Object* blenderobject = base->object;
2038                 allblobj.insert(blenderobject);
2039
2040                 KX_GameObject* gameobj = gameobject_from_blenderobject(
2041                                                                                 base->object, 
2042                                                                                 kxscene, 
2043                                                                                 rendertools, 
2044                                                                                 converter);
2045                                                                                 
2046                 bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0;
2047                 bool addobj=true;
2048                 
2049                 if (converter->addInitFromFrame)
2050                         if (!isInActiveLayer)
2051                                 addobj=false;
2052
2053                 if (gameobj&&addobj)
2054                 {
2055                         MT_Point3 posPrev;                      
2056                         MT_Matrix3x3 angor;                     
2057                         if (converter->addInitFromFrame) blenderscene->r.cfra=blenderscene->r.sfra;
2058                         
2059                         MT_Point3 pos;
2060                         pos.setValue(
2061                                 blenderobject->loc[0]+blenderobject->dloc[0],
2062                                 blenderobject->loc[1]+blenderobject->dloc[1],
2063                                 blenderobject->loc[2]+blenderobject->dloc[2]
2064                         );
2065                         MT_Vector3 eulxyz(blenderobject->rot);
2066                         MT_Vector3 scale(blenderobject->size);
2067                         if (converter->addInitFromFrame){//rcruiz
2068                                 float eulxyzPrev[3];
2069                                 blenderscene->r.cfra=blenderscene->r.sfra-1;
2070                                 //XXX update_for_newframe();
2071                                 MT_Vector3 tmp=pos-MT_Point3(blenderobject->loc[0]+blenderobject->dloc[0],
2072                                                                                         blenderobject->loc[1]+blenderobject->dloc[1],
2073                                                                                         blenderobject->loc[2]+blenderobject->dloc[2]
2074                                                                         );
2075                                 eulxyzPrev[0]=blenderobject->rot[0];
2076                                 eulxyzPrev[1]=blenderobject->rot[1];
2077                                 eulxyzPrev[2]=blenderobject->rot[2];
2078
2079                                 double fps = (double) blenderscene->r.frs_sec/
2080                                         (double) blenderscene->r.frs_sec_base;
2081
2082                                 tmp.scale(fps, fps, fps);
2083                                 inivel.push_back(tmp);
2084                                 tmp=eulxyz-eulxyzPrev;
2085                                 tmp.scale(fps, fps, fps);
2086                                 iniang.push_back(tmp);
2087                                 blenderscene->r.cfra=blenderscene->r.sfra;
2088                                 //XXX update_for_newframe();
2089                         }               
2090                                                 
2091                         gameobj->NodeSetLocalPosition(pos);
2092                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
2093                         gameobj->NodeSetLocalScale(scale);
2094                         gameobj->NodeUpdateGS(0);
2095                         
2096                         BL_ConvertIpos(blenderobject,gameobj,converter);
2097                         BL_ConvertMaterialIpos(blenderobject, gameobj, converter);
2098                         
2099                         sumolist->Add(gameobj->AddRef());
2100                         
2101                         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
2102                         
2103                         gameobj->SetName(blenderobject->id.name + 2);
2104         
2105                         // update children/parent hierarchy
2106                         if ((blenderobject->parent != 0)&&(!converter->addInitFromFrame))
2107                         {
2108                                 // blender has an additional 'parentinverse' offset in each object
2109                                 SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc);
2110                                 SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback);
2111                         
2112                                 // define a normal parent relationship for this node.
2113                                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
2114                                 parentinversenode->SetParentRelation(parent_relation);
2115         
2116                                 parentChildLink pclink;
2117                                 pclink.m_blenderchild = blenderobject;
2118                                 pclink.m_gamechildnode = parentinversenode;
2119                                 vec_parent_child.push_back(pclink);
2120
2121                                 float* fl = (float*) blenderobject->parentinv;
2122                                 MT_Transform parinvtrans(fl);
2123                                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
2124                                 // problem here: the parent inverse transform combines scaling and rotation 
2125                                 // in the basis but the scenegraph needs separate rotation and scaling.
2126                                 // This is not important for OpenGL (it uses 4x4 matrix) but it is important
2127                                 // for the physic engine that needs a separate scaling
2128                                 //parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
2129
2130                                 // Extract the rotation and the scaling from the basis
2131                                 MT_Matrix3x3 ori(parinvtrans.getBasis());
2132                                 MT_Vector3 x(ori.getColumn(0));
2133                                 MT_Vector3 y(ori.getColumn(1));
2134                                 MT_Vector3 z(ori.getColumn(2));
2135                                 MT_Vector3 parscale(x.length(), y.length(), z.length());
2136                                 if (!MT_fuzzyZero(parscale[0]))
2137                                         x /= parscale[0];
2138                                 if (!MT_fuzzyZero(parscale[1]))
2139                                         y /= parscale[1];
2140                                 if (!MT_fuzzyZero(parscale[2]))
2141                                         z /= parscale[2];
2142                                 ori.setColumn(0, x);                                                            
2143                                 ori.setColumn(1, y);                                                            
2144                                 ori.setColumn(2, z);                                                            
2145                                 parentinversenode->SetLocalOrientation(ori);
2146                                 parentinversenode->SetLocalScale(parscale);
2147                                 
2148                                 parentinversenode->AddChild(gameobj->GetSGNode());
2149                         }
2150                         
2151                         // needed for python scripting
2152                         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
2153
2154                         // needed for group duplication
2155                         logicmgr->RegisterGameObj(blenderobject, gameobj);
2156                         for (int i = 0; i < gameobj->GetMeshCount(); i++)
2157                                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
2158         
2159                         converter->RegisterGameObject(gameobj, blenderobject);  
2160                         // this was put in rapidly, needs to be looked at more closely
2161                         // only draw/use objects in active 'blender' layers
2162         
2163                         logicbrick_conversionlist->Add(gameobj->AddRef());
2164                         
2165                         if (converter->addInitFromFrame){
2166                                 posPrev=gameobj->NodeGetWorldPosition();
2167                                 angor=gameobj->NodeGetWorldOrientation();
2168                         }
2169                         if (isInActiveLayer)
2170                         {
2171                                 objectlist->Add(gameobj->AddRef());
2172                                 //tf.Add(gameobj->GetSGNode());
2173                                 
2174                                 gameobj->NodeUpdateGS(0);
2175                                 gameobj->AddMeshUser();
2176                 
2177                         }
2178                         else
2179                         {
2180                                 //we must store this object otherwise it will be deleted 
2181                                 //at the end of this function if it is not a root object
2182                                 inactivelist->Add(gameobj->AddRef());
2183                         }
2184                         if (gameobj->IsDupliGroup())
2185                                 grouplist.insert(blenderobject->dup_group);
2186                         if (converter->addInitFromFrame){
2187                                 gameobj->NodeSetLocalPosition(posPrev);
2188                                 gameobj->NodeSetLocalOrientation(angor);
2189                         }
2190                                                 
2191                 }
2192                 /* Note about memory leak issues:
2193                    When a CValue derived class is created, m_refcount is initialized to 1
2194                    so the class must be released after being used to make sure that it won't 
2195                    hang in memory. If the object needs to be stored for a long time, 
2196                    use AddRef() so that this Release() does not free the object.
2197                    Make sure that for any AddRef() there is a Release()!!!! 
2198                    Do the same for any object derived from CValue, CExpression and NG_NetworkMessage
2199                  */
2200                 if (gameobj)
2201                         gameobj->Release();
2202
2203         }
2204
2205         if (!grouplist.empty())
2206         {
2207                 // now convert the group referenced by dupli group object
2208                 // keep track of all groups already converted
2209                 set<Group*> allgrouplist = grouplist;
2210                 set<Group*> tempglist;
2211                 // recurse
2212                 while (!grouplist.empty())
2213                 {
2214                         set<Group*>::iterator git;
2215                         tempglist.clear();
2216                         tempglist.swap(grouplist);
2217                         for (git=tempglist.begin(); git!=tempglist.end(); git++)
2218                         {
2219                                 Group* group = *git;
2220                                 GroupObject* go;
2221                                 for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
2222                                 {
2223                                         Object* blenderobject = go->ob;
2224                                         if (converter->FindGameObject(blenderobject) == NULL)
2225                                         {
2226                                                 allblobj.insert(blenderobject);
2227                                                 groupobj.insert(blenderobject);
2228                                                 KX_GameObject* gameobj = gameobject_from_blenderobject(
2229                                                                                                                 blenderobject, 
2230                                                                                                                 kxscene, 
2231                                                                                                                 rendertools, 
2232                                                                                                                 converter);
2233                                                                                 
2234                                                 // this code is copied from above except that
2235                                                 // object from groups are never in active layer
2236                                                 bool isInActiveLayer = false;
2237                                                 bool addobj=true;
2238                                                 
2239                                                 if (converter->addInitFromFrame)
2240                                                         if (!isInActiveLayer)
2241                                                                 addobj=false;
2242                                                                                                                 
2243                                                 if (gameobj&&addobj)
2244                                                 {
2245                                                         MT_Point3 posPrev;                      
2246                                                         MT_Matrix3x3 angor;                     
2247                                                         if (converter->addInitFromFrame) 
2248                                                                 blenderscene->r.cfra=blenderscene->r.sfra;
2249                                                         
2250                                                         MT_Point3 pos(
2251                                                                 blenderobject->loc[0]+blenderobject->dloc[0],
2252                                                                 blenderobject->loc[1]+blenderobject->dloc[1],
2253                                                                 blenderobject->loc[2]+blenderobject->dloc[2]
2254                                                         );
2255                                                         MT_Vector3 eulxyz(blenderobject->rot);
2256                                                         MT_Vector3 scale(blenderobject->size);
2257                                                         if (converter->addInitFromFrame){//rcruiz
2258                                                                 float eulxyzPrev[3];
2259                                                                 blenderscene->r.cfra=blenderscene->r.sfra-1;
2260                                                                 //XXX update_for_newframe();
2261                                                                 MT_Vector3 tmp=pos-MT_Point3(blenderobject->loc[0]+blenderobject->dloc[0],
2262                                                                                                                         blenderobject->loc[1]+blenderobject->dloc[1],
2263                                                                                                                         blenderobject->loc[2]+blenderobject->dloc[2]
2264                                                                                                         );
2265                                                                 eulxyzPrev[0]=blenderobject->rot[0];
2266                                                                 eulxyzPrev[1]=blenderobject->rot[1];
2267                                                                 eulxyzPrev[2]=blenderobject->rot[2];
2268
2269                                                                 double fps = (double) blenderscene->r.frs_sec/
2270                                                                         (double) blenderscene->r.frs_sec_base;
2271
2272                                                                 tmp.scale(fps, fps, fps);
2273                                                                 inivel.push_back(tmp);
2274                                                                 tmp=eulxyz-eulxyzPrev;
2275                                                                 tmp.scale(fps, fps, fps);
2276                                                                 iniang.push_back(tmp);
2277                                                                 blenderscene->r.cfra=blenderscene->r.sfra;
2278                                                                 //XXX update_for_newframe();
2279                                                         }               
2280                                                                                 
2281                                                         gameobj->NodeSetLocalPosition(pos);
2282                                                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
2283                                                         gameobj->NodeSetLocalScale(scale);
2284                                                         gameobj->NodeUpdateGS(0);
2285                                                         
2286                                                         BL_ConvertIpos(blenderobject,gameobj,converter);
2287                                                         BL_ConvertMaterialIpos(blenderobject,gameobj, converter);       
2288                                         
2289                                                         sumolist->Add(gameobj->AddRef());
2290                                                         
2291                                                         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
2292                                                         
2293                                         
2294                                                         gameobj->SetName(blenderobject->id.name + 2);
2295                                         
2296                                                         // update children/parent hierarchy
2297                                                         if ((blenderobject->parent != 0)&&(!converter->addInitFromFrame))
2298                                                         {
2299                                                                 // blender has an additional 'parentinverse' offset in each object
2300                                                                 SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc);
2301                                                                 SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback);
2302                                                         
2303                                                                 // define a normal parent relationship for this node.
2304                                                                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
2305                                                                 parentinversenode->SetParentRelation(parent_relation);
2306                                         
2307                                                                 parentChildLink pclink;
2308                                                                 pclink.m_blenderchild = blenderobject;
2309                                                                 pclink.m_gamechildnode = parentinversenode;
2310                                                                 vec_parent_child.push_back(pclink);
2311
2312                                                                 float* fl = (float*) blenderobject->parentinv;
2313                                                                 MT_Transform parinvtrans(fl);
2314                                                                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
2315
2316                                                                 // Extract the rotation and the scaling from the basis
2317                                                                 MT_Matrix3x3 ori(parinvtrans.getBasis());
2318                                                                 MT_Vector3 x(ori.getColumn(0));
2319                                                                 MT_Vector3 y(ori.getColumn(1));
2320                                                                 MT_Vector3 z(ori.getColumn(2));
2321                                                                 MT_Vector3 localscale(x.length(), y.length(), z.length());
2322                                                                 if (!MT_fuzzyZero(localscale[0]))
2323                                                                         x /= localscale[0];
2324                                                                 if (!MT_fuzzyZero(localscale[1]))
2325                                                                         y /= localscale[1];
2326                                                                 if (!MT_fuzzyZero(localscale[2]))
2327                                                                         z /= localscale[2];
2328                                                                 ori.setColumn(0, x);                                                            
2329                                                                 ori.setColumn(1, y);                                                            
2330                                                                 ori.setColumn(2, z);                                                            
2331                                                                 parentinversenode->SetLocalOrientation(ori);
2332                                                                 parentinversenode->SetLocalScale(localscale);
2333                                                                 
2334                                                                 parentinversenode->AddChild(gameobj->GetSGNode());
2335                                                         }
2336                                                         
2337                                                         // needed for python scripting
2338                                                         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
2339
2340                                                         // needed for group duplication
2341                                                         logicmgr->RegisterGameObj(blenderobject, gameobj);
2342                                                         for (int i = 0; i < gameobj->GetMeshCount(); i++)
2343                                                                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
2344                                         
2345                                                         converter->RegisterGameObject(gameobj, blenderobject);  
2346                                                         // this was put in rapidly, needs to be looked at more closely
2347                                                         // only draw/use objects in active 'blender' layers
2348                                         
2349                                                         logicbrick_conversionlist->Add(gameobj->AddRef());
2350                                                         
2351                                                         if (converter->addInitFromFrame){
2352                                                                 posPrev=gameobj->NodeGetWorldPosition();
2353                                                                 angor=gameobj->NodeGetWorldOrientation();
2354                                                         }
2355                                                         if (isInActiveLayer)
2356                                                         {
2357                                                                 objectlist->Add(gameobj->AddRef());
2358                                                                 //tf.Add(gameobj->GetSGNode());
2359                                                                 
2360                                                                 gameobj->NodeUpdateGS(0);
2361                                                                 gameobj->AddMeshUser();
2362                                                         }
2363                                                         else
2364                                                         {
2365                                                                 //we must store this object otherwise it will be deleted 
2366                                                                 //at the end of this function if it is not a root object
2367                                                                 inactivelist->Add(gameobj->AddRef());
2368
2369                                                         }
2370                                                         if (gameobj->IsDupliGroup())
2371                                                         {
2372                                                                 // check that the group is not already converted
2373                                                                 if (allgrouplist.insert(blenderobject->dup_group).second)
2374                                                                         grouplist.insert(blenderobject->dup_group);
2375                                                         }
2376                                                         if (converter->addInitFromFrame){
2377                                                                 gameobj->NodeSetLocalPosition(posPrev);
2378                                                                 gameobj->NodeSetLocalOrientation(angor);
2379                                                         }
2380                                                                                 
2381                                                 }
2382                                                 if (gameobj)
2383                                                         gameobj->Release();
2384                                         }
2385                                 }
2386                         }
2387                 }
2388         }
2389
2390         // non-camera objects not supported as camera currently
2391         if (blenderscene->camera && blenderscene->camera->type == OB_CAMERA) {
2392                 KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
2393                 
2394                 if(gamecamera)
2395                         kxscene->SetActiveCamera(gamecamera);
2396         }
2397
2398         //      Set up armatures
2399         set<Object*>::iterator oit;
2400         for(oit=allblobj.begin(); oit!=allblobj.end(); oit++)
2401         {
2402                 Object* blenderobj = *oit;
2403                 if (blenderobj->type==OB_MESH) {
2404                         Mesh *me = (Mesh*)blenderobj->data;
2405         
2406                         if (me->dvert){
2407                                 BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj);
2408
2409                                 if (obj && BL_ModifierDeformer::HasArmatureDeformer(blenderobj) && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE){
2410                                         KX_GameObject *par = converter->FindGameObject(blenderobj->parent);
2411                                         if (par && obj->GetDeformer())
2412                                                 ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par);
2413                                 }
2414                         }
2415                 }
2416         }
2417         
2418         // create hierarchy information
2419         int i;
2420         vector<parentChildLink>::iterator pcit;
2421         
2422         for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit)
2423         {
2424         
2425                 struct Object* blenderchild = pcit->m_blenderchild;
2426                 struct Object* blenderparent = blenderchild->parent;
2427                 KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
2428                 KX_GameObject* childobj = converter->FindGameObject(blenderchild);
2429
2430                 assert(childobj);
2431
2432                 if (!parentobj || objectlist->SearchValue(childobj) != objectlist->SearchValue(parentobj))
2433                 {
2434                         // special case: the parent and child object are not in the same layer. 
2435                         // This weird situation is used in Apricot for test purposes.
2436                         // Resolve it by not converting the child
2437                         childobj->GetSGNode()->DisconnectFromParent();
2438                         delete pcit->m_gamechildnode;
2439                         // Now destroy the child object but also all its descendent that may already be linked
2440                         // Remove the child reference in the local list!
2441                         // Note: there may be descendents already if the children of the child were processed
2442                         //       by this loop before the child. In that case, we must remove the children also
2443                         CListValue* childrenlist = childobj->GetChildrenRecursive();
2444                         childrenlist->Add(childobj->AddRef());
2445                         for ( i=0;i<childrenlist->GetCount();i++)
2446                         {
2447                                 KX_GameObject* obj = static_cast<KX_GameObject*>(childrenlist->GetValue(i));
2448                                 if (sumolist->RemoveValue(obj))
2449                                         obj->Release();
2450                                 if (logicbrick_conversionlist->RemoveValue(obj))
2451                                         obj->Release();
2452                         }
2453                         childrenlist->Release();
2454                         
2455                         // now destroy recursively
2456                         converter->UnregisterGameObject(childobj); // removing objects during conversion make sure this runs too
2457                         kxscene->RemoveObject(childobj);
2458                         
2459                         continue;
2460                 }
2461
2462                 switch (blenderchild->partype)
2463                 {
2464                         case PARVERT1:
2465                         {
2466                                 // creat a new vertex parent relationship for this node.
2467                                 KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New();
2468                                 pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation);
2469                                 break;
2470                         }
2471                         case PARSLOW:
2472                         {
2473                                 // creat a new slow parent relationship for this node.
2474                                 KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
2475                                 pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
2476                                 break;
2477                         }       
2478                         case PARBONE:
2479                         {
2480                                 // parent this to a bone
2481                                 Bone *parent_bone = get_named_bone( (bArmature *)(blenderchild->parent)->data, blenderchild->parsubstr);
2482
2483                                 if(parent_bone) {
2484                                         KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
2485                                         pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
2486                                 }
2487                         
2488                                 break;
2489                         }
2490                         case PARSKEL: // skinned - ignore
2491                                 break;
2492                         case PAROBJECT:
2493                         case PARCURVE:
2494                         case PARKEY:
2495                         case PARVERT3:
2496                         default:
2497                                 // unhandled
2498                                 break;
2499                 }
2500         
2501                 parentobj->     GetSGNode()->AddChild(pcit->m_gamechildnode);
2502         }
2503         vec_parent_child.clear();
2504         
2505         // find 'root' parents (object that has not parents in SceneGraph)
2506         for (i=0;i<sumolist->GetCount();++i)
2507         {
2508                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2509                 if (gameobj->GetSGNode()->GetSGParent() == 0)
2510                 {
2511                         parentlist->Add(gameobj->AddRef());
2512                         gameobj->NodeUpdateGS(0);
2513                 }
2514         }
2515
2516         // create graphic controller for culling
2517         if (kxscene->GetDbvtCulling())
2518         {
2519                 bool occlusion = false;
2520                 for (i=0; i<sumolist->GetCount();i++)
2521                 {
2522                         KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2523                         if (gameobj->GetMeshCount() > 0) 
2524                         {
2525                                 MT_Point3 box[2];
2526                                 gameobj->GetSGNode()->BBox().getmm(box, MT_Transform::Identity());
2527                                 // box[0] is the min, box[1] is the max
2528                                 bool isactive = objectlist->SearchValue(gameobj);
2529                                 BL_CreateGraphicObjectNew(gameobj,box[0],box[1],kxscene,isactive,physics_engine);
2530                                 if (gameobj->GetOccluder())
2531                                         occlusion = true;
2532                         }
2533                 }
2534                 if (occlusion)
2535                         kxscene->SetDbvtOcclusionRes(blenderscene->gm.occlusionRes);
2536         }
2537         if (blenderscene->world)
2538                 kxscene->GetPhysicsEnvironment()->setNumTimeSubSteps(blenderscene->gm.physubstep);
2539
2540         // now that the scenegraph is complete, let's instantiate the deformers.
2541         // We need that to create reusable derived mesh and physic shapes
2542         for (i=0;i<sumolist->GetCount();++i)
2543         {
2544                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2545                 if (gameobj->GetDeformer())
2546                         gameobj->GetDeformer()->UpdateBuckets();
2547         }
2548
2549         // Set up armature constraints
2550         for (i=0;i<sumolist->GetCount();++i)
2551         {
2552                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2553                 if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
2554                         ((BL_ArmatureObject*)gameobj)->LoadConstraints(converter);
2555         }
2556
2557         bool processCompoundChildren = false;
2558
2559         // create physics information
2560         for (i=0;i<sumolist->GetCount();i++)
2561         {
2562                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2563                 struct Object* blenderobject = gameobj->GetBlenderObject();
2564                 int nummeshes = gameobj->GetMeshCount();
2565                 RAS_MeshObject* meshobj = 0;
2566                 if (nummeshes > 0)
2567                 {
2568                         meshobj = gameobj->GetMesh(0);
2569                 }
2570                 int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
2571                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,physics_engine,converter,processCompoundChildren);
2572         }
2573
2574         processCompoundChildren = true;
2575         // create physics information
2576         for (i=0;i<sumolist->GetCount();i++)
2577         {
2578                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2579                 struct Object* blenderobject = gameobj->GetBlenderObject();
2580                 int nummeshes = gameobj->GetMeshCount();
2581                 RAS_MeshObject* meshobj = 0;
2582                 if (nummeshes > 0)
2583                 {
2584                         meshobj = gameobj->GetMesh(0);
2585                 }
2586                 int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
2587                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,physics_engine,converter,processCompoundChildren);
2588         }
2589         
2590         //set ini linearVel and int angularVel //rcruiz
2591         if (converter->addInitFromFrame)
2592                 for (i=0;i<sumolist->GetCount();i++)
2593                 {
2594                         KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2595                         if (gameobj->IsDynamic()){
2596                                 gameobj->setLinearVelocity(inivel[i],false);
2597                                 gameobj->setAngularVelocity(iniang[i],false);
2598                         }
2599                 
2600                 
2601                 }       
2602
2603                 // create physics joints
2604         for (i=0;i<sumolist->GetCount();i++)
2605         {
2606                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2607                 struct Object* blenderobject = gameobj->GetBlenderObject();
2608                 ListBase *conlist;
2609                 bConstraint *curcon;
2610                 conlist = get_active_constraints2(blenderobject);
2611
2612                 if (conlist) {
2613                         for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
2614                                 if (curcon->type==CONSTRAINT_TYPE_RIGIDBODYJOINT){
2615
2616                                         bRigidBodyJointConstraint *dat=(bRigidBodyJointConstraint *)curcon->data;
2617
2618                                         if (!dat->child){
2619
2620                                                 PHY_IPhysicsController* physctr2 = 0;
2621
2622                                                 if (dat->tar)
2623                                                 {
2624                                                         KX_GameObject *gotar=getGameOb(dat->tar->id.name+2,sumolist);
2625                                                         if (gotar && gotar->GetPhysicsController())
2626                                                                 physctr2 = (PHY_IPhysicsController*) gotar->GetPhysicsController()->GetUserData();
2627                                                 }
2628
2629                                                 if (gameobj->GetPhysicsController())
2630                                                 {
2631                                                         PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) gameobj->GetPhysicsController()->GetUserData();
2632                                                         //we need to pass a full constraint frame, not just axis
2633                                     
2634                                                         //localConstraintFrameBas