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