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