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