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