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