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