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