0f55438ecf6bb188c0fb3003406f4929e6ed9b43
[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 /* Since threaded object update we've disabled in-place
38  * curve evaluation (in cases when applying curve modifier
39  * with target curve non-evaluated yet).
40  *
41  * This requires game engine to take care of DAG and object
42  * evaluation (currently it's designed to export only objects
43  * it able to render).
44  *
45  * This workaround will make sure that curve_cache for curves
46  * is up-to-date.
47  */
48 #define THREADED_DAG_WORKAROUND
49
50 #include <math.h>
51 #include <vector>
52 #include <algorithm>
53
54 #include "BL_BlenderDataConversion.h"
55
56 #include "MT_Transform.h"
57 #include "MT_MinMax.h"
58
59 #include "PHY_Pro.h"
60 #include "PHY_IPhysicsEnvironment.h"
61
62 #include "RAS_MeshObject.h"
63 #include "RAS_IRasterizer.h"
64 #include "RAS_ILightObject.h"
65
66 #include "KX_ConvertActuators.h"
67 #include "KX_ConvertControllers.h"
68 #include "KX_ConvertSensors.h"
69 #include "SCA_LogicManager.h"
70 #include "SCA_TimeEventManager.h"
71
72 #include "KX_ClientObjectInfo.h"
73 #include "KX_Scene.h"
74 #include "KX_GameObject.h"
75 #include "KX_Light.h"
76 #include "KX_Camera.h"
77 #include "KX_EmptyObject.h"
78 #include "KX_FontObject.h"
79
80 #include "RAS_TexMatrix.h"
81 #include "RAS_ICanvas.h"
82 #include "RAS_Polygon.h"
83 #include "RAS_TexVert.h"
84 #include "RAS_BucketManager.h"
85 #include "RAS_IPolygonMaterial.h"
86 #include "BL_Material.h"
87 #include "KX_BlenderMaterial.h"
88 #include "BL_Texture.h"
89
90 #include "BKE_main.h"
91 #include "BKE_global.h"
92 #include "BKE_object.h"
93 #include "BL_ModifierDeformer.h"
94 #include "BL_ShapeDeformer.h"
95 #include "BL_SkinDeformer.h"
96 #include "BL_MeshDeformer.h"
97 #include "KX_SoftBodyDeformer.h"
98 #include "BLI_utildefines.h"
99 #include "BLI_listbase.h"
100
101 #include "KX_WorldInfo.h"
102
103 #include "KX_KetsjiEngine.h"
104 #include "KX_BlenderSceneConverter.h"
105
106 /* This little block needed for linking to Blender... */
107 #ifdef WIN32
108 #include "BLI_winstuff.h"
109 #endif
110
111 /* This list includes only data type definitions */
112 #include "DNA_object_types.h"
113 #include "DNA_material_types.h"
114 #include "DNA_texture_types.h"
115 #include "DNA_image_types.h"
116 #include "DNA_lamp_types.h"
117 #include "DNA_group_types.h"
118 #include "DNA_scene_types.h"
119 #include "DNA_camera_types.h"
120 #include "DNA_property_types.h"
121 #include "DNA_text_types.h"
122 #include "DNA_sensor_types.h"
123 #include "DNA_controller_types.h"
124 #include "DNA_actuator_types.h"
125 #include "DNA_mesh_types.h"
126 #include "DNA_meshdata_types.h"
127 #include "DNA_view3d_types.h"
128 #include "DNA_world_types.h"
129 #include "DNA_sound_types.h"
130 #include "DNA_key_types.h"
131 #include "DNA_armature_types.h"
132 #include "DNA_action_types.h"
133 #include "DNA_object_force.h"
134 #include "DNA_constraint_types.h"
135
136 #include "MEM_guardedalloc.h"
137
138 #include "BKE_key.h"
139 #include "BKE_mesh.h"
140
141 #include "BLI_math.h"
142
143 extern "C" {
144 #include "BKE_scene.h"
145 #include "BKE_customdata.h"
146 #include "BKE_cdderivedmesh.h"
147 #include "BKE_DerivedMesh.h"
148 #include "BKE_material.h" /* give_current_material */
149 #include "BKE_image.h"
150 #include "IMB_imbuf_types.h"
151 #include "BKE_displist.h"
152
153 extern Material defmaterial;    /* material.c */
154 }
155
156 /* end of blender include block */
157
158 #include "KX_BlenderInputDevice.h"
159 #include "KX_ConvertProperties.h"
160
161 #include "SG_Node.h"
162 #include "SG_BBox.h"
163 #include "SG_Tree.h"
164 #include "KX_SG_NodeRelationships.h"
165 #include "KX_SG_BoneParentNodeRelationship.h"
166
167 #ifdef WITH_BULLET
168 #include "CcdPhysicsEnvironment.h"
169 #include "CcdGraphicController.h"
170 #endif
171
172 #include "KX_MotionState.h"
173
174 #include "BL_ArmatureObject.h"
175 #include "BL_DeformableGameObject.h"
176
177 #include "KX_NavMeshObject.h"
178 #include "KX_ObstacleSimulation.h"
179
180 #include "BLI_threads.h"
181
182
183 static bool default_light_mode = 0;
184
185 static std::map<int, SCA_IInputDevice::KX_EnumInputs> create_translate_table()
186 {
187         std::map<int, SCA_IInputDevice::KX_EnumInputs> m;
188                 
189         /* The reverse table. In order to not confuse ourselves, we      */
190         /* immediately convert all events that come in to KX codes.      */
191         m[LEFTMOUSE                     ] =     SCA_IInputDevice::KX_LEFTMOUSE;
192         m[MIDDLEMOUSE           ] =     SCA_IInputDevice::KX_MIDDLEMOUSE;
193         m[RIGHTMOUSE            ] =     SCA_IInputDevice::KX_RIGHTMOUSE;
194         m[WHEELUPMOUSE          ] =     SCA_IInputDevice::KX_WHEELUPMOUSE;
195         m[WHEELDOWNMOUSE        ] =     SCA_IInputDevice::KX_WHEELDOWNMOUSE;
196         m[MOUSEX                        ] = SCA_IInputDevice::KX_MOUSEX;
197         m[MOUSEY                        ] =     SCA_IInputDevice::KX_MOUSEY;
198                 
199         // TIMERS                                                                                                  
200                 
201         m[TIMER0                        ] = SCA_IInputDevice::KX_TIMER0;                  
202         m[TIMER1                        ] = SCA_IInputDevice::KX_TIMER1;                  
203         m[TIMER2                        ] = SCA_IInputDevice::KX_TIMER2;                  
204                 
205         // SYSTEM                                                                                                  
206                 
207 #if 0
208         /* **** XXX **** */
209         m[KEYBD                         ] = SCA_IInputDevice::KX_KEYBD;                  
210         m[RAWKEYBD                      ] = SCA_IInputDevice::KX_RAWKEYBD;                  
211         m[REDRAW                        ] = SCA_IInputDevice::KX_REDRAW;                  
212         m[INPUTCHANGE           ] = SCA_IInputDevice::KX_INPUTCHANGE;                  
213         m[QFULL                         ] = SCA_IInputDevice::KX_QFULL;                  
214         m[WINFREEZE                     ] = SCA_IInputDevice::KX_WINFREEZE;                  
215         m[WINTHAW                       ] = SCA_IInputDevice::KX_WINTHAW;                  
216         m[WINCLOSE                      ] = SCA_IInputDevice::KX_WINCLOSE;                  
217         m[WINQUIT                       ] = SCA_IInputDevice::KX_WINQUIT;                  
218         m[Q_FIRSTTIME           ] = SCA_IInputDevice::KX_Q_FIRSTTIME;                  
219         /* **** XXX **** */
220 #endif
221                 
222         // standard keyboard                                                                                       
223                 
224         m[AKEY                          ] = SCA_IInputDevice::KX_AKEY;                  
225         m[BKEY                          ] = SCA_IInputDevice::KX_BKEY;                  
226         m[CKEY                          ] = SCA_IInputDevice::KX_CKEY;                  
227         m[DKEY                          ] = SCA_IInputDevice::KX_DKEY;                  
228         m[EKEY                          ] = SCA_IInputDevice::KX_EKEY;                  
229         m[FKEY                          ] = SCA_IInputDevice::KX_FKEY;                  
230         m[GKEY                          ] = SCA_IInputDevice::KX_GKEY;                  
231
232 //XXX clean up
233 #ifdef WIN32
234 #define HKEY    'h'
235 #endif
236         m[HKEY                          ] = SCA_IInputDevice::KX_HKEY;                  
237 //XXX clean up
238 #ifdef WIN32
239 #undef HKEY
240 #endif
241
242         m[IKEY                          ] = SCA_IInputDevice::KX_IKEY;                  
243         m[JKEY                          ] = SCA_IInputDevice::KX_JKEY;                  
244         m[KKEY                          ] = SCA_IInputDevice::KX_KKEY;                  
245         m[LKEY                          ] = SCA_IInputDevice::KX_LKEY;                  
246         m[MKEY                          ] = SCA_IInputDevice::KX_MKEY;                  
247         m[NKEY                          ] = SCA_IInputDevice::KX_NKEY;                  
248         m[OKEY                          ] = SCA_IInputDevice::KX_OKEY;                  
249         m[PKEY                          ] = SCA_IInputDevice::KX_PKEY;                  
250         m[QKEY                          ] = SCA_IInputDevice::KX_QKEY;                  
251         m[RKEY                          ] = SCA_IInputDevice::KX_RKEY;                  
252         m[SKEY                          ] = SCA_IInputDevice::KX_SKEY;                  
253         m[TKEY                          ] = SCA_IInputDevice::KX_TKEY;                  
254         m[UKEY                          ] = SCA_IInputDevice::KX_UKEY;                  
255         m[VKEY                          ] = SCA_IInputDevice::KX_VKEY;                  
256         m[WKEY                          ] = SCA_IInputDevice::KX_WKEY;                  
257         m[XKEY                          ] = SCA_IInputDevice::KX_XKEY;                  
258         m[YKEY                          ] = SCA_IInputDevice::KX_YKEY;                  
259         m[ZKEY                          ] = SCA_IInputDevice::KX_ZKEY;                  
260                 
261         m[ZEROKEY                       ] = SCA_IInputDevice::KX_ZEROKEY;                  
262         m[ONEKEY                        ] = SCA_IInputDevice::KX_ONEKEY;                  
263         m[TWOKEY                        ] = SCA_IInputDevice::KX_TWOKEY;                  
264         m[THREEKEY                      ] = SCA_IInputDevice::KX_THREEKEY;                  
265         m[FOURKEY                       ] = SCA_IInputDevice::KX_FOURKEY;                  
266         m[FIVEKEY                       ] = SCA_IInputDevice::KX_FIVEKEY;                  
267         m[SIXKEY                        ] = SCA_IInputDevice::KX_SIXKEY;                  
268         m[SEVENKEY                      ] = SCA_IInputDevice::KX_SEVENKEY;                  
269         m[EIGHTKEY                      ] = SCA_IInputDevice::KX_EIGHTKEY;                  
270         m[NINEKEY                       ] = SCA_IInputDevice::KX_NINEKEY;                  
271                 
272         m[CAPSLOCKKEY           ] = SCA_IInputDevice::KX_CAPSLOCKKEY;                  
273                 
274         m[LEFTCTRLKEY           ] = SCA_IInputDevice::KX_LEFTCTRLKEY;                  
275         m[LEFTALTKEY            ] = SCA_IInputDevice::KX_LEFTALTKEY;                  
276         m[RIGHTALTKEY           ] = SCA_IInputDevice::KX_RIGHTALTKEY;                  
277         m[RIGHTCTRLKEY          ] = SCA_IInputDevice::KX_RIGHTCTRLKEY;                  
278         m[RIGHTSHIFTKEY         ] = SCA_IInputDevice::KX_RIGHTSHIFTKEY;                  
279         m[LEFTSHIFTKEY          ] = SCA_IInputDevice::KX_LEFTSHIFTKEY;                  
280                 
281         m[ESCKEY                        ] = SCA_IInputDevice::KX_ESCKEY;                  
282         m[TABKEY                        ] = SCA_IInputDevice::KX_TABKEY;                  
283         m[RETKEY                        ] = SCA_IInputDevice::KX_RETKEY;                  
284         m[SPACEKEY                      ] = SCA_IInputDevice::KX_SPACEKEY;                  
285         m[LINEFEEDKEY           ] = SCA_IInputDevice::KX_LINEFEEDKEY;                  
286         m[BACKSPACEKEY          ] = SCA_IInputDevice::KX_BACKSPACEKEY;                  
287         m[DELKEY                        ] = SCA_IInputDevice::KX_DELKEY;                  
288         m[SEMICOLONKEY          ] = SCA_IInputDevice::KX_SEMICOLONKEY;                  
289         m[PERIODKEY                     ] = SCA_IInputDevice::KX_PERIODKEY;                  
290         m[COMMAKEY                      ] = SCA_IInputDevice::KX_COMMAKEY;                  
291         m[QUOTEKEY                      ] = SCA_IInputDevice::KX_QUOTEKEY;                  
292         m[ACCENTGRAVEKEY        ] = SCA_IInputDevice::KX_ACCENTGRAVEKEY;                  
293         m[MINUSKEY                      ] = SCA_IInputDevice::KX_MINUSKEY;                  
294         m[SLASHKEY                      ] = SCA_IInputDevice::KX_SLASHKEY;                  
295         m[BACKSLASHKEY          ] = SCA_IInputDevice::KX_BACKSLASHKEY;                  
296         m[EQUALKEY                      ] = SCA_IInputDevice::KX_EQUALKEY;                  
297         m[LEFTBRACKETKEY        ] = SCA_IInputDevice::KX_LEFTBRACKETKEY;                  
298         m[RIGHTBRACKETKEY       ] = SCA_IInputDevice::KX_RIGHTBRACKETKEY;                  
299                 
300         m[LEFTARROWKEY          ] = SCA_IInputDevice::KX_LEFTARROWKEY;                  
301         m[DOWNARROWKEY          ] = SCA_IInputDevice::KX_DOWNARROWKEY;                  
302         m[RIGHTARROWKEY         ] = SCA_IInputDevice::KX_RIGHTARROWKEY;                  
303         m[UPARROWKEY            ] = SCA_IInputDevice::KX_UPARROWKEY;                  
304                 
305         m[PAD2                          ] = SCA_IInputDevice::KX_PAD2;                  
306         m[PAD4                          ] = SCA_IInputDevice::KX_PAD4;                  
307         m[PAD6                          ] = SCA_IInputDevice::KX_PAD6;                  
308         m[PAD8                          ] = SCA_IInputDevice::KX_PAD8;                  
309                 
310         m[PAD1                          ] = SCA_IInputDevice::KX_PAD1;                  
311         m[PAD3                          ] = SCA_IInputDevice::KX_PAD3;                  
312         m[PAD5                          ] = SCA_IInputDevice::KX_PAD5;                  
313         m[PAD7                          ] = SCA_IInputDevice::KX_PAD7;                  
314         m[PAD9                          ] = SCA_IInputDevice::KX_PAD9;                  
315                 
316         m[PADPERIOD                     ] = SCA_IInputDevice::KX_PADPERIOD;                  
317         m[PADSLASHKEY           ] = SCA_IInputDevice::KX_PADSLASHKEY;                  
318         m[PADASTERKEY           ] = SCA_IInputDevice::KX_PADASTERKEY;                  
319                 
320         m[PAD0                          ] = SCA_IInputDevice::KX_PAD0;                  
321         m[PADMINUS                      ] = SCA_IInputDevice::KX_PADMINUS;                  
322         m[PADENTER                      ] = SCA_IInputDevice::KX_PADENTER;                  
323         m[PADPLUSKEY            ] = SCA_IInputDevice::KX_PADPLUSKEY;                  
324                 
325                 
326         m[F1KEY                         ] = SCA_IInputDevice::KX_F1KEY;                  
327         m[F2KEY                         ] = SCA_IInputDevice::KX_F2KEY;                  
328         m[F3KEY                         ] = SCA_IInputDevice::KX_F3KEY;                  
329         m[F4KEY                         ] = SCA_IInputDevice::KX_F4KEY;                  
330         m[F5KEY                         ] = SCA_IInputDevice::KX_F5KEY;                  
331         m[F6KEY                         ] = SCA_IInputDevice::KX_F6KEY;                  
332         m[F7KEY                         ] = SCA_IInputDevice::KX_F7KEY;                  
333         m[F8KEY                         ] = SCA_IInputDevice::KX_F8KEY;                  
334         m[F9KEY                         ] = SCA_IInputDevice::KX_F9KEY;                  
335         m[F10KEY                        ] = SCA_IInputDevice::KX_F10KEY;                  
336         m[F11KEY                        ] = SCA_IInputDevice::KX_F11KEY;                  
337         m[F12KEY                        ] = SCA_IInputDevice::KX_F12KEY;
338         m[F13KEY                        ] = SCA_IInputDevice::KX_F13KEY;
339         m[F14KEY                        ] = SCA_IInputDevice::KX_F14KEY;
340         m[F15KEY                        ] = SCA_IInputDevice::KX_F15KEY;
341         m[F16KEY                        ] = SCA_IInputDevice::KX_F16KEY;
342         m[F17KEY                        ] = SCA_IInputDevice::KX_F17KEY;
343         m[F18KEY                        ] = SCA_IInputDevice::KX_F18KEY;
344         m[F19KEY                        ] = SCA_IInputDevice::KX_F19KEY;
345
346         m[OSKEY                         ] = SCA_IInputDevice::KX_OSKEY;
347
348         m[PAUSEKEY                      ] = SCA_IInputDevice::KX_PAUSEKEY;                  
349         m[INSERTKEY                     ] = SCA_IInputDevice::KX_INSERTKEY;                  
350         m[HOMEKEY                       ] = SCA_IInputDevice::KX_HOMEKEY;                  
351         m[PAGEUPKEY                     ] = SCA_IInputDevice::KX_PAGEUPKEY;                  
352         m[PAGEDOWNKEY           ] = SCA_IInputDevice::KX_PAGEDOWNKEY;                  
353         m[ENDKEY                        ] = SCA_IInputDevice::KX_ENDKEY;
354
355         return m;
356 }
357
358 static std::map<int, SCA_IInputDevice::KX_EnumInputs> gReverseKeyTranslateTable = create_translate_table();
359
360 SCA_IInputDevice::KX_EnumInputs ConvertKeyCode(int key_code)
361 {
362         return gReverseKeyTranslateTable[key_code];
363 }
364
365 static unsigned int KX_rgbaint2uint_new(unsigned int icol)
366 {
367         union
368         {
369                 unsigned int integer;
370                 unsigned char cp[4];
371         } out_color, in_color;
372         
373         in_color.integer = icol;
374         out_color.cp[0] = in_color.cp[3]; // red
375         out_color.cp[1] = in_color.cp[2]; // green
376         out_color.cp[2] = in_color.cp[1]; // blue
377         out_color.cp[3] = in_color.cp[0]; // alpha
378         
379         return out_color.integer;
380 }
381
382 /* Now the real converting starts... */
383 static unsigned int KX_Mcol2uint_new(MCol col)
384 {
385         /* color has to be converted without endian sensitivity. So no shifting! */
386         union
387         {
388                 MCol col;
389                 unsigned int integer;
390                 unsigned char cp[4];
391         } out_color, in_color;
392
393         in_color.col = col;
394         out_color.cp[0] = in_color.cp[3]; // red
395         out_color.cp[1] = in_color.cp[2]; // green
396         out_color.cp[2] = in_color.cp[1]; // blue
397         out_color.cp[3] = in_color.cp[0]; // alpha
398         
399         return out_color.integer;
400 }
401
402 static void SetDefaultLightMode(Scene* scene)
403 {
404         default_light_mode = false;
405         Scene *sce_iter;
406         Base *base;
407
408         for (SETLOOPER(scene, sce_iter, base))
409         {
410                 if (base->object->type == OB_LAMP)
411                 {
412                         default_light_mode = true;
413                         return;
414                 }
415         }
416 }
417
418
419 static bool GetMaterialUseVColor(Material *ma, const bool glslmat)
420 {
421         if (ma) {
422                 /* glsl uses vertex colors, otherwise use material setting
423                  * defmaterial doesn't have VERTEXCOLP as default [#34505] */
424                 return (glslmat || ma == &defmaterial || (ma->mode & MA_VERTEXCOLP) != 0);
425         }
426         else {
427                 /* no material, use vertex colors */
428                 return true;
429         }
430 }
431
432 // --
433 static void GetRGB(
434         const bool use_vcol,
435         MFace* mface,
436         MCol* mmcol,
437         Material *mat,
438         unsigned int c[4])
439 {
440         unsigned int color = 0xFFFFFFFFL;
441         if (use_vcol == true) {
442                 if (mmcol) {
443                         c[0] = KX_Mcol2uint_new(mmcol[0]);
444                         c[1] = KX_Mcol2uint_new(mmcol[1]);
445                         c[2] = KX_Mcol2uint_new(mmcol[2]);
446                         if (mface->v4)
447                                 c[3] = KX_Mcol2uint_new(mmcol[3]);
448                 }
449                 else { // backup white
450                         c[0] = KX_rgbaint2uint_new(color);
451                         c[1] = KX_rgbaint2uint_new(color);
452                         c[2] = KX_rgbaint2uint_new(color);
453                         if (mface->v4)
454                                 c[3] = KX_rgbaint2uint_new( color );
455                 }
456         }
457         else {
458                 /* material rgba */
459                 if (mat) {
460                         union {
461                                 unsigned char cp[4];
462                                 unsigned int integer;
463                         } col_converter;
464                         col_converter.cp[3] = (unsigned char) (mat->r     * 255.0f);
465                         col_converter.cp[2] = (unsigned char) (mat->g     * 255.0f);
466                         col_converter.cp[1] = (unsigned char) (mat->b     * 255.0f);
467                         col_converter.cp[0] = (unsigned char) (mat->alpha * 255.0f);
468                         color = col_converter.integer;
469                 }
470                 c[0] = KX_rgbaint2uint_new(color);
471                 c[1] = KX_rgbaint2uint_new(color);
472                 c[2] = KX_rgbaint2uint_new(color);
473                 if (mface->v4) {
474                         c[3] = KX_rgbaint2uint_new(color);
475                 }
476         }
477
478 #if 0  /* white, unused */
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 #endif
487 }
488
489 typedef struct MTF_localLayer {
490         MTFace *face;
491         const char *name;
492 } MTF_localLayer;
493
494 static void GetUVs(BL_Material *material, MTF_localLayer *layers, MFace *mface, MTFace *tface, MT_Point2 uvs[4][MAXTEX])
495 {
496         int unit = 0;
497         if (tface)
498         {
499                         
500                 uvs[0][0].setValue(tface->uv[0]);
501                 uvs[1][0].setValue(tface->uv[1]);
502                 uvs[2][0].setValue(tface->uv[2]);
503
504                 if (mface->v4) 
505                         uvs[3][0].setValue(tface->uv[3]);
506         }
507         else
508         {
509                 uvs[0][0] = uvs[1][0] = uvs[2][0] = uvs[3][0] = MT_Point2(0.f, 0.f);
510         }
511         
512         vector<STR_String> found_layers;
513
514         for (int vind = 0; vind<MAXTEX; vind++)
515         {
516                 BL_Mapping &map = material->mapping[vind];
517
518                 if (!(map.mapping & USEUV)) continue;
519
520                 if (std::find(found_layers.begin(), found_layers.end(), map.uvCoName) != found_layers.end())
521                         continue;
522
523                 //If no UVSet is specified, try grabbing one from the UV/Image editor
524                 if (map.uvCoName.IsEmpty() && tface)
525                 {                       
526                         uvs[0][unit].setValue(tface->uv[0]);
527                         uvs[1][unit].setValue(tface->uv[1]);
528                         uvs[2][unit].setValue(tface->uv[2]);
529
530                         if (mface->v4) 
531                                 uvs[3][unit].setValue(tface->uv[3]);
532
533                         ++unit;
534                         continue;
535                 }
536
537
538                 for (int lay=0; lay<MAX_MTFACE; lay++)
539                 {
540                         MTF_localLayer& layer = layers[lay];
541                         if (layer.face == 0) break;
542
543                         if (map.uvCoName.IsEmpty() || strcmp(map.uvCoName.ReadPtr(), layer.name)==0)
544                         {
545                                 uvs[0][unit].setValue(layer.face->uv[0]);
546                                 uvs[1][unit].setValue(layer.face->uv[1]);
547                                 uvs[2][unit].setValue(layer.face->uv[2]);
548
549                                 if (mface->v4) 
550                                         uvs[3][unit].setValue(layer.face->uv[3]);
551                                 else
552                                         uvs[3][unit].setValue(0.0f, 0.0f);
553
554                                 ++unit;
555                                 found_layers.push_back(map.uvCoName);
556                                 break;
557                         }
558                 }
559         }
560 }
561
562 // ------------------------------------
563 static bool ConvertMaterial(
564         BL_Material *material,
565         Material *mat,
566         MTFace *tface,
567         const char *tfaceName,
568         MFace *mface,
569         MCol *mmcol,
570         bool glslmat)
571 {
572         material->Initialize();
573         int texalpha = 0;
574         const bool validmat  = (mat != NULL);
575         const bool validface = (tface != NULL);
576         const bool use_vcol  = GetMaterialUseVColor(mat, glslmat);
577         
578         material->IdMode = DEFAULT_BLENDER;
579         material->glslmat = (validmat) ? glslmat: false;
580         material->materialindex = mface->mat_nr;
581
582         // --------------------------------
583         if (validmat) {
584
585                 // use lighting?
586                 material->ras_mode |= (mat->mode & MA_SHLESS) ? 0 : USE_LIGHT;
587                 material->ras_mode |= (mat->game.flag & GEMAT_BACKCULL) ? 0 : TWOSIDED;
588
589                 // cast shadows?
590                 material->ras_mode |= ((mat->mode2 & MA_CASTSHADOW) && (mat->mode & MA_SHADBUF)) ? CAST_SHADOW : 0;
591
592                 // only shadows?
593                 material->ras_mode |= (mat->mode & MA_ONLYCAST) ? ONLY_SHADOW : 0;
594
595                 MTex *mttmp = NULL;
596                 int valid_index = 0;
597
598                 /* In Multitexture use the face texture if and only if
599                  * it is set in the buttons
600                  * In GLSL is not working yet :/ 3.2011 */
601                 bool facetex = false;
602                 if (validface && mat->mode & MA_FACETEXTURE) {
603                         facetex = true;
604                 }
605
606                 // foreach MTex
607                 for (int i = 0; i < MAXTEX; i++) {
608                         // use face tex
609                         if (i == 0 && facetex ) {
610                                 facetex = false;
611                                 Image *tmp = (Image *)(tface->tpage);
612
613                                 if (tmp) {
614                                         material->img[i] = tmp;
615                                         material->texname[i] = material->img[i]->id.name;
616                                         material->flag[i] |= MIPMAP;
617
618                                         material->flag[i] |= (mat->game.alpha_blend & GEMAT_ALPHA_SORT) ? USEALPHA : 0;
619                                         material->flag[i] |= (mat->game.alpha_blend & GEMAT_ALPHA) ? USEALPHA : 0;
620                                         material->flag[i] |= (mat->game.alpha_blend & GEMAT_ADD) ? CALCALPHA : 0;
621
622                                         if (material->img[i]->flag & IMA_REFLECT) {
623                                                 material->mapping[i].mapping |= USEREFL;
624                                         }
625                                         else {
626                                                 mttmp = getMTexFromMaterial(mat, i);
627                                                 if (mttmp && (mttmp->texco & TEXCO_UV)) {
628                                                         /* string may be "" but thats detected as empty after */
629                                                         material->mapping[i].uvCoName = mttmp->uvname;
630                                                 }
631                                                 material->mapping[i].mapping |= USEUV;
632                                         }
633
634                                         valid_index++;
635                                 }
636                                 else {
637                                         material->img[i] = 0;
638                                         material->texname[i] = "";
639                                 }
640                                 continue;
641                         }
642
643                         mttmp = getMTexFromMaterial(mat, i);
644                         if (mttmp) {
645                                 if (mttmp->tex) {
646                                         if (mttmp->tex->type == TEX_IMAGE) {
647                                                 material->mtexname[i] = mttmp->tex->id.name;
648                                                 material->img[i] = mttmp->tex->ima;
649                                                 if (material->img[i]) {
650
651                                                         material->texname[i] = material->img[i]->id.name;
652                                                         material->flag[i] |= (mttmp->tex->imaflag &TEX_MIPMAP) ? MIPMAP : 0;
653                                                         if (material->img[i] && (material->img[i]->flag & IMA_IGNORE_ALPHA) == 0) {
654                                                                 material->flag[i] |= USEALPHA;
655                                                         }
656                                                         if (mttmp->tex->imaflag & TEX_CALCALPHA) {
657                                                                 material->flag[i] |= CALCALPHA;
658                                                         }
659                                                         else if (mttmp->tex->flag & TEX_NEGALPHA) {
660                                                                 material->flag[i] |= USENEGALPHA;
661                                                         }
662
663                                                         material->color_blend[i] = mttmp->colfac;
664                                                         material->flag[i] |= (mttmp->mapto & MAP_ALPHA) ? TEXALPHA : 0;
665                                                         material->flag[i] |= (mttmp->texflag & MTEX_NEGATIVE) ? TEXNEG : 0;
666
667                                                         if (!glslmat && (material->flag[i] & TEXALPHA)) {
668                                                                 texalpha = 1;
669                                                         }
670                                                 }
671                                         }
672                                         else if (mttmp->tex->type == TEX_ENVMAP) {
673                                                 if (mttmp->tex->env->stype == ENV_LOAD) {
674                                                         material->mtexname[i] = mttmp->tex->id.name;
675                                                         EnvMap *env = mttmp->tex->env;
676                                                         env->ima = mttmp->tex->ima;
677                                                         material->cubemap[i] = env;
678
679                                                         if (material->cubemap[i]) {
680                                                                 if (!material->cubemap[i]->cube[0]) {
681                                                                         BL_Texture::SplitEnvMap(material->cubemap[i]);
682                                                                 }
683
684                                                                 material->texname[i] = material->cubemap[i]->ima->id.name;
685                                                                 material->mapping[i].mapping |= USEENV;
686                                                         }
687                                                 }
688                                         }
689 #if 0                           /* this flag isn't used anymore */
690                                         material->flag[i] |= (BKE_animdata_from_id(mat->id) != NULL) ? HASIPO : 0;
691 #endif
692                                         /// --------------------------------
693                                         // mapping methods
694                                         if (mat->septex & (1 << i)) {
695                                                 // If this texture slot isn't in use, set it to disabled to prevent multi-uv problems
696                                                 material->mapping[i].mapping = DISABLE;
697                                         } 
698                                         else {
699                                                 material->mapping[i].mapping |= (mttmp->texco & TEXCO_REFL) ? USEREFL : 0;
700
701                                                 if (mttmp->texco & TEXCO_OBJECT) {
702                                                         material->mapping[i].mapping |= USEOBJ;
703                                                         if (mttmp->object) {
704                                                                 material->mapping[i].objconame = mttmp->object->id.name;
705                                                         }
706                                                 }
707                                                 else if (mttmp->texco & TEXCO_REFL) {
708                                                         material->mapping[i].mapping |= USEREFL;
709                                                 }
710                                                 else if (mttmp->texco & (TEXCO_ORCO | TEXCO_GLOB)) {
711                                                         material->mapping[i].mapping |= USEORCO;
712                                                 }
713                                                 else if (mttmp->texco & TEXCO_UV) {
714                                                         /* string may be "" but thats detected as empty after */
715                                                         material->mapping[i].uvCoName = mttmp->uvname;
716                                                         material->mapping[i].mapping |= USEUV;
717                                                 }
718                                                 else if (mttmp->texco & TEXCO_NORM) {
719                                                         material->mapping[i].mapping |= USENORM;
720                                                 }
721                                                 else if (mttmp->texco & TEXCO_TANGENT) {
722                                                         material->mapping[i].mapping |= USETANG;
723                                                 }
724                                                 else {
725                                                         material->mapping[i].mapping |= DISABLE;
726                                                 }
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
822                 material->SetUsers(-1);
823                 material->num_enabled = valid;
824                 material->IdMode = TEXFACE;
825                 material->speccolor[0] = 1.0f;
826                 material->speccolor[1] = 1.0f;
827                 material->speccolor[2] = 1.0f;
828                 material->hard = 35.0f;
829                 material->matcolor[0] = 0.5f;
830                 material->matcolor[1] = 0.5f;
831                 material->matcolor[2] = 0.5f;
832                 material->spec_f = 0.5f;
833                 material->ref = 0.8f;
834
835                 // No material - old default TexFace properties
836                 material->ras_mode |= USE_LIGHT;
837         }
838
839         /* No material, what to do? let's see what is in the UV and set the material accordingly
840          * light and visible is always on */
841         if (validface) {
842                 material->tile = tface->tile;
843         }
844         else {
845                 // nothing at all
846                 material->alphablend = GEMAT_SOLID;
847                 material->tile = 0;
848         }
849
850         if (validmat && validface) {
851                 material->alphablend = mat->game.alpha_blend;
852         }
853
854         // with ztransp enabled, enforce alpha blending mode
855         if (validmat && (mat->mode & MA_TRANSP) && (mat->mode & MA_ZTRANSP) && (material->alphablend == GEMAT_SOLID)) {
856                 material->alphablend = GEMAT_ALPHA;
857         }
858
859         // always zsort alpha + add
860         if ((ELEM(material->alphablend, GEMAT_ALPHA, GEMAT_ALPHA_SORT, GEMAT_ADD) || texalpha) && (material->alphablend != GEMAT_CLIP)) {
861                 material->ras_mode |= ALPHA;
862                 material->ras_mode |= (mat && (mat->game.alpha_blend & GEMAT_ALPHA_SORT)) ? ZSORT : 0;
863         }
864
865         // XXX The RGB values here were meant to be temporary storage for the conversion process,
866         // but fonts now make use of them too, so we leave them in for now.
867         unsigned int rgb[4];
868         GetRGB(use_vcol, mface, mmcol, mat, rgb);
869
870         // swap the material color, so MCol on bitmap font works
871         if (validmat && (use_vcol == false) && (mat->game.flag & GEMAT_TEXT)) {
872                 material->rgb[0] = KX_rgbaint2uint_new(rgb[0]);
873                 material->rgb[1] = KX_rgbaint2uint_new(rgb[1]);
874                 material->rgb[2] = KX_rgbaint2uint_new(rgb[2]);
875                 material->rgb[3] = KX_rgbaint2uint_new(rgb[3]);
876         }
877
878         if (validmat) {
879                 material->matname =(mat->id.name);
880         }
881
882         if (tface) {
883                 ME_MTEXFACE_CPY(&material->mtexpoly, tface);
884         }
885         else {
886                 memset(&material->mtexpoly, 0, sizeof(material->mtexpoly));
887         }
888         material->material = mat;
889         return true;
890 }
891
892 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)
893 {
894         RAS_IPolyMaterial* polymat = converter->FindCachedPolyMaterial(scene, ma);
895         BL_Material* bl_mat = converter->FindCachedBlenderMaterial(scene, ma);
896         KX_BlenderMaterial* kx_blmat = NULL;
897
898         /* first is the BL_Material */
899         if (!bl_mat)
900         {
901                 bl_mat = new BL_Material();
902
903                 ConvertMaterial(bl_mat, ma, tface, tfaceName, mface, mcol,
904                         converter->GetGLSLMaterials());
905
906                 if (ma && (ma->mode & MA_FACETEXTURE) == 0)
907                         converter->CacheBlenderMaterial(scene, ma, bl_mat);
908         }
909
910         const bool use_vcol = GetMaterialUseVColor(ma, bl_mat->glslmat);
911         GetRGB(use_vcol, mface, mcol, ma, rgb);
912
913         GetUVs(bl_mat, layers, mface, tface, uvs);
914
915         /* then the KX_BlenderMaterial */
916         if (polymat == NULL)
917         {
918                 kx_blmat = new KX_BlenderMaterial();
919
920                 kx_blmat->Initialize(scene, bl_mat, (ma?&ma->game:NULL), lightlayer);
921                 polymat = static_cast<RAS_IPolyMaterial*>(kx_blmat);
922                 if (ma && (ma->mode & MA_FACETEXTURE) == 0)
923                         converter->CachePolyMaterial(scene, ma, polymat);
924         }
925         
926         // see if a bucket was reused or a new one was created
927         // this way only one KX_BlenderMaterial object has to exist per bucket
928         bool bucketCreated; 
929         RAS_MaterialBucket* bucket = scene->FindBucket(polymat, bucketCreated);
930
931         // this is needed to free up memory afterwards.
932         // the converter will also prevent duplicates from being registered,
933         // so just register everything.
934         converter->RegisterPolyMaterial(polymat);
935         converter->RegisterBlenderMaterial(bl_mat);
936
937         return bucket;
938 }
939
940 /* blenderobj can be NULL, make sure its checked for */
941 RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, KX_Scene* scene, KX_BlenderSceneConverter *converter, bool libloading)
942 {
943         RAS_MeshObject *meshobj;
944         int lightlayer = blenderobj ? blenderobj->lay:(1<<20)-1; // all layers if no object.
945
946         // Without checking names, we get some reuse we don't want that can cause
947         // problems with material LoDs.
948         if (blenderobj && ((meshobj = converter->FindGameMesh(mesh/*, ob->lay*/)) != NULL)) {
949                 const char *bge_name = meshobj->GetName().ReadPtr();
950                 const char *blender_name = ((ID *)blenderobj->data)->name + 2;
951                 if (STREQ(bge_name, blender_name)) {
952                         return meshobj;
953                 }
954         }
955
956         // Get DerivedMesh data
957         DerivedMesh *dm = CDDM_from_mesh(mesh);
958         DM_ensure_tessface(dm);
959
960         MVert *mvert = dm->getVertArray(dm);
961         int totvert = dm->getNumVerts(dm);
962
963         MFace *mface = dm->getTessFaceArray(dm);
964         MTFace *tface = static_cast<MTFace*>(dm->getTessFaceDataArray(dm, CD_MTFACE));
965         MCol *mcol = static_cast<MCol*>(dm->getTessFaceDataArray(dm, CD_MCOL));
966         float (*tangent)[4] = NULL;
967         int totface = dm->getNumTessFaces(dm);
968         const char *tfaceName = "";
969
970         /* needs to be rewritten for loopdata */
971         if (tface) {
972                 if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) == -1) {
973                         bool generate_data = false;
974                         if (CustomData_get_layer_index(&dm->loopData, CD_TANGENT) == -1) {
975                                 DM_calc_loop_tangents(dm);
976                                 generate_data = true;
977                         }
978                         DM_generate_tangent_tessface_data(dm, generate_data);
979                 }
980                 tangent = (float(*)[4])dm->getTessFaceDataArray(dm, CD_TANGENT);
981         }
982
983         meshobj = new RAS_MeshObject(mesh);
984
985         // Extract avaiable layers
986         MTF_localLayer *layers =  new MTF_localLayer[MAX_MTFACE];
987         for (int lay=0; lay<MAX_MTFACE; lay++) {
988                 layers[lay].face = 0;
989                 layers[lay].name = "";
990         }
991
992         int validLayers = 0;
993         for (int i=0; i<dm->faceData.totlayer; i++)
994         {
995                 if (dm->faceData.layers[i].type == CD_MTFACE)
996                 {
997                         if (validLayers >= MAX_MTFACE) {
998                                 printf("%s: corrupted mesh %s - too many CD_MTFACE layers\n", __func__, mesh->id.name);
999                                 break;
1000                         }
1001
1002                         layers[validLayers].face = (MTFace*)(dm->faceData.layers[i].data);
1003                         layers[validLayers].name = dm->faceData.layers[i].name;
1004                         if (tface == layers[validLayers].face)
1005                                 tfaceName = layers[validLayers].name;
1006                         validLayers++;
1007                 }
1008         }
1009
1010         meshobj->SetName(mesh->id.name + 2);
1011         meshobj->m_sharedvertex_map.resize(totvert);
1012
1013         Material* ma = 0;
1014         MT_Point2 uvs[4][RAS_TexVert::MAX_UNIT];
1015         unsigned int rgb[4] = {0};
1016
1017         MT_Point3 pt[4];
1018         MT_Vector3 no[4];
1019         MT_Vector4 tan[4];
1020
1021         /* ugh, if there is a less annoying way to do this please use that.
1022          * since these are converted from floats to floats, theres no real
1023          * advantage to use MT_ types - campbell */
1024         for (unsigned int i = 0; i < 4; i++) {
1025                 const float zero_vec[4] = {0.0f};
1026                 pt[i].setValue(zero_vec);
1027                 no[i].setValue(zero_vec);
1028                 tan[i].setValue(zero_vec);
1029         }
1030
1031         /* we need to manually initialize the uvs (MoTo doesn't do that) [#34550] */
1032         for (unsigned int i = 0; i < RAS_TexVert::MAX_UNIT; i++) {
1033                 uvs[0][i] = uvs[1][i] = uvs[2][i] = uvs[3][i] = MT_Point2(0.f, 0.f);
1034         }
1035
1036         for (int f=0;f<totface;f++,mface++)
1037         {
1038                 /* get coordinates, normals and tangents */
1039                 pt[0].setValue(mvert[mface->v1].co);
1040                 pt[1].setValue(mvert[mface->v2].co);
1041                 pt[2].setValue(mvert[mface->v3].co);
1042                 if (mface->v4) pt[3].setValue(mvert[mface->v4].co);
1043
1044                 if (mface->flag & ME_SMOOTH) {
1045                         float n0[3], n1[3], n2[3], n3[3];
1046
1047                         normal_short_to_float_v3(n0, mvert[mface->v1].no);
1048                         normal_short_to_float_v3(n1, mvert[mface->v2].no);
1049                         normal_short_to_float_v3(n2, mvert[mface->v3].no);
1050                         no[0] = n0;
1051                         no[1] = n1;
1052                         no[2] = n2;
1053
1054                         if (mface->v4) {
1055                                 normal_short_to_float_v3(n3, mvert[mface->v4].no);
1056                                 no[3] = n3;
1057                         }
1058                 }
1059                 else {
1060                         float fno[3];
1061
1062                         if (mface->v4)
1063                                 normal_quad_v3(fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
1064                         else
1065                                 normal_tri_v3(fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
1066
1067                         no[0] = no[1] = no[2] = no[3] = MT_Vector3(fno);
1068                 }
1069
1070                 if (tangent) {
1071                         tan[0] = tangent[f*4 + 0];
1072                         tan[1] = tangent[f*4 + 1];
1073                         tan[2] = tangent[f*4 + 2];
1074
1075                         if (mface->v4)
1076                                 tan[3] = tangent[f*4 + 3];
1077                 }
1078                 if (blenderobj)
1079                         ma = give_current_material(blenderobj, mface->mat_nr+1);
1080                 else
1081                         ma = mesh->mat ? mesh->mat[mface->mat_nr]:NULL;
1082
1083                 // Check for blender material
1084                 if (ma == NULL) {
1085                         ma= &defmaterial;
1086                 }
1087
1088                 {
1089
1090                         RAS_MaterialBucket* bucket = material_from_mesh(ma, mface, tface, mcol, layers, lightlayer, rgb, uvs, tfaceName, scene, converter);
1091
1092                         // set render flags
1093                         bool visible = ((ma->game.flag & GEMAT_INVISIBLE)==0);
1094                         bool twoside = ((ma->game.flag  & GEMAT_BACKCULL)==0);
1095                         bool collider = ((ma->game.flag & GEMAT_NOPHYSICS)==0);
1096
1097                         /* mark face as flat, so vertices are split */
1098                         bool flat = (mface->flag & ME_SMOOTH) == 0;
1099                                 
1100                         int nverts = (mface->v4)? 4: 3;
1101
1102                         RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts);
1103
1104                         poly->SetVisible(visible);
1105                         poly->SetCollider(collider);
1106                         poly->SetTwoside(twoside);
1107                         //poly->SetEdgeCode(mface->edcode);
1108
1109                         meshobj->AddVertex(poly,0,pt[0],uvs[0],tan[0],rgb[0],no[0],flat,mface->v1);
1110                         meshobj->AddVertex(poly,1,pt[1],uvs[1],tan[1],rgb[1],no[1],flat,mface->v2);
1111                         meshobj->AddVertex(poly,2,pt[2],uvs[2],tan[2],rgb[2],no[2],flat,mface->v3);
1112
1113                         if (nverts==4)
1114                                 meshobj->AddVertex(poly,3,pt[3],uvs[3],tan[3],rgb[3],no[3],flat,mface->v4);
1115                 }
1116
1117                 if (tface) 
1118                         tface++;
1119                 if (mcol)
1120                         mcol+=4;
1121
1122                 for (int lay=0; lay<MAX_MTFACE; lay++)
1123                 {
1124                         MTF_localLayer &layer = layers[lay];
1125                         if (layer.face == 0) break;
1126
1127                         layer.face++;
1128                 }
1129         }
1130         // keep meshobj->m_sharedvertex_map for reinstance phys mesh.
1131         // 2.49a and before it did: meshobj->m_sharedvertex_map.clear();
1132         // but this didnt save much ram. - Campbell
1133         meshobj->EndConversion();
1134
1135         // pre calculate texture generation
1136         // However, we want to delay this if we're libloading so we can make sure we have the right scene.
1137         if (!libloading) {
1138                 for (list<RAS_MeshMaterial>::iterator mit = meshobj->GetFirstMaterial();
1139                         mit != meshobj->GetLastMaterial(); ++ mit) {
1140                         mit->m_bucket->GetPolyMaterial()->OnConstruction();
1141                 }
1142         }
1143
1144         if (layers)
1145                 delete []layers;
1146         
1147         dm->release(dm);
1148
1149         converter->RegisterGameMesh(meshobj, mesh);
1150         return meshobj;
1151 }
1152
1153         
1154         
1155 static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject)
1156 {
1157         PHY_MaterialProps *materialProps = new PHY_MaterialProps;
1158         
1159         MT_assert(materialProps && "Create physics material properties failed");
1160                 
1161         Material* blendermat = give_current_material(blenderobject, 1);
1162                 
1163         if (blendermat)
1164         {
1165                 MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f);
1166         
1167                 materialProps->m_restitution = blendermat->reflect;
1168                 materialProps->m_friction = blendermat->friction;
1169                 materialProps->m_fh_spring = blendermat->fh;
1170                 materialProps->m_fh_damping = blendermat->xyfrict;
1171                 materialProps->m_fh_distance = blendermat->fhdist;
1172                 materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0;
1173         }
1174         else {
1175                 //give some defaults
1176                 materialProps->m_restitution = 0.f;
1177                 materialProps->m_friction = 0.5;
1178                 materialProps->m_fh_spring = 0.f;
1179                 materialProps->m_fh_damping = 0.f;
1180                 materialProps->m_fh_distance = 0.f;
1181                 materialProps->m_fh_normal = false;
1182
1183         }
1184         
1185         return materialProps;
1186 }
1187
1188 static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject)
1189 {
1190         PHY_ShapeProps *shapeProps = new PHY_ShapeProps;
1191         
1192         MT_assert(shapeProps);
1193                 
1194         shapeProps->m_mass = blenderobject->mass;
1195         
1196 //  This needs to be fixed in blender. For now, we use:
1197         
1198 // in Blender, inertia stands for the size value which is equivalent to
1199 // the sphere radius
1200         shapeProps->m_inertia = blenderobject->formfactor;
1201         
1202         MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f);
1203         MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f);
1204         
1205         shapeProps->m_lin_drag = 1.0f - blenderobject->damping;
1206         shapeProps->m_ang_drag = 1.0f - blenderobject->rdamping;
1207         
1208         shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0]; 
1209         shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1];
1210         shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2];
1211         shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0);
1212         
1213         shapeProps->m_do_fh     = (blenderobject->gameflag & OB_DO_FH) != 0; 
1214         shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0;
1215         
1216 //      velocity clamping XXX
1217         shapeProps->m_clamp_vel_min = blenderobject->min_vel;
1218         shapeProps->m_clamp_vel_max = blenderobject->max_vel;
1219         shapeProps->m_clamp_angvel_min = blenderobject->min_angvel;
1220         shapeProps->m_clamp_angvel_max = blenderobject->max_angvel;
1221
1222 //  Character physics properties
1223         shapeProps->m_step_height = blenderobject->step_height;
1224         shapeProps->m_jump_speed = blenderobject->jump_speed;
1225         shapeProps->m_fall_speed = blenderobject->fall_speed;
1226         shapeProps->m_max_jumps = blenderobject->max_jumps;
1227
1228         return shapeProps;
1229 }
1230
1231         
1232         
1233         
1234                 
1235 //////////////////////////////////////////////////////////
1236         
1237
1238
1239 static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
1240 {
1241         MVert *mvert;
1242         BoundBox *bb;
1243         float min[3], max[3];
1244         float mloc[3], msize[3];
1245         float radius_sq=0.0f, vert_radius_sq, *co;
1246         int a;
1247         
1248         if (me->bb==0) {
1249                 me->bb = BKE_boundbox_alloc_unit();
1250         }
1251         bb= me->bb;
1252         
1253         INIT_MINMAX(min, max);
1254
1255         if (!loc) loc= mloc;
1256         if (!size) size= msize;
1257         
1258         mvert= me->mvert;
1259         for (a = 0; a<me->totvert; a++, mvert++) {
1260                 co = mvert->co;
1261                 
1262                 /* bounds */
1263                 minmax_v3v3_v3(min, max, co);
1264                 
1265                 /* radius */
1266
1267                 vert_radius_sq = len_squared_v3(co);
1268                 if (vert_radius_sq > radius_sq)
1269                         radius_sq = vert_radius_sq;
1270         }
1271                 
1272         if (me->totvert) {
1273                 loc[0] = (min[0] + max[0]) / 2.0f;
1274                 loc[1] = (min[1] + max[1]) / 2.0f;
1275                 loc[2] = (min[2] + max[2]) / 2.0f;
1276                 
1277                 size[0] = (max[0] - min[0]) / 2.0f;
1278                 size[1] = (max[1] - min[1]) / 2.0f;
1279                 size[2] = (max[2] - min[2]) / 2.0f;
1280         }
1281         else {
1282                 loc[0] = loc[1] = loc[2] = 0.0f;
1283                 size[0] = size[1] = size[2] = 0.0f;
1284         }
1285                 
1286         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = loc[0]-size[0];
1287         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = loc[0]+size[0];
1288                 
1289         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = loc[1]-size[1];
1290         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = loc[1]+size[1];
1291
1292         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = loc[2]-size[2];
1293         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = loc[2]+size[2];
1294
1295         return sqrtf_signed(radius_sq);
1296 }
1297
1298 //////////////////////////////////////////////////////
1299
1300
1301 static void BL_CreateGraphicObjectNew(KX_GameObject* gameobj,
1302                                       const MT_Point3& localAabbMin,
1303                                       const MT_Point3& localAabbMax,
1304                                       KX_Scene* kxscene,
1305                                       bool isActive,
1306                                       e_PhysicsEngine physics_engine)
1307 {
1308         if (gameobj->GetMeshCount() > 0)
1309         {
1310                 switch (physics_engine)
1311                 {
1312 #ifdef WITH_BULLET
1313                 case UseBullet:
1314                         {
1315                                 CcdPhysicsEnvironment* env = (CcdPhysicsEnvironment*)kxscene->GetPhysicsEnvironment();
1316                                 assert(env);
1317                                 PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
1318                                 CcdGraphicController* ctrl = new CcdGraphicController(env, motionstate);
1319                                 gameobj->SetGraphicController(ctrl);
1320                                 ctrl->SetNewClientInfo(gameobj->getClientInfo());
1321                                 ctrl->SetLocalAabb(localAabbMin, localAabbMax);
1322                                 if (isActive) {
1323                                         // add first, this will create the proxy handle, only if the object is visible
1324                                         if (gameobj->GetVisible())
1325                                                 env->AddCcdGraphicController(ctrl);
1326                                         // update the mesh if there is a deformer, this will also update the bounding box for modifiers
1327                                         RAS_Deformer* deformer = gameobj->GetDeformer();
1328                                         if (deformer)
1329                                                 deformer->UpdateBuckets();
1330                                 }
1331                         }
1332                         break;
1333 #endif
1334                 default:
1335                         break;
1336                 }
1337         }
1338 }
1339
1340 static void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
1341                                       struct Object* blenderobject,
1342                                       RAS_MeshObject* meshobj,
1343                                       KX_Scene* kxscene,
1344                                       int activeLayerBitInfo,
1345                                       KX_BlenderSceneConverter *converter,
1346                                       bool processCompoundChildren
1347                                       )
1348
1349 {
1350         //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
1351         //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
1352         //bool bRigidBody = (userigidbody == 0);
1353
1354         // object has physics representation?
1355         if (!(blenderobject->gameflag & OB_COLLISION)) {
1356                 // Respond to all collisions so that Near sensors work on No Collision
1357                 // objects.
1358                 gameobj->SetUserCollisionGroup(0xffff);
1359                 gameobj->SetUserCollisionMask(0xffff);
1360                 return;
1361         }
1362
1363         gameobj->SetUserCollisionGroup(blenderobject->col_group);
1364         gameobj->SetUserCollisionMask(blenderobject->col_mask);
1365
1366         // get Root Parent of blenderobject
1367         struct Object* parent= blenderobject->parent;
1368         while (parent && parent->parent) {
1369                 parent= parent->parent;
1370         }
1371
1372         bool isCompoundChild = false;
1373         bool hasCompoundChildren = !parent && (blenderobject->gameflag & OB_CHILD) && !(blenderobject->gameflag & OB_SOFT_BODY);
1374
1375         /* When the parent is not OB_DYNAMIC and has no OB_COLLISION then it gets no bullet controller
1376          * and cant be apart of the parents compound shape, same goes for OB_SOFT_BODY */
1377         if (parent && (parent->gameflag & (OB_DYNAMIC | OB_COLLISION))) {
1378                 if( (parent->gameflag & OB_CHILD)!=0 && (blenderobject->gameflag & OB_CHILD) && !(parent->gameflag & OB_SOFT_BODY)) {
1379                         isCompoundChild = true;
1380                 }
1381         }
1382         if (processCompoundChildren != isCompoundChild)
1383                 return;
1384
1385
1386         PHY_ShapeProps* shapeprops =
1387                         CreateShapePropsFromBlenderObject(blenderobject);
1388
1389         
1390         PHY_MaterialProps* smmaterial = 
1391                 CreateMaterialFromBlenderObject(blenderobject);
1392
1393         DerivedMesh* dm = NULL;
1394         if (gameobj->GetDeformer())
1395                 dm = gameobj->GetDeformer()->GetPhysicsMesh();
1396
1397         class PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode());
1398
1399         kxscene->GetPhysicsEnvironment()->ConvertObject(gameobj, meshobj, dm, kxscene, shapeprops, smmaterial, motionstate, activeLayerBitInfo, isCompoundChild, hasCompoundChildren);
1400
1401         bool isActor = (blenderobject->gameflag & OB_ACTOR)!=0;
1402         bool isSensor = (blenderobject->gameflag & OB_SENSOR) != 0;
1403         gameobj->getClientInfo()->m_type =
1404                 (isSensor) ? ((isActor) ? KX_ClientObjectInfo::OBACTORSENSOR : KX_ClientObjectInfo::OBSENSOR) :
1405                 (isActor) ? KX_ClientObjectInfo::ACTOR : KX_ClientObjectInfo::STATIC;
1406
1407         // should we record animation for this object?
1408         if ((blenderobject->gameflag & OB_RECORD_ANIMATION) != 0)
1409                 gameobj->SetRecordAnimation(true);
1410
1411         delete shapeprops;
1412         delete smmaterial;
1413         if (dm) {
1414                 dm->needsFree = 1;
1415                 dm->release(dm);
1416         }
1417 }
1418
1419
1420
1421
1422
1423 static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRasterizer *rasterizer, KX_BlenderSceneConverter *converter)
1424 {
1425         RAS_ILightObject *lightobj = rasterizer->CreateLight();
1426         KX_LightObject *gamelight;
1427         
1428         lightobj->m_att1 = la->att1;
1429         lightobj->m_att2 = (la->mode & LA_QUAD) ? la->att2 : 0.0f;
1430         lightobj->m_color[0] = la->r;
1431         lightobj->m_color[1] = la->g;
1432         lightobj->m_color[2] = la->b;
1433         lightobj->m_distance = la->dist;
1434         lightobj->m_energy = la->energy;
1435         lightobj->m_shadowclipstart = la->clipsta;
1436         lightobj->m_shadowclipend = la->clipend;
1437         lightobj->m_shadowbias = la->bias;
1438         lightobj->m_shadowbleedbias = la->bleedbias;
1439         lightobj->m_shadowmaptype = la->shadowmap_type;
1440         lightobj->m_shadowfrustumsize = la->shadow_frustum_size;
1441         lightobj->m_shadowcolor[0] = la->shdwr;
1442         lightobj->m_shadowcolor[1] = la->shdwg;
1443         lightobj->m_shadowcolor[2] = la->shdwb;
1444         lightobj->m_layer = layerflag;
1445         lightobj->m_spotblend = la->spotblend;
1446         lightobj->m_spotsize = la->spotsize;
1447         
1448         lightobj->m_nodiffuse = (la->mode & LA_NO_DIFF) != 0;
1449         lightobj->m_nospecular = (la->mode & LA_NO_SPEC) != 0;
1450         
1451         bool glslmat = converter->GetGLSLMaterials();
1452
1453         // in GLSL NEGATIVE LAMP is handled inside the lamp update function
1454         if (glslmat==0) {
1455                 if (la->mode & LA_NEG)
1456                 {
1457                         lightobj->m_color[0] = -lightobj->m_color[0];
1458                         lightobj->m_color[1] = -lightobj->m_color[1];
1459                         lightobj->m_color[2] = -lightobj->m_color[2];
1460                 }
1461         }
1462                 
1463         if (la->type==LA_SUN) {
1464                 lightobj->m_type = RAS_ILightObject::LIGHT_SUN;
1465         } else if (la->type==LA_SPOT) {
1466                 lightobj->m_type = RAS_ILightObject::LIGHT_SPOT;
1467         } else {
1468                 lightobj->m_type = RAS_ILightObject::LIGHT_NORMAL;
1469         }
1470
1471         gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rasterizer,
1472                 lightobj, glslmat);
1473         
1474         return gamelight;
1475 }
1476
1477 static KX_Camera *gamecamera_from_bcamera(Object *ob, KX_Scene *kxscene, KX_BlenderSceneConverter *converter)
1478 {
1479         Camera* ca = static_cast<Camera*>(ob->data);
1480         RAS_CameraData camdata(ca->lens, ca->ortho_scale, ca->sensor_x, ca->sensor_y, ca->sensor_fit, ca->shiftx, ca->shifty, ca->clipsta, ca->clipend, ca->type == CAM_PERSP, ca->YF_dofdist);
1481         KX_Camera *gamecamera;
1482         
1483         gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
1484         gamecamera->SetName(ca->id.name + 2);
1485         
1486         return gamecamera;
1487 }
1488
1489 static KX_GameObject *gameobject_from_blenderobject(
1490                                                                 Object *ob, 
1491                                                                 KX_Scene *kxscene, 
1492                                                                 RAS_IRasterizer *rendertools,
1493                                                                 KX_BlenderSceneConverter *converter,
1494                                                                 bool libloading) 
1495 {
1496         KX_GameObject *gameobj = NULL;
1497         Scene *blenderscene = kxscene->GetBlenderScene();
1498         
1499         switch (ob->type) {
1500         case OB_LAMP:
1501         {
1502                 KX_LightObject* gamelight = gamelight_from_blamp(ob, static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
1503                 gameobj = gamelight;
1504                 
1505                 if (blenderscene->lay & ob->lay)
1506                 {
1507                         gamelight->AddRef();
1508                         kxscene->GetLightList()->Add(gamelight);
1509                 }
1510
1511                 break;
1512         }
1513         
1514         case OB_CAMERA:
1515         {
1516                 KX_Camera* gamecamera = gamecamera_from_bcamera(ob, kxscene, converter);
1517                 gameobj = gamecamera;
1518                 
1519                 //don't add a reference: the camera list in kxscene->m_cameras is not released at the end
1520                 //gamecamera->AddRef();
1521                 kxscene->AddCamera(gamecamera);
1522                 
1523                 break;
1524         }
1525         
1526         case OB_MESH:
1527         {
1528                 Mesh* mesh = static_cast<Mesh*>(ob->data);
1529                 float center[3], extents[3];
1530                 float radius = my_boundbox_mesh((Mesh*) ob->data, center, extents);
1531                 RAS_MeshObject* meshobj = BL_ConvertMesh(mesh,ob,kxscene,converter, libloading);
1532                 
1533                 // needed for python scripting
1534                 kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1535
1536                 if (ob->gameflag & OB_NAVMESH)
1537                 {
1538                         gameobj = new KX_NavMeshObject(kxscene,KX_Scene::m_callbacks);
1539                         gameobj->AddMesh(meshobj);
1540                         break;
1541                 }
1542
1543                 gameobj = new BL_DeformableGameObject(ob,kxscene,KX_Scene::m_callbacks);
1544         
1545                 // set transformation
1546                 gameobj->AddMesh(meshobj);
1547
1548                 // gather levels of detail
1549                 if (BLI_listbase_count_ex(&ob->lodlevels, 2) > 1) {
1550                         LodLevel *lod = ((LodLevel*)ob->lodlevels.first)->next;
1551                         Mesh* lodmesh = mesh;
1552                         Object* lodmatob = ob;
1553                         gameobj->AddLodMesh(meshobj);
1554                         for (; lod; lod = lod->next) {
1555                                 if (!lod->source || lod->source->type != OB_MESH) continue;
1556                                 if (lod->flags & OB_LOD_USE_MESH) {
1557                                         lodmesh = static_cast<Mesh*>(lod->source->data);
1558                                 }
1559                                 if (lod->flags & OB_LOD_USE_MAT) {
1560                                         lodmatob = lod->source;
1561                                 }
1562                                 gameobj->AddLodMesh(BL_ConvertMesh(lodmesh, lodmatob, kxscene, converter, libloading));
1563                         }
1564                         if (blenderscene->gm.lodflag & SCE_LOD_USE_HYST) {
1565                                 kxscene->SetLodHysteresis(true);
1566                                 kxscene->SetLodHysteresisValue(blenderscene->gm.scehysteresis);
1567                         }
1568                 }
1569         
1570                 // for all objects: check whether they want to
1571                 // respond to updates
1572                 bool ignoreActivityCulling =  
1573                         ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
1574                 gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
1575                 gameobj->SetOccluder((ob->gameflag & OB_OCCLUDER) != 0, false);
1576
1577                 // we only want obcolor used if there is a material in the mesh
1578                 // that requires it
1579                 Material *mat= NULL;
1580                 bool bUseObjectColor=false;
1581                 
1582                 for (int i=0;i<mesh->totcol;i++) {
1583                         mat=mesh->mat[i];
1584                         if (!mat) break;
1585                         if ((mat->shade_flag & MA_OBCOLOR)) {
1586                                 bUseObjectColor = true;
1587                                 break;
1588                         }
1589                 }
1590                 if (bUseObjectColor)
1591                         gameobj->SetObjectColor(ob->col);
1592         
1593                 // two options exists for deform: shape keys and armature
1594                 // only support relative shape key
1595                 bool bHasShapeKey = mesh->key != NULL && mesh->key->type==KEY_RELATIVE;
1596                 bool bHasDvert = mesh->dvert != NULL && ob->defbase.first;
1597                 bool bHasArmature = (BL_ModifierDeformer::HasArmatureDeformer(ob) && ob->parent && ob->parent->type == OB_ARMATURE && bHasDvert);
1598                 bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(ob);
1599 #ifdef WITH_BULLET
1600                 bool bHasSoftBody = (!ob->parent && (ob->gameflag & OB_SOFT_BODY));
1601 #endif
1602                 if (bHasModifier) {
1603                         BL_ModifierDeformer *dcont = new BL_ModifierDeformer((BL_DeformableGameObject *)gameobj,
1604                                                                                                                                 kxscene->GetBlenderScene(), ob, meshobj);
1605                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1606                 } else if (bHasShapeKey) {
1607                         // not that we can have shape keys without dvert! 
1608                         BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj, 
1609                                                                                                                         ob, meshobj);
1610                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1611                 } else if (bHasArmature) {
1612                         BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj,
1613                                                                                                                         ob, meshobj);
1614                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1615                 } else if (bHasDvert) {
1616                         // this case correspond to a mesh that can potentially deform but not with the
1617                         // object to which it is attached for the moment. A skin mesh was created in
1618                         // BL_ConvertMesh() so must create a deformer too!
1619                         BL_MeshDeformer *dcont = new BL_MeshDeformer((BL_DeformableGameObject*)gameobj,
1620                                                                                                                   ob, meshobj);
1621                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1622 #ifdef WITH_BULLET
1623                 } else if (bHasSoftBody) {
1624                         KX_SoftBodyDeformer *dcont = new KX_SoftBodyDeformer(meshobj, (BL_DeformableGameObject*)gameobj);
1625                         ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont);
1626 #endif
1627                 }
1628                 
1629                 MT_Point3 min = MT_Point3(center) - MT_Vector3(extents);
1630                 MT_Point3 max = MT_Point3(center) + MT_Vector3(extents);
1631                 SG_BBox bbox = SG_BBox(min, max);
1632                 gameobj->GetSGNode()->SetBBox(bbox);
1633                 gameobj->GetSGNode()->SetRadius(radius);
1634         
1635                 break;
1636         }
1637         
1638         case OB_ARMATURE:
1639         {
1640                 bArmature *arm = (bArmature*)ob->data;
1641                 gameobj = new BL_ArmatureObject(
1642                         kxscene,
1643                         KX_Scene::m_callbacks,
1644                         ob,
1645                         kxscene->GetBlenderScene(), // handle
1646                         arm->gevertdeformer
1647                 );
1648                 /* Get the current pose from the armature object and apply it as the rest pose */
1649                 break;
1650         }
1651         
1652         case OB_EMPTY:
1653         {
1654                 gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks);
1655                 // set transformation
1656                 break;
1657         }
1658
1659         case OB_FONT:
1660         {
1661                 bool do_color_management = BKE_scene_check_color_management_enabled(blenderscene);
1662                 /* font objects have no bounding box */
1663                 gameobj = new KX_FontObject(kxscene,KX_Scene::m_callbacks, rendertools, ob, do_color_management);
1664
1665                 /* add to the list only the visible fonts */
1666                 if ((ob->lay & kxscene->GetBlenderScene()->lay) != 0)
1667                         kxscene->AddFont(static_cast<KX_FontObject*>(gameobj));
1668                 break;
1669         }
1670
1671 #ifdef THREADED_DAG_WORKAROUND
1672         case OB_CURVE:
1673         {
1674                 if (ob->curve_cache == NULL) {
1675                         BKE_displist_make_curveTypes(blenderscene, ob, false);
1676                 }
1677         }
1678 #endif
1679
1680         }
1681         if (gameobj) 
1682         {
1683                 gameobj->SetLayer(ob->lay);
1684                 gameobj->SetBlenderObject(ob);
1685                 /* set the visibility state based on the objects render option in the outliner */
1686                 if (ob->restrictflag & OB_RESTRICT_RENDER) gameobj->SetVisible(0, 0);
1687         }
1688         return gameobj;
1689 }
1690
1691 struct parentChildLink {
1692         struct Object* m_blenderchild;
1693         SG_Node* m_gamechildnode;
1694 };
1695
1696 static bPoseChannel *get_active_posechannel2(Object *ob)
1697 {
1698         bArmature *arm= (bArmature*)ob->data;
1699         bPoseChannel *pchan;
1700         
1701         /* find active */
1702         for (pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1703                 if (pchan->bone && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
1704                         return pchan;
1705         }
1706         
1707         return NULL;
1708 }
1709
1710 static ListBase *get_active_constraints2(Object *ob)
1711 {
1712         if (!ob)
1713                 return NULL;
1714
1715   // XXX - shouldnt we care about the pose data and not the mode???
1716         if (ob->mode & OB_MODE_POSE) { 
1717                 bPoseChannel *pchan;
1718
1719                 pchan = get_active_posechannel2(ob);
1720                 if (pchan)
1721                         return &pchan->constraints;
1722         }
1723         else 
1724                 return &ob->constraints;
1725
1726         return NULL;
1727 }
1728
1729 static void UNUSED_FUNCTION(print_active_constraints2)(Object *ob) //not used, use to debug
1730 {
1731         bConstraint* curcon;
1732         ListBase* conlist = get_active_constraints2(ob);
1733
1734         if (conlist) {
1735                 for (curcon = (bConstraint *)conlist->first; curcon; curcon = (bConstraint *)curcon->next) {
1736                         printf("%i\n",curcon->type);
1737                 }
1738         }
1739 }
1740
1741 // Copy base layer to object layer like in BKE_scene_set_background
1742 static void blenderSceneSetBackground(Scene *blenderscene)
1743 {
1744         Scene *it;
1745         Base *base;
1746
1747         for (SETLOOPER(blenderscene, it, base)) {
1748                 base->object->lay = base->lay;
1749                 base->object->flag = base->flag;
1750         }
1751 }
1752
1753 static KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist)
1754 {
1755
1756         for (int j=0;j<sumolist->GetCount();j++)
1757         {
1758                 KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1759                 if (gameobje->GetName()==busc)
1760                         return gameobje;
1761         }
1762         
1763         return 0;
1764
1765 }
1766
1767 static bool bl_isConstraintInList(KX_GameObject *gameobj, set<KX_GameObject*> convertedlist)
1768 {
1769         set<KX_GameObject*>::iterator gobit;
1770         for (gobit = convertedlist.begin(); gobit != convertedlist.end(); gobit++) {
1771                 if ((*gobit)->GetName() == gameobj->GetName())
1772                         return true;
1773         }
1774         return false;
1775 }
1776
1777 /* helper for BL_ConvertBlenderObjects, avoids code duplication
1778  * note: all var names match args are passed from the caller */
1779 static void bl_ConvertBlenderObject_Single(
1780         KX_BlenderSceneConverter *converter,
1781        Object *blenderobject,
1782         vector<parentChildLink> &vec_parent_child,
1783         CListValue* logicbrick_conversionlist,
1784         CListValue* objectlist, CListValue* inactivelist, CListValue*   sumolist,
1785         KX_Scene* kxscene, KX_GameObject* gameobj,
1786         SCA_LogicManager* logicmgr, SCA_TimeEventManager* timemgr,
1787         bool isInActiveLayer
1788         )
1789 {
1790         MT_Point3 pos(
1791                 blenderobject->loc[0]+blenderobject->dloc[0],
1792                 blenderobject->loc[1]+blenderobject->dloc[1],
1793                 blenderobject->loc[2]+blenderobject->dloc[2]
1794         );
1795
1796         MT_Matrix3x3 rotation;
1797         float rotmat[3][3];
1798         BKE_object_rot_to_mat3(blenderobject, rotmat, false);
1799         rotation.setValue3x3((float*)rotmat);
1800
1801         MT_Vector3 scale(blenderobject->size);
1802
1803         gameobj->NodeSetLocalPosition(pos);
1804         gameobj->NodeSetLocalOrientation(rotation);
1805         gameobj->NodeSetLocalScale(scale);
1806         gameobj->NodeUpdateGS(0);
1807
1808         sumolist->Add(gameobj->AddRef());
1809
1810         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
1811
1812         gameobj->SetName(blenderobject->id.name + 2);
1813
1814         // update children/parent hierarchy
1815         if (blenderobject->parent != 0)
1816         {
1817                 // blender has an additional 'parentinverse' offset in each object
1818                 SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc);
1819                 SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback);
1820
1821                 // define a normal parent relationship for this node.
1822                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
1823                 parentinversenode->SetParentRelation(parent_relation);
1824
1825                 parentChildLink pclink;
1826                 pclink.m_blenderchild = blenderobject;
1827                 pclink.m_gamechildnode = parentinversenode;
1828                 vec_parent_child.push_back(pclink);
1829
1830                 float* fl = (float*) blenderobject->parentinv;
1831                 MT_Transform parinvtrans(fl);
1832                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
1833                 // problem here: the parent inverse transform combines scaling and rotation
1834                 // in the basis but the scenegraph needs separate rotation and scaling.
1835                 // This is not important for OpenGL (it uses 4x4 matrix) but it is important
1836                 // for the physic engine that needs a separate scaling
1837                 //parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
1838
1839                 // Extract the rotation and the scaling from the basis
1840                 MT_Matrix3x3 ori(parinvtrans.getBasis());
1841                 MT_Vector3 x(ori.getColumn(0));
1842                 MT_Vector3 y(ori.getColumn(1));
1843                 MT_Vector3 z(ori.getColumn(2));
1844                 MT_Vector3 parscale(x.length(), y.length(), z.length());
1845                 if (!MT_fuzzyZero(parscale[0]))
1846                         x /= parscale[0];
1847                 if (!MT_fuzzyZero(parscale[1]))
1848                         y /= parscale[1];
1849                 if (!MT_fuzzyZero(parscale[2]))
1850                         z /= parscale[2];
1851                 ori.setColumn(0, x);
1852                 ori.setColumn(1, y);
1853                 ori.setColumn(2, z);
1854                 parentinversenode->SetLocalOrientation(ori);
1855                 parentinversenode->SetLocalScale(parscale);
1856
1857                 parentinversenode->AddChild(gameobj->GetSGNode());
1858         }
1859
1860         // needed for python scripting
1861         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
1862
1863         // needed for group duplication
1864         logicmgr->RegisterGameObj(blenderobject, gameobj);
1865         for (int i = 0; i < gameobj->GetMeshCount(); i++)
1866                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
1867
1868         converter->RegisterGameObject(gameobj, blenderobject);
1869         // this was put in rapidly, needs to be looked at more closely
1870         // only draw/use objects in active 'blender' layers
1871
1872         logicbrick_conversionlist->Add(gameobj->AddRef());
1873
1874         if (isInActiveLayer)
1875         {
1876                 objectlist->Add(gameobj->AddRef());
1877                 //tf.Add(gameobj->GetSGNode());
1878
1879                 gameobj->NodeUpdateGS(0);
1880                 gameobj->AddMeshUser();
1881         }
1882         else
1883         {
1884                 //we must store this object otherwise it will be deleted
1885                 //at the end of this function if it is not a root object
1886                 inactivelist->Add(gameobj->AddRef());
1887         }
1888 }
1889
1890
1891 // convert blender objects into ketsji gameobjects
1892 void BL_ConvertBlenderObjects(struct Main* maggie,
1893                                                           KX_Scene* kxscene,
1894                                                           KX_KetsjiEngine* ketsjiEngine,
1895                                                           e_PhysicsEngine       physics_engine,
1896                                                           RAS_IRasterizer* rendertools,
1897                                                           RAS_ICanvas* canvas,
1898                                                           KX_BlenderSceneConverter* converter,
1899                                                           bool alwaysUseExpandFraming,
1900                                                           bool libloading
1901                                                           )
1902 {
1903
1904 #define BL_CONVERTBLENDEROBJECT_SINGLE                                 \
1905         bl_ConvertBlenderObject_Single(converter,                          \
1906                                        blenderobject,                      \
1907                                        vec_parent_child,                   \
1908                                        logicbrick_conversionlist,          \
1909                                        objectlist, inactivelist, sumolist, \
1910                                        kxscene, gameobj,                   \
1911                                        logicmgr, timemgr,                  \
1912                                        isInActiveLayer                     \
1913                                        )
1914
1915
1916
1917         Scene *blenderscene = kxscene->GetBlenderScene();
1918         // for SETLOOPER
1919         Scene *sce_iter;
1920         Base *base;
1921
1922         // Get the frame settings of the canvas.
1923         // Get the aspect ratio of the canvas as designed by the user.
1924
1925         RAS_FrameSettings::RAS_FrameType frame_type;
1926         int aspect_width;
1927         int aspect_height;
1928         set<Group*> grouplist;  // list of groups to be converted
1929         set<Object*> allblobj;  // all objects converted
1930         set<Object*> groupobj;  // objects from groups (never in active layer)
1931
1932         // This is bad, but we use this to make sure the first time this is called
1933         // is not in a separate thread.
1934         BL_Texture::GetMaxUnits();
1935
1936         /* We have to ensure that group definitions are only converted once
1937          * push all converted group members to this set.
1938          * This will happen when a group instance is made from a linked group instance
1939          * and both are on the active layer. */
1940         set<KX_GameObject*> convertedlist;
1941
1942         if (alwaysUseExpandFraming) {
1943                 frame_type = RAS_FrameSettings::e_frame_extend;
1944                 aspect_width = canvas->GetWidth();
1945                 aspect_height = canvas->GetHeight();
1946         } else {
1947                 if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_BARS) {
1948                         frame_type = RAS_FrameSettings::e_frame_bars;
1949                 } else if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_EXTEND) {
1950                         frame_type = RAS_FrameSettings::e_frame_extend;
1951                 } else {
1952                         frame_type = RAS_FrameSettings::e_frame_scale;
1953                 }
1954                 
1955                 aspect_width  = (int)(blenderscene->r.xsch * blenderscene->r.xasp);
1956                 aspect_height = (int)(blenderscene->r.ysch * blenderscene->r.yasp);
1957         }
1958         
1959         RAS_FrameSettings frame_settings(
1960                 frame_type,
1961                 blenderscene->gm.framing.col[0],
1962                 blenderscene->gm.framing.col[1],
1963                 blenderscene->gm.framing.col[2],
1964                 aspect_width,
1965                 aspect_height
1966         );
1967         kxscene->SetFramingType(frame_settings);
1968
1969         kxscene->SetGravity(MT_Vector3(0,0, -blenderscene->gm.gravity));
1970         
1971         /* set activity culling parameters */
1972         kxscene->SetActivityCulling( (blenderscene->gm.mode & WO_ACTIVITY_CULLING) != 0);
1973         kxscene->SetActivityCullingRadius(blenderscene->gm.activityBoxRadius);
1974         kxscene->SetDbvtCulling((blenderscene->gm.mode & WO_DBVT_CULLING) != 0);
1975         
1976         // no occlusion culling by default
1977         kxscene->SetDbvtOcclusionRes(0);
1978
1979         int activeLayerBitInfo = blenderscene->lay;
1980         
1981         // list of all object converted, active and inactive
1982         CListValue*     sumolist = new CListValue();
1983         
1984         vector<parentChildLink> vec_parent_child;
1985         
1986         CListValue* objectlist = kxscene->GetObjectList();
1987         CListValue* inactivelist = kxscene->GetInactiveList();
1988         CListValue* parentlist = kxscene->GetRootParentList();
1989         
1990         SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
1991         SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager();
1992         
1993         CListValue* logicbrick_conversionlist = new CListValue();
1994         
1995         //SG_TreeFactory tf;
1996         
1997         // Convert actions to actionmap
1998         bAction *curAct;
1999         for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next)
2000         {
2001                 logicmgr->RegisterActionName(curAct->id.name + 2, curAct);
2002         }
2003
2004         SetDefaultLightMode(blenderscene);
2005
2006         blenderSceneSetBackground(blenderscene);
2007
2008         // Let's support scene set.
2009         // Beware of name conflict in linked data, it will not crash but will create confusion
2010         // in Python scripting and in certain actuators (replace mesh). Linked scene *should* have
2011         // no conflicting name for Object, Object data and Action.
2012         for (SETLOOPER(blenderscene, sce_iter, base))
2013         {
2014                 Object* blenderobject = base->object;
2015                 allblobj.insert(blenderobject);
2016
2017                 KX_GameObject* gameobj = gameobject_from_blenderobject(
2018                                                                                 base->object, 
2019                                                                                 kxscene, 
2020                                                                                 rendertools, 
2021                                                                                 converter,
2022                                                                                 libloading);
2023
2024                 bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0;
2025                 if (gameobj)
2026                 {
2027                         /* macro calls object conversion funcs */
2028                         BL_CONVERTBLENDEROBJECT_SINGLE;
2029
2030                         if (gameobj->IsDupliGroup()) {
2031                                 grouplist.insert(blenderobject->dup_group);
2032                         }
2033
2034                         /* Note about memory leak issues:
2035                          * When a CValue derived class is created, m_refcount is initialized to 1
2036                          * so the class must be released after being used to make sure that it won't
2037                          * hang in memory. If the object needs to be stored for a long time,
2038                          * use AddRef() so that this Release() does not free the object.
2039                          * Make sure that for any AddRef() there is a Release()!!!!
2040                          * Do the same for any object derived from CValue, CExpression and NG_NetworkMessage
2041                          */
2042                         gameobj->Release();
2043                 }
2044         }
2045
2046         if (!grouplist.empty())
2047         {
2048                 // now convert the group referenced by dupli group object
2049                 // keep track of all groups already converted
2050                 set<Group*> allgrouplist = grouplist;
2051                 set<Group*> tempglist;
2052                 // recurse
2053                 while (!grouplist.empty())
2054                 {
2055                         set<Group*>::iterator git;
2056                         tempglist.clear();
2057                         tempglist.swap(grouplist);
2058                         for (git=tempglist.begin(); git!=tempglist.end(); git++)
2059                         {
2060                                 Group* group = *git;
2061                                 GroupObject* go;
2062                                 for (go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next)
2063                                 {
2064                                         Object* blenderobject = go->ob;
2065                                         if (converter->FindGameObject(blenderobject) == NULL)
2066                                         {
2067                                                 allblobj.insert(blenderobject);
2068                                                 groupobj.insert(blenderobject);
2069                                                 KX_GameObject* gameobj = gameobject_from_blenderobject(
2070                                                                                                                 blenderobject, 
2071                                                                                                                 kxscene, 
2072                                                                                                                 rendertools, 
2073                                                                                                                 converter,
2074                                                                                                                 libloading);
2075
2076                                                 bool isInActiveLayer = false;
2077                                                 if (gameobj) {
2078                                                         /* Insert object to the constraint game object list
2079                                                          * so we can check later if there is a instance in the scene or
2080                                                          * an instance and its actual group definition. */
2081                                                         convertedlist.insert((KX_GameObject*)gameobj->AddRef());
2082
2083                                                         /* macro calls object conversion funcs */
2084                                                         BL_CONVERTBLENDEROBJECT_SINGLE;
2085
2086                                                         if (gameobj->IsDupliGroup())
2087                                                         {
2088                                                                 if (allgrouplist.insert(blenderobject->dup_group).second)
2089                                                                 {
2090                                                                         grouplist.insert(blenderobject->dup_group);
2091                                                                 }
2092                                                         }
2093
2094                                                         /* see comment above re: mem leaks */
2095                                                         gameobj->Release();
2096                                                 }
2097                                         }
2098                                 }
2099                         }
2100                 }
2101         }
2102
2103         // non-camera objects not supported as camera currently
2104         if (blenderscene->camera && blenderscene->camera->type == OB_CAMERA) {
2105                 KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
2106                 
2107                 if (gamecamera)
2108                         kxscene->SetActiveCamera(gamecamera);
2109         }
2110
2111         //      Set up armatures
2112         set<Object*>::iterator oit;
2113         for (oit=allblobj.begin(); oit!=allblobj.end(); oit++)
2114         {
2115                 Object* blenderobj = *oit;
2116                 if (blenderobj->type==OB_MESH) {
2117                         Mesh *me = (Mesh*)blenderobj->data;
2118         
2119                         if (me->dvert) {
2120                                 BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj);
2121
2122                                 if (obj && BL_ModifierDeformer::HasArmatureDeformer(blenderobj) && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE) {
2123                                         KX_GameObject *par = converter->FindGameObject(blenderobj->parent);
2124                                         if (par && obj->GetDeformer())
2125                                                 ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par);
2126                                 }
2127                         }
2128                 }
2129         }
2130         
2131         // create hierarchy information
2132         int i;
2133         vector<parentChildLink>::iterator pcit;
2134         
2135         for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit)
2136         {
2137         
2138                 struct Object* blenderchild = pcit->m_blenderchild;
2139                 struct Object* blenderparent = blenderchild->parent;
2140                 KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
2141                 KX_GameObject* childobj = converter->FindGameObject(blenderchild);
2142
2143                 assert(childobj);
2144
2145                 if (!parentobj || objectlist->SearchValue(childobj) != objectlist->SearchValue(parentobj))
2146                 {
2147                         // special case: the parent and child object are not in the same layer. 
2148                         // This weird situation is used in Apricot for test purposes.
2149                         // Resolve it by not converting the child
2150                         childobj->GetSGNode()->DisconnectFromParent();
2151                         delete pcit->m_gamechildnode;
2152                         // Now destroy the child object but also all its descendent that may already be linked
2153                         // Remove the child reference in the local list!
2154                         // Note: there may be descendents already if the children of the child were processed
2155                         //       by this loop before the child. In that case, we must remove the children also
2156                         CListValue* childrenlist = childobj->GetChildrenRecursive();
2157                         childrenlist->Add(childobj->AddRef());
2158                         for ( i=0;i<childrenlist->GetCount();i++)
2159                         {
2160                                 KX_GameObject* obj = static_cast<KX_GameObject*>(childrenlist->GetValue(i));
2161                                 if (sumolist->RemoveValue(obj))
2162                                         obj->Release();
2163                                 if (logicbrick_conversionlist->RemoveValue(obj))
2164                                         obj->Release();
2165                         }
2166                         childrenlist->Release();
2167                         
2168                         // now destroy recursively
2169                         converter->UnregisterGameObject(childobj); // removing objects during conversion make sure this runs too
2170                         kxscene->RemoveObject(childobj);
2171                         
2172                         continue;
2173                 }
2174
2175                 switch (blenderchild->partype)
2176                 {
2177                         case PARVERT1:
2178                         {
2179                                 // creat a new vertex parent relationship for this node.
2180                                 KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New();
2181                                 pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation);
2182                                 break;
2183                         }
2184                         case PARSLOW:
2185                         {
2186                                 // creat a new slow parent relationship for this node.
2187                                 KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
2188                                 pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
2189                                 break;
2190                         }
2191                         case PARBONE:
2192                         {
2193                                 // parent this to a bone
2194                                 Bone *parent_bone = BKE_armature_find_bone_name(BKE_armature_from_object(blenderchild->parent),
2195                                                                                 blenderchild->parsubstr);
2196
2197                                 if (parent_bone) {
2198                                         KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
2199                                         pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
2200                                 }
2201                         
2202                                 break;
2203                         }
2204                         case PARSKEL: // skinned - ignore
2205                                 break;
2206                         case PAROBJECT:
2207                         case PARVERT3:
2208                         default:
2209                                 // unhandled
2210                                 break;
2211                 }
2212         
2213                 parentobj->     GetSGNode()->AddChild(pcit->m_gamechildnode);
2214         }
2215         vec_parent_child.clear();
2216         
2217         // find 'root' parents (object that has not parents in SceneGraph)
2218         for (i=0;i<sumolist->GetCount();++i)
2219         {
2220                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2221                 if (gameobj->GetSGNode()->GetSGParent() == 0)
2222                 {
2223                         parentlist->Add(gameobj->AddRef());
2224                         gameobj->NodeUpdateGS(0);
2225                 }
2226         }
2227
2228         // create graphic controller for culling
2229         if (kxscene->GetDbvtCulling())
2230         {
2231                 bool occlusion = false;
2232                 for (i=0; i<sumolist->GetCount();i++)
2233                 {
2234                         KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2235                         if (gameobj->GetMeshCount() > 0) 
2236                         {
2237                                 MT_Point3 box[2];
2238                                 gameobj->GetSGNode()->BBox().getmm(box, MT_Transform::Identity());
2239                                 // box[0] is the min, box[1] is the max
2240                                 bool isactive = objectlist->SearchValue(gameobj);
2241                                 BL_CreateGraphicObjectNew(gameobj,box[0],box[1],kxscene,isactive,physics_engine);
2242                                 if (gameobj->GetOccluder())
2243                                         occlusion = true;
2244                         }
2245                 }
2246                 if (occlusion)
2247                         kxscene->SetDbvtOcclusionRes(blenderscene->gm.occlusionRes);
2248         }
2249         if (blenderscene->world)
2250                 kxscene->GetPhysicsEnvironment()->SetNumTimeSubSteps(blenderscene->gm.physubstep);
2251
2252         // now that the scenegraph is complete, let's instantiate the deformers.
2253         // We need that to create reusable derived mesh and physic shapes
2254         for (i=0;i<sumolist->GetCount();++i)
2255         {
2256                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2257                 if (gameobj->GetDeformer())
2258                         gameobj->GetDeformer()->UpdateBuckets();
2259         }
2260
2261         // Set up armature constraints and shapekey drivers
2262         for (i=0;i<sumolist->GetCount();++i)
2263         {
2264                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2265                 if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
2266                 {
2267                         BL_ArmatureObject *armobj = (BL_ArmatureObject*)gameobj;
2268                         armobj->LoadConstraints(converter);
2269
2270                         CListValue *children = armobj->GetChildren();
2271                         for (int j=0; j<children->GetCount();++j)
2272                         {
2273                                 BL_ShapeDeformer *deform = dynamic_cast<BL_ShapeDeformer*>(((KX_GameObject*)children->GetValue(j))->GetDeformer());
2274                                 if (deform)
2275                                         deform->LoadShapeDrivers(armobj);
2276                         }
2277
2278                         children->Release();
2279                 }
2280         }
2281
2282         bool processCompoundChildren = false;
2283         // create physics information
2284         for (i=0;i<sumolist->GetCount();i++)
2285         {
2286                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2287                 struct Object* blenderobject = gameobj->GetBlenderObject();
2288                 int nummeshes = gameobj->GetMeshCount();
2289                 RAS_MeshObject* meshobj = 0;
2290                 if (nummeshes > 0)
2291                 {
2292                         meshobj = gameobj->GetMesh(0);
2293                 }
2294                 int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
2295                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,converter,processCompoundChildren);
2296         }
2297
2298         processCompoundChildren = true;
2299         // create physics information
2300         for (i=0;i<sumolist->GetCount();i++)
2301         {
2302                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
2303                 struct Object* blenderobject = gameobj->GetBlenderObject();
2304                 int nummeshes = gameobj->GetMeshCount();
2305                 RAS_MeshObject* meshobj = 0;
2306                 if (nummeshes > 0)
2307                 {
2308                         meshobj = gameobj->GetMesh(0);
2309                 }
2310                 int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0;
2311                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,converter,processCompoundChildren);
2312         }
2313
2314         // create physics joints
2315         for (i=0;i<sumolist->GetCount();i++)
2316         {
2317                 PHY_IPhysicsEnvironment *physEnv = kxscene->GetPhysicsEnvironment();
2318                 KX_GameObject *gameobj = (KX_GameObject *)sumolist->GetValue(i);
2319                 struct Object *blenderobject = gameobj->GetBlenderObject();
2320                 ListBase *conlist = get_active_constraints2(blenderobject);
2321                 bConstraint *curcon;
2322
2323                 if (!conlist)
2324                         continue;
2325
2326                 for (curcon = (bConstraint *)conlist->first; curcon; curcon = (bConstraint *)curcon->next) {
2327                         if (curcon->type != CONSTRAINT_TYPE_RIGIDBODYJOINT)
2328                                 continue;
2329
2330                         bRigidBodyJointConstraint *dat = (bRigidBodyJointConstraint *)curcon->data;
2331                                         
2332                         /* Skip if no target or a child object is selected or constraints are deactivated */
2333                         if (!dat->tar || dat->child || (curcon->flag & CONSTRAINT_OFF))
2334                                 continue;
2335
2336                         /* Store constraints of grouped and instanced objects for all layers */
2337                         gameobj->AddConstraint(dat);
2338
2339                         /** if it's during libload we only add constraints in the object but
2340                          * doesn't create it. Constraint will be replicated later in scene->MergeScene
2341                          */
2342                         if (libloading)
2343                                 continue;
2344
2345                         /* Skipped already converted constraints. 
2346                          * This will happen when a group instance is made from a linked group instance
2347                          * and both are on the active layer. */
2348                         if (bl_isConstraintInList(gameobj, convertedlist))
2349                                 continue;
2350
2351                         KX_GameObject *gotar = getGameOb(dat->tar->id.name + 2, sumolist);
2352
2353                         if (gotar && (gotar->GetLayer()&activeLayerBitInfo) && gotar->GetPhysicsController() &&
2354                                 (gameobj->GetLayer()&activeLayerBitInfo) && gameobj->GetPhysicsController())
2355                         {
2356                                 physEnv->SetupObjectConstraints(gameobj, gotar, dat);
2357                         }
2358                 }
2359         }
2360
2361         /* cleanup converted set of group objects */
2362         set<KX_GameObject*>::iterator gobit;
2363         for (gobit = convertedlist.begin(); gobit != convertedlist.end(); gobit++)
2364                 (*gobit)->Release();
2365                 
2366         convertedlist.clear();
2367         sumolist->Release();
2368
2369         // convert world
2370         KX_WorldInfo* worldinfo = new KX_WorldInfo(blenderscene, blenderscene->world);
2371         converter->RegisterWorldInfo(worldinfo);
2372         kxscene->SetWorldInfo(worldinfo);
2373
2374         //create object representations for obstacle simulation
2375         KX_ObstacleSimulation* obssimulation = kxscene->GetObstacleSimulation();
2376         if (obssimulation)
2377         {
2378                 for ( i=0;i<objectlist->GetCount();i++)
2379                 {
2380                         KX_GameObject* gameobj = static_cast<KX_GameObject*>(objectlist->GetValue(i));
2381                         struct Object* blenderobject = gameobj->GetBlenderObject();
2382                         if (blenderobject->gameflag & OB_HASOBSTACLE)
2383                         {
2384                                 obssimulation->AddObstacleForObj(gameobj);
2385                         }
2386                 }
2387         }
2388
2389         //process navigation mesh objects
2390         for ( i=0; i<objectlist->GetCount();i++)
2391         {
2392                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(objectlist->GetValue(i));
2393                 struct Object* blenderobject = gameobj->GetBlenderObject();
2394                 if (blenderobject->type==OB_MESH && (blenderobject->gameflag & OB_NAVMESH))
2395                 {
2396                         KX_NavMeshObject* navmesh = static_cast<KX_NavMeshObject*>(gameobj);
2397                         navmesh->SetVisible(0, true);
2398                         navmesh->BuildNavMesh();
2399                         if (obssimulation)
2400                                 obssimulation->AddObstaclesForNavMesh(navmesh);
2401                 }
2402         }
2403         for ( i=0; i<inactivelist->GetCount();i++)
2404         {
2405                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(inactivelist->GetValue(i));
2406                 struct Object* blenderobject = gameobj->GetBlenderObject();
2407                 if (blenderobject->type==OB_MESH && (blenderobject->gameflag & OB_NAVMESH))
2408                 {
2409                         KX_NavMeshObject* navmesh = static_cast<KX_NavMeshObject*>(gameobj);
2410                         navmesh->SetVisible(0, true);
2411                 }
2412         }
2413
2414         // convert logic bricks, sensors, controllers and actuators
2415         for (i=0;i<logicbrick_conversionlist->GetCount();i++)
2416         {
2417                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2418                 struct Object* blenderobj = gameobj->GetBlenderObject();
2419                 int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
2420                 bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
2421                 BL_ConvertActuators(maggie->name, blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,layerMask,isInActiveLayer,converter);
2422         }
2423         for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
2424         {
2425                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2426                 struct Object* blenderobj = gameobj->GetBlenderObject();
2427                 int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
2428                 bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
2429                 BL_ConvertControllers(blenderobj,gameobj,logicmgr, layerMask,isInActiveLayer,converter, libloading);
2430         }
2431         for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
2432         {
2433                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2434                 struct Object* blenderobj = gameobj->GetBlenderObject();
2435                 int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0;
2436                 bool isInActiveLayer = (blenderobj->lay & layerMask)!=0;
2437                 BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,layerMask,isInActiveLayer,canvas,converter);
2438                 // set the init state to all objects
2439                 gameobj->SetInitState((blenderobj->init_state)?blenderobj->init_state:blenderobj->state);
2440         }
2441         // apply the initial state to controllers, only on the active objects as this registers the sensors
2442         for ( i=0;i<objectlist->GetCount();i++)
2443         {
2444                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(objectlist->GetValue(i));
2445                 gameobj->ResetState();
2446         }
2447
2448         logicbrick_conversionlist->Release();
2449         
2450         // Calculate the scene btree -
2451         // too slow - commented out.
2452         //kxscene->SetNodeTree(tf.MakeTree());
2453
2454         // instantiate dupli group, we will loop trough the object
2455         // that are in active layers. Note that duplicating group
2456         // has the effect of adding objects at the end of objectlist.
2457         // Only loop through the first part of the list.
2458         int objcount = objectlist->GetCount();
2459         for (i=0;i<objcount;i++)
2460         {
2461                 KX_GameObject* gameobj = (KX_GameObject*) objectlist->GetValue(i);
2462                 if (gameobj->IsDupliGroup())
2463                 {
2464                         kxscene->DupliGroupRecurse(gameobj, 0);
2465                 }
2466         }
2467
2468         KX_Camera *activecam = kxscene->GetActiveCamera();
2469         MT_Scalar distance = (activecam)? activecam->GetCameraFar() - activecam->GetCameraNear(): 100.0f;
2470         RAS_BucketManager *bucketmanager = kxscene->GetBucketManager();
2471         bucketmanager->OptimizeBuckets(distance);
2472 }
2473