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