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