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