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