contribution from RCRuiz:
[blender.git] / source / gameengine / Converter / BL_BlenderDataConversion.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * Convert blender data to ketsji
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #ifdef WIN32
39 #pragma warning (disable : 4786)
40 #endif
41
42 #include <math.h>
43
44 #include "BL_BlenderDataConversion.h"
45 #include "KX_BlenderGL.h"
46 #include "KX_BlenderScalarInterpolator.h"
47
48 #include "RAS_IPolygonMaterial.h"
49 #include "KX_PolygonMaterial.h"
50
51 // Expressions
52 #include "ListValue.h"
53 #include "IntValue.h"
54 // Collision & Fuzzics LTD
55
56 #include "PHY_Pro.h"
57
58
59 #include "KX_Scene.h"
60 #include "KX_GameObject.h"
61 #include "RAS_FramingManager.h"
62 #include "RAS_MeshObject.h"
63
64 #include "KX_ConvertActuators.h"
65 #include "KX_ConvertControllers.h"
66 #include "KX_ConvertSensors.h"
67
68 #include "SCA_LogicManager.h"
69 #include "SCA_EventManager.h"
70 #include "SCA_TimeEventManager.h"
71 #include "KX_Light.h"
72 #include "KX_Camera.h"
73 #include "KX_EmptyObject.h"
74 #include "MT_Point3.h"
75 #include "MT_Transform.h"
76 #include "MT_MinMax.h"
77 #include "SCA_IInputDevice.h"
78 #include "RAS_TexMatrix.h"
79 #include "RAS_ICanvas.h"
80 #include "RAS_MaterialBucket.h"
81 //#include "KX_BlenderPolyMaterial.h"
82 #include "RAS_Polygon.h"
83 #include "RAS_TexVert.h"
84 #include "RAS_BucketManager.h"
85 #include "RAS_IRenderTools.h"
86 #include "BL_Material.h"
87 #include "KX_BlenderMaterial.h"
88 #include "BL_Texture.h"
89
90 #include "DNA_action_types.h"
91 #include "BKE_main.h"
92 #include "BKE_global.h"
93 #include "BL_SkinMeshObject.h"
94 #include "BL_SkinDeformer.h"
95 #include "BL_MeshDeformer.h"
96 //#include "BL_ArmatureController.h"
97
98 #include "BlenderWorldInfo.h"
99
100 #include "KX_KetsjiEngine.h"
101 #include "KX_BlenderSceneConverter.h"
102
103 #include"SND_Scene.h"
104 #include "SND_SoundListener.h"
105
106 /* This little block needed for linking to Blender... */
107 #ifdef WIN32
108 #include "BLI_winstuff.h"
109 #endif
110
111 /* This list includes only data type definitions */
112 #include "DNA_object_types.h"
113 #include "DNA_material_types.h"
114 #include "DNA_texture_types.h"
115 #include "DNA_image_types.h"
116 #include "DNA_lamp_types.h"
117 #include "DNA_group_types.h"
118 #include "DNA_scene_types.h"
119 #include "DNA_camera_types.h"
120 #include "DNA_property_types.h"
121 #include "DNA_text_types.h"
122 #include "DNA_sensor_types.h"
123 #include "DNA_controller_types.h"
124 #include "DNA_actuator_types.h"
125 #include "DNA_mesh_types.h"
126 #include "DNA_meshdata_types.h"
127 #include "DNA_view3d_types.h"
128 #include "DNA_world_types.h"
129 #include "DNA_sound_types.h"
130 #include "DNA_key_types.h"
131 #include "DNA_armature_types.h"
132
133 #include "MEM_guardedalloc.h"
134 #include "BKE_utildefines.h"
135 #include "BKE_key.h"
136 #include "BKE_mesh.h"
137 #include "MT_Point3.h"
138
139
140 #include "BKE_material.h" /* give_current_material */
141 /* end of blender include block */
142
143 #include "KX_BlenderInputDevice.h"
144 #include "KX_ConvertProperties.h"
145 #include "KX_HashedPtr.h"
146
147
148 #include "KX_ScalarInterpolator.h"
149
150 #include "KX_IpoConvert.h"
151 #include "SYS_System.h"
152
153 #include "SG_Node.h"
154 #include "SG_BBox.h"
155 #include "SG_Tree.h"
156
157 // defines USE_ODE to choose physics engine
158 #include "KX_ConvertPhysicsObject.h"
159
160
161 // This file defines relationships between parents and children
162 // in the game engine.
163
164 #include "KX_SG_NodeRelationships.h"
165 #include "KX_SG_BoneParentNodeRelationship.h"
166
167 #include "BL_ArmatureObject.h"
168 #include "BL_DeformableGameObject.h"
169
170 #ifdef __cplusplus
171 extern "C" {
172 #endif
173 #include "BSE_headerbuttons.h"
174 void update_for_newframe();
175 //void scene_update_for_newframe(struct Scene *sce, unsigned int lay);
176 //#include "BKE_ipo.h"
177 //void do_all_data_ipos(void);
178 #ifdef __cplusplus
179 }
180 #endif
181
182 static int default_face_mode = TF_DYNAMIC;
183
184 static unsigned int KX_rgbaint2uint_new(unsigned int icol)
185 {
186         union
187         {
188                 unsigned int integer;
189                 unsigned char cp[4];
190         } out_colour, in_colour;
191         
192         in_colour.integer = icol;
193         out_colour.cp[0] = in_colour.cp[3]; // red
194         out_colour.cp[1] = in_colour.cp[2]; // green
195         out_colour.cp[2] = in_colour.cp[1]; // blue
196         out_colour.cp[3] = in_colour.cp[0]; // alpha
197         
198         return out_colour.integer;
199 }
200
201 /* Now the real converting starts... */
202 static unsigned int KX_Mcol2uint_new(MCol col)
203 {
204         /* color has to be converted without endian sensitivity. So no shifting! */
205         union
206         {
207                 MCol col;
208                 unsigned int integer;
209                 unsigned char cp[4];
210         } out_colour, in_colour;
211
212         in_colour.col = col;
213         out_colour.cp[0] = in_colour.cp[3]; // red
214         out_colour.cp[1] = in_colour.cp[2]; // green
215         out_colour.cp[2] = in_colour.cp[1]; // blue
216         out_colour.cp[3] = in_colour.cp[0]; // alpha
217         
218         return out_colour.integer;
219 }
220
221 static void SetDefaultFaceType(Scene* scene)
222 {
223         default_face_mode = TF_DYNAMIC;
224         Base *base = static_cast<Base*>(scene->base.first);
225         while(base)
226         {
227                 if (base->object->type == OB_LAMP)
228                 {
229                         default_face_mode = TF_DYNAMIC|TF_LIGHT;
230                         return;
231                 }
232                 base = base->next;
233         }
234 }
235
236
237 // --
238 static void GetRGB(short type,
239         MFace* mface,
240         MCol* mmcol,
241         Material *mat,
242         unsigned int &c0, 
243         unsigned int &c1, 
244         unsigned int &c2, 
245         unsigned int &c3)
246 {
247         unsigned int colour = 0xFFFFFFFFL;
248         switch(type)
249         {
250                 case 0: // vertex colors
251                 {
252                         if(mmcol) {
253                                 c0 = KX_Mcol2uint_new(mmcol[0]);
254                                 c1 = KX_Mcol2uint_new(mmcol[1]);
255                                 c2 = KX_Mcol2uint_new(mmcol[2]);
256                                 if (mface->v4)
257                                         c3 = KX_Mcol2uint_new(mmcol[3]);
258                         }else // backup white
259                         {
260                                 c0 = KX_rgbaint2uint_new(colour);
261                                 c1 = KX_rgbaint2uint_new(colour);
262                                 c2 = KX_rgbaint2uint_new(colour);       
263                                 if (mface->v4)
264                                         c3 = KX_rgbaint2uint_new( colour );
265                         }
266                 } break;
267                 
268         
269                 case 1: // material rgba
270                 {
271                         if (mat) {
272                                 union {
273                                         unsigned char cp[4];
274                                         unsigned int integer;
275                                 } col_converter;
276                                 col_converter.cp[3] = (unsigned char) (mat->r*255.0);
277                                 col_converter.cp[2] = (unsigned char) (mat->g*255.0);
278                                 col_converter.cp[1] = (unsigned char) (mat->b*255.0);
279                                 col_converter.cp[0] = (unsigned char) (mat->alpha*255.0);
280                                 colour = col_converter.integer;
281                         }
282                         c0 = KX_rgbaint2uint_new(colour);
283                         c1 = KX_rgbaint2uint_new(colour);
284                         c2 = KX_rgbaint2uint_new(colour);       
285                         if (mface->v4)
286                                 c3 = KX_rgbaint2uint_new(colour);
287                 } break;
288                 
289                 default: // white
290                 {
291                         c0 = KX_rgbaint2uint_new(colour);
292                         c1 = KX_rgbaint2uint_new(colour);
293                         c2 = KX_rgbaint2uint_new(colour);       
294                         if (mface->v4)
295                                 c3 = KX_rgbaint2uint_new(colour);
296                 } break;
297         }
298 }
299
300 // ------------------------------------
301 BL_Material* ConvertMaterial(  Mesh* mesh, Material *mat, MTFace* tface,  MFace* mface, MCol* mmcol, int lightlayer, Object* blenderobj )
302 {
303         //this needs some type of manager
304         BL_Material *material = new BL_Material();
305
306         int numchan =   -1;
307         bool validmat   = (mat!=0);
308         bool validface  = (mesh->mtface && tface);
309         
310         short type = 0;
311         if( validmat )
312                 type = 1; // material color 
313         
314         material->IdMode = DEFAULT_BLENDER;
315
316         // --------------------------------
317         if(validmat) {
318
319                 // use vertex colors by explicitly setting
320                 if(mat->mode &MA_VERTEXCOLP)
321                         type = 0;
322
323                 // use lighting?
324                 material->ras_mode |= ( mat->mode & MA_SHLESS )?0:USE_LIGHT;
325                 MTex *mttmp = 0;
326                 numchan = getNumTexChannels(mat);
327                 int valid_index = 0;
328                 
329                 // use the face texture if
330                 // 1) it is set in the buttons
331                 // 2) we have a face texture and a material but no valid texture in slot 1
332                 bool facetex = false;
333                 if(validface && mat->mode &MA_FACETEXTURE) 
334                         facetex = true;
335                 if(validface && !mat->mtex[0])
336                         facetex = true;
337                 if(validface && mat->mtex[0]) {
338                         MTex *tmp = mat->mtex[0];
339                         if(!tmp->tex || tmp->tex && !tmp->tex->ima )
340                                 facetex = true;
341                 }
342                 numchan = numchan>MAXTEX?MAXTEX:numchan;
343         
344                 // foreach MTex
345                 for(int i=0; i<numchan; i++) {
346                         // use face tex
347                         if(i==0 && facetex ) {
348                                 Image*tmp = (Image*)(tface->tpage);
349                                 if(tmp) {
350                                         material->img[i] = tmp;
351                                         material->texname[i] = material->img[i]->id.name;
352                                         material->flag[i] |= ( tface->transp  &TF_ALPHA )?USEALPHA:0;
353                                         material->flag[i] |= ( tface->transp  &TF_ADD   )?CALCALPHA:0;
354                                         material->ras_mode|= ( tface->transp  &(TF_ADD | TF_ALPHA))?TRANSP:0;
355                                         if(material->img[i]->flag & IMA_REFLECT)
356                                                 material->mapping[i].mapping |= USEREFL;
357                                         else
358                                                 material->mapping[i].mapping |= USEUV;
359                                         if(material->ras_mode & USE_LIGHT)
360                                                 material->ras_mode &= ~USE_LIGHT;
361                                         if(tface->mode & TF_LIGHT)
362                                                 material->ras_mode |= USE_LIGHT;
363
364                                         valid_index++;
365                                 }
366                                 else {
367                                         material->img[i] = 0;
368                                         material->texname[i] = "";
369                                 }
370                                 continue;
371                         }
372
373                         mttmp = getImageFromMaterial( mat, i );
374                         if( mttmp ) {
375                                 if( mttmp->tex ) {
376                                         if( mttmp->tex->type == TEX_IMAGE ) {
377                                                 material->mtexname[i] = mttmp->tex->id.name;
378                                                 material->img[i] = mttmp->tex->ima;
379                                                 if( material->img[i] ) {
380
381                                                         material->texname[i] = material->img[i]->id.name;
382                                                         material->flag[i] |= ( mttmp->tex->imaflag &TEX_MIPMAP )?MIPMAP:0;
383                                                         // -----------------------
384                                                         if( mttmp->tex->imaflag &TEX_USEALPHA ) {
385                                                                 material->flag[i]       |= USEALPHA;
386                                                         }
387                                                         // -----------------------
388                                                         else if( mttmp->tex->imaflag &TEX_CALCALPHA ) {
389                                                                 material->flag[i]       |= CALCALPHA;
390                                                         }
391                                                         else if(mttmp->tex->flag &TEX_NEGALPHA) {
392                                                                 material->flag[i]       |= USENEGALPHA;
393                                                         }
394
395                                                         material->color_blend[i] = mttmp->colfac;
396                                                         material->flag[i] |= ( mttmp->mapto  & MAP_ALPHA                )?TEXALPHA:0;
397                                                         material->flag[i] |= ( mttmp->texflag& MTEX_NEGATIVE    )?TEXNEG:0;
398
399                                                 }
400                                         }
401                                         else if(mttmp->tex->type == TEX_ENVMAP) {
402                                                 if( mttmp->tex->env->stype == ENV_LOAD ) {
403                                         
404                                                         material->mtexname[i]= mttmp->tex->id.name;
405                                                         material->cubemap[i] = mttmp->tex->env;
406                                                         if(material->cubemap[i]->ima) {
407                                                                 material->texname[i] = material->cubemap[i]->ima->id.name;
408                                                                 material->mapping[i].mapping |= USEENV;
409                                                         }
410                                                         else {
411                                                                 // in the player, we need to split it our self
412                                                                 material->cubemap[i]->ima = mttmp->tex->ima;
413                                                                 if(material->cubemap[i]->ima) {
414                                                                         material->texname[i] = material->cubemap[i]->ima->id.name;
415                                                                         material->mapping[i].mapping |= USEENV;
416                                                                 }
417                                                                 //
418                                                         }
419                                                 }
420                                         }
421                                         material->flag[i] |= (mat->ipo!=0)?HASIPO:0;
422                                         /// --------------------------------
423                                         // mapping methods
424                                         material->mapping[i].mapping |= ( mttmp->texco  & TEXCO_REFL    )?USEREFL:0;
425                                         
426                                         if(mttmp->texco & TEXCO_OBJECT) {
427                                                 material->mapping[i].mapping |= USEOBJ;
428                                                 if(mttmp->object)
429                                                         material->mapping[i].objconame = mttmp->object->id.name;
430                                         }
431                                         else if(mttmp->texco &TEXCO_REFL)
432                                                 material->mapping[i].mapping |= USEREFL;
433                                         else if(mttmp->texco &(TEXCO_ORCO|TEXCO_GLOB))
434                                                 material->mapping[i].mapping |= USEORCO;
435                                         else if(mttmp->texco &TEXCO_UV)
436                                                 material->mapping[i].mapping |= USEUV;
437                                         else if(mttmp->texco &TEXCO_NORM)
438                                                 material->mapping[i].mapping |= USENORM;
439                                         else if(mttmp->texco &TEXCO_TANGENT)
440                                                 material->mapping[i].mapping |= USETANG;
441                                         else
442                                                 material->mapping[i].mapping |= DISABLE;
443                                         
444                                         material->mapping[i].scale[0] = mttmp->size[0];
445                                         material->mapping[i].scale[1] = mttmp->size[1];
446                                         material->mapping[i].scale[2] = mttmp->size[2];
447                                         material->mapping[i].offsets[0] = mttmp->ofs[0];
448                                         material->mapping[i].offsets[1] = mttmp->ofs[1];
449                                         material->mapping[i].offsets[2] = mttmp->ofs[2];
450
451                                         material->mapping[i].projplane[0] = mttmp->projx;
452                                         material->mapping[i].projplane[1] = mttmp->projy;
453                                         material->mapping[i].projplane[2] = mttmp->projz;
454                                         /// --------------------------------
455                                         
456                                         switch( mttmp->blendtype ) {
457                                         case MTEX_BLEND:
458                                                 material->blend_mode[i] = BLEND_MIX;
459                                                 break;
460                                         case MTEX_MUL:
461                                                 material->blend_mode[i] = BLEND_MUL;
462                                                 break;
463                                         case MTEX_ADD:
464                                                 material->blend_mode[i] = BLEND_ADD;
465                                                 break;
466                                         case MTEX_SUB:
467                                                 material->blend_mode[i] = BLEND_SUB;
468                                                 break;
469                                         case MTEX_SCREEN:
470                                                 material->blend_mode[i] = BLEND_SCR;
471                                                 break;
472                                         }
473                                         valid_index++;
474                                 }
475                         }
476                 }
477                 // above one tex the switches here
478                 // are not used
479                 switch(valid_index) {
480                 case 0:
481                         material->IdMode = DEFAULT_BLENDER;
482                         break;
483                 case 1:
484                         material->IdMode = ONETEX;
485                         break;
486                 default:
487                         material->IdMode = GREATERTHAN2;
488                         break;
489                 }
490                 material->SetUsers(mat->id.us);
491
492                 material->num_enabled = valid_index;
493
494                 material->speccolor[0]  = mat->specr;
495                 material->speccolor[1]  = mat->specg;
496                 material->speccolor[2]  = mat->specb;
497                 material->hard                  = (float)mat->har/4.0f;
498                 material->matcolor[0]   = mat->r;
499                 material->matcolor[1]   = mat->g;
500                 material->matcolor[2]   = mat->b;
501                 material->matcolor[3]   = mat->alpha;
502                 material->alpha                 = mat->alpha;
503                 material->emit                  = mat->emit;
504                 material->spec_f                = mat->spec;
505                 material->ref                   = mat->ref;
506                 material->amb                   = mat->amb;
507
508                 // set alpha testing without z-sorting
509                 if( ( validface && (!tface->transp)) && mat->mode & MA_ZTRA) {
510                         // sets the RAS_IPolyMaterial::m_flag |RAS_FORCEALPHA
511                         // this is so we don't have the overhead of the z-sorting code
512                         material->ras_mode|=ALPHA_TEST;
513                 }
514                 else{
515                         // use regular z-sorting
516                         material->ras_mode |= ((mat->mode & MA_ZTRA) != 0)?ZSORT:0;
517                 }
518                 material->ras_mode |= ((mat->mode & MA_WIRE) != 0)?WIRE:0;
519         }
520         else {
521                 int valid = 0;
522                 // check for tface tex to fallback on
523                 if( validface ){
524
525                         // no light bugfix
526                         if(tface->mode) material->ras_mode |= USE_LIGHT;
527
528                         material->img[0] = (Image*)(tface->tpage);
529                         // ------------------------
530                         if(material->img[0]) {
531                                 material->texname[0] = material->img[0]->id.name;
532                                 material->mapping[0].mapping |= ( (material->img[0]->flag & IMA_REFLECT)!=0 )?USEREFL:0;
533                                 material->flag[0] |= ( tface->transp  &TF_ALPHA )?USEALPHA:0;
534                                 material->flag[0] |= ( tface->transp  &TF_ADD   )?CALCALPHA:0;
535                                 material->ras_mode|= ( tface->transp  & (TF_ADD|TF_ALPHA))?TRANSP:0;
536                                 valid++;
537                         }
538                 }
539                 material->SetUsers(-1);
540                 material->num_enabled   = valid;
541                 material->IdMode                = TEXFACE;
542                 material->speccolor[0]  = 1.f;
543                 material->speccolor[1]  = 1.f;
544                 material->speccolor[2]  = 1.f;
545                 material->hard                  = 35.f;
546                 material->matcolor[0]   = 0.5f;
547                 material->matcolor[1]   = 0.5f;
548                 material->matcolor[2]   = 0.5f;
549                 material->spec_f                = 0.5f;
550                 material->ref                   = 0.8f;
551         }
552         MT_Point2 uv[4];
553
554         if( validface ) {
555
556                 material->ras_mode |= !( 
557                         (tface->flag & TF_HIDE) ||
558                         (tface->mode & TF_INVISIBLE)
559                         )?POLY_VIS:0;
560
561                 material->ras_mode |= ( (tface->mode & TF_DYNAMIC)!= 0 )?COLLIDER:0;
562                 material->transp = tface->transp;
563                 
564                 if(tface->transp)
565                         material->ras_mode |= TRANSP;
566
567                 material->tile  = tface->tile;
568                 material->mode  = tface->mode;
569                         
570                 uv[0]   = MT_Point2(tface->uv[0]);
571                 uv[1]   = MT_Point2(tface->uv[1]);
572                 uv[2]   = MT_Point2(tface->uv[2]);
573
574                 if (mface->v4) 
575                         uv[3]   = MT_Point2(tface->uv[3]);
576         } 
577         else {
578                 // nothing at all
579                 material->ras_mode |= (COLLIDER|POLY_VIS| (validmat?0:USE_LIGHT));
580                 material->mode          = default_face_mode;    
581                 material->transp        = TF_SOLID;
582                 material->tile          = 0;
583         }
584         unsigned int rgb[4];
585         GetRGB(type,mface,mmcol,mat,rgb[0],rgb[1],rgb[2], rgb[3]);
586         material->SetConversionRGB(rgb);
587         material->SetConversionUV(uv);
588
589         material->ras_mode |= (mface->v4==0)?TRIANGLE:0;
590         if(validmat)
591                 material->matname       =(mat->id.name);
592
593         material->tface         = tface;
594         material->material      = mat;
595         return material;
596 }
597
598
599 static void BL_ComputeTriTangentSpace(const MT_Vector3 &v1, const MT_Vector3 &v2, const MT_Vector3 &v3, 
600         const MT_Vector2 &uv1, const MT_Vector2 &uv2, const MT_Vector2 &uv3, 
601         MFace* mface, MT_Vector3 *tan1, MT_Vector3 *tan2)
602 {
603                 MT_Vector3 dx1(v2 - v1), dx2(v3 - v1);
604                 MT_Vector2 duv1(uv2 - uv1), duv2(uv3 - uv1);
605                 
606                 MT_Scalar r = 1.0 / (duv1.x() * duv2.y() - duv2.x() * duv1.y());
607                 duv1 *= r;
608                 duv2 *= r;
609                 MT_Vector3 sdir(duv2.y() * dx1 - duv1.y() * dx2);
610                 MT_Vector3 tdir(duv1.x() * dx2 - duv2.x() * dx1);
611                 
612                 tan1[mface->v1] += sdir;
613                 tan1[mface->v2] += sdir;
614                 tan1[mface->v3] += sdir;
615                 
616                 tan2[mface->v1] += tdir;
617                 tan2[mface->v2] += tdir;
618                 tan2[mface->v3] += tdir;
619 }
620
621 static MT_Vector4*  BL_ComputeMeshTangentSpace(Mesh* mesh)
622 {
623         MFace* mface = static_cast<MFace*>(mesh->mface);
624         MTFace* tface = static_cast<MTFace*>(mesh->mtface);
625
626         MT_Vector3 *tan1 = new MT_Vector3[mesh->totvert];
627         MT_Vector3 *tan2 = new MT_Vector3[mesh->totvert];
628         
629         unsigned int v;
630         for (v = 0; v < mesh->totvert; v++)
631         {
632                 tan1[v] = MT_Vector3(0.0, 0.0, 0.0);
633                 tan2[v] = MT_Vector3(0.0, 0.0, 0.0);
634         }
635         
636         for (unsigned int p = 0; p < mesh->totface; p++, mface++, tface++)
637         {
638                 MT_Vector3      v1(mesh->mvert[mface->v1].co),
639                                 v2(mesh->mvert[mface->v2].co),
640                                 v3(mesh->mvert[mface->v3].co);
641                                 
642                 MT_Vector2      uv1(tface->uv[0]),
643                                 uv2(tface->uv[1]),
644                                 uv3(tface->uv[2]);
645                                 
646                 BL_ComputeTriTangentSpace(v1, v2, v3, uv1, uv2, uv3, mface, tan1, tan2);
647                 if (mface->v4)
648                 {
649                         MT_Vector3 v4(mesh->mvert[mface->v4].co);
650                         MT_Vector2 uv4(tface->uv[3]);
651                         
652                         BL_ComputeTriTangentSpace(v1, v3, v4, uv1, uv3, uv4, mface, tan1, tan2);
653                 }
654         }
655         
656         MT_Vector4 *tangent = new MT_Vector4[mesh->totvert];
657         for (v = 0; v < mesh->totvert; v++)
658         {
659                 const MT_Vector3 no(mesh->mvert[v].no[0]/32767.0, 
660                                         mesh->mvert[v].no[1]/32767.0, 
661                                         mesh->mvert[v].no[2]/32767.0);
662                 // Gram-Schmidt orthogonalize
663                 MT_Vector3 t(tan1[v] - no.cross(no.cross(tan1[v])));
664                 if (!MT_fuzzyZero(t))
665                         t /= t.length();
666
667                 tangent[v].x() = t.x();
668                 tangent[v].y() = t.y();
669                 tangent[v].z() = t.z();
670                 // Calculate handedness
671                 tangent[v].w() = no.dot(tan1[v].cross(tan2[v])) < 0.0 ? -1.0 : 1.0;
672         }
673         
674         delete [] tan1;
675         delete [] tan2;
676         
677         return tangent;
678 }
679
680 RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* rendertools, KX_Scene* scene, KX_BlenderSceneConverter *converter)
681 {
682         RAS_MeshObject *meshobj;
683         bool    skinMesh = false;
684         
685         int lightlayer = blenderobj->lay;
686         
687         MFace* mface = static_cast<MFace*>(mesh->mface);
688         MTFace* tface = static_cast<MTFace*>(mesh->mtface);
689         MCol* mmcol = mesh->mcol;
690         MT_assert(mface || mesh->totface == 0);
691         
692         // Determine if we need to make a skinned mesh
693         if (mesh->dvert){
694                 meshobj = new BL_SkinMeshObject(lightlayer);
695                 skinMesh = true;
696         }
697         else {
698                 meshobj = new RAS_MeshObject(lightlayer);
699         }
700         MT_Vector4 *tangent = 0;
701         if (tface)
702                 tangent = BL_ComputeMeshTangentSpace(mesh);
703         
704         meshobj->SetName(mesh->id.name);
705         
706         meshobj->m_xyz_index_to_vertex_index_mapping.resize(mesh->totvert);
707         
708         for (int f=0;f<mesh->totface;f++,mface++)
709         {
710                 
711                 bool collider = true;
712                 
713                 // only add valid polygons
714                 if (mface->v3)
715                 {
716                         MT_Point2 uv0(0.0,0.0),uv1(0.0,0.0),uv2(0.0,0.0),uv3(0.0,0.0);
717                         // rgb3 is set from the adjoint face in a square
718                         unsigned int rgb0,rgb1,rgb2,rgb3 = 0;
719                         MT_Vector3      no0(mesh->mvert[mface->v1].no[0], mesh->mvert[mface->v1].no[1], mesh->mvert[mface->v1].no[2]),
720                                         no1(mesh->mvert[mface->v2].no[0], mesh->mvert[mface->v2].no[1], mesh->mvert[mface->v2].no[2]),
721                                         no2(mesh->mvert[mface->v3].no[0], mesh->mvert[mface->v3].no[1], mesh->mvert[mface->v3].no[2]),
722                                         no3(0.0, 0.0, 0.0);
723                         MT_Point3       pt0(mesh->mvert[mface->v1].co),
724                                         pt1(mesh->mvert[mface->v2].co),
725                                         pt2(mesh->mvert[mface->v3].co),
726                                         pt3(0.0, 0.0, 0.0);
727                         MT_Vector4      tan0(0.0, 0.0, 0.0, 0.0),
728                                         tan1(0.0, 0.0, 0.0, 0.0),
729                                         tan2(0.0, 0.0, 0.0, 0.0),
730                                         tan3(0.0, 0.0, 0.0, 0.0);
731
732                         no0 /= 32767.0;
733                         no1 /= 32767.0;
734                         no2 /= 32767.0;
735                         if (mface->v4)
736                         {
737                                 pt3 = MT_Point3(mesh->mvert[mface->v4].co);
738                                 no3 = MT_Vector3(mesh->mvert[mface->v4].no[0], mesh->mvert[mface->v4].no[1], mesh->mvert[mface->v4].no[2]);
739                                 no3 /= 32767.0;
740                         }
741         
742                         if(!(mface->flag & ME_SMOOTH))
743                         {
744                                 MT_Vector3 norm = ((pt1-pt0).cross(pt2-pt0)).safe_normalized();
745                                 norm[0] = ((int) (10*norm[0]))/10.0;
746                                 norm[1] = ((int) (10*norm[1]))/10.0;
747                                 norm[2] = ((int) (10*norm[2]))/10.0;
748                                 no0=no1=no2=no3= norm;
749         
750                         }
751                 
752                         {
753                                 Material* ma = 0;
754                                 bool polyvisible = true;
755                                 RAS_IPolyMaterial* polymat = NULL;
756
757                                 if(converter->GetMaterials()) 
758                                 {       
759                                         if(mesh->totcol > 1)
760                                                 ma = mesh->mat[mface->mat_nr];
761                                         else 
762                                                 ma = give_current_material(blenderobj, 1);
763
764                                         BL_Material *bl_mat = ConvertMaterial(mesh, ma, tface, mface, mmcol, lightlayer, blenderobj);
765                                         // set the index were dealing with
766                                         bl_mat->material_index =  (int)mface->mat_nr;
767
768                                         polyvisible = ((bl_mat->ras_mode & POLY_VIS)!=0);
769                                         collider = ((bl_mat->ras_mode & COLLIDER)!=0);
770                                         
771                                         polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer, blenderobj );
772                                         converter->RegisterBlenderMaterial(bl_mat);
773                                         
774                                         unsigned int rgb[4];
775                                         bl_mat->GetConversionRGB(rgb);
776                                         rgb0 = rgb[0];
777                                         rgb1 = rgb[1];
778                                         rgb2 = rgb[2];
779                                         rgb3 = rgb[3];
780                                         MT_Point2 uv[4];
781                                         bl_mat->GetConversionUV(uv);
782                                         uv0 = uv[0];
783                                         uv1 = uv[1];
784                                         uv2 = uv[2];
785                                         uv3 = uv[3];
786                                         if(tangent){
787                                                 tan0 = tangent[mface->v1];
788                                                 tan1 = tangent[mface->v2];
789                                                 tan2 = tangent[mface->v3];
790                                                 if (mface->v4)
791                                                         tan3 = tangent[mface->v4];
792                                         }
793                                         // this is needed to free up memory afterwards
794                                         converter->RegisterPolyMaterial(polymat);
795                                 }
796                                 else
797                                 {
798                                         ma = give_current_material(blenderobj, 1);
799
800                                         Image* bima = ((mesh->mtface && tface) ? (Image*) tface->tpage : NULL);
801                 
802                                         STR_String imastr = 
803                                                 ((mesh->mtface && tface) ? 
804                                                 (bima? (bima)->id.name : "" ) : "" );
805                         
806                                         char transp=0;
807                                         short mode=0, tile=0;
808                                         int     tilexrep=4,tileyrep = 4;
809                                         
810                                         if (bima)
811                                         {
812                                                 tilexrep = bima->xrep;
813                                                 tileyrep = bima->yrep;
814                                 
815                                         }
816
817                                         if (mesh->mtface && tface)
818                                         {
819                                                 // Use texface colors if available
820                                                 //TF_DYNAMIC means the polygon is a collision face
821                                                 collider = ((tface->mode & TF_DYNAMIC) != 0);
822                                                 transp = tface->transp;
823                                                 tile = tface->tile;
824                                                 mode = tface->mode;
825                                                 
826                                                 polyvisible = !((tface->flag & TF_HIDE)||(tface->mode & TF_INVISIBLE));
827                                                 
828                                                 uv0 = MT_Point2(tface->uv[0]);
829                                                 uv1 = MT_Point2(tface->uv[1]);
830                                                 uv2 = MT_Point2(tface->uv[2]);
831                 
832                                                 if (mface->v4)
833                                                         uv3 = MT_Point2(tface->uv[3]);
834                                         } 
835                                         if (mmcol)
836                                         {
837                                                 // Use vertex colours
838                                                 rgb0 = KX_Mcol2uint_new(mmcol[0]);
839                                                 rgb1 = KX_Mcol2uint_new(mmcol[1]);
840                                                 rgb2 = KX_Mcol2uint_new(mmcol[2]);
841                                                 
842                                                 if (mface->v4)
843                                                         rgb3 = KX_Mcol2uint_new(mmcol[3]);
844                                         }
845                                         else
846                                         {
847                                                 // If there are no vertex colors OR texfaces,
848                                                 // Initialize face to white and set COLLSION true and everything else FALSE
849                                                 unsigned int colour = 0xFFFFFFFFL;
850                                                 mode = default_face_mode;       
851                                                 transp = TF_SOLID;
852                                                 tile = 0;
853                                                 if (ma)
854                                                 {
855                                                         // If we have a material, take the default colour from the material.
856                                                         union
857                                                         {
858                                                                 unsigned char cp[4];
859                                                                 unsigned int integer;
860                                                         } col_converter;
861                                                         
862                                                         col_converter.cp[3] = (unsigned char) (ma->r*255.0);
863                                                         col_converter.cp[2] = (unsigned char) (ma->g*255.0);
864                                                         col_converter.cp[1] = (unsigned char) (ma->b*255.0);
865                                                         col_converter.cp[0] = (unsigned char) (ma->alpha*255.0);
866                                                         
867                                                         colour = col_converter.integer;
868                                                 }
869                                                 
870                                                 rgb0 = KX_rgbaint2uint_new(colour);
871                                                 rgb1 = KX_rgbaint2uint_new(colour);
872                                                 rgb2 = KX_rgbaint2uint_new(colour);     
873                                                 
874                                                 if (mface->v4)
875                                                         rgb3 = KX_rgbaint2uint_new(colour);
876                                         }
877                                         
878                                         bool istriangle = (mface->v4==0);
879                                         bool zsort = ma?(ma->mode & MA_ZTRA) != 0:false;
880                                         
881                                         polymat = new KX_PolygonMaterial(imastr, ma,
882                                                 tile, tilexrep, tileyrep, 
883                                                 mode, transp, zsort, lightlayer, istriangle, blenderobj, tface, (unsigned int*)mmcol);
884                 
885                                         if (ma)
886                                         {
887                                                 polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec;
888                                                 polymat->m_shininess = (float)ma->har/4.0; // 0 < ma->har <= 512
889                                                 polymat->m_diffuse = MT_Vector3(ma->r, ma->g, ma->b)*(ma->emit + ma->ref);
890
891                                         } else
892                                         {
893                                                 polymat->m_specular = MT_Vector3(0.0f,0.0f,0.0f);
894                                                 polymat->m_shininess = 35.0;
895                                         }
896                                         // this is needed to free up memory afterwards
897                                         converter->RegisterPolyMaterial(polymat);
898
899                                 }
900         
901                                 RAS_MaterialBucket* bucket = scene->FindBucket(polymat);
902                                                          
903                                 int nverts = mface->v4?4:3;
904                                 int vtxarray = meshobj->FindVertexArray(nverts,polymat);
905                                 RAS_Polygon* poly = new RAS_Polygon(bucket,polyvisible,nverts,vtxarray);
906                                 if (skinMesh) {
907                                         int d1, d2, d3, d4=0;
908                                         bool flat;
909
910                                         /* If the face is set to solid, all fnors are the same */
911                                         if (mface->flag & ME_SMOOTH)
912                                                 flat = false;
913                                         else
914                                                 flat = true;
915                                         
916                                         d1=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v1, &mesh->dvert[mface->v1], polymat);
917                                         d2=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v2, &mesh->dvert[mface->v2], polymat);
918                                         d3=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v3, &mesh->dvert[mface->v3], polymat);
919                                         if (nverts==4)
920                                                 d4=((BL_SkinMeshObject*)meshobj)->FindOrAddDeform(vtxarray, mface->v4, &mesh->dvert[mface->v4], polymat);
921                                         poly->SetVertex(0,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt0,uv0,tan0,rgb0,no0,d1,flat, polymat));
922                                         poly->SetVertex(1,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt1,uv1,tan1,rgb1,no1,d2,flat, polymat));
923                                         poly->SetVertex(2,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt2,uv2,tan2,rgb2,no2,d3,flat, polymat));
924                                         if (nverts==4)
925                                                 poly->SetVertex(3,((BL_SkinMeshObject*)meshobj)->FindOrAddVertex(vtxarray,pt3,uv3,tan3,rgb3,no3,d4, flat,polymat));
926                                 }
927                                 else
928                                 {
929                                         poly->SetVertex(0,meshobj->FindOrAddVertex(vtxarray,pt0,uv0,tan0,rgb0,no0,polymat,mface->v1));
930                                         poly->SetVertex(1,meshobj->FindOrAddVertex(vtxarray,pt1,uv1,tan1,rgb1,no1,polymat,mface->v2));
931                                         poly->SetVertex(2,meshobj->FindOrAddVertex(vtxarray,pt2,uv2,tan2,rgb2,no2,polymat,mface->v3));
932                                         if (nverts==4)
933                                                 poly->SetVertex(3,meshobj->FindOrAddVertex(vtxarray,pt3,uv3,tan3,rgb3,no3,polymat,mface->v4));
934                                 }
935                                 meshobj->AddPolygon(poly);
936                                 if (poly->IsCollider())
937                                 {
938                                         RAS_TriangleIndex idx;
939                                         idx.m_index[0] = mface->v1;
940                                         idx.m_index[1] = mface->v2;
941                                         idx.m_index[2] = mface->v3;
942                                         idx.m_collider = collider;
943                                         meshobj->m_triangle_indices.push_back(idx);
944                                         if (nverts==4)
945                                         {
946                                         idx.m_index[0] = mface->v1;
947                                         idx.m_index[1] = mface->v3;
948                                         idx.m_index[2] = mface->v4;
949                                         idx.m_collider = collider;
950                                         meshobj->m_triangle_indices.push_back(idx);
951                                         }
952                                 }
953                                 
954 //                              poly->SetVisibleWireframeEdges(mface->edcode);
955                                 poly->SetCollider(collider);
956                         }
957                 }
958                 if (tface) 
959                         tface++;
960                 if (mmcol)
961                         mmcol+=4;
962         }
963         meshobj->UpdateMaterialList();
964
965
966
967         // -----------------------------------
968         // pre calculate texture generation
969         for(RAS_MaterialBucket::Set::iterator mit = meshobj->GetFirstMaterial();
970                 mit != meshobj->GetLastMaterial(); ++ mit) {
971                 (*mit)->GetPolyMaterial()->OnConstruction();
972         }
973
974         if(tangent)
975                 delete [] tangent;
976
977
978         return meshobj;
979 }
980
981         
982         
983 static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject,
984                                                                                                   KX_Scene *kxscene)
985 {
986         PHY_MaterialProps *materialProps = new PHY_MaterialProps;
987         
988         MT_assert(materialProps && "Create physics material properties failed");
989                 
990         Material* blendermat = give_current_material(blenderobject, 0);
991                 
992         if (blendermat)
993         {
994                 MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f);
995         
996                 materialProps->m_restitution = blendermat->reflect;
997                 materialProps->m_friction = blendermat->friction;
998                 materialProps->m_fh_spring = blendermat->fh;
999                 materialProps->m_fh_damping = blendermat->xyfrict;
1000                 materialProps->m_fh_distance = blendermat->fhdist;
1001                 materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0;
1002         }
1003         else {
1004                 //give some defaults
1005                 materialProps->m_restitution = 0.f;
1006                 materialProps->m_friction = 0.5;
1007                 materialProps->m_fh_spring = 0.f;
1008                 materialProps->m_fh_damping = 0.f;
1009                 materialProps->m_fh_distance = 0.f;
1010                 materialProps->m_fh_normal = false;
1011
1012         }
1013         
1014         return materialProps;
1015 }
1016
1017 static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject,
1018                                                                                                  KX_Scene *kxscene)
1019 {
1020         PHY_ShapeProps *shapeProps = new PHY_ShapeProps;
1021         
1022         MT_assert(shapeProps);
1023                 
1024         shapeProps->m_mass = blenderobject->mass;
1025         
1026 //  This needs to be fixed in blender. For now, we use:
1027         
1028 // in Blender, inertia stands for the size value which is equivalent to
1029 // the sphere radius
1030         shapeProps->m_inertia = blenderobject->formfactor;
1031         
1032         MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f);
1033         MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f);
1034         
1035         shapeProps->m_lin_drag = 1.0 - blenderobject->damping;
1036         shapeProps->m_ang_drag = 1.0 - blenderobject->rdamping;
1037         
1038         shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0]; 
1039         shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1];
1040         shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2];
1041         shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0);
1042         
1043         shapeProps->m_do_fh     = (blenderobject->gameflag & OB_DO_FH) != 0; 
1044         shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0;
1045         
1046         return shapeProps;
1047 }
1048
1049         
1050         
1051         
1052                 
1053 //////////////////////////////////////////////////////////
1054         
1055
1056
1057 static float my_boundbox_mesh(Mesh *me, float *loc, float *size)
1058 {
1059         MVert *mvert;
1060         BoundBox *bb;
1061         MT_Point3 min, max;
1062         float mloc[3], msize[3];
1063         int a;
1064         
1065         if(me->bb==0) me->bb= (struct BoundBox *)MEM_callocN(sizeof(BoundBox), "boundbox");
1066         bb= me->bb;
1067         
1068         INIT_MINMAX(min, max);
1069
1070         if (!loc) loc= mloc;
1071         if (!size) size= msize;
1072         
1073         mvert= me->mvert;
1074         for(a=0; a<me->totvert; a++, mvert++) {
1075                 DO_MINMAX(mvert->co, min, max);
1076         }
1077                 
1078         if(me->totvert) {
1079                 loc[0]= (min[0]+max[0])/2.0;
1080                 loc[1]= (min[1]+max[1])/2.0;
1081                 loc[2]= (min[2]+max[2])/2.0;
1082                 
1083                 size[0]= (max[0]-min[0])/2.0;
1084                 size[1]= (max[1]-min[1])/2.0;
1085                 size[2]= (max[2]-min[2])/2.0;
1086         }
1087         else {
1088                 loc[0]= loc[1]= loc[2]= 0.0;
1089                 size[0]= size[1]= size[2]= 0.0;
1090         }
1091                 
1092         bb->vec[0][0]=bb->vec[1][0]=bb->vec[2][0]=bb->vec[3][0]= loc[0]-size[0];
1093         bb->vec[4][0]=bb->vec[5][0]=bb->vec[6][0]=bb->vec[7][0]= loc[0]+size[0];
1094                 
1095         bb->vec[0][1]=bb->vec[1][1]=bb->vec[4][1]=bb->vec[5][1]= loc[1]-size[1];
1096         bb->vec[2][1]=bb->vec[3][1]=bb->vec[6][1]=bb->vec[7][1]= loc[1]+size[1];
1097
1098         bb->vec[0][2]=bb->vec[3][2]=bb->vec[4][2]=bb->vec[7][2]= loc[2]-size[2];
1099         bb->vec[1][2]=bb->vec[2][2]=bb->vec[5][2]=bb->vec[6][2]= loc[2]+size[2];
1100
1101         float radius = 0;
1102         for (a=0, mvert = me->mvert; a < me->totvert; a++, mvert++)
1103         {
1104                 float vert_radius = MT_Vector3(mvert->co).length2();
1105                 if (vert_radius > radius)
1106                         radius = vert_radius;
1107         } 
1108         return sqrt(radius);
1109 }
1110                 
1111
1112
1113
1114 static void my_tex_space_mesh(Mesh *me)
1115                 {
1116         KeyBlock *kb;
1117         float *fp, loc[3], size[3], min[3], max[3];
1118         int a;
1119
1120         my_boundbox_mesh(me, loc, size);
1121         
1122         if(me->texflag & AUTOSPACE) {
1123                 if(me->key) {
1124                         kb= me->key->refkey;
1125                         if (kb) {
1126         
1127                                 INIT_MINMAX(min, max);
1128                 
1129                                 fp= (float *)kb->data;
1130                                 for(a=0; a<kb->totelem; a++, fp+=3) {   
1131                                         DO_MINMAX(fp, min, max);
1132                                 }
1133                                 if(kb->totelem) {
1134                                         loc[0]= (min[0]+max[0])/2.0; loc[1]= (min[1]+max[1])/2.0; loc[2]= (min[2]+max[2])/2.0;
1135                                         size[0]= (max[0]-min[0])/2.0; size[1]= (max[1]-min[1])/2.0; size[2]= (max[2]-min[2])/2.0;
1136         } 
1137         else {
1138                                         loc[0]= loc[1]= loc[2]= 0.0;
1139                                         size[0]= size[1]= size[2]= 0.0;
1140                                 }
1141                                 
1142                         }
1143                                 }
1144         
1145                 VECCOPY(me->loc, loc);
1146                 VECCOPY(me->size, size);
1147                 me->rot[0]= me->rot[1]= me->rot[2]= 0.0;
1148         
1149                 if(me->size[0]==0.0) me->size[0]= 1.0;
1150                 else if(me->size[0]>0.0 && me->size[0]<0.00001) me->size[0]= 0.00001;
1151                 else if(me->size[0]<0.0 && me->size[0]> -0.00001) me->size[0]= -0.00001;
1152         
1153                 if(me->size[1]==0.0) me->size[1]= 1.0;
1154                 else if(me->size[1]>0.0 && me->size[1]<0.00001) me->size[1]= 0.00001;
1155                 else if(me->size[1]<0.0 && me->size[1]> -0.00001) me->size[1]= -0.00001;
1156                                                 
1157                 if(me->size[2]==0.0) me->size[2]= 1.0;
1158                 else if(me->size[2]>0.0 && me->size[2]<0.00001) me->size[2]= 0.00001;
1159                 else if(me->size[2]<0.0 && me->size[2]> -0.00001) me->size[2]= -0.00001;
1160         }
1161         
1162 }
1163
1164 static void my_get_local_bounds(Object *ob, float *centre, float *size)
1165 {
1166         BoundBox *bb= NULL;
1167         /* uses boundbox, function used by Ketsji */
1168         switch (ob->type)
1169         {
1170                 case OB_MESH:
1171                         bb= ( (Mesh *)ob->data )->bb;
1172                         if(bb==0) 
1173                         {
1174                                 my_tex_space_mesh((struct Mesh *)ob->data);
1175                                 bb= ( (Mesh *)ob->data )->bb;
1176                         }
1177                         break;
1178                 case OB_CURVE:
1179                 case OB_SURF:
1180                 case OB_FONT:
1181                         centre[0]= centre[1]= centre[2]= 0.0;
1182                         size[0]  = size[1]=size[2]=0.0;
1183                         break;
1184                 case OB_MBALL:
1185                         bb= ob->bb;
1186                         break;
1187         }
1188         
1189         if(bb==NULL) 
1190         {
1191                 centre[0]= centre[1]= centre[2]= 0.0;
1192                 size[0] = size[1]=size[2]=1.0;
1193         }
1194         else 
1195         {
1196                 size[0]= 0.5*fabs(bb->vec[0][0] - bb->vec[4][0]);
1197                 size[1]= 0.5*fabs(bb->vec[0][1] - bb->vec[2][1]);
1198                 size[2]= 0.5*fabs(bb->vec[0][2] - bb->vec[1][2]);
1199                                         
1200                 centre[0]= 0.5*(bb->vec[0][0] + bb->vec[4][0]);
1201                 centre[1]= 0.5*(bb->vec[0][1] + bb->vec[2][1]);
1202                 centre[2]= 0.5*(bb->vec[0][2] + bb->vec[1][2]);
1203         }
1204 }
1205         
1206
1207
1208
1209 //////////////////////////////////////////////////////
1210
1211
1212
1213
1214
1215 void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj,
1216                                                  struct Object* blenderobject,
1217                                                  RAS_MeshObject* meshobj,
1218                                                  KX_Scene* kxscene,
1219                                                  int activeLayerBitInfo,
1220                                                  e_PhysicsEngine        physics_engine,
1221                                                  KX_BlenderSceneConverter *converter,
1222                                                  bool processCompoundChildren
1223                                                  )
1224                                         
1225 {
1226         //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
1227         //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0);
1228         //bool bRigidBody = (userigidbody == 0);
1229
1230         // get Root Parent of blenderobject
1231         struct Object* parent= blenderobject->parent;
1232         while(parent && parent->parent) {
1233                 parent= parent->parent;
1234         }
1235
1236         bool isCompoundChild = false;
1237
1238         if (parent && (parent->gameflag & OB_DYNAMIC)) {
1239                 
1240                 if ((parent->gameflag & OB_CHILD) != 0)
1241                 {
1242                         isCompoundChild = true;
1243                 } 
1244         }
1245         if (processCompoundChildren != isCompoundChild)
1246                 return;
1247
1248
1249         PHY_ShapeProps* shapeprops =
1250                         CreateShapePropsFromBlenderObject(blenderobject, 
1251                         kxscene);
1252
1253         
1254         PHY_MaterialProps* smmaterial = 
1255                 CreateMaterialFromBlenderObject(blenderobject, kxscene);
1256                                         
1257         KX_ObjectProperties objprop;
1258
1259         objprop.m_isCompoundChild = isCompoundChild;
1260         objprop.m_hasCompoundChildren = (blenderobject->gameflag & OB_CHILD) != 0;
1261
1262         if ((objprop.m_isactor = (blenderobject->gameflag & OB_ACTOR)!=0))
1263         {
1264                 objprop.m_dyna = (blenderobject->gameflag & OB_DYNAMIC) != 0;
1265                 objprop.m_angular_rigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0;
1266                 objprop.m_ghost = (blenderobject->gameflag & OB_GHOST) != 0;
1267                 objprop.m_disableSleeping = (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0;//abuse the OB_COLLISION_RESPONSE flag
1268         } else {
1269                 objprop.m_dyna = false;
1270                 objprop.m_angular_rigidbody = false;
1271                 objprop.m_ghost = false;
1272                 objprop.m_disableSleeping = false;
1273         }
1274         //mmm, for now, taks this for the size of the dynamicobject
1275         // Blender uses inertia for radius of dynamic object
1276         objprop.m_radius = blenderobject->inertia;
1277         objprop.m_in_active_layer = (blenderobject->lay & activeLayerBitInfo) != 0;
1278         objprop.m_dynamic_parent=NULL;
1279         objprop.m_isdeformable = ((blenderobject->gameflag2 & 2)) != 0;
1280         objprop.m_boundclass = objprop.m_dyna?KX_BOUNDSPHERE:KX_BOUNDMESH;
1281         KX_BoxBounds bb;
1282         my_get_local_bounds(blenderobject,objprop.m_boundobject.box.m_center,bb.m_extends);
1283         if (blenderobject->gameflag & OB_BOUNDS)
1284         {
1285                 switch (blenderobject->boundtype)
1286                 {
1287                         case OB_BOUND_BOX:
1288                                 objprop.m_boundclass = KX_BOUNDBOX;
1289                                 //mmm, has to be divided by 2 to be proper extends
1290                                 objprop.m_boundobject.box.m_extends[0]=2.f*bb.m_extends[0];
1291                                 objprop.m_boundobject.box.m_extends[1]=2.f*bb.m_extends[1];
1292                                 objprop.m_boundobject.box.m_extends[2]=2.f*bb.m_extends[2];
1293                                 break;
1294                         case OB_BOUND_POLYT:
1295                                 if (blenderobject->type == OB_MESH)
1296                                 {
1297                                         objprop.m_boundclass = KX_BOUNDPOLYTOPE;
1298                                         break;
1299                                 }
1300                                 // Object is not a mesh... fall through OB_BOUND_POLYH to 
1301                                 // OB_BOUND_SPHERE
1302                         case OB_BOUND_POLYH:
1303                                 if (blenderobject->type == OB_MESH)
1304                                 {
1305                                         objprop.m_boundclass = KX_BOUNDMESH;
1306                                         break;
1307                                 }
1308                                 // Object is not a mesh... can't use polyheder. 
1309                                 // Fall through and become a sphere.
1310                         case OB_BOUND_SPHERE:
1311                         {
1312                                 objprop.m_boundclass = KX_BOUNDSPHERE;
1313                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], MT_max(bb.m_extends[1], bb.m_extends[2]));
1314                                 break;
1315                         }
1316                         case OB_BOUND_CYLINDER:
1317                         {
1318                                 objprop.m_boundclass = KX_BOUNDCYLINDER;
1319                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1320                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1321                                 break;
1322                         }
1323                         case OB_BOUND_CONE:
1324                         {
1325                                 objprop.m_boundclass = KX_BOUNDCONE;
1326                                 objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], bb.m_extends[1]);
1327                                 objprop.m_boundobject.c.m_height = 2.f*bb.m_extends[2];
1328                                 break;
1329                         }
1330                 }
1331         }
1332
1333         
1334         if (parent && (parent->gameflag & OB_DYNAMIC)) {
1335                 
1336                 KX_GameObject *parentgameobject = converter->FindGameObject(parent);
1337                 objprop.m_dynamic_parent = parentgameobject;
1338                 //cannot be dynamic:
1339                 objprop.m_dyna = false;
1340                 shapeprops->m_mass = 0.f;
1341         }
1342
1343         
1344         objprop.m_concave = (blenderobject->boundtype & 4) != 0;
1345         
1346         switch (physics_engine)
1347         {
1348 #ifdef USE_BULLET
1349                 case UseBullet:
1350                         KX_ConvertBulletObject(gameobj, meshobj, kxscene, shapeprops, smmaterial, &objprop);
1351                         break;
1352
1353 #endif
1354 #ifdef USE_SUMO_SOLID
1355                 case UseSumo:
1356                         KX_ConvertSumoObject(gameobj, meshobj, kxscene, shapeprops, smmaterial, &objprop);
1357                         break;
1358 #endif
1359                         
1360 #ifdef USE_ODE
1361                 case UseODE:
1362                         KX_ConvertODEEngineObject(gameobj, meshobj, kxscene, shapeprops, smmaterial, &objprop);
1363                         break;
1364 #endif //USE_ODE
1365
1366                 case UseDynamo:
1367                         //KX_ConvertDynamoObject(gameobj,meshobj,kxscene,shapeprops,    smmaterial,     &objprop);
1368                         break;
1369                         
1370                 case UseNone:
1371                 default:
1372                         break;
1373         }
1374
1375 }
1376
1377
1378
1379
1380
1381 static KX_LightObject *gamelight_from_blamp(Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRenderTools *rendertools, KX_BlenderSceneConverter *converter) {
1382         RAS_LightObject lightobj;
1383         KX_LightObject *gamelight;
1384         
1385         lightobj.m_att1 = la->att1;
1386         lightobj.m_att2 = (la->mode & LA_QUAD)?la->att2:0.0;
1387         lightobj.m_red = la->r;
1388         lightobj.m_green = la->g;
1389         lightobj.m_blue = la->b;
1390         lightobj.m_distance = la->dist;
1391         lightobj.m_energy = la->energy;
1392         lightobj.m_layer = layerflag;
1393         lightobj.m_spotblend = la->spotblend;
1394         lightobj.m_spotsize = la->spotsize;
1395         
1396         lightobj.m_nodiffuse = (la->mode & LA_NO_DIFF) != 0;
1397         lightobj.m_nospecular = (la->mode & LA_NO_SPEC) != 0;
1398         
1399         if (la->mode & LA_NEG)
1400         {
1401                 lightobj.m_red = -lightobj.m_red;
1402                 lightobj.m_green = -lightobj.m_green;
1403                 lightobj.m_blue = -lightobj.m_blue;
1404         }
1405                 
1406         if (la->type==LA_SUN) {
1407                 lightobj.m_type = RAS_LightObject::LIGHT_SUN;
1408         } else if (la->type==LA_SPOT) {
1409                 lightobj.m_type = RAS_LightObject::LIGHT_SPOT;
1410         } else {
1411                 lightobj.m_type = RAS_LightObject::LIGHT_NORMAL;
1412         }
1413         
1414         gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, lightobj);
1415         BL_ConvertLampIpos(la, gamelight, converter);
1416         
1417         return gamelight;
1418 }
1419
1420 static KX_Camera *gamecamera_from_bcamera(Camera *ca, KX_Scene *kxscene, KX_BlenderSceneConverter *converter) {
1421         RAS_CameraData camdata(ca->lens, ca->clipsta, ca->clipend, ca->type == CAM_PERSP);
1422         KX_Camera *gamecamera;
1423         
1424         gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata);
1425         gamecamera->SetName(ca->id.name + 2);
1426         
1427         BL_ConvertCameraIpos(ca, gamecamera, converter);
1428         
1429         return gamecamera;
1430 }
1431
1432 static KX_GameObject *gameobject_from_blenderobject(
1433                                                                 Object *ob, 
1434                                                                 KX_Scene *kxscene, 
1435                                                                 RAS_IRenderTools *rendertools, 
1436                                                                 KX_BlenderSceneConverter *converter,
1437                                                                 Scene *blenderscene) 
1438 {
1439         KX_GameObject *gameobj = NULL;
1440         
1441         switch(ob->type)
1442         {
1443         case OB_LAMP:
1444         {
1445                 KX_LightObject* gamelight= gamelight_from_blamp(static_cast<Lamp*>(ob->data), ob->lay, kxscene, rendertools, converter);
1446                 gameobj = gamelight;
1447                 
1448                 gamelight->AddRef();
1449                 kxscene->GetLightList()->Add(gamelight);
1450                 
1451                 break;
1452         }
1453         
1454         case OB_CAMERA:
1455         {
1456                 KX_Camera* gamecamera = gamecamera_from_bcamera(static_cast<Camera*>(ob->data), kxscene, converter);
1457                 gameobj = gamecamera;
1458                 
1459                 gamecamera->AddRef();
1460                 kxscene->AddCamera(gamecamera);
1461                 
1462                 break;
1463         }
1464         
1465         case OB_MESH:
1466         {
1467                 Mesh* mesh = static_cast<Mesh*>(ob->data);
1468                 RAS_MeshObject* meshobj = converter->FindGameMesh(mesh, ob->lay);
1469                 float centre[3], extents[3];
1470                 float radius = my_boundbox_mesh((Mesh*) ob->data, centre, extents);
1471                 
1472                 if (!meshobj) {
1473                         meshobj = BL_ConvertMesh(mesh,ob,rendertools,kxscene,converter);
1474                         converter->RegisterGameMesh(meshobj, mesh);
1475                 }
1476                 
1477                 // needed for python scripting
1478                 kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1479         
1480                 gameobj = new BL_DeformableGameObject(kxscene,KX_Scene::m_callbacks);
1481         
1482                 // set transformation
1483                 gameobj->AddMesh(meshobj);
1484         
1485                 // for all objects: check whether they want to
1486                 // respond to updates
1487                 bool ignoreActivityCulling =  
1488                         ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0);
1489                 gameobj->SetIgnoreActivityCulling(ignoreActivityCulling);
1490         
1491                 //      If this is a skin object, make Skin Controller
1492                 if (ob->parent && ob->parent->type == OB_ARMATURE && ob->partype==PARSKEL && ((Mesh*)ob->data)->dvert){
1493                         BL_SkinDeformer *dcont = new BL_SkinDeformer(ob, (BL_SkinMeshObject*)meshobj );                         
1494                         ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
1495                 }
1496                 else if (((Mesh*)ob->data)->dvert){
1497                         BL_MeshDeformer *dcont = new BL_MeshDeformer(ob, (BL_SkinMeshObject*)meshobj );
1498                         ((BL_DeformableGameObject*)gameobj)->m_pDeformer = dcont;
1499                 }
1500                 
1501                 MT_Point3 min = MT_Point3(centre) - MT_Vector3(extents);
1502                 MT_Point3 max = MT_Point3(centre) + MT_Vector3(extents);
1503                 SG_BBox bbox = SG_BBox(min, max);
1504                 gameobj->GetSGNode()->SetBBox(bbox);
1505                 gameobj->GetSGNode()->SetRadius(radius);
1506         
1507                 break;
1508         }
1509         
1510         case OB_ARMATURE:
1511         {
1512                 gameobj = new BL_ArmatureObject(
1513                         kxscene,
1514                         KX_Scene::m_callbacks,
1515                         ob // handle
1516                 );
1517                 /* Get the current pose from the armature object and apply it as the rest pose */
1518                 break;
1519         }
1520         
1521         case OB_EMPTY:
1522         {
1523                 gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks);
1524                 // set transformation
1525                 break;
1526         }
1527         }
1528         
1529         return gameobj;
1530 }
1531
1532 struct parentChildLink {
1533         struct Object* m_blenderchild;
1534         SG_Node* m_gamechildnode;
1535 };
1536
1537         /**
1538          * Find the specified scene by name, or the first
1539          * scene if nothing matches (shouldn't happen).
1540          */
1541 static struct Scene *GetSceneForName(struct Main *maggie, const STR_String& scenename) {
1542         Scene *sce;
1543
1544         for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next)
1545                 if (scenename == (sce->id.name+2))
1546                         return sce;
1547
1548         return (Scene*) maggie->scene.first;
1549 }
1550
1551 #include "DNA_constraint_types.h"
1552 #include "BIF_editconstraint.h"
1553
1554 bPoseChannel *get_active_posechannel2 (Object *ob)
1555 {
1556         bArmature *arm= (bArmature*)ob->data;
1557         bPoseChannel *pchan;
1558         
1559         /* find active */
1560         for(pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1561                 if(pchan->bone && (pchan->bone->flag & BONE_ACTIVE) && (pchan->bone->layer & arm->layer))
1562                         return pchan;
1563         }
1564         
1565         return NULL;
1566 }
1567
1568 ListBase *get_active_constraints2(Object *ob)
1569 {
1570         if (!ob)
1571                 return NULL;
1572
1573         if (ob->flag & OB_POSEMODE) {
1574                 bPoseChannel *pchan;
1575
1576                 pchan = get_active_posechannel2(ob);
1577                 if (pchan)
1578                         return &pchan->constraints;
1579         }
1580         else 
1581                 return &ob->constraints;
1582
1583         return NULL;
1584 }
1585
1586
1587 void RBJconstraints(Object *ob)//not used
1588 {
1589         ListBase *conlist;
1590         bConstraint *curcon;
1591
1592         conlist = get_active_constraints2(ob);
1593
1594         if (conlist) {
1595                 for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
1596
1597                         printf("%i\n",curcon->type);
1598                 }
1599
1600
1601         }
1602 }
1603
1604 #include "PHY_IPhysicsEnvironment.h"
1605 #include "KX_IPhysicsController.h"
1606 #include "PHY_DynamicTypes.h"
1607
1608 KX_IPhysicsController* getPhId(CListValue* sumolist,STR_String busc){//not used
1609
1610     for (int j=0;j<sumolist->GetCount();j++)
1611         {
1612             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1613             if (gameobje->GetName()==busc)
1614             return gameobje->GetPhysicsController();
1615         }
1616
1617         return 0;
1618
1619 }
1620
1621 KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist){
1622
1623     for (int j=0;j<sumolist->GetCount();j++)
1624         {
1625             KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j);
1626             if (gameobje->GetName()==busc)
1627             return gameobje;
1628         }
1629         
1630         return 0;
1631
1632 }
1633 #include "BLI_arithb.h"
1634 // convert blender objects into ketsji gameobjects
1635 void BL_ConvertBlenderObjects(struct Main* maggie,
1636                                                           const STR_String& scenename,
1637                                                           KX_Scene* kxscene,
1638                                                           KX_KetsjiEngine* ketsjiEngine,
1639                                                           e_PhysicsEngine       physics_engine,
1640                                                           PyObject* pythondictionary,
1641                                                           SCA_IInputDevice* keydev,
1642                                                           RAS_IRenderTools* rendertools,
1643                                                           RAS_ICanvas* canvas,
1644                                                           KX_BlenderSceneConverter* converter,
1645                                                           bool alwaysUseExpandFraming
1646                                                           )
1647 {       
1648
1649         Scene *blenderscene = GetSceneForName(maggie, scenename);
1650
1651         // Get the frame settings of the canvas.
1652         // Get the aspect ratio of the canvas as designed by the user.
1653
1654         RAS_FrameSettings::RAS_FrameType frame_type;
1655         int aspect_width;
1656         int aspect_height;
1657         vector<MT_Vector3> inivel,iniang;
1658         
1659         if (alwaysUseExpandFraming) {
1660                 frame_type = RAS_FrameSettings::e_frame_extend;
1661                 aspect_width = canvas->GetWidth();
1662                 aspect_height = canvas->GetHeight();
1663         } else {
1664                 if (blenderscene->framing.type == SCE_GAMEFRAMING_BARS) {
1665                         frame_type = RAS_FrameSettings::e_frame_bars;
1666                 } else if (blenderscene->framing.type == SCE_GAMEFRAMING_EXTEND) {
1667                         frame_type = RAS_FrameSettings::e_frame_extend;
1668                 } else {
1669                         frame_type = RAS_FrameSettings::e_frame_scale;
1670                 }
1671                 
1672                 aspect_width = blenderscene->r.xsch;
1673                 aspect_height = blenderscene->r.ysch;
1674         }
1675         
1676         RAS_FrameSettings frame_settings(
1677                 frame_type,
1678                 blenderscene->framing.col[0],
1679                 blenderscene->framing.col[1],
1680                 blenderscene->framing.col[2],
1681                 aspect_width,
1682                 aspect_height
1683         );
1684         kxscene->SetFramingType(frame_settings);
1685
1686         kxscene->SetGravity(MT_Vector3(0,0,(blenderscene->world != NULL) ? -blenderscene->world->gravity : -9.8));
1687         
1688         /* set activity culling parameters */
1689         if (blenderscene->world) {
1690                 kxscene->SetActivityCulling( (blenderscene->world->mode & WO_ACTIVITY_CULLING) != 0);
1691                 kxscene->SetActivityCullingRadius(blenderscene->world->activityBoxRadius);
1692         } else {
1693                 kxscene->SetActivityCulling(false);
1694         }
1695         
1696         int activeLayerBitInfo = blenderscene->lay;
1697         
1698         // templist to find Root Parents (object with no parents)
1699         CListValue* templist = new CListValue();
1700         CListValue*     sumolist = new CListValue();
1701         
1702         vector<parentChildLink> vec_parent_child;
1703         
1704         CListValue* objectlist = kxscene->GetObjectList();
1705         CListValue* parentlist = kxscene->GetRootParentList();
1706         
1707         SCA_LogicManager* logicmgr = kxscene->GetLogicManager();
1708         SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager();
1709         
1710         CListValue* logicbrick_conversionlist = new CListValue();
1711         
1712         SG_TreeFactory tf;
1713         
1714         // Convert actions to actionmap
1715         bAction *curAct;
1716         for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next)
1717         {
1718                 logicmgr->RegisterActionName(curAct->id.name, curAct);
1719         }
1720
1721         SetDefaultFaceType(blenderscene);
1722         
1723         Base *base = static_cast<Base*>(blenderscene->base.first);
1724         while(base)
1725         {
1726                 Object* blenderobject = base->object;
1727                 KX_GameObject* gameobj = gameobject_from_blenderobject(
1728                                                                                 base->object, 
1729                                                                                 kxscene, 
1730                                                                                 rendertools, 
1731                                                                                 converter,
1732                                                                                 blenderscene);
1733                                                                                         
1734                 if (gameobj)
1735                 {
1736                         MT_Point3 posPrev;                      
1737                         MT_Matrix3x3 angor;                     
1738                         if (converter->addInitFromFrame) blenderscene->r.cfra=blenderscene->r.sfra;
1739                         
1740                         MT_Point3 pos = MT_Point3(
1741                                 blenderobject->loc[0]+blenderobject->dloc[0],
1742                                 blenderobject->loc[1]+blenderobject->dloc[1],
1743                                 blenderobject->loc[2]+blenderobject->dloc[2]
1744                         );
1745                         MT_Vector3 eulxyz = MT_Vector3(
1746                                 blenderobject->rot[0],
1747                                 blenderobject->rot[1],
1748                                 blenderobject->rot[2]
1749                         );
1750                         MT_Vector3 scale = MT_Vector3(
1751                                 blenderobject->size[0],
1752                                 blenderobject->size[1],
1753                                 blenderobject->size[2]
1754                         );
1755                         if (converter->addInitFromFrame){//rcruiz
1756                                 float eulxyzPrev[3];
1757                                 blenderscene->r.cfra=blenderscene->r.sfra-1;
1758                                 update_for_newframe();
1759                                 MT_Vector3 tmp=pos-MT_Point3(blenderobject->loc[0]+blenderobject->dloc[0],
1760                                                                                         blenderobject->loc[1]+blenderobject->dloc[1],
1761                                                                                         blenderobject->loc[2]+blenderobject->dloc[2]
1762                                                                         );
1763                                 eulxyzPrev[0]=blenderobject->rot[0];
1764                                 eulxyzPrev[1]=blenderobject->rot[1];
1765                                 eulxyzPrev[2]=blenderobject->rot[2];
1766                                 tmp.scale((float)blenderscene->r.frs_sec,(float)blenderscene->r.frs_sec,(float)blenderscene->r.frs_sec);
1767                                 inivel.push_back(tmp);
1768                                 tmp=eulxyz-eulxyzPrev;
1769                                 tmp.scale((float)blenderscene->r.frs_sec,(float)blenderscene->r.frs_sec,(float)blenderscene->r.frs_sec);
1770                                 iniang.push_back(tmp);
1771                                 blenderscene->r.cfra=blenderscene->r.sfra;
1772                                 update_for_newframe();
1773                         }               
1774                                                 
1775                         gameobj->NodeSetLocalPosition(pos);
1776                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
1777                         gameobj->NodeSetLocalScale(scale);
1778                         gameobj->NodeUpdateGS(0,true);
1779                         
1780                         BL_ConvertIpos(blenderobject,gameobj,converter);
1781                         // TODO: expand to multiple ipos per mesh
1782                         Material *mat = give_current_material(blenderobject, 1);
1783                         if(mat) BL_ConvertMaterialIpos(mat, gameobj, converter);        
1784         
1785                         bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0;
1786         
1787                         sumolist->Add(gameobj->AddRef());
1788                         
1789                         BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer);
1790                         
1791         
1792                         gameobj->SetName(blenderobject->id.name);
1793         
1794                         // templist to find Root Parents (object with no parents)
1795                         templist->Add(gameobj->AddRef());
1796                         
1797                         // update children/parent hierarchy
1798                         if ((blenderobject->parent != 0)&&(!converter->addInitFromFrame))
1799                         {
1800                                 // blender has an additional 'parentinverse' offset in each object
1801                                 SG_Node* parentinversenode = new SG_Node(NULL,NULL,SG_Callbacks());
1802                         
1803                                 // define a normal parent relationship for this node.
1804                                 KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New();
1805                                 parentinversenode->SetParentRelation(parent_relation);
1806         
1807                                 parentChildLink pclink;
1808                                 pclink.m_blenderchild = blenderobject;
1809                                 pclink.m_gamechildnode = parentinversenode;
1810                                 vec_parent_child.push_back(pclink);
1811
1812                                 float* fl = (float*) blenderobject->parentinv;
1813                                 MT_Transform parinvtrans(fl);
1814                                 parentinversenode->SetLocalPosition(parinvtrans.getOrigin());
1815                                 parentinversenode->SetLocalOrientation(parinvtrans.getBasis());
1816                                 
1817                                 parentinversenode->AddChild(gameobj->GetSGNode());
1818                         }
1819                         
1820                         // needed for python scripting
1821                         logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj);
1822
1823                         // needed for dynamic object morphing
1824                         logicmgr->RegisterGameObj(gameobj, blenderobject);
1825                         for (int i = 0; i < gameobj->GetMeshCount(); i++)
1826                                 logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject);
1827         
1828                         converter->RegisterGameObject(gameobj, blenderobject);  
1829                         // this was put in rapidly, needs to be looked at more closely
1830                         // only draw/use objects in active 'blender' layers
1831         
1832                         logicbrick_conversionlist->Add(gameobj->AddRef());
1833                         
1834                         if (converter->addInitFromFrame){
1835                                 posPrev=gameobj->NodeGetWorldPosition();
1836                                 angor=gameobj->NodeGetWorldOrientation();
1837                         }
1838                         if (isInActiveLayer)
1839                         {
1840                                 objectlist->Add(gameobj->AddRef());
1841                                 tf.Add(gameobj->GetSGNode());
1842                                 
1843                                 gameobj->NodeUpdateGS(0,true);
1844                                 gameobj->Bucketize();
1845                                 
1846                         }
1847                         if (converter->addInitFromFrame){
1848                                 gameobj->NodeSetLocalPosition(posPrev);
1849                                 gameobj->NodeSetLocalOrientation(angor);
1850                         }
1851                                                 
1852                 }
1853                         
1854                 base = base->next;
1855         }
1856
1857         if (blenderscene->camera) {
1858                 KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera);
1859                 
1860                 kxscene->SetActiveCamera(gamecamera);
1861         }
1862
1863         //      Set up armatures
1864         for (base = static_cast<Base*>(blenderscene->base.first); base; base=base->next){
1865                 if (base->object->type==OB_MESH){
1866                         Mesh *me = (Mesh*)base->object->data;
1867         
1868                         if (me->dvert){
1869                                 KX_GameObject *obj = converter->FindGameObject(base->object);
1870         
1871                                 if (base->object->parent && base->object->parent->type==OB_ARMATURE && base->object->partype==PARSKEL){
1872                                         KX_GameObject *par = converter->FindGameObject(base->object->parent);
1873                                         if (par)
1874                                                 ((BL_SkinDeformer*)(((BL_DeformableGameObject*)obj)->m_pDeformer))->SetArmature((BL_ArmatureObject*) par);
1875                                 }
1876                         }
1877                 }
1878         }
1879         
1880         // create hierarchy information
1881         int i;
1882         vector<parentChildLink>::iterator pcit;
1883         
1884         for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit)
1885         {
1886         
1887                 struct Object* blenderchild = pcit->m_blenderchild;
1888                 switch (blenderchild->partype)
1889                 {
1890                         case PARVERT1:
1891                         {
1892                                 // creat a new vertex parent relationship for this node.
1893                                 KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New();
1894                                 pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation);
1895                                 break;
1896                         }
1897                         case PARSLOW:
1898                         {
1899                                 // creat a new slow parent relationship for this node.
1900                                 KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf);
1901                                 pcit->m_gamechildnode->SetParentRelation(slow_parent_relation);
1902                                 break;
1903                         }       
1904                         case PARBONE:
1905                         {
1906                                 // parent this to a bone
1907                                 Bone *parent_bone = get_named_bone(get_armature(blenderchild->parent), blenderchild->parsubstr);
1908                                 KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone);
1909                                 pcit->m_gamechildnode->SetParentRelation(bone_parent_relation);
1910                         
1911                                 break;
1912                         }
1913                         case PARSKEL: // skinned - ignore
1914                                 break;
1915                         case PAROBJECT:
1916                         case PARCURVE:
1917                         case PARKEY:
1918                         case PARVERT3:
1919                         default:
1920                                 // unhandled
1921                                 break;
1922                 }
1923         
1924                 struct Object* blenderparent = blenderchild->parent;
1925                 KX_GameObject* parentobj = converter->FindGameObject(blenderparent);
1926                 if (parentobj)
1927                 {
1928                         parentobj->     GetSGNode()->AddChild(pcit->m_gamechildnode);
1929                 }
1930         }
1931         vec_parent_child.clear();
1932         
1933         // find 'root' parents (object that has not parents in SceneGraph)
1934         for (i=0;i<templist->GetCount();++i)
1935         {
1936                 KX_GameObject* gameobj = (KX_GameObject*) templist->GetValue(i);
1937                 if (gameobj->GetSGNode()->GetSGParent() == 0)
1938                 {
1939                         parentlist->Add(gameobj->AddRef());
1940                         gameobj->NodeUpdateGS(0,true);
1941                 }
1942         }
1943         
1944         bool processCompoundChildren = false;
1945
1946         // create physics information
1947         for (i=0;i<sumolist->GetCount();i++)
1948         {
1949                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
1950                 struct Object* blenderobject = converter->FindBlenderObject(gameobj);
1951                 int nummeshes = gameobj->GetMeshCount();
1952                 RAS_MeshObject* meshobj = 0;
1953                 if (nummeshes > 0)
1954                 {
1955                         meshobj = gameobj->GetMesh(0);
1956                 }
1957                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,activeLayerBitInfo,physics_engine,converter,processCompoundChildren);
1958         }
1959
1960         processCompoundChildren = true;
1961         // create physics information
1962         for (i=0;i<sumolist->GetCount();i++)
1963         {
1964                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
1965                 struct Object* blenderobject = converter->FindBlenderObject(gameobj);
1966                 int nummeshes = gameobj->GetMeshCount();
1967                 RAS_MeshObject* meshobj = 0;
1968                 if (nummeshes > 0)
1969                 {
1970                         meshobj = gameobj->GetMesh(0);
1971                 }
1972                 BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,activeLayerBitInfo,physics_engine,converter,processCompoundChildren);
1973         }
1974         
1975         
1976         //set ini linearVel and int angularVel //rcruiz
1977         if (converter->addInitFromFrame)
1978                 for (i=0;i<sumolist->GetCount();i++)
1979                 {
1980                         KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
1981                         if (gameobj->IsDynamic()){
1982                                 gameobj->setLinearVelocity(inivel[i],false);
1983                                 gameobj->setAngularVelocity(iniang[i],false);
1984                         }
1985                 
1986                 
1987                 }       
1988
1989                 // create physics joints
1990         for (i=0;i<sumolist->GetCount();i++)
1991         {
1992                 KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i);
1993                 struct Object* blenderobject = converter->FindBlenderObject(gameobj);
1994                 int nummeshes = gameobj->GetMeshCount();
1995                 RAS_MeshObject* meshobj = 0;
1996         ListBase *conlist;
1997         bConstraint *curcon;
1998         conlist = get_active_constraints2(blenderobject);
1999         if (conlist) {
2000             for (curcon = (bConstraint *)conlist->first; curcon; curcon=(bConstraint *)curcon->next) {
2001                 if (curcon->type==CONSTRAINT_TYPE_RIGIDBODYJOINT){
2002                     bRigidBodyJointConstraint *dat=(bRigidBodyJointConstraint *)curcon->data;
2003                     //if (dat->tar)
2004                         if (!dat->child){
2005                                                         PHY_IPhysicsController* physctr2 = 0;
2006                                                         if (dat->tar)
2007                                                         {
2008                                                                 KX_GameObject *gotar=getGameOb(dat->tar->id.name,sumolist);
2009                                                                 if (gotar)
2010                                                                         physctr2 = (PHY_IPhysicsController*) gotar->GetPhysicsController()->GetUserData();
2011                                                         }
2012
2013                                                         if (gameobj->GetPhysicsController())
2014                                                         {
2015                                                                 PHY_IPhysicsController* physctrl = (PHY_IPhysicsController*) gameobj->GetPhysicsController()->GetUserData();
2016                                                                 //we need to pass a full constraint frame, not just axis
2017                                     
2018                                                                 //localConstraintFrameBasis
2019                                                                 MT_Matrix3x3 localCFrame(MT_Vector3(dat->axX,dat->axY,dat->axZ));
2020                                                                 MT_Vector3 axis0 = localCFrame.getColumn(0);
2021                                                                 MT_Vector3 axis1 = localCFrame.getColumn(1);
2022                                                                 MT_Vector3 axis2 = localCFrame.getColumn(2);
2023                                                                 
2024                                                                 int constraintId = kxscene->GetPhysicsEnvironment()->createConstraint(physctrl,physctr2,(PHY_ConstraintType)dat->type,(float)dat->pivX,(float)dat->pivY,(float)dat->pivZ,
2025                                                                 (float)axis0.x(),(float)axis0.y(),(float)axis0.z(),
2026                                                                 (float)axis1.x(),(float)axis1.y(),(float)axis1.z(),
2027                                                                 (float)axis2.x(),(float)axis2.y(),(float)axis2.z()
2028                                                                                         );
2029                                                                 //if it is a generic 6DOF constraint, set all the limits accordingly
2030                                                                 if (dat->type == PHY_GENERIC_6DOF_CONSTRAINT)
2031                                                                 {
2032                                                                         int dof;
2033                                                                         int dofbit=1;
2034                                                                         for (dof=0;dof<6;dof++)
2035                                                                         {
2036                                                                                 if (dat->flag & dofbit)
2037                                                                                 {
2038                                                                                         kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,dat->minLimit[dof],dat->maxLimit[dof]);
2039                                                                                 } else
2040                                                                                 {
2041                                                                                         //minLimit > maxLimit means free(disabled limit) for this degree of freedom
2042                                                                                         kxscene->GetPhysicsEnvironment()->setConstraintParam(constraintId,dof,1,-1);
2043                                                                                 }
2044                                                                                 dofbit<<=1;
2045                                                                         }
2046                                                                 }
2047                                                         }
2048                         }
2049                 }
2050             }
2051         }
2052
2053         }
2054
2055         templist->Release();
2056         sumolist->Release();    
2057
2058         int executePriority=0; /* incremented by converter routines */
2059         
2060         // convert global sound stuff
2061
2062         /* XXX, glob is the very very wrong place for this
2063          * to be, re-enable once the listener has been moved into
2064          * the scene. */
2065 #if 1
2066         SND_Scene* soundscene = kxscene->GetSoundScene();
2067         SND_SoundListener* listener = soundscene->GetListener();
2068         if (listener && G.listener)
2069         {
2070                 listener->SetDopplerFactor(G.listener->dopplerfactor);
2071                 listener->SetDopplerVelocity(G.listener->dopplervelocity);
2072                 listener->SetGain(G.listener->gain);
2073         }
2074 #endif
2075
2076         // convert world
2077         KX_WorldInfo* worldinfo = new BlenderWorldInfo(blenderscene->world);
2078         converter->RegisterWorldInfo(worldinfo);
2079         kxscene->SetWorldInfo(worldinfo);
2080
2081 #define CONVERT_LOGIC
2082 #ifdef CONVERT_LOGIC
2083         // convert logic bricks, sensors, controllers and actuators
2084         for (i=0;i<logicbrick_conversionlist->GetCount();i++)
2085         {
2086                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2087                 struct Object* blenderobj = converter->FindBlenderObject(gameobj);
2088                 bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
2089                 BL_ConvertActuators(maggie->name, blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,executePriority, activeLayerBitInfo,isInActiveLayer,rendertools,converter);
2090         }
2091         for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
2092         {
2093                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2094                 struct Object* blenderobj = converter->FindBlenderObject(gameobj);
2095                 bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
2096                 BL_ConvertControllers(blenderobj,gameobj,logicmgr,pythondictionary,executePriority,activeLayerBitInfo,isInActiveLayer,converter);
2097         }
2098         for ( i=0;i<logicbrick_conversionlist->GetCount();i++)
2099         {
2100                 KX_GameObject* gameobj = static_cast<KX_GameObject*>(logicbrick_conversionlist->GetValue(i));
2101                 struct Object* blenderobj = converter->FindBlenderObject(gameobj);
2102                 bool isInActiveLayer = (blenderobj->lay & activeLayerBitInfo)!=0;
2103                 BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,keydev,executePriority,activeLayerBitInfo,isInActiveLayer,canvas,converter);
2104         }
2105 #endif //CONVERT_LOGIC
2106
2107         logicbrick_conversionlist->Release();
2108         
2109         // Calculate the scene btree -
2110         // too slow - commented out.
2111         //kxscene->SetNodeTree(tf.MakeTree());
2112 }
2113