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