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