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