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