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