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