- Main Page
- Packages
- Classes
- Files

- File List
- File Members

# D:/guillaume/guillara/3D/DXGfx/Backup/DXGfxLib/ColladaLoader.cs

Go to the documentation of this file.

    00001 //BSD License
    00002 //DXGfx® - http://www.eteractions.com
    00003 //Copyright (c) 2005
    00004 //by Guillaume Randon
    00005 //Permission is hereby granted, free of charge, to any person obtaining a copy of this software
    00006 //and associated documentation files (the "Software"), to deal in the Software without restriction,
    00007 //including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
    00008 //and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
    00009 //subject to the following conditions:
    00010 //The above copyright notice and this permission notice shall be included in all copies or substantial
    00011 //portions of the Software.
    00012 //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
    00013 //INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
    00014 //AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    00015 //DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    00016 //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    00017 using System;
    00018 using System.Collections.Generic;
    00019 using System.Text;
    00020 using System.IO;
    00021 using System.Drawing;
    00022 using Microsoft.DirectX;
    00023 using Microsoft.DirectX.Direct3D;
    00024 using Microsoft.Samples.DirectX.UtilityToolkit;
    00025 using System.Collections;
    00026 using System.Windows;
    00027 using System.Windows.Forms;
    00028 using System.Xml;
    00029 using System.Diagnostics;
    00030
    00031 namespace DXGfxLib
    00032 {
    00033     public interface IHaveID
    00034     {
    00035         string ID { get; }
    00036     }
    00037
    00038     public class HaveID : IHaveID
    00039     {
    00040         public string id;
    00041
    00042         public string ID
    00043         {
    00044             get { return id; }
    00045         }
    00046     }
    00047
    00048     public class FloatArray : HaveID
    00049     {
    00050         public int count;
    00051         public float[] floats;
    00052     }
    00053
    00054     public class ColladaSource : HaveID
    00055     {
    00056         public List<FloatArray> floatArrays;
    00057
    00058         public ColladaSource()
    00059         {
    00060             floatArrays = new List<FloatArray>();
    00061         }
    00062     }
    00063
    00064     public class VerticesMapping : HaveID
    00065     {
    00066         public string positionSource;
    00067     }
    00068
    00069     public class ColladaMaterial : HaveID
    00070     {
    00071         public string effectInstance;
    00072     }
    00073
    00074     public class ColladaEffectProp
    00075     {
    00076         public float thefloat;
    00077         public System.Drawing.Color color;
    00078         public string texture;
    00079
    00080         public ColladaEffectProp()
    00081         {
    00082         }
    00083
    00084         public ColladaEffectProp(XmlNode xmlNode, XmlNamespaceManager nsmgr)
    00085         {
    00086             SetValues(xmlNode, nsmgr);
    00087         }
    00088
    00089         public void SetValues(XmlNode xmlNode, XmlNamespaceManager nsmgr)
    00090         {
    00091             XmlNode xmlColor = xmlNode.SelectSingleNode("colladans:color", nsmgr);
    00092
    00093             if (xmlColor != null)
    00094             {
    00095                 string[] stringValues = xmlColor.InnerText.Split(new char[] { ' ' });
    00096                 byte r = (byte)(float.Parse(stringValues[0], new System.Globalization.CultureInfo("en-US")));
    00097                 byte g = (byte)(float.Parse(stringValues[1], new System.Globalization.CultureInfo("en-US")));
    00098                 byte b = (byte)(float.Parse(stringValues[2], new System.Globalization.CultureInfo("en-US")));
    00099                 byte a = (byte)(float.Parse(stringValues[3], new System.Globalization.CultureInfo("en-US")));
    00100
    00101                 color = System.Drawing.Color.FromArgb(a, r, g, b);
    00102             }
    00103
    00104             XmlNode xmlTex = xmlNode.SelectSingleNode("colladans:texture", nsmgr);
    00105
    00106             if (xmlTex != null)
    00107             {
    00108                 texture = (string)xmlTex.Attributes["texture"].Value;
    00109             }
    00110
    00111             XmlNode xmlFloat = xmlNode.SelectSingleNode("colladans:float", nsmgr);
    00112
    00113             if (xmlFloat != null)
    00114             {
    00115                 thefloat = float.Parse(xmlFloat.InnerText, new System.Globalization.CultureInfo("en-US"));
    00116             }
    00117         }
    00118     }
    00119
    00120     public class ColladaEffect : HaveID
    00121     {
    00122         public ColladaEffectProp emission;
    00123         public ColladaEffectProp ambiant;
    00124         public ColladaEffectProp diffuse;
    00125         public ColladaEffectProp specular;
    00126         public ColladaEffectProp shininess;
    00127         public ColladaEffectProp reflectivity;
    00128         public ColladaEffectProp transparent;
    00129         public ColladaEffectProp transparency;
    00130     }
    00131
    00132     public class ColladaImage : HaveID
    00133     {
    00134         public string filename;
    00135     }
    00136
    00137     public class Triangles
    00138     {
    00139         public string vertices;
    00140         public int voffset;
    00141         public string normals;
    00142         public int noffset;
    00143         public string texcoords;
    00144         public int toffset;
    00145         public List<int> indices;
    00146         public int numPrimitives;
    00147
    00148         public string material;
    00149
    00150         public Triangles()
    00151         {
    00152             indices = new List<int>();
    00153         }
    00154     }
    00155
    00156     public class LoadedEntity
    00157     {
    00158         public VertexBuffer vBuff;
    00159         public IndexBuffer iBuff;
    00160         public int numVertices = 0;
    00161         public int numPrimitives = 0;
    00162         public Material[] materials = null;
    00163         public Texture[] textures = null;
    00164     }
    00165
    00166     public class ColladaGeometry : HaveID
    00167     {
    00168         public List<LoadedEntity> models;
    00169
    00170         public ColladaGeometry()
    00171         {
    00172             models = new List<LoadedEntity>();
    00173         }
    00174     }
    00175
    00176     public class ColladaLoader
    00177     {
    00178         public Device d3ddevice = null;
    00179         public XmlDocument colladaDocument;
    00180         public Hashtable colladaGeometries;
    00181         public Hashtable colladaImages;
    00182         public Hashtable colladaMaterials;
    00183         public Hashtable colladaEffects;
    00184
    00185
    00186
    00187         public ColladaLoader(Device device)
    00188         {
    00189             d3ddevice = device;
    00190
    00191             colladaGeometries = new Hashtable();
    00192             colladaImages = new Hashtable();
    00193             colladaMaterials = new Hashtable();
    00194             colladaEffects = new Hashtable();
    00195         }
    00196
    00197
    00198         public void Load(string fileName)
    00199         {
    00200             colladaGeometries.Clear();
    00201             colladaImages.Clear();
    00202             colladaMaterials.Clear();
    00203             colladaEffects.Clear();
    00204
    00205             if (File.Exists(fileName))
    00206             {
    00207                 ParseColladaFile(fileName);
    00208             }
    00209             else
    00210             {
    00211                 string currentFolder = Directory.GetCurrentDirectory();
    00212
    00213                 OpenFileDialog opdlg = new OpenFileDialog();
    00214
    00215                 opdlg.Filter = "collada files (*.dae)|*.dae|All files (*.*)|*.*";
    00216                 opdlg.FilterIndex = 2;
    00217
    00218                 if (opdlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    00219                 {
    00220                     ParseColladaFile(opdlg.FileName);
    00221                 }
    00222
    00223                 Directory.SetCurrentDirectory(currentFolder);
    00224             }
    00225         }
    00226
    00227         public void ParseColladaFile(string fileName)
    00228         {
    00229             // 1.Load DOM
    00230             // 2.Parse Geometry_Library
    00231             // 3.For each Geometry_Library defer work to ParseGeometryLibrary
    00232             colladaDocument = new XmlDocument();
    00233             colladaDocument.Load(fileName);
    00234
    00235             XmlNode root = colladaDocument.DocumentElement;
    00236
    00237             XmlNamespaceManager nsmgr = new XmlNamespaceManager(colladaDocument.NameTable);
    00238             nsmgr.AddNamespace("colladans", "http://www.collada.org/2005/11/COLLADASchema");
    00239
    00240             XmlNode imagesLib = root.SelectSingleNode("colladans:library_images", nsmgr);
    00241             XmlNodeList images = imagesLib.SelectNodes("colladans:image", nsmgr);
    00242
    00243             foreach (XmlNode colladaImage in images)
    00244             {
    00245                 ColladaImage img = ParseImage(colladaImage, nsmgr);
    00246                 colladaImages.Add(img.ID, img);
    00247             }
    00248
    00249             XmlNode materialsLib = root.SelectSingleNode("colladans:library_materials", nsmgr);
    00250             XmlNodeList materials = materialsLib.SelectNodes("colladans:material", nsmgr);
    00251
    00252             foreach (XmlNode colladaMaterial in materials)
    00253             {
    00254                 ColladaMaterial mate = ParseMaterial(colladaMaterial, nsmgr);
    00255                 colladaMaterials.Add(mate.ID, mate);
    00256             }
    00257
    00258             XmlNode effectsLib = root.SelectSingleNode("colladans:library_effects", nsmgr);
    00259             XmlNodeList effects = effectsLib.SelectNodes("colladans:effect", nsmgr);
    00260
    00261             foreach (XmlNode colladaEffect in effects)
    00262             {
    00263                 ColladaEffect eff = ParseEffect(colladaEffect, nsmgr);
    00264                 colladaEffects.Add(eff.ID, eff);
    00265             }
    00266
    00267             XmlNode geometryLib = root.SelectSingleNode("colladans:library_geometries", nsmgr);
    00268             XmlNodeList geometries = geometryLib.SelectNodes("colladans:geometry", nsmgr);
    00269
    00270             foreach (XmlNode geometry in geometries)
    00271             {
    00272                 ColladaGeometry geom = ParseGeometry(geometry, nsmgr);
    00273                 colladaGeometries.Add(geom.ID, geom);
    00274             }
    00275
    00276             // TODO ! Here we should parse the scene information and modify the geometries transform accordingly!!
    00277         }
    00278
    00279         public ColladaImage ParseImage(XmlNode colladaImage, XmlNamespaceManager nsmgr)
    00280         {
    00281             ColladaImage output = new ColladaImage();
    00282             output.id = (string)colladaImage.Attributes["id"].Value;
    00283
    00284             output.filename = colladaImage.SelectSingleNode("colladans:init_from", nsmgr).InnerText;
    00285
    00286             return output;
    00287         }
    00288
    00289         public ColladaMaterial ParseMaterial(XmlNode colladaMaterial, XmlNamespaceManager nsmgr)
    00290         {
    00291             ColladaMaterial output = new ColladaMaterial();
    00292
    00293             output.id = (string)colladaMaterial.Attributes["id"].Value;
    00294
    00295             XmlNode instEff = colladaMaterial.SelectSingleNode("colladans:instance_effect", nsmgr);
    00296             output.effectInstance = (string)instEff.Attributes["url"].Value;
    00297             // remove # at beginning of string
    00298             output.effectInstance = output.effectInstance.Substring(1);
    00299
    00300             return output;
    00301         }
    00302
    00303         public ColladaEffect ParseEffect(XmlNode colladaEffect, XmlNamespaceManager nsmgr)
    00304         {
    00305             ColladaEffect output = new ColladaEffect();
    00306
    00307             output.id = (string)colladaEffect.Attributes["id"].Value;
    00308
    00309             output.emission = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:emission", nsmgr), nsmgr);
    00310             output.ambiant = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:ambient", nsmgr), nsmgr);
    00311             output.diffuse = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:diffuse", nsmgr), nsmgr);
    00312             output.specular = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:specular", nsmgr), nsmgr);
    00313             output.shininess = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:shininess", nsmgr), nsmgr);
    00314             output.reflectivity = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:reflectivity", nsmgr), nsmgr);
    00315             output.transparent = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:transparent", nsmgr), nsmgr);
    00316             output.transparency = new ColladaEffectProp(colladaEffect.SelectSingleNode("colladans:profile_COMMON/colladans:technique/colladans:phong/colladans:transparency", nsmgr), nsmgr);
    00317
    00318             return output;
    00319         }
    00320
    00321         public  ColladaGeometry ParseGeometry(XmlNode colladaGeom, XmlNamespaceManager nsmgr)
    00322         {
    00323             // On Cherche le mesh pour chaque mesh on cherche triangles.
    00324             // A partir des données de triangles on lit le reste pour construire le bon GeometryModel3D!
    00325             ColladaGeometry output = new ColladaGeometry();
    00326             output.id = (string)colladaGeom.Attributes["id"].Value;
    00327             List<LoadedEntity> computedModels = output.models;
    00328
    00329             // Get the mesh. There should be only one mesh.
    00330             XmlNode colladaMesh = colladaGeom.SelectSingleNode("colladans:mesh", nsmgr);
    00331             Hashtable sources = new Hashtable();
    00332
    00333             XmlNodeList colladaSources = colladaMesh.SelectNodes("colladans:source", nsmgr);
    00334             foreach (XmlNode colladaSource in colladaSources)
    00335             {
    00336                 ColladaSource src = ParseSource(colladaSource, nsmgr);
    00337                 sources.Add(src.id, src);
    00338             }
    00339
    00340             Hashtable mappings = new Hashtable();
    00341             XmlNodeList colladaVertices = colladaMesh.SelectNodes("colladans:vertices", nsmgr);
    00342             foreach (XmlNode colladaVertice in colladaVertices)
    00343             {
    00344                 VerticesMapping mapp = ParseVertices(colladaVertice, nsmgr);
    00345                 mappings.Add(mapp.id, mapp);
    00346             }
    00347
    00348             List<Triangles> trianglesList = new List<Triangles>();
    00349             XmlNodeList colladaTrianglesList = colladaMesh.SelectNodes("colladans:triangles", nsmgr);
    00350             foreach (XmlNode colladaTriangles in colladaTrianglesList)
    00351             {
    00352                 trianglesList.Add(ParseTriangles(colladaTriangles, nsmgr));
    00353             }
    00354
    00355             // We have finished loading everything we need to build our GeometryModel3D, let's do it.
    00356             foreach (Triangles triang in trianglesList)
    00357             {
    00358                 computedModels.Add(BuildGeometryModel3D(ref sources, ref mappings, triang));
    00359             }
    00360
    00361             return output;
    00362         }
    00363
    00364         public ColladaSource ParseSource(XmlNode colladaSource, XmlNamespaceManager nsmgr)
    00365         {
    00366             ColladaSource source = new ColladaSource();
    00367
    00368             source.id = colladaSource.Attributes["id"].Value;
    00369
    00370             XmlNodeList colladaarrays = colladaSource.SelectNodes("colladans:float_array", nsmgr);
    00371             foreach (XmlNode colladafarray in colladaarrays)
    00372             {
    00373                 FloatArray farray = new FloatArray();
    00374                 farray.id = colladafarray.Attributes["id"].Value;
    00375                 farray.count = int.Parse(colladafarray.Attributes["count"].Value);
    00376
    00377                 string[] stringValues = colladafarray.InnerText.Split(new Char[] { ' ' });
    00378
    00379                 farray.floats = new float[farray.count];
    00380
    00381                 for (int findex = 0; findex < farray.count; findex++)
    00382                 {
    00383                     farray.floats[findex] = float.Parse(stringValues[findex], new System.Globalization.CultureInfo("en-US"));
    00384                 }
    00385
    00386                 source.floatArrays.Add(farray);
    00387             }
    00388             return source;
    00389         }
    00390
    00391         public VerticesMapping ParseVertices(XmlNode colladaVertices, XmlNamespaceManager nsmgr)
    00392         {
    00393             VerticesMapping mapping = new VerticesMapping();
    00394
    00395             mapping.id = (string)(colladaVertices.Attributes["id"].Value);
    00396
    00397             XmlNode positionSource = colladaVertices.SelectSingleNode("colladans:input[@semantic='POSITION']", nsmgr);
    00398             mapping.positionSource = (string)(positionSource.Attributes["source"].Value);
    00399             // remove starting # to have the id of the source in the positionSource string.
    00400             mapping.positionSource = mapping.positionSource.Substring(1);
    00401
    00402             return mapping;
    00403         }
    00404
    00405         public Triangles ParseTriangles(XmlNode colladaTriangles, XmlNamespaceManager nsmgr)
    00406         {
    00407             Triangles triangles = new Triangles();
    00408
    00409             triangles.material = (string)colladaTriangles.Attributes["material"].Value;
    00410
    00411             XmlNode vertices = colladaTriangles.SelectSingleNode("colladans:input[@semantic='VERTEX']", nsmgr);
    00412             triangles.vertices = (string)(vertices.Attributes["source"].Value);
    00413             // remove starting # to have the id of the source in the positionSource string.
    00414             triangles.vertices = triangles.vertices.Substring(1);
    00415             triangles.voffset = int.Parse(vertices.Attributes["offset"].Value);
    00416
    00417             XmlNode normals = colladaTriangles.SelectSingleNode("colladans:input[@semantic='NORMAL']", nsmgr);
    00418             triangles.normals = (string)(normals.Attributes["source"].Value);
    00419             // remove starting # to have the id of the source in the positionSource string.
    00420             triangles.normals = triangles.normals.Substring(1);
    00421             triangles.noffset = int.Parse(normals.Attributes["offset"].Value);
    00422
    00423             XmlNode texcoords = colladaTriangles.SelectSingleNode("colladans:input[@semantic='TEXCOORD']", nsmgr);
    00424             if (texcoords != null)
    00425             {
    00426                 triangles.texcoords = (string)(texcoords.Attributes["source"].Value);
    00427                 // remove starting # to have the id of the source in the positionSource string.
    00428                 triangles.texcoords = triangles.texcoords.Substring(1);
    00429                 triangles.toffset = int.Parse(texcoords.Attributes["offset"].Value);
    00430             }
    00431             else
    00432             {
    00433                 triangles.texcoords = "";
    00434                 triangles.toffset = -1;
    00435             }
    00436
    00437             triangles.numPrimitives = int.Parse(colladaTriangles.Attributes["count"].Value);
    00438             string[] stringValues = colladaTriangles.InnerText.Split(new Char[] { ' ' });
    00439
    00440             // Last string is empty don't forget to remove it.
    00441             for (int sindex = 0; sindex < stringValues.Length - 1; sindex++)
    00442             {
    00443                 triangles.indices.Add(int.Parse(stringValues[sindex]));
    00444             }
    00445
    00446             return triangles;
    00447         }
    00448
    00449         public LoadedEntity BuildGeometryModel3D(ref Hashtable sources, ref Hashtable mappings, Triangles triangles)
    00450         {
    00451             VerticesMapping map = (VerticesMapping)mappings[triangles.vertices];
    00452             ColladaSource positions = (ColladaSource)sources[map.positionSource];
    00453
    00454
    00455             int res;
    00456             int n = Math.DivRem(positions.floatArrays[0].floats.Length, 3, out res);
    00457
    00458             List<Vector3> points = new List<Vector3>();
    00459             List<Vector3> normals = new List<Vector3>();
    00460
    00461             if (res != 0)
    00462             {
    00463                 throw new Exception("This is terribly wrong! Check input file.");
    00464             }
    00465
    00466             for (int i = 0; i < n; i++)
    00467             {
    00468                 float X = positions.floatArrays[0].floats[3*i];
    00469                 float Z = positions.floatArrays[0].floats[3*i+1];
    00470                 float Y = positions.floatArrays[0].floats[3*i+2];
    00471                 points.Add(new Vector3(X,Y,Z));
    00472             }
    00473
    00474             int indicesStride = 1;
    00475
    00476
    00477             if (!triangles.normals.Equals(""))
    00478             {
    00479                 indicesStride++;
    00480
    00481
    00482                 ColladaSource normalsSrc = (ColladaSource)sources[triangles.normals];
    00483
    00484                 n = Math.DivRem(normalsSrc.floatArrays[0].floats.Length, 3, out res);
    00485
    00486                 if (res != 0)
    00487                 {
    00488                     throw new Exception("This is terribly wrong! Check input file.");
    00489                 }
    00490
    00491                 for (int j = 0; j < n; j++)
    00492                 {
    00493                     float X = normalsSrc.floatArrays[0].floats[3 * j];
    00494                     float Z = normalsSrc.floatArrays[0].floats[3 * j + 1];
    00495                     float Y = normalsSrc.floatArrays[0].floats[3 * j + 2];
    00496                     normals.Add(new Vector3(X, Y, Z));
    00497                 }
    00498             }
    00499
    00500             List<Vector2> myTextureCoordinatesCollection = new List<Vector2>();
    00501             // Create a collection of texture coordinates for the MeshGeometry3D.
    00502             if (!triangles.texcoords.Equals(""))
    00503             {
    00504                 indicesStride++;
    00505
    00506                 ColladaSource texcoords = (ColladaSource)sources[triangles.texcoords];
    00507
    00508                 n = Math.DivRem(texcoords.floatArrays[0].floats.Length, 2, out res);
    00509
    00510                 if (res != 0)
    00511                 {
    00512                     throw new Exception("This is terribly wrong! Check input file.");
    00513                 }
    00514
    00515                 myTextureCoordinatesCollection = new List<Vector2>();
    00516
    00517                 for (int k = 0; k < n; k++)
    00518                 {
    00519                     float U = texcoords.floatArrays[0].floats[2*k];
    00520                     float V = 1 - texcoords.floatArrays[0].floats[2*k + 1];
    00521                     myTextureCoordinatesCollection.Add(new Vector2(U, V));
    00522                 }
    00523             }
    00524
    00525             // We should have position normal texcoord so this makes 3 and num of indices divided by 3
    00526             // should give an int. Let's Check it!
    00527             n = Math.DivRem(triangles.indices.Count, indicesStride * triangles.numPrimitives, out res);
    00528
    00529             if (res != 0)
    00530             {
    00531                 throw new Exception("This is terribly wrong! Check input file.");
    00532             }
    00533
    00534             // Create a collection of triangle indices for the MeshGeometry3D.
    00535             List<Int32> myTriangleIndicesCollection = new List<Int32>();
    00536             List<Vector3> destPoints = new List<Vector3>();
    00537             List<Vector3> destNormals = new List<Vector3>();;
    00538             List<Vector2> destTexCoord = new List<Vector2>();
    00539
    00540
    00541             for (int h = 0; h < triangles.numPrimitives; h++)
    00542             {
    00543                 // This is tricky in list of indices first refers to vertices (offset 0)
    00544                 // then second to normal (offset 1)
    00545                 // then third to texcoord (offset 2)
    00546                 // technically as I can not guarantee I can share any vertex it is here I should build
    00547                 // vertex/normal/tex association for each indice in the list !
    00548                 destPoints.Add(points[triangles.indices[3 * indicesStride * h]]);
    00549                 if (indicesStride >= 2)
    00550                 {
    00551                     destNormals.Add(normals[triangles.indices[3 * indicesStride * h + 1]]);
    00552                 }
    00553                 if (indicesStride == 3)
    00554                 {
    00555                     destTexCoord.Add(myTextureCoordinatesCollection[triangles.indices[3 * indicesStride * h + 2]]);
    00556                 }
    00557
    00558                 destPoints.Add(points[triangles.indices[3 * (indicesStride * h + 2)]]);
    00559                 if (indicesStride >= 2)
    00560                 {
    00561                     destNormals.Add(normals[triangles.indices[3 * (indicesStride * h + 2) + 1]]);
    00562                 }
    00563                 if (indicesStride == 3)
    00564                 {
    00565                     destTexCoord.Add(myTextureCoordinatesCollection[triangles.indices[3 * (indicesStride * h + 2) + 2]]);
    00566                 }
    00567
    00568                 destPoints.Add(points[triangles.indices[3 * (indicesStride * h + 1)]]);
    00569                 if (indicesStride >= 2)
    00570                 {
    00571                     destNormals.Add(normals[triangles.indices[3 * (indicesStride * h + 1) + 1]]);
    00572                 }
    00573                 if (indicesStride == 3)
    00574                 {
    00575                     destTexCoord.Add(myTextureCoordinatesCollection[triangles.indices[3 * (indicesStride * h + 1) + 2]]);
    00576                 }
    00577
    00578                 myTriangleIndicesCollection.Add(3*h);
    00579                 myTriangleIndicesCollection.Add(3*h + 1);
    00580                 myTriangleIndicesCollection.Add(3*h + 2);
    00581             }
    00582
    00583
    00584             LoadedEntity entity = new LoadedEntity();
    00585
    00586             if (!triangles.normals.Equals(""))
    00587             {
    00588                 if (!triangles.texcoords.Equals(""))
    00589                 {
    00590                     int numVertices = triangles.numPrimitives * 3;
    00591
    00592                     CustomVertex.PositionNormalTextured[] vertices = new CustomVertex.PositionNormalTextured[numVertices];
    00593                     for (int i = 0; i < numVertices; i++)
    00594                     {
    00595                         vertices[i].Position = destPoints[i];
    00596                         vertices[i].Normal = destNormals[i];
    00597                         vertices[i].Tu = destTexCoord[i].X;
    00598                         vertices[i].Tv = destTexCoord[i].Y;
    00599                     }
    00600
    00601                     entity.vBuff = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured),
    00602                         numVertices, d3ddevice, Usage.Dynamic, CustomVertex.PositionNormalTextured.Format, Pool.SystemMemory);
    00603
    00604
    00605                     GraphicsStream stm = entity.vBuff.Lock(0, 0, LockFlags.NoOverwrite);
    00606                     stm.Write(vertices);
    00607                     entity.vBuff.Unlock();
    00608
    00609                     entity.iBuff = new IndexBuffer(typeof(Int32), numVertices, d3ddevice, Usage.Dynamic, Pool.SystemMemory);
    00610
    00611                     GraphicsStream stmi = entity.iBuff.Lock(0, 0, LockFlags.NoOverwrite);
    00612                     stmi.Write(myTriangleIndicesCollection.ToArray());
    00613                     entity.iBuff.Unlock();
    00614
    00615                     entity.numPrimitives = triangles.numPrimitives;
    00616                     entity.numVertices = numVertices;
    00617                 }
    00618                 else
    00619                 {
    00620                     //entity.geometry = new Mesh(triangles.numPrimitives, n, MeshFlags.WriteOnly, CustomVertex.PositionNormal.Format, d3ddevice);
    00621                 }
    00622             }
    00623             else
    00624             {
    00625                 if (!triangles.texcoords.Equals(""))
    00626                 {
    00627                     //entity.geometry = new Mesh(triangles.numPrimitives, n, MeshFlags.WriteOnly, CustomVertex.PositionTextured.Format, d3ddevice);
    00628                 }
    00629                 else
    00630                 {
    00631                     //entity.geometry = new Mesh(triangles.numPrimitives, n, MeshFlags.WriteOnly, CustomVertex.PositionColored.Format, d3ddevice);
    00632                 }
    00633             }
    00634
    00635             //Define material and apply to the mesh geometries.
    00636             List<Material> destMaterials = new List<Material>();
    00637             List<Texture> destTextures = new List<Texture>();
    00638
    00639             if (!triangles.material.Equals(""))
    00640             {
    00641                 ColladaMaterial mat = colladaMaterials[triangles.material] as ColladaMaterial;
    00642
    00643                 if (mat != null)
    00644                 {
    00645                     ColladaEffect eff = colladaEffects[mat.effectInstance] as ColladaEffect;
    00646
    00647                     if (eff != null)
    00648                     {
    00649                         if (eff.diffuse.texture != null)
    00650                         {
    00651                             if (!eff.diffuse.texture.Equals(""))
    00652                             {
    00653                                 string filename = ((ColladaImage)colladaImages[eff.diffuse.texture]).filename;
    00654
    00655
    00656                                 Microsoft.DirectX.Direct3D.Material mate = new Microsoft.DirectX.Direct3D.Material();
    00657                                 mate.Ambient = System.Drawing.Color.AliceBlue;
    00658                                 mate.Diffuse = System.Drawing.Color.Beige;
    00659                                 mate.Emissive = System.Drawing.Color.White;
    00660                                 mate.Specular = System.Drawing.Color.Red;
    00661                                 mate.SpecularSharpness = 2;
    00662
    00663                                 destMaterials.Add(mate);
    00664
    00665                                 Texture currTex = TextureLoader.FromFile(d3ddevice, filename);
    00666                                 destTextures.Add(currTex);
    00667                             }
    00668                         }
    00669                     }
    00670                 }
    00671             }
    00672
    00673             entity.materials = destMaterials.ToArray();
    00674             entity.textures = destTextures.ToArray();
    00675
    00676
    00677
    00678             return entity;
    00679         }
    00680
    00681 //        To use
    00682 //            collada = new ColladaLoader(e.Device);
    00683
    00684 //collada.Load("Villada.dae");
    00685
    00686 //Puis utiliser le code suivant pour effectuer le rendu de ce qui a été chargé:
    00687
    00688 //IDictionaryEnumerator enumGeometrie = collada.colladaGeometries.GetEnumerator();
    00689
    00690 //while (enumGeometrie.MoveNext())
    00691
    00692 //{
    00693
    00694 //   ColladaGeometry collGeom = enumGeometrie.Value as ColladaGeometry;
    00695
    00696 //   if (collGeom == null)
    00697
    00698 //      continue;
    00699
    00700 //   foreach (LoadedEntity entity in collGeom.models)
    00701
    00702 //   {
    00703
    00704 //            if (entity.materials.Length == 0)
    00705
    00706 //               continue;
    00707
    00708 //            if (entity.textures.Length == 0)
    00709
    00710 //               continue;
    00711
    00712 //            device.SetTransform(TransformType.World,
    00713
    00714 //                        Matrix.Multiply(Matrix.Scaling(0.1f, 0.1f, 0.1f),  Matrix.Translation(0.0f, 5.0f, 0.0f)));
    00715
    00716 //            device.Indices = entity.iBuff;
    00717
    00718 //            device.SetStreamSource(0, entity.vBuff, 0);
    00719
    00720 //            device.Material = entity.materials[0];
    00721
    00722 //            device.SetTexture(0, entity.textures[0]);
    00723
    00724 //            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0,
    00725
    00726 //                        entity.numVertices, 0,   entity.numPrimitives);
    00727
    00728 //    }}
    00729
    00730     }
    00731 }