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