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