Beispiel #1
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "bool_array":
                    Array	= Doc.Load<bool_array>(this,Child);
                    break;

                case "float_array":
                    Array	= Doc.Load<float_array>(this,Child);
                    break;

                case "IDREF_array":
                    Array	= Doc.Load<IDREF_array>(this,Child);
                    break;

                case "int_array":
                    Array	= Doc.Load<int_array>(this,Child);
                    break;

                case "Name_array":
                    Array	= Doc.Load<Name_array>(this,Child);
                    break;

                case "SIDREF_array":
                    Array	= Doc.Load<SIDREF_array>(this,Child);
                    break;

                case "token_array":
                    break;

                case "technique":
                    break;
            }
        }
Beispiel #2
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "animation":
                    if(Childs == null)
                        Childs	= new List<animation>();
                    Childs.Add(Doc.Load<animation>(this,Child));
                    break;

                case "source":
                    if(Sources == null)
                        Sources	= new List<source>();
                    Sources.Add(Doc.Load<source>(this,Child));
                    break;

                case "sampler":
                    if(Samplers == null)
                        Samplers	= new List<sampler>();
                    Samplers.Add(Doc.Load<sampler>(this,Child));
                    break;

                case "channel":
                    if(Channels == null)
                        Channels	= new List<channel>();
                    Channels.Add(Doc.Load<channel>(this,Child));
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #3
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "annotate":
                    if(Annotates == null)
                        Annotates	= new List<annotate>();
                    Annotates.Add(Doc.Load<annotate>(this,Child));
                    break;

                case "newparam":
                    if(Params == null)
                        Params	= new List<newparam>();
                    Params.Add(Doc.Load<newparam>(this,Child));
                    break;

                case "profile":
                    if(Profiles == null)
                        Profiles	= new List<profile>();
                    Profiles.Add(Doc.Load<profile>(this,Child));
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #4
0
 //        public List<render> Renders;
 void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
 {
     if(Child.Name == "render")
     {
     }
     else throw new Exception("Invalid Child Node");
 }
Beispiel #5
0
        protected override void InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "constant_attenuation":
                    ConstantAtten	= float.Parse(Child.InnerText);
                    break;
                case "linear_attenuation":
                    LinearAtten	= float.Parse(Child.InnerText);
                    break;
                case "quadratic_attenuation":
                    QuadraticAtten	= float.Parse(Child.InnerText);
                    break;

                case "falloff_angle":
                    FallOffAngle	= float.Parse(Child.InnerText);
                    break;
                case "falloff_exponent":
                    FallOffExponent	= byte.Parse(Child.InnerText);
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #6
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "lookat":
                    ChildNodes.Add(Doc.Load<lookat>(this,Child));
                    break;

                case "matrix":
                    ChildNodes.Add(Doc.Load<matrix>(this,Child));
                    break;

                case "rotate":
                    ChildNodes.Add(Doc.Load<rotate>(this,Child));
                    break;

                case "scale":
                    ChildNodes.Add(Doc.Load<scale>(this,Child));
                    break;

                case "skew":
                    ChildNodes.Add(Doc.Load<skew>(this,Child));
                    break;

                case "translate":
                    ChildNodes.Add(Doc.Load<translate>(this,Child));
                    break;

                case "instance_camera":
                    ChildNodes.Add(Doc.Load<instance_camera>(this,Child));
                    break;

                case "instance_controller":
                    ChildNodes.Add(Doc.Load<instance_controller>(this,Child));
                    break;

                case "instance_geometry":
                    ChildNodes.Add(Doc.Load<instance_geometry>(this,Child));
                    break;

                case "instance_light":
                    ChildNodes.Add(Doc.Load<instance_light>(this,Child));
                    break;

                case "instance_node":
                    ChildNodes.Add(Doc.Load<instance_node>(this,Child));
                    break;

                case "node":
                    ChildNodes.Add(Doc.Load<node>(this,Child));
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #7
0
 void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
 {
     if(Child.Name == "input")
     {
         if(Inputs == null)
             Inputs	= new List<input>();
         Inputs.Add(Doc.Load<input>(this,Child));
     }
     else throw new Exception("Invalid Child Node");
 }
Beispiel #8
0
 void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
 {
     if(Child.Name == "param")
     {
         if(Params == null)
             Params	= new List<param>();
         Params.Add(Doc.Load<param>(this,Child));
     }
     else throw new Exception("Invalid Child Node");
 }
Beispiel #9
0
 void IHasTechChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
 {
     if(Child.Name == "instance_material")
     {
         if(Materials == null)
             Materials	= new List<instance_materials>();
         Materials.Add(Doc.Load<instance_materials>(this,Child));
     }
     else throw new Exception("Invalid Child Node");
 }
Beispiel #10
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            if(Child.Name == "color")
            {
                char[] Splitter	= {' ','\n'};
                string[] C	= Child.InnerText.Split(Splitter,StringSplitOptions.RemoveEmptyEntries);

                Color	= new ClampColor(float.Parse(C[0]),float.Parse(C[1]),float.Parse(C[2]),1);
            }
            else InitChildNode(Doc,Child);
        }
Beispiel #11
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "renderable":
                    break;

                case "init_from":
                    InitData	= Doc.Load<init_from>(this,Child);
                    break;
            }
        }
Beispiel #12
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "contributor":
                    if(Contributors == null)
                        Contributors	= new List<contributor>();
                    Contributors.Add(Doc.Load<contributor>(this,Child));
                    break;

                case "coverage":
                    break;

                case "created":
                    Created	= DateTime.Parse(Child.InnerText);
                    break;

                case "keywords":
                    Keywords	= Child.InnerText;
                    break;

                case "modified":
                    Modified	= DateTime.Parse(Child.InnerText);
                    break;

                case "revision":
                    Revision	= Child.InnerText;
                    break;

                case "subject":
                    Subject	= Child.InnerText;
                    break;

                case "title":
                    Title	= Child.InnerText;
                    break;

                case "unit":
                    Unit	= float.Parse(Child.Attributes["meter"].InnerText);
                    UnitType	= Child.Attributes["name"].InnerText;
                    break;

                case "up_axis":
                    UpAxis	= (SixAxis)Enum.Parse(typeof(SixAxis),Child.InnerText);
                    break;

                default:
                    throw new Exception("Invalid Child");
            }
        }
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Node)
        {
            char[] Splitter	= {' ','\n'};
            string[] Values	= Node.InnerText.Split(Splitter,StringSplitOptions.RemoveEmptyEntries);

            float[] V	= new float[Values.Length];

            int i	= 0;
            while(i < V.Length)
            {
                V[i]	= float.Parse(Values[i]);
                i++;
            }
            SetValue(V);
        }
Beispiel #14
0
        void IHasTechChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "orthographic":
                    Projection	= Doc.Load<orthographic>(this,Child);
                    break;

                case "perspective":
                    Projection	= Doc.Load<perspective>(this,Child);
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #15
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "optics":
                    Optics	= Doc.Load<optics>(this,Child);
                    break;

                case "imager":
                    Imager	= Doc.Load<imager>(this,Child);
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #16
0
        protected override void InitChild(COLLADA Doc,XmlNode Child)
        {
            if(Child.Name == "vertices")
                Vertices	= Doc.Load<vertices>(this,Child);
            else
            {
                primitive_element PrmElement	= null;
                switch(Child.Name)
                {
                    case "lines":
                        PrmElement	= Doc.Load<lines>(this,Child);
                        break;

                    case "linestrips":
                        PrmElement	= Doc.Load<linestrips>(this,Child);
                        break;

                    case "polygons":
                        PrmElement	= Doc.Load<polygons>(this,Child);
                        break;

                    case "polylist":
                        PrmElement	= Doc.Load<polylist>(this,Child);
                        break;

                    case "triangles":
                        PrmElement	= Doc.Load<triangles>(this,Child);
                        break;

                    case "trifans":
                        PrmElement	= Doc.Load<trifans>(this,Child);
                        break;

                    case "tristrips":
                        PrmElement	= Doc.Load<tristrips>(this,Child);
                        break;

                    default:
                        throw new Exception("Invalid Child Node");
                }

                if(Primitives == null)
                    Primitives	= new List<primitive_element>();
                if(PrmElement != null)
                    Primitives.Add(PrmElement);
            }
        }
Beispiel #17
0
        protected override void InitChild(COLLADA Doc,XmlNode Child)
        {
            if(Child.Name == "vcount")
            {
                VCount	= new uint[Count];

                char[] Splitter	= {' ','\n'};
                string[] VC	= Child.InnerText.Split(Splitter,StringSplitOptions.RemoveEmptyEntries);

                int i	= 0;
                while(i < Count)
                {
                    VCount[i]	= uint.Parse(VC[i]);
                    i++;
                }
            }
        }
Beispiel #18
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "instance_physics_scene":
                    break;

                case "instance_visual_scene":
                    VisualScene	= Doc.Load<instance_visual_scene>(this,Child);
                    break;

                case "instance_kinematics_scene":
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #19
0
        public void UnknownSource_spriggan_proto_skel_chr_NoMaterialFile()
        {
            var args   = new string[] { $@"{userHome}\OneDrive\ResourceFiles\spriggan_proto_skel.chr" };
            int result = testUtils.argsHandler.ProcessArgs(args);

            Assert.AreEqual(0, result);
            CryEngine cryData = new CryEngine(args[0], testUtils.argsHandler.DataDir.FullName);

            cryData.ProcessCryengineFiles();

            COLLADA colladaData = new COLLADA(testUtils.argsHandler, cryData);

            colladaData.GenerateDaeObject();

            int actualMaterialsCount = colladaData.DaeObject.Library_Materials.Material.Count();

            Assert.AreEqual(0, actualMaterialsCount);

            testUtils.ValidateColladaXml(colladaData);
        }
Beispiel #20
0
        public void Prey_Dahl_GenMaleBody01_MaterialFileNotAvailable()
        {
            var args   = new string[] { $@"{userHome}\OneDrive\ResourceFiles\Prey\Dahl_GenMaleBody01.skin" };
            int result = testUtils.argsHandler.ProcessArgs(args);

            Assert.AreEqual(0, result);
            CryEngine cryData = new CryEngine(args[0], testUtils.argsHandler.DataDir.FullName);

            cryData.ProcessCryengineFiles();

            COLLADA colladaData = new COLLADA(testUtils.argsHandler, cryData);

            colladaData.GenerateDaeObject();

            int actualMaterialsCount = colladaData.DaeObject.Library_Materials.Material.Count();

            Assert.AreEqual(1, actualMaterialsCount);

            testUtils.ValidateColladaXml(colladaData);
        }
Beispiel #21
0
        public void Evolve_griffin_menu_harpoon_skin_NoMaterialFile()
        {
            var args   = new string[] { $@"{userHome}\OneDrive\ResourceFiles\Evolve\griffin_menu_harpoon.skin" };
            int result = testUtils.argsHandler.ProcessArgs(args);

            Assert.AreEqual(0, result);
            CryEngine cryData = new CryEngine(args[0], testUtils.argsHandler.DataDir.FullName);

            cryData.ProcessCryengineFiles();

            COLLADA colladaData = new COLLADA(testUtils.argsHandler, cryData);

            colladaData.GenerateDaeObject();

            int actualMaterialsCount = colladaData.DaeObject.Library_Materials.Material.Count();

            Assert.AreEqual(0, actualMaterialsCount);

            testUtils.ValidateColladaXml(colladaData);
        }
Beispiel #22
0
        public void GhostSniper3_raquel_eyeoverlay_skin()
        {
            var args   = new string[] { $@"{userHome}\OneDrive\ResourceFiles\Test01\raquel_eyeoverlay.skin", "-dds", "-dae", "-objectdir", @"..\..\ResourceFiles\Test01\" };
            int result = testUtils.argsHandler.ProcessArgs(args);

            Assert.AreEqual(0, result);
            CryEngine cryData = new CryEngine(args[0], testUtils.argsHandler.DataDir.FullName);

            cryData.ProcessCryengineFiles();

            COLLADA colladaData = new COLLADA(testUtils.argsHandler, cryData);

            colladaData.GenerateDaeObject();

            int actualMaterialsCount = colladaData.DaeObject.Library_Materials.Material.Count();

            Assert.AreEqual(6, actualMaterialsCount);

            testUtils.ValidateColladaXml(colladaData);
        }
Beispiel #23
0
        public void UnknownSource_forest_ruin()
        {
            var args   = new string[] { $@"{userHome}\OneDrive\ResourceFiles\forest_ruin.cgf", "-dds", "-dae", "-objectdir", @"..\..\ResourceFiles\" };
            int result = testUtils.argsHandler.ProcessArgs(args);

            Assert.AreEqual(0, result);
            CryEngine cryData = new CryEngine(args[0], testUtils.argsHandler.DataDir.FullName);

            cryData.ProcessCryengineFiles();

            COLLADA colladaData = new COLLADA(testUtils.argsHandler, cryData);

            colladaData.GenerateDaeObject();

            int actualMaterialsCount = colladaData.DaeObject.Library_Materials.Material.Count();

            Assert.AreEqual(13, actualMaterialsCount);

            testUtils.ValidateColladaXml(colladaData);
        }
Beispiel #24
0
        public void SC_LR7_UOPP_VerifyImageFilePath()
        {
            var args   = new string[] { $@"{userHome}\OneDrive\ResourceFiles\SC\LR-7_UOPP.cga" };
            int result = testUtils.argsHandler.ProcessArgs(args);

            Assert.AreEqual(0, result);
            CryEngine cryData = new CryEngine(args[0], testUtils.argsHandler.DataDir.FullName);

            cryData.ProcessCryengineFiles();

            COLLADA colladaData = new COLLADA(testUtils.argsHandler, cryData);

            colladaData.GenerateDaeObject();

            int actualMaterialsCount = colladaData.DaeObject.Library_Materials.Material.Count();

            Assert.AreEqual(2, actualMaterialsCount);

            testUtils.ValidateColladaXml(colladaData);
        }
        public void AEGS_Avenger_IntegrationTest()
        {
            var args   = new string[] { @"..\..\ResourceFiles\SC\AEGS_Avenger.cga", "-dds", "-dae", "-objectdir", @"..\..\ResourceFiles\SC\" };
            int result = argsHandler.ProcessArgs(args);

            Assert.AreEqual(0, result);
            CryEngine cryData = new CryEngine(args[0], argsHandler.DataDir.FullName);

            var colladaData = new COLLADA(argsHandler, cryData);
            var daeObject   = colladaData.DaeObject;

            colladaData.GenerateDaeObject();
            // Make sure Rotations are still right
            const string frontLGDoorLeftMatrix = "1.000000 0.000000 0.000000 -0.300001 0.000000 -0.938131 -0.346280 0.512432 0.000000 0.346280 -0.938131 -1.835138 0.000000 0.000000 0.000000 1.000000";
            var          noseNode = daeObject.Library_Visual_Scene.Visual_Scene[0].Node[0].node[0];

            Assert.AreEqual("Nose", noseNode.ID);
            Assert.AreEqual("Front_LG_Door_Left", noseNode.node[28].ID);
            Assert.AreEqual(frontLGDoorLeftMatrix, noseNode.node[28].Matrix[0].Value_As_String);
        }
Beispiel #26
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "node":
                    if(Nodes == null)
                        Nodes	= new List<node>();
                    Nodes.Add(Doc.Load<node>(this,Child));
                    break;

                case "evaluate_scene":
                    if(EvaluateScenes == null)
                        EvaluateScenes	= new List<evaluate_scene>();
                    EvaluateScenes.Add(Doc.Load<evaluate_scene>(this,Child));
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #27
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "instance_animation":
                    if(InstanceAnimations == null)
                        InstanceAnimations	= new List<instance_animation>();
                    InstanceAnimations.Add(Doc.Load<instance_animation>(this,Child));
                    break;

                case "instance_formula":
                    if(InstanceFormulas == null)
                        InstanceFormulas	= new List<instance_formula>();
                    InstanceFormulas.Add(Doc.Load<instance_formula>(this,Child));
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #28
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "param":
                    if(Params == null)
                        Params	= new List<param>();
                    Params.Add(Doc.Load<param>(this,Child));
                    break;

                case "technique":
                    if(Technique == null)
                        Technique	= new List<technique>();
                    Technique.Add(Doc.Load<technique>(this,Child));
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #29
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "annotate":
                    if(Annotates == null)
                        Annotates	= new List<annotate>();
                    Annotates.Add(Doc.Load<annotate>(this,Child));
                    break;
                case "semantic":
                    Semantic	= Child.Value;
                    break;
                case "modifier":
                    Modifier	= (modifier)Enum.Parse(typeof(modifier),Child.Value);
                    break;

                case "float":
                    Value	= float.Parse(Child.Value);
                    break;

                case "float2":
                case "float3":
                case "float4":
                    char[] Splitter	= {' ','\n'};
                    string[] V	= Child.Value.Split(Splitter,StringSplitOptions.RemoveEmptyEntries);

                    Value	= new float[V.Length];

                    int i	= 0;
                    while(i < V.Length)
                    {
                        (Value as float[])[i]	= float.Parse(V[i]);
                        i++;
                    }

                    break;

                case "sampler2D":
                    break;
            }
        }
Beispiel #30
0
            public ISID GetElement(COLLADA root, out string selector)
            {
                selector = null;
                string[]   parts  = Path.Split('/');
                string     idName = parts[0];
                List <IID> ids    = root.GetIDEntries(idName);

                if (ids.Count == 0)
                {
                    return(null);
                }
                if (ids.Count > 1)
                {
                    //Minor edge case which doesn't typically happen.
                    //TODO: determine which is which
                    throw new InvalidOperationException($"{ids.Count} ID entries named '{idName}'. Cannot determine which is which.");
                }
                ISIDAncestor ancestor = ids[0];

                for (int i = 1; i < parts.Length; ++i)
                {
                    string part          = parts[i];
                    int    selectorIndex = part.IndexOf('.');
                    if (selectorIndex >= 0)
                    {
                        selector = part.Substring(selectorIndex + 1);
                        part     = part.Substring(0, selectorIndex);
                    }
                    else
                    {
                        int dimSelector = part.IndexOf('(');
                        if (dimSelector >= 0)
                        {
                            selector = part.Substring(dimSelector);
                            part     = part.Substring(0, dimSelector);
                        }
                    }
                    ancestor = ancestor.SIDElementChildren.FirstOrDefault(x => string.Equals(x.SID, part, StringComparison.InvariantCulture));
                }
                return(ancestor as ISID);
            }
        public void TestColladaImportMesh()
        {
            TheWizards.WorldDatabase.WorldDatabase db =
                new MHGameWork.TheWizards.WorldDatabase.WorldDatabase(System.Windows.Forms.Application.StartupPath +
                                                                      "\\Test\\Entity\\Editor\\ImportMeshParts");
            ColladaMeshImporter importer = new ColladaMeshImporter(db);

            COLLADA    collada;
            EditorMesh mesh;



            collada = COLLADA.FromStream(ColladaFiles.GetSimplePlaneDAE());
            mesh    = importer.ImportMesh(collada);

            collada = COLLADA.FromStream(ColladaFiles.GetAdvancedScene001DAE());
            mesh    = importer.ImportMesh(collada);

            collada = COLLADA.FromStream(ColladaFiles.GetTeapot001DAE());
            mesh    = importer.ImportMesh(collada);
        }
Beispiel #32
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "convex_mesh":
                    break;

                case "mesh":
                    Geometric	= Doc.Load<mesh>(this,Child);
                    break;

                case "spline":
                    break;

                case "brep":
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #33
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            if(Doc.Version < new Version(1,5))
                Ref	= Child.Value;
            else
            {
                switch(Child.Name)
                {
                    case "ref":
                        Ref	= Child.Value;
                        break;

                    case "hex":
                        Format	= Child.ChildNodes[0].Value;
                        break;

                    default:
                        throw new Exception("Invalid Child Node");
                }
            }
        }
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "input":
                    if(Inputs == null)
                        Inputs	= new List<input>();

                    input I	= Doc.Load<input>(this,Child);
                    Inputs.Add(I);

                    if(MaxOffset < I.Offset + 1)
                        MaxOffset	= I.Offset + 1;
                    break;

                case "p":
                    char[] Splitter	= {' ','\n'};
                    string[] V	= Child.InnerText.Split(Splitter,StringSplitOptions.RemoveEmptyEntries);

                    P	= new uint[MaxOffset,V.Length / MaxOffset];

                    int i	= 0;
                    while(i < MaxOffset)
                    {
                        int  j	= 0;
                        while(j < P.GetLength(1))
                        {
                            P[i,j]	= uint.Parse(V[i + (j * MaxOffset)]);
                            j++;
                        }

                        i++;
                    }
                    break;

                default:
                    InitChild(Doc,Child);
                    break;
            }
        }
Beispiel #35
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "xfov":
                    XFOV	= float.Parse(Child.InnerText);
                    break;

                case "yfov":
                    YFOV	= float.Parse(Child.InnerText);
                    break;

                case "aspect_ratio":
                    AspectRatio	= float.Parse(Child.InnerText);
                    break;

                case "znear":
                    ZNear	= float.Parse(Child.InnerText);
                    break;

                case "zfar":
                    ZFar	= float.Parse(Child.InnerText);
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }

            if(AspectRatio != 0)
            {
                if(YFOV != 0)
                    XFOV	= YFOV * AspectRatio;
                else if(XFOV != 0)
                    YFOV	= XFOV * AspectRatio;
            }
            else AspectRatio	= XFOV / YFOV;
        }
Beispiel #36
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "xmag":
                    XMag	= float.Parse(Child.InnerText);
                    break;

                case "ymag":
                    YMag	= float.Parse(Child.InnerText);
                    break;

                case "aspect_ratio>":
                    AspectRatio	= float.Parse(Child.InnerText);
                    break;

                case "znear":
                    ZNear	= float.Parse(Child.InnerText);
                    break;

                case "zfar":
                    ZFar	= float.Parse(Child.InnerText);
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }

            if(AspectRatio != 0)
            {
                if(YMag != 0)
                    XMag	= YMag * AspectRatio;
                else if(XMag != 0)
                    YMag	= XMag * AspectRatio;
            }
            else AspectRatio	= XMag / YMag;
        }
Beispiel #37
0
        void IHasChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "author":
                    Author	= Child.InnerText;
                    break;

                case "author_email":
                    Email	= Child.InnerText;
                    break;

                case "author_website":
                    Website	= new Uri(Child.InnerText);
                    break;

                case "authoring_tool":
                    Tool	= Child.InnerText;
                    break;

                case "comments":
                    Comments	= Child.InnerText;
                    break;

                case "copyright":
                    Copyright	= Child.InnerText;
                    break;

                case "source_data":
                    SourceData	= new Uri(Child.InnerText);
                    break;

                default:
                    throw new Exception("Invalid Child");
            }
        }
Beispiel #38
0
        private void LoadFromCollada(COLLADA dae, int roomIndex, int roomTableIndex)
        {
            m_UpAxis = dae.asset.up_axis;

            library_geometries    geo = (library_geometries)Array.Find(dae.Items, x => x.GetType() == typeof(library_geometries));
            library_visual_scenes vis = (library_visual_scenes)Array.Find(dae.Items, x => x.GetType() == typeof(library_visual_scenes));

            visual_scene scene = vis.visual_scene[0];

            RootNode = LoadGroupsFromColladaRecursive(null, scene.node[0], geo.geometry);

            FinalizeLoad();

            // Automatically set the room number.
            RootNode.RoomNumber = roomIndex;

            // Copy the room table index used by the original collision mesh's root node to all of the groups loaded from the dae.
            // This isn't perfect because some rooms (like dungeon hub rooms) have different collision groups using different room tables, and this method doesn't preserve that.
            // But this does work much better than not setting the room table index at all.
            foreach (CollisionGroupNode node in m_Nodes)
            {
                node.RoomTableIndex = roomTableIndex;
            }
        }
Beispiel #39
0
        public static void dumpModelToCOLLADA(Model3D mdl, float scale)
        {
            _scale = scale;
            COLLADA model = new COLLADA();

            model.scene = new COLLADAScene();
            model.scene.instance_visual_scene     = new InstanceWithExtra();
            model.scene.instance_visual_scene.url = "#scene";
            model.asset            = new asset();
            model.asset.unit       = new assetUnit();
            model.asset.unit.meter = 1.0;
            model.asset.unit.name  = "meter";
            model.asset.up_axis    = UpAxisType.Z_UP;

            model.Items = new object[] {
                MakeImagesLibrary(ref mdl, "Test"),
                MakeEffectsLibrary(ref mdl, "Test"),
                MakeMaterialsLibrary(ref mdl),
                MakeGeometryLibrary(ref mdl),
                MakeVisualScenesLibrary(ref mdl)
            };
            WriteAllTextures(mdl.builder.TextureImages, "Test");
            model.Save("Test.dae");
        }
        /// <summary>
        /// recursively find meshes in robot description
        /// </summary>
        /// <param name="elements"></param>
        /// <returns>success?</returns>
        private bool Parse(IEnumerable <XElement> elements = null)
        {
            if (elements == null)
            {
                RobotDescription = XDocument.Parse(this.robotdescription);
                if (RobotDescription != null && RobotDescription.Root != null)
                {
                    return(Parse(RobotDescription.Elements()));
                }
                return(false);
            }
            bool success = true;

            foreach (XElement element in elements)
            {
                if (element.Name == "mesh")
                {
                    COLLADA model = Load(element);
                    FindMatrices(model.Items);
                }
                success &= Parse(element.Elements());
            }
            return(success);
        }
Beispiel #41
0
            public ColladaScene(COLLADA collada, DAE.ImportSettings settings)
            {
                Settings    = settings;
                geometries  = FindLibraryItem <library_geometries>(collada.Items);
                images      = FindLibraryItem <library_images>(collada.Items);
                scenes      = FindLibraryItem <library_visual_scenes>(collada.Items);
                effects     = FindLibraryItem <library_effects>(collada.Items);
                controllers = FindLibraryItem <library_controllers>(collada.Items);
                materials   = FindLibraryItem <library_materials>(collada.Items);

                if (effects != null)
                {
                    for (int i = 0; i < effects.effect.Length; i++)
                    {
                        effectLookup.Add(effects.effect[i].id, effects.effect[i]);
                    }
                }

                if (collada.asset != null)
                {
                    UpAxisType = collada.asset.up_axis;
                    UintSize   = collada.asset.unit;
                }
            }
Beispiel #42
0
        void IHasTechChildNode.InitChildNode(COLLADA Doc,XmlNode Child)
        {
            switch(Child.Name)
            {
                case "ambient":
                    LightSource	= Doc.Load<ambient>(this,Child);
                    break;

                case "directional":
                    LightSource	= Doc.Load<directional>(this,Child);
                    break;

                case "point":
                    LightSource	= Doc.Load<point>(this,Child);
                    break;

                case "spot":
                    LightSource	= Doc.Load<spot>(this,Child);
                    break;

                default:
                    throw new Exception("Invalid Child Node");
            }
        }
Beispiel #43
0
        public bool LoadFile(string FileName)
        {
            GlobalTransform = Matrix4.Identity;

            COLLADA collada = COLLADA.Load(FileName);


            //Check axis up
            if (collada.asset != null)
            {
                switch (collada.asset.up_axis)
                {
                case UpAxisType.X_UP:
                    GlobalTransform = Matrix4.CreateRotationX(90);
                    break;

                case UpAxisType.Y_UP:
                    GlobalTransform = Matrix4.CreateRotationY(90);
                    break;

                case UpAxisType.Z_UP:
                    GlobalTransform = Matrix4.CreateRotationZ(90);
                    break;
                }

                if (collada.asset.unit != null)
                {
                    var amount = collada.asset.unit.meter;
                    var type   = collada.asset.unit.name;
                    if (type == "meter")
                    {
                    }
                    else if (type == "centimeter")
                    {
                    }
                }
            }

            foreach (var item in collada.Items)
            {
                if (item is library_controllers)
                {
                    LoadControllers((library_controllers)item);
                }
                if (item is library_geometries)
                {
                    LoadGeometry((library_geometries)item);
                }
                if (item is library_images)
                {
                    LoadImages((library_images)item);
                }
                if (item is library_controllers)
                {
                    LoadControllers((library_controllers)item);
                }
                if (item is library_nodes)
                {
                    LoadNodes((library_nodes)item);
                }
                if (item is library_visual_scenes)
                {
                    LoadVisualScenes((library_visual_scenes)item);
                }
            }

            return(true);
        }
Beispiel #44
0
        public Root Import(string inputPath)
        {
            var collada = COLLADA.Load(inputPath);
            var root    = new Root();

            root.ArtToolInfo = ImportArtToolInfo(collada);
            if (!Options.StripMetadata)
            {
                root.ExporterInfo = ImportExporterInfo(collada);
            }

            root.FromFileName = inputPath;

            root.Skeletons     = new List <Skeleton>();
            root.VertexDatas   = new List <VertexData>();
            root.TriTopologies = new List <TriTopology>();
            root.Meshes        = new List <Mesh>();
            root.Models        = new List <Model>();
            root.TrackGroups   = new List <TrackGroup>();
            root.Animations    = new List <Animation>();

            ColladaGeometries = new Dictionary <string, Mesh>();
            SkinnedMeshes     = new HashSet <string>();

            var collGeometries = new List <geometry>();
            var collSkins      = new List <skin>();
            var collAnimations = new List <animation>();
            var rootBones      = new List <RootBoneInfo>();

            // Import skinning controllers after skeleton and geometry loading has finished, as
            // we reference both of them during skin import
            foreach (var item in collada.Items)
            {
                if (item is library_controllers)
                {
                    var controllers = item as library_controllers;
                    if (controllers.controller != null)
                    {
                        foreach (var controller in controllers.controller)
                        {
                            if (controller.Item is skin)
                            {
                                collSkins.Add(controller.Item as skin);
                                SkinnedMeshes.Add((controller.Item as skin).source1.Substring(1));
                            }
                            else
                            {
                                Utils.Warn(String.Format("Controller {0} is unsupported and will be ignored", controller.Item.GetType().Name));
                            }
                        }
                    }
                }
                else if (item is library_visual_scenes)
                {
                    var scenes = item as library_visual_scenes;
                    if (scenes.visual_scene != null)
                    {
                        foreach (var scene in scenes.visual_scene)
                        {
                            if (scene.node != null)
                            {
                                foreach (var node in scene.node)
                                {
                                    FindRootBones(new List <node>(), node, rootBones);
                                }
                            }
                        }
                    }
                }
                else if (item is library_geometries)
                {
                    var geometries = item as library_geometries;
                    if (geometries.geometry != null)
                    {
                        foreach (var geometry in geometries.geometry)
                        {
                            if (geometry.Item is mesh)
                            {
                                collGeometries.Add(geometry);
                            }
                            else
                            {
                                Utils.Warn(String.Format("Geometry type {0} is unsupported and will be ignored", geometry.Item.GetType().Name));
                            }
                        }
                    }
                }
                else if (item is library_animations)
                {
                    var animations = item as library_animations;
                    if (animations.animation != null)
                    {
                        collAnimations.AddRange(animations.animation);
                    }
                }
                else
                {
                    Utils.Warn(String.Format("Library {0} is unsupported and will be ignored", item.GetType().Name));
                }
            }

            foreach (var bone in rootBones)
            {
                var skeleton      = Skeleton.FromCollada(bone.Bone);
                var rootTransform = NodeHelpers.GetTransformHierarchy(bone.Parents);
                skeleton.TransformRoots(rootTransform.Inverted());
                root.Skeletons.Add(skeleton);
            }

            foreach (var geometry in collGeometries)
            {
                VertexDescriptor vertexFormat = null;
                // Use the override vertex format, if one was specified
                Options.VertexFormats.TryGetValue(geometry.name, out vertexFormat);
                var mesh = ImportMesh(root, geometry.name, geometry, geometry.Item as mesh, vertexFormat);
                ColladaGeometries.Add(geometry.id, mesh);
            }

            // Import skinning controllers after skeleton and geometry loading has finished, as
            // we reference both of them during skin import
            if (rootBones.Count > 0)
            {
                foreach (var skin in collSkins)
                {
                    ImportSkin(root, skin);
                }
            }

            if (collAnimations.Count > 0)
            {
                ImportAnimations(collAnimations, root, root.Skeletons.FirstOrDefault());
            }

            var rootModel = new Model();

            rootModel.Name = "Unnamed"; // TODO
            if (root.Skeletons.Count > 0)
            {
                rootModel.Skeleton = root.Skeletons[0];
                rootModel.Name     = rootModel.Skeleton.Bones[0].Name;
            }
            rootModel.InitialPlacement = new Transform();
            rootModel.MeshBindings     = new List <MeshBinding>();
            foreach (var mesh in root.Meshes)
            {
                var binding = new MeshBinding();
                binding.Mesh = mesh;
                rootModel.MeshBindings.Add(binding);
            }

            root.Models.Add(rootModel);
            // TODO: make this an option!
            if (root.Skeletons.Count > 0)
            {
                root.Skeletons[0].UpdateWorldTransforms();
            }
            root.ZUp = ZUp;
            root.PostLoad(GR2.Header.DefaultTag);

            this.UpdateUserDefinedProperties(root);

            return(root);
        }
Beispiel #45
0
        public void ExportToCollada(string outputPath)
        {
            var collada     = new COLLADA();
            var asset       = new asset();
            var contributor = new assetContributor();

            if (ArtToolInfo != null)
            {
                contributor.authoring_tool = ArtToolInfo.FromArtToolName;
            }
            else
            {
                contributor.authoring_tool = "LSLib COLLADA Exporter v" + Common.LibraryVersion();
            }
            asset.contributor = new assetContributor[] { contributor };
            asset.created     = DateTime.Now;
            asset.modified    = DateTime.Now;
            asset.unit        = new assetUnit();
            asset.unit.name   = "meter";
            // TODO: Handle up vector, etc. properly?
            if (ArtToolInfo != null)
            {
                asset.unit.meter = ArtToolInfo.UnitsPerMeter;
            }
            else
            {
                asset.unit.meter = 1;
            }
            asset.up_axis = UpAxisType.Y_UP;
            collada.asset = asset;

            var geometries  = new List <geometry>();
            var controllers = new List <controller>();
            var geomNodes   = new List <node>();

            ExportModels(geometries, controllers, geomNodes);

            var animations     = new List <animation>();
            var animationClips = new List <animation_clip>();

            if (Animations != null)
            {
                foreach (var anim in Animations)
                {
                    var anims = anim.ExportAnimations();
                    animations.AddRange(anims);
                    var clip = new animation_clip();
                    clip.id           = anim.Name + "_Animation";
                    clip.name         = anim.Name;
                    clip.start        = 0.0;
                    clip.end          = anim.Duration;
                    clip.endSpecified = true;

                    var animInstances = new List <InstanceWithExtra>();
                    foreach (var animChannel in anims)
                    {
                        var instance = new InstanceWithExtra();
                        instance.url = "#" + animChannel.id;
                        animInstances.Add(instance);
                    }

                    clip.instance_animation = animInstances.ToArray();
                    animationClips.Add(clip);
                }
            }

            var rootElements = new List <object>();

            if (animations.Count > 0)
            {
                var animationLib = new library_animations();
                animationLib.animation = animations.ToArray();
                rootElements.Add(animationLib);
            }

            if (animationClips.Count > 0)
            {
                var animationClipLib = new library_animation_clips();
                animationClipLib.animation_clip = animationClips.ToArray();
                rootElements.Add(animationClipLib);
            }

            if (geometries.Count > 0)
            {
                var geometryLib = new library_geometries();
                geometryLib.geometry = geometries.ToArray();
                rootElements.Add(geometryLib);
            }

            if (controllers.Count > 0)
            {
                var controllerLib = new library_controllers();
                controllerLib.controller = controllers.ToArray();
                rootElements.Add(controllerLib);
            }

            var visualScenes = new library_visual_scenes();
            var visualScene  = new visual_scene();

            visualScene.id   = "DefaultVisualScene";
            visualScene.name = "unnamed";

            visualScene.node          = geomNodes.ToArray();
            visualScenes.visual_scene = new visual_scene[] { visualScene };

            var visualSceneInstance = new InstanceWithExtra();

            visualSceneInstance.url = "#DefaultVisualScene";
            rootElements.Add(visualScenes);

            var scene = new COLLADAScene();

            scene.instance_visual_scene = visualSceneInstance;
            collada.scene = scene;

            collada.Items = rootElements.ToArray();

            collada.Save(outputPath);
        }
Beispiel #46
0
        public void ImportFromCollada(string inputPath)
        {
            var collada = COLLADA.Load(inputPath);

            ImportArtToolInfo(collada);
            ImportExporterInfo(collada);
            FromFileName = inputPath;

            Skeletons     = new List <Skeleton>();
            VertexDatas   = new List <VertexData>();
            TriTopologies = new List <TriTopology>();
            Meshes        = new List <Mesh>();
            Models        = new List <Model>();
            TrackGroups   = new List <TrackGroup>();
            Animations    = new List <Animation>();

            ColladaGeometries = new Dictionary <string, Mesh>();
            SkinnedMeshes     = new HashSet <string>();

            var collGeometries = new List <geometry>();
            var collSkins      = new List <skin>();
            var collAnimations = new List <animation>();
            var rootBones      = new List <node>();

            // Import skinning controllers after skeleton and geometry loading has finished, as
            // we reference both of them during skin import
            foreach (var item in collada.Items)
            {
                if (item is library_controllers)
                {
                    var controllers = item as library_controllers;
                    if (controllers.controller != null)
                    {
                        foreach (var controller in controllers.controller)
                        {
                            if (controller.Item is skin)
                            {
                                collSkins.Add(controller.Item as skin);
                                SkinnedMeshes.Add((controller.Item as skin).source1.Substring(1));
                            }
                            else
                            {
                                Utils.Warn(String.Format("Controller {0} is unsupported and will be ignored", controller.Item.GetType().Name));
                            }
                        }
                    }
                }
                else if (item is library_visual_scenes)
                {
                    var scenes = item as library_visual_scenes;
                    if (scenes.visual_scene != null)
                    {
                        foreach (var scene in scenes.visual_scene)
                        {
                            foreach (var node in scene.node)
                            {
                                FindRootBones(null, node, rootBones);
                            }
                        }
                    }
                }
                else if (item is library_geometries)
                {
                    var geometries = item as library_geometries;
                    if (geometries.geometry != null)
                    {
                        foreach (var geometry in geometries.geometry)
                        {
                            if (geometry.Item is mesh)
                            {
                                collGeometries.Add(geometry);
                            }
                            else
                            {
                                Utils.Warn(String.Format("Geometry type {0} is unsupported and will be ignored", geometry.Item.GetType().Name));
                            }
                        }
                    }
                }
                else if (item is library_animations)
                {
                    var animations = item as library_animations;
                    if (animations.animation != null)
                    {
                        collAnimations.AddRange(animations.animation);
                    }
                }
                else
                {
                    Utils.Warn(String.Format("Library {0} is unsupported and will be ignored", item.GetType().Name));
                }
            }

            foreach (var bone in rootBones)
            {
                var skeleton = Skeleton.FromCollada(bone);
                Skeletons.Add(skeleton);
            }

            foreach (var geometry in collGeometries)
            {
                var mesh = ImportMesh(geometry.name, geometry.Item as mesh, FindVertexFormat(geometry));
                ColladaGeometries.Add(geometry.id, mesh);
            }

            // Import skinning controllers after skeleton and geometry loading has finished, as
            // we reference both of them during skin import
            foreach (var skin in collSkins)
            {
                ImportSkin(skin);
            }

            if (collAnimations.Count > 0)
            {
                ImportAnimations(collAnimations);
            }

            var rootModel = new Model();

            rootModel.Name = "Unnamed"; // TODO
            if (Skeletons.Count > 0)
            {
                rootModel.Skeleton = Skeletons[0];
                rootModel.Name     = rootModel.Skeleton.Bones[0].Name;
            }
            rootModel.InitialPlacement = new Transform();
            rootModel.MeshBindings     = new List <MeshBinding>();
            foreach (var mesh in Meshes)
            {
                var binding = new MeshBinding();
                binding.Mesh = mesh;
                rootModel.MeshBindings.Add(binding);
            }

            Models.Add(rootModel);
            // TODO: make this an option!
            if (Skeletons.Count > 0)
            {
                Skeletons[0].UpdateInverseWorldTransforms();
            }
            PostLoad();
        }
Beispiel #47
0
    static List <CELLMARK> cellmark_List  = new List <CELLMARK>();  // для текущей сцены

    static void Main()
    {
        var filesName = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.cellgrup", SearchOption.AllDirectories);

        System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

        List <Model> Models = new List <Model>(); // список мешей на сцене

        foreach (var file in filesName)
        {
            byte[] array1d = File.ReadAllBytes(file);

            int ci = 0; // счётчик вхождений

//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

            using (var br = new BinaryReader(File.Open(file, FileMode.Open)))
            {
                for (int i = 0; i < array1d.Length; i++)                                                                        // проходим по всем байтам файла *.cellgrup
                {
                    if (array1d[i + 0] == 0x69 && array1d[i + 1] == 0x00 && array1d[i + 2] == 0x00 && array1d[i + 3] == 0x00 && // i***
                        array1d[i + 4] == 0x64 && array1d[i + 5] == 0x65 && array1d[i + 6] == 0x66 && array1d[i + 7] == 0x61 && // defa
                        array1d[i + 8] == 0x75 && array1d[i + 9] == 0x6C && array1d[i + 10] == 0x74 && array1d[i + 11] == 0x00) // ult*
                    {
                        br.BaseStream.Position = i + 12;                                                                        // отступаем от "вхождения" на i***default* байт
                        int BlockSize = br.ReadInt32();                                                                         // размер блока
                        br.ReadInt32();                                                                                         // пропускаем пустые байты [00 00 00 00]

                        int type = br.ReadInt32();                                                                              // "тип" модели

                        if (type == 1819045731)
                        {
                            ci++;         // coll[modc]
                        }
                        if (type == 1634493549)
                        {
                            ci++;                           // mdla[ttr*]
                        }
                        if (type == 6581618)                // только для rmd*[****]
                        {
                            br.BaseStream.Position = i + 4; // "возвращаемся", чтобы скопировать модель
                            Model mesh = new Model();       // создаём модель
                            mesh.BaseStreamPosition = br.BaseStream.Position;
                            mesh.type    = type;
                            mesh.index   = ci++; // присваиваем и увеличиваем индекс
                            mesh.content = br.ReadBytes(BlockSize).ToList();
                            Models.Add(mesh);    // добавляем её в список моделей на "сцене"
                        }
                        i = i + BlockSize;       // ускоряем поиск?
                    }

                    // 63 65 6C 6C 69 6E 73 74 (места моделей)

                    if (array1d[i + 0] == 0x63 && array1d[i + 1] == 0x65 && array1d[i + 2] == 0x6C && array1d[i + 3] == 0x6C && // cell
                        array1d[i + 4] == 0x69 && array1d[i + 5] == 0x6E && array1d[i + 6] == 0x73 && array1d[i + 7] == 0x74)   // inst
                    {
                        br.BaseStream.Position = i + 16;

                        int count = br.ReadInt32(); // кол-во координат для расстановки моделей

                        for (int j = 0; j < count; j++)
                        {
                            CELLINST cellinst = new CELLINST(br);
                            cellinst_List.Add(cellinst);
                        }
                    }

                    // 63 65 6C 6C 6D 61 72 6B cellmark

                    if (array1d[i + 0] == 0x63 && array1d[i + 1] == 0x65 && array1d[i + 2] == 0x6C && array1d[i + 3] == 0x6C && // cell
                        array1d[i + 4] == 0x6D && array1d[i + 5] == 0x61 && array1d[i + 6] == 0x72 && array1d[i + 7] == 0x6B)   // mark
                    {
                        br.BaseStream.Position = i + 16;

                        int count = br.ReadInt32(); // кол-во координат для расстановки моделей

                        for (int j = 0; j < count; j++)
                        {
                            CELLMARK cellmark = new CELLMARK(br);
                            cellmark_List.Add(cellmark);
                        }
                    }
                }

//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

                foreach (var mesh in Models)
                {
                    for (int ji = 0; ji < mesh.content.Count; ji++)
                    {
                        // ИЩЕМ ВЕРШИНЫ // v // если нашли строку "position" = 00 00 00 00 70 6F 73 69 74 69 6F 6E

                        if (mesh.content[ji + 0] == 0x70 && mesh.content[ji + 1] == 0x6F && mesh.content[ji + 2] == 0x73 && mesh.content[ji + 3] == 0x69 && // 70 6F 73 69
                            mesh.content[ji + 4] == 0x74 && mesh.content[ji + 5] == 0x69 && mesh.content[ji + 6] == 0x6F && mesh.content[ji + 7] == 0x6E)   // 74 69 6F 6E
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;                                                                     // +20, если отступаем OOOO_position

                            int count = br.ReadInt32();
                            for (int j = 0; j < count; j++)
                            {
                                mesh.positionList.Add(new Vector3(br));
                            }
                        }

///////////// ИЩЕМ Vn (нормали)

                        if (mesh.content[ji + 0] == 0x6E && mesh.content[ji + 1] == 0x6F && mesh.content[ji + 2] == 0x72 && mesh.content[ji + 3] == 0x6D && // 6E 6F 72 6D
                            mesh.content[ji + 4] == 0x61 && mesh.content[ji + 5] == 0x6C && mesh.content[ji + 6] == 0x73 && mesh.content[ji + 7] == 0x00)   // 61 6C 73 00
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;
                            int count = br.ReadInt32();
                            for (int j = 0; j < count; j++)
                            {
                                mesh.normalsList.Add(new Vector3(br));
                            }
                        }

///////////// ИЩЕМ ГРАНИ FACES // 70 72 69 6D // 73 ( 00 00 00 )

                        if (mesh.content[ji + 0] == 0x70 && mesh.content[ji + 1] == 0x72 && mesh.content[ji + 2] == 0x69 && mesh.content[ji + 3] == 0x6D) // 70 72 69 6D 73
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;

                            int primsCount = br.ReadInt32();

                            for (int j = 0; j < primsCount; j++)
                            {
                                int faceNumber = br.ReadInt32();
                                int faceCount  = br.ReadInt32();
                                int faceSize   = br.ReadInt32();

                                List <TRI> face = new List <TRI>();

                                for (int f = 0; f < faceCount; f++)
                                {
                                    face.Add(new TRI(br, faceNumber));
                                }

                                mesh.subMeshFaces.Add(face);

                                for (int jj = 0; jj < 10; jj++)
                                {
                                    br.ReadInt32();                  // непонятные данные, мб для наложения текстур
                                }
                                if ((faceCount % 2) != 0)
                                {
                                    br.ReadUInt16();         // для "выравнивания" читается FF FF
                                }
                            }
                        }

///////////// ИЩЕМ uvs index , индексы текстурных координат // строку "textures" = // (00 00 FF FF) 74 65 78 74 75 72 65 73

                        //        if ( mesh.content[ji+0] == 0x00 && mesh.content[ji+1] == 0x00 && mesh.content[ji+2]  == 0x00 && mesh.content[ji+3]  == 0x00 && // это необходимо ?
                        if (mesh.content[ji + 0] == 0x74 && mesh.content[ji + 1] == 0x65 && mesh.content[ji + 2] == 0x78 && mesh.content[ji + 3] == 0x74 && // если да
                            mesh.content[ji + 4] == 0x75 && mesh.content[ji + 5] == 0x72 && mesh.content[ji + 6] == 0x65 && mesh.content[ji + 7] == 0x73)   // то изменить индексы
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;                                                                     // или +20 в big файле
                            int count = br.ReadInt32();
                            for (int j = 0; j < count; j++)
                            {
                                mesh.texturesList.Add(br.ReadUInt16());
                            }
                        }

///////////// ТЕКСТУРНЫЕ  КООРДИНАТЫ // vt // uvs. // 75 76 73 00 00 00 00 00
                        // может попастся два набора, поэтому пока что сохраняем смещение, а затем читаем что надо

                        if (mesh.content[ji + 0] == 0x75 && mesh.content[ji + 1] == 0x76 && mesh.content[ji + 2] == 0x73 && mesh.content[ji + 3] == 0x00) // 75 76 73 00
                        {
                            uvs_offset_int_list.Add(ji);
                        }

///////////////

/*
 *            // mdlattr*
 *
 *            if ( mesh.content[ji+0] == 0x6D && mesh.content[ji+1] == 0x64 && mesh.content[ji+2] == 0x6C && mesh.content[ji+3] == 0x61 &&
 *                 mesh.content[ji+4] == 0x74 && mesh.content[ji+5] == 0x74 && mesh.content[ji+6] == 0x72 && mesh.content[ji+7] == 0x00)
 *            {
 *                br.BaseStream.Position = mesh.BaseStreamPosition + ji + 8;
 *                int BlockSize = br.ReadInt32(); br.ReadInt32(); // 00 00 00 00
 *
 *                br.ReadInt32(); // 00 00 00 00
 *                br.ReadInt32(); // 00 00 00 00
 *
 *                int defaultBlockSize = br.ReadInt32();
 *
 *                br.ReadInt32();
 *                br.ReadInt32();
 *            }
 */
///////////// mtlctrl* // 6D 74 6C 63 74 72 6C 00

                        if (mesh.content[ji + 0] == 0x6D && mesh.content[ji + 1] == 0x74 && mesh.content[ji + 2] == 0x6C && mesh.content[ji + 3] == 0x63 && // 6D 74 6C 63
                            mesh.content[ji + 4] == 0x74 && mesh.content[ji + 5] == 0x72 && mesh.content[ji + 6] == 0x6C && mesh.content[ji + 7] == 0x00)   // 74 72 6C 00
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;
                            int count = br.ReadInt32();
                            for (int j = 0; j < count; j++)
                            {
                                Mtlctrl mtlctrl = new Mtlctrl(br);
                                mesh.mtlctrlList.Add(mtlctrl);
                            }
                        }

///////////// mlyrcolr ??? привильно ли я добавляю в список? по "сомнению" надо выделить три "строки" в один объект

                        if (mesh.content[ji + 0] == 0x6D && mesh.content[ji + 1] == 0x6C && mesh.content[ji + 2] == 0x79 && mesh.content[ji + 3] == 0x72 && // 6D 6C 79 72
                            mesh.content[ji + 4] == 0x63 && mesh.content[ji + 5] == 0x6F && mesh.content[ji + 6] == 0x6C && mesh.content[ji + 7] == 0x72)   // 63 6F 6C 72
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 20;
                            int count = br.ReadInt32();

                            for (int j = 0; j < count; j++)
                            {
                                for (int jj = 0; jj < 3; jj++)
                                {
                                    Mlyrcolr mlyrcolr = new Mlyrcolr(br);
                                    mesh.mlyrcolrList.Add(mlyrcolr);
                                }
                            }
                        }

///////////// mlyrctrl +++

                        if (mesh.content[ji + 0] == 0x6D && mesh.content[ji + 1] == 0x6C && mesh.content[ji + 2] == 0x79 && mesh.content[ji + 3] == 0x72 && // 6D 6C 79 72
                            mesh.content[ji + 4] == 0x63 && mesh.content[ji + 5] == 0x74 && mesh.content[ji + 6] == 0x72 && mesh.content[ji + 7] == 0x6C)   // 63 74 72 6C
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;
                            int flag  = br.ReadInt32(); // 0 или 1
                            int count = br.ReadInt32();

                            for (int j = 0; j < count; j++)
                            {
                                Mlyrctrl m = new Mlyrctrl(br);
                                mesh.mlyrctrlList.Add(m);
                            }
                        }

///////////// texture* +++

                        if (mesh.content[ji + 0] == 0x74 && mesh.content[ji + 1] == 0x65 && mesh.content[ji + 2] == 0x78 && mesh.content[ji + 3] == 0x74 && // 74 65 78 74
                            mesh.content[ji + 4] == 0x75 && mesh.content[ji + 5] == 0x72 && mesh.content[ji + 6] == 0x65 && mesh.content[ji + 7] == 0x00)   // 75 72 65 00
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 20;                                                                     // br.BaseStream.Position = mesh.BaseStreamPosition + ji + 20;

                            int count = br.ReadInt32();

                            for (int j = 0; j < count; j++)
                            {
                                Texture thz = new Texture(br);
                                mesh.texture_List.Add(thz);
                            }
                        }

///////////// vtxweigh +++

                        if (mesh.content[ji + 0] == 0x76 && mesh.content[ji + 1] == 0x74 && mesh.content[ji + 2] == 0x78 && mesh.content[ji + 3] == 0x77 && // 76 74 78 77
                            mesh.content[ji + 4] == 0x65 && mesh.content[ji + 5] == 0x69 && mesh.content[ji + 6] == 0x67 && mesh.content[ji + 7] == 0x68)   // 65 69 67 68
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;
                            int count = br.ReadInt32();
                            for (int ii = 0; ii < count; ii++)
                            {
                                mesh.vtxweighList.Add(br.ReadSingle());
                            }
                        }

///////////// jointidx +++

                        if (mesh.content[ji + 0] == 0x6A && mesh.content[ji + 1] == 0x6F && mesh.content[ji + 2] == 0x69 && mesh.content[ji + 3] == 0x6E && // 6A 6F 69 6E // join
                            mesh.content[ji + 4] == 0x74 && mesh.content[ji + 5] == 0x69 && mesh.content[ji + 6] == 0x64 && mesh.content[ji + 7] == 0x78)   // 74 69 64 78 // tidx
                        {
                            br.BaseStream.Position = mesh.BaseStreamPosition + ji + 16;

                            int count = br.ReadInt32();

                            for (int j = 0; j < count; j++)
                            {
                                mesh.jointidxList.Add(br.ReadUInt16());
                            }

                            int ffff = 0;
                            if (count % 2 != 0)
                            {
                                ffff = br.ReadUInt16();
                            }
                        }

///////////// collmodc
                    } // для массива внутри модели

//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

                    if (uvs_offset_int_list.Count > 0)
                    {
                        br.BaseStream.Position = mesh.BaseStreamPosition + uvs_offset_int_list[0] + 8;
                        int BlockSizeU0 = br.ReadInt32();  br.ReadInt32();
                        int number0     = br.ReadInt32(); // 00 00 00 00
                        int uvsCount    = br.ReadInt32();

                        for (int uvc = 0; uvc < uvsCount; uvc++)
                        {
                            mesh.uvs0.Add(new Vector2(br));
                        }

                        mesh.uvsList.Add(mesh.uvs0);
                    }

                    if (uvs_offset_int_list.Count > 1)
                    {
                        br.BaseStream.Position = mesh.BaseStreamPosition + uvs_offset_int_list[1] + 8;
                        int BlockSizeU1 = br.ReadInt32();  br.ReadInt32();
                        int number1     = br.ReadInt32(); // 01 00 00 00
                        int uvsCount    = br.ReadInt32();

                        for (int uvc = 0; uvc < uvsCount; uvc++)
                        {
                            mesh.uvs1.Add(new Vector2(br));
                        }

                        mesh.uvsList.Add(mesh.uvs1);
                    }

                    uvs_offset_int_list.Clear(); // обязательно очищаем для другой модели
                } // для каждой модели
            } //  binary reader

//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

            string name = file.Replace(".cellgrup", "");

            library_geometries lgeom = new library_geometries() // создаём библиотеку мешей
            {
                geometry = new geometry[Models.Count]           // в библиотеке геометрии Models.Count мешей
            };

/////////////////////////////////////////////////////////////////////////////////////////////////

            int qqq = 0;                 // шагаем по списку геометрий в файле

            foreach (var mesh in Models) // для каждой модели
            {
//-----------------------------------------------------------------------------------------------

                //{ создаём массив координат для вершин модели

                float_array xyz_N_array = new float_array() // массив для координат
                {
                    count = (ulong)mesh.positionList.Count * 3,
                    id    = "mesh_" + mesh.index + "_positions_array"
                };

                float_coords = new List <double>();

                foreach (var fl in mesh.positionList)
                {
                    float_coords.Add(fl.x);
                    float_coords.Add(fl.y);
                    float_coords.Add(fl.z);
                }

                xyz_N_array.Values = float_coords.ToArray();

//----------------------------------

                source pos_source = new source() //  источник для координат
                {
                    Item = xyz_N_array,
                    id   = "mesh_" + mesh.index + "_positions",

                    technique_common = new sourceTechnique_common()
                    {
                        accessor = new accessor()
                        {
                            count  = (ulong)mesh.positionList.Count,
                            offset = 0L,
                            source = "#" + xyz_N_array.id,
                            stride = 3L,
                            param  = new param[]
                            {
                                new param()
                                {
                                    name = "X", type = "float"
                                },
                                new param()
                                {
                                    name = "Y", type = "float"
                                },
                                new param()
                                {
                                    name = "Z", type = "float"
                                }
                            }
                        }
                    }
                };
                //}

//-----------------------------------------------------------------------------------------------

/*
 *      //{ создаём массив координат для нормалей модели
 *
 *          float_array xyz_Normals = new float_array()
 *          {
 *              count = (ulong)mesh.normalsList.Count * 3;
 *              id    = "mesh_" + mesh.index + "_normals_array";
 *          }
 *
 *          float_coords = new List<double>();
 *
 *          foreach(var fl in mesh.positionList)
 *          {
 *              float_coords.Add(fl.x);
 *              float_coords.Add(fl.y);
 *              float_coords.Add(fl.z);
 *          }
 *
 *          xyz_Normals.Values = float_coords.ToArray();
 *
 * //----------------------------------
 *
 *          source norm_source = new source()
 *          {
 *              Item  =  xyz_N_array,
 *              id    =  "mesh_" + mesh.index + "_positions",
 *
 *              technique_common = new sourceTechnique_common()
 *              {
 *                  accessor = new accessor()
 *                  {
 *                    count = (ulong)mesh.positionList.Count,
 *                    offset = 0L,
 *                    source = "#" + xyz_N_array.id,
 *                    stride = 3L,
 *
 *                    param = new param[]
 *                    {
 *                      new param()  {  name = "X",  type = "float" },
 *                      new param()  {  name = "Y",  type = "float" },
 *                      new param()  {  name = "Z",  type = "float" }
 *                    }
 *                  }
 *              }
 *          };
 *      //}
 */

//-----------------------------------------------------------------------------------------------

                vertices v = new vertices() //  вершины = часть объекта mesh
                {
                    id = "mesh_" + mesh.index + "_vertices",

                    input = new InputLocal[]
                    {
                        new InputLocal() // пока что только коорднаты
                        {
                            semantic = "POSITION",
                            source   = "#" + pos_source.id
                        }
                    }
                };

//-----------------------------------------------------------------------------------------------

                int faceNumber = 0;

                foreach (var q in mesh.subMeshFaces)
                {
                    foreach (var qq in q)
                    {
                        faceNumber++;
                    }
                }

                triangles tres = new triangles() //  треугольники = часть объекта mesh
                {
                    count = (ulong)faceNumber,
                    input = new InputLocalOffset[]
                    {
                        new InputLocalOffset() //  пока что только для координат
                        {
                            semantic = "VERTEX",
                            offset   = 0L,
                            source   = "#" + v.id
                        }
                    }
                };

//----------------------------------

                StringBuilder all_TRI = new StringBuilder();

                foreach (var q in mesh.subMeshFaces)
                {
                    foreach (var qq in q)
                    {
                        string str = qq.vi0 + " " + qq.vi1 + " " + qq.vi2 + " ";
                        all_TRI.Append(str);
                    }
                }

                tres.p = all_TRI.ToString();

//-----------------------------------------------------------------------------------------------

                mesh m = new mesh() //  создаём объект меша
                {
                    vertices = v,

                    source = new source[1] //  пока что только 1 источник для position
                    {
                        pos_source
                    },

                    Items = new object[1] //  для треугольников
                    {
                        tres
                    }
                };

//-----------------------------------------------------------------------------------------------

                geometry geom = new geometry()   // создаём оболочку для меши
                {
                    id   = "mesh_" + mesh.index, // задаём ей имя mesh_№
                    Item = m
                };

                lgeom.geometry[qqq++] = geom;
            } // для каждой модели в файле cellgrup создаём блоки с геометрией

//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

            library_visual_scenes lvs = new library_visual_scenes(); // создаём библиотеку сцен

            visual_scene vs = new visual_scene()                     //  создаём сцену, вроде всегда одна
            {
                id   = "MyScene",                                    //  обзываем её
                node = new node[Models.Count]                        //  добавляем узлы для моделей на сцене
            };

//===============================================================================================

            qqq = 0; // шагаем по списку мешей, создаём им ноды, задаём расположение

            foreach (var mesh in Models)
            {
//----------------------------------

                node n = new node()
                {
                    id = "mesh" + mesh.index,

                    instance_geometry = new instance_geometry[]
                    {
                        new instance_geometry()
                        {
                            url = "#" + lgeom.geometry[qqq].id
                        }
                    }
                };

//----------------------------------

                n.ItemsElementName = new ItemsChoiceType2[5]
                {
                    ItemsChoiceType2.translate,
                    ItemsChoiceType2.rotate,
                    ItemsChoiceType2.rotate,
                    ItemsChoiceType2.rotate,
                    ItemsChoiceType2.scale
                };

//----------------------------------

                float xx = 0.0f;
                float yy = 0.0f;
                float zz = 0.0f;

                float rx = 0.0f;
                float ry = 0.0f;
                float rz = 0.0f;

                for (int ccc = 0; ccc < cellinst_List.Count; ccc++)
                {
                    if (mesh.index == cellinst_List[ccc].number)
                    {
                        xx = cellinst_List[ccc].position.x;
                        yy = cellinst_List[ccc].position.y;
                        zz = cellinst_List[ccc].position.z;

                        rx = cellinst_List[ccc].rotation.x;
                        ry = cellinst_List[ccc].rotation.y;
                        rz = cellinst_List[ccc].rotation.z;
                    }
                }

                for (int ccc = 0; ccc < cellmark_List.Count; ccc++)
                {
                    if (mesh.index == cellmark_List[ccc].number1)
                    {
                        xx = cellmark_List[ccc].position.x;
                        yy = cellmark_List[ccc].position.y;
                        zz = cellmark_List[ccc].position.z;

                        rx = cellmark_List[ccc].rotation.x;
                        ry = cellmark_List[ccc].rotation.y;
                        rz = cellmark_List[ccc].rotation.z;
                    }
                }

//----------------------------------

                n.Items = new object[5]
                {
                    new TargetableFloat3()
                    {
                        sid    = "location", // translate
                        Values = new double[3] {
                            xx, yy, zz
                        }
                    },

                    new rotate()
                    {
                        sid = "rotationX", Values = new double[4] {
                            0, 0, 1, rz *57.5
                        }
                    },                                                                           // Z
                    new rotate()
                    {
                        sid = "rotationY", Values = new double[4] {
                            0, 1, 0, ry *57.5
                        }
                    },                                                                           // Y почему такой "угол" ?
                    new rotate()
                    {
                        sid = "rotationZ", Values = new double[4] {
                            1, 0, 0, rx *57.5
                        }
                    },                                                                           // X

                    new TargetableFloat3()
                    {
                        sid = "scale", Values = new double[3] {
                            1, 1, 1
                        }
                    }
                };

//----------------------------------

                vs.node[qqq] = n;

                qqq++;
            } // для каждой модели в файле cellgrup

//-----------------------------------------------------------------------------------------------

            lvs.visual_scene = new visual_scene[1] // создаём массив для сцен
            {
                vs                                 // добавляем visual_scene в library_visual_scenes
            };

//-----------------------------------------------------------------------------------------------

            COLLADA collada = new COLLADA()
            {
                asset = new asset()
                {
                    up_axis = UpAxisType.Z_UP
                },

                Items = new object[] // для библиотеки мешей и сцен
                {
                    lgeom,           // присваиваем колладе библиотеку геометрию
                    lvs              // в массив Item добавляем библиотеку сцен
                },

                scene = new COLLADAScene()
                {
                    instance_visual_scene = new InstanceWithExtra()
                    {
                        url = "#" + vs.id
                    }
                }
            };

//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

            collada.Save(name + ".dae");

            Models.Clear();

            cellinst_List.Clear();
            cellmark_List.Clear();

//88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
        } // для каждого cellgrup файла
    }     // void Main()
Beispiel #48
0
        public COLLADA ToCollada(string[] textures)
        {
            COLLADA result = new COLLADA
            {
                version = VersionType.Item140,
                asset   = new asset
                {
                    contributor = new assetContributor[] { new assetContributor()
                                                           {
                                                               authoring_tool = "SAModel"
                                                           } },
                    created  = DateTime.UtcNow,
                    modified = DateTime.UtcNow
                }
            };
            List <object> libraries = new List <object>();
            List <image>  images    = new List <image>();

            if (textures != null)
            {
                for (int i = 0; i < textures.Length; i++)
                {
                    images.Add(new image
                    {
                        id   = "image_" + (i + 1).ToString(NumberFormatInfo.InvariantInfo),
                        name = "image_" + (i + 1).ToString(NumberFormatInfo.InvariantInfo),
                        Item = textures[i] + ".png"
                    });
                }
            }
            libraries.Add(new library_images {
                image = images.ToArray()
            });
            List <material> materials       = new List <material>();
            List <effect>   effects         = new List <effect>();
            List <geometry> geometries      = new List <geometry>();
            List <string>   visitedAttaches = new List <string>();
            int             nodeID          = -1;
            node            node            = AddToCollada(materials, effects, geometries, visitedAttaches, textures != null, ref nodeID);

            libraries.Add(new library_materials {
                material = materials.ToArray()
            });
            libraries.Add(new library_effects {
                effect = effects.ToArray()
            });
            libraries.Add(new library_geometries {
                geometry = geometries.ToArray()
            });
            libraries.Add(new library_visual_scenes
            {
                visual_scene = new visual_scene[]
                {
                    new visual_scene
                    {
                        id   = "RootNode",
                        node = new node[] { node }
                    }
                }
            });
            result.Items = libraries.ToArray();
            result.scene = new COLLADAScene {
                instance_visual_scene = new InstanceWithExtra {
                    url = "#RootNode"
                }
            };
            return(result);
        }
Beispiel #49
0
        public void Export(RootEntity[] entities, string selectedPath)
        {
            for (int i = 0; i < entities.Length; i++)
            {
                var entity     = entities[i];
                var modelCount = entity.ChildEntities.Length;
                var geometries = new library_geometries
                {
                    geometry = new geometry[modelCount]
                };
                var          visualSceneNodes = new node[modelCount];
                const string visualSceneName  = "visual-scene";
                var          visualScenes     = new library_visual_scenes
                {
                    visual_scene = new[]
                    {
                        new visual_scene
                        {
                            id   = visualSceneName,
                            name = visualSceneName,
                            node = visualSceneNodes
                        }
                    }
                };
                for (int j = 0; j < modelCount; j++)
                {
                    var model             = (ModelEntity)entity.ChildEntities[j];
                    var modelName         = string.Format("model-{0}-lib", j);
                    var materialName      = string.Format("{0}-material", modelName);
                    var triangleCount     = model.Triangles.Count();
                    var elementGroupCount = triangleCount * 3;
                    var elementCount      = elementGroupCount * 3;

                    var acessorParams = new[]
                    {
                        new param
                        {
                            name = "X",
                            type = "float"
                        },
                        new param
                        {
                            name = "Y",
                            type = "float"
                        },
                        new param
                        {
                            name = "Z",
                            type = "float"
                        }
                    };

                    #region Position

                    var positionArrayName = string.Format("{0}-positions-array", modelName);
                    var positionAccessor  = new accessor
                    {
                        count  = (ulong)elementGroupCount,
                        offset = 0,
                        source = string.Format("#{0}", positionArrayName),
                        stride = 3,
                        param  = acessorParams
                    };
                    var positionTechnique = new sourceTechnique_common
                    {
                        accessor = positionAccessor
                    };
                    var positionArrayValues = new double[elementCount];
                    var positionArray       = new float_array
                    {
                        id     = positionArrayName,
                        count  = (ulong)elementCount,
                        Values = positionArrayValues
                    };
                    var positionName   = string.Format("{0}-positions", modelName);
                    var positionSource = new source
                    {
                        id               = positionName,
                        name             = "position",
                        Item             = positionArray,
                        technique_common = positionTechnique
                    };
                    #endregion

                    #region Normal
                    var normalArrayName = string.Format("{0}-normals-array", modelName);
                    var normalAccessor  = new accessor
                    {
                        count  = (ulong)elementGroupCount,
                        offset = 0,
                        source = string.Format("#{0}", normalArrayName),
                        stride = 3,
                        param  = acessorParams
                    };
                    var normalTechinique =
                        new sourceTechnique_common
                    {
                        accessor = normalAccessor
                    };
                    var normalArrayValues = new double[elementCount];
                    var normalArray       = new float_array
                    {
                        id     = normalArrayName,
                        count  = (ulong)elementCount,
                        Values = normalArrayValues
                    };
                    var normalName   = string.Format("{0}-normals", modelName);
                    var normalSource = new source
                    {
                        id               = normalName,
                        name             = "normal",
                        Item             = normalArray,
                        technique_common = normalTechinique
                    };
                    #endregion

                    #region Processing
                    var triangleIndices = new StringBuilder();
                    for (int l = 0; l < model.Triangles.Length; l++)
                    {
                        var triangle = model.Triangles[l];
                        for (var k = 0; k < 3; k++)
                        {
                            var elementIndex = l * 3 + k;

                            var vertex = triangle.Vertices[k];
                            var normal = triangle.Normals[k];
                            var color  = triangle.Colors[k];
                            var uv     = triangle.Uv[k];

                            positionArrayValues[elementIndex]     = vertex.X;
                            positionArrayValues[elementIndex + 1] = vertex.Y;
                            positionArrayValues[elementIndex + 2] = vertex.Z;

                            normalArrayValues[elementIndex]     = normal.X;
                            normalArrayValues[elementIndex + 1] = normal.Y;
                            normalArrayValues[elementIndex + 2] = normal.Z;

                            triangleIndices.Append(elementIndex);
                            triangleIndices.Append(" ");
                        }
                    }

                    #endregion

                    #region Vertices
                    var verticesName = string.Format("{0}-vertices", modelName);
                    var triangles    = new triangles
                    {
                        count    = (ulong)triangleCount,
                        material = materialName,
                        input    = new[]
                        {
                            new InputLocalOffset
                            {
                                offset   = 0,
                                semantic = "VERTEX",
                                source   = string.Format("#{0}", verticesName)
                            }//,
                             //new InputLocalOffset
                             //{
                             //    offset = 1,
                             //    semantic = "NORMAL",
                             //    source = string.Format("#{0}", normalName)
                             //}
                        },
                        p = triangleIndices.ToString()
                    };
                    #endregion

                    #region Mesh
                    var mesh = new mesh
                    {
                        source   = new[] { positionSource, normalSource },
                        vertices = new vertices
                        {
                            id    = verticesName,
                            input = new[]
                            {
                                new InputLocal
                                {
                                    semantic = "POSITION",
                                    source   = string.Format("#{0}", positionName)
                                }
                            }
                        },
                        Items = new object[] { triangles }
                    };
                    #endregion

                    #region Geometry
                    var geometryName = string.Format("{0}-geometry", modelName);
                    var geometry     = new geometry
                    {
                        id   = geometryName,
                        name = geometryName,
                        Item = mesh
                    };
                    geometries.geometry[j] = geometry;
                    #endregion

                    #region Visual Node
                    var visualSceneNodeName = string.Format("{0}-node", modelName);
                    visualSceneNodes[j] = new node
                    {
                        name = visualSceneNodeName,
                        id   = visualSceneNodeName,
                        instance_geometry = new[]
                        {
                            new instance_geometry
                            {
                                url = string.Format("#{0}", geometryName)
                            }
                        }
                    };
                    #endregion
                }
                var collada = new COLLADA
                {
                    Items = new Object[]
                    {
                        geometries,
                        visualScenes
                    },
                    scene = new COLLADAScene
                    {
                        instance_visual_scene = new InstanceWithExtra
                        {
                            url = string.Format("#{0}", visualSceneName)
                        }
                    }
                };
                var fileName = string.Format("{0}/dae{1}.dae", selectedPath, i);
                collada.Save(fileName);
            }
        }
Beispiel #50
0
 private void SetControllers(COLLADA collada)
 {
 }
        public static string ExportFile(FullModelData data, string path)
        {
            path = path.Replace(".model", ".dae");

            List <SectionHeader>          sections        = data.sections;
            Dictionary <UInt32, ISection> parsed_sections = data.parsed_sections;

            byte[] leftover_data = data.leftover_data;

            // Set up the XML structure
            library_geometries libgeoms = new library_geometries();

            library_visual_scenes libscenes = new library_visual_scenes();

            COLLADAScene scene = new COLLADAScene
            {
                instance_visual_scene = new InstanceWithExtra
                {
                    url = "#scene"
                }
            };

            COLLADA collada = new COLLADA
            {
                Items = new object[] { libgeoms, libscenes },
                scene = scene,
                asset = new asset
                {
                    created  = DateTime.UtcNow,
                    modified = DateTime.UtcNow,

                    // Otherwise it defaults to Y-up (see asset's constructor), while we're
                    //  using Z-up. Without the asset tag Blender defaults to Z-up, so if you
                    //  remove this then the presence of the asset tag flips the model.
                    up_axis = UpAxisType.Z_UP,
                },
            };

            // Build the mesh

            List <geometry> geometries = new List <geometry>();
            List <node>     nodes      = new List <node>();

            int model_i = 0;

            foreach (SectionHeader sectionheader in sections)
            {
                if (sectionheader.type == model_data_tag)
                {
                    Model model_data = (Model)parsed_sections[sectionheader.id];
                    if (model_data.version == 6)
                    {
                        continue;
                    }

                    model_i++;

                    string model_id = model_i + "-" + model_data.HashName.String;

                    PassthroughGP passthrough_section = model_data.PassthroughGP;
                    Geometry      geometry_section    = passthrough_section.Geometry;
                    Topology      topology_section    = passthrough_section.Topology;
                    geometry      geom = SerializeModel(geometry_section, topology_section, model_data, model_id);

                    geometries.Add(geom);

                    node root_node = new node
                    {
                        id   = "model-" + model_id,
                        name = "Model " + model_id,
                        type = NodeType.NODE,

                        instance_geometry = new instance_geometry[]
                        {
                            new instance_geometry
                            {
                                url  = "#model-geom-" + model_id,
                                name = "Model Geom" + model_id
                            }
                        }
                    };

                    nodes.Add(root_node);

                    if (model_data.SkinBones == null)
                    {
                        continue;
                    }

                    SkinBones sb = model_data.SkinBones;
                    //Console.WriteLine(sb.bones);
                    //Console.WriteLine(sb);

                    node bone_root_node = new node
                    {
                        id   = "model-" + model_id + "-boneroot",
                        name = "Model " + model_id + " Bones",
                        type = NodeType.NODE,

                        /*Items = new object[]
                         *  {
                         *      new matrix
                         *      {
                         *          sid = "transform", // Apparently Blender really wants this
                         *          Values = MathUtil.Serialize(sb.unknown_matrix)
                         *      }
                         *  },
                         * ItemsElementName = new ItemsChoiceType2[]
                         *  {
                         *      ItemsChoiceType2.matrix
                         *  }*/
                    };
                    root_node.node1 = new node[] { bone_root_node };

                    Dictionary <Object3D, node> bones = new Dictionary <Object3D, node>();

                    // In order to find locators, which aren't present in the SkinBones
                    // object, we check the child of each object we process.
                    //
                    // To then process those, we use a queue (to_parse) which lists the
                    // objects in our TODO list to search. We draw from this as we process them.
                    //
                    // We also keep the list of what we have processed in (parsed), so we don't
                    // process anything twice.
                    //
                    // TODO rewrite this code to be based around children, removing the need for a seperate
                    // loop after this that arranges the heirachy of nodes.
                    List <Object3D>  parsed   = new List <Object3D>(sb.Objects);
                    Queue <Object3D> to_parse = new Queue <Object3D>(sb.Objects);

                    int i = 0;
                    while (to_parse.Count != 0)
                    {
                        Object3D obj = to_parse.Dequeue();

                        string bonename = obj.HashName.String;

                        // Find the locators and such, and add them to the TODO list
                        foreach (Object3D child in obj.children)
                        {
                            if (!parsed.Contains(child)) // Don't process something twice
                            {
                                parsed.Add(child);
                                to_parse.Enqueue(child);
                            }
                        }

                        Vector3    translate;
                        Quaternion rotate;
                        Vector3    scale;
                        Matrix4x4.Decompose(obj.Transform, out scale, out rotate, out translate);

                        Matrix4x4 final_rot = Matrix4x4.CreateFromQuaternion(rotate);
                        final_rot.Translation = translate;

                        if (obj.Parent == null || !sb.Objects.Contains(obj.Parent))
                        {
                            Matrix4x4 fixed_obj_transform = obj.WorldTransform;
                            Matrix4x4.Decompose(fixed_obj_transform, out scale, out rotate, out translate);

                            // Fixes the head, but breaks the arms
                            // For now, leave it like this
                            //final_rot = final_rot.MultDiesel(fixed_obj_transform);
                        }

                        // If the object is not contained within the SkinBones
                        // object, it must be a locator.
                        bool locator = !sb.Objects.Contains(obj);

                        // Add the node
                        bones[obj] = new node
                        {
                            id    = "model-" + model_id + "-bone-" + bonename,
                            name  = (locator ? "locator-" : "") + bonename,
                            type  = NodeType.JOINT,
                            Items = new object[]
                            {
                                new matrix
                                {
                                    sid    = "transform", // Apparently Blender really wants this
                                    Values = MathUtil.Serialize(final_rot)
                                },
                            },
                            ItemsElementName = new ItemsChoiceType2[]
                            {
                                ItemsChoiceType2.matrix
                            }
                        };

                        i++;
                    }

                    foreach (var(obj, nod) in bones)
                    {
                        node parent = bone_root_node;

                        if (bones.ContainsKey(obj))
                        {
                            parent = bones[obj.Parent];
                        }

                        if (parent.node1 == null)
                        {
                            parent.node1 = new node[1];
                        }
                        else
                        {
                            node[] children = parent.node1;
                            Array.Resize(ref children, children.Length + 1);
                            parent.node1 = children;
                        }

                        parent.node1[parent.node1.Length - 1] = nod;
                    }
                }
            }

            libgeoms.geometry = geometries.ToArray();

            libscenes.visual_scene = new visual_scene[]
            {
                new visual_scene
                {
                    id   = "scene",
                    name = "Scene",
                    node = nodes.ToArray()
                }
            };

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                collada.Save(fs);

                // Do we need this?
                // fs.Close();
            }

            return(path);
        }
Beispiel #52
0
        public KSPPartAttrib(TextReader stream)
        {
            int    lineIdx = 0;
            String line;

            Regex r = new Regex(@"((\s)*(?<Key>([^\=^\s^\n]+))[\s^\n] \= (\s)*(?<Value>([^\n^\s]+(\n){0,1})))", RegexOptions.Compiled | RegexOptions.ExplicitCapture);

            List <String[]> extraLines = new List <string[]>();

            while ((line = stream.ReadLine()) != "")
            {
                lineIdx++;

                if (line.Substring(0, 1) == "//")
                {
                    continue;
                }

                var match = r.Match(line);

                var key = match.Groups["Key"].Value;
                var val = match.Groups["Value"].Value;

                switch (key.Trim())
                {
                case "name":
                    name = val;
                    break;

                case "module":
                    if (!Enum.TryParse <KSPPartModule>(val, out module))
                    {
                        throw new Exception(String.Format("Module string '{0}' could not be parsed into a module known to this program. (Line {1})", val, lineIdx));
                    }
                    break;

                case "author":
                    author = val;
                    break;

                case "mesh":
                    mesh = COLLADA.Load(val);
                    break;

                case "scale":
                    try
                    {
                        scale = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("scale string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "texture":
                    texture = val;
                    break;

                case "specPower":
                    try
                    {
                        specPower = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("specPower string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "rimFalloff":
                    try
                    {
                        rimFalloff = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("rimFalloff string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "alphaCutoff":
                    try
                    {
                        alphaCutoff = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("alphaCutoff string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "iconCenter":
                    var comps = val.Split(',');
                    try
                    {
                        double x = Double.Parse(comps[0].Trim());
                        double y = Double.Parse(comps[1].Trim());
                        double z = Double.Parse(comps[2].Trim());

                        iconCenter = new Point3()
                        {
                            x = x, y = y, z = z
                        };
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("iconCenter string '{0}' could not be parsed into doubles. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "cost":
                    try
                    {
                        cost = Int32.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("cost string '{0}' could not be parsed into Int32. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "category":
                    try
                    {
                        category = Int32.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("category string '{0}' could not be parsed into Int32. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "subcategory":
                    try
                    {
                        subcategory = Int32.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("subcategory string '{0}' could not be parsed into Int32. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "title":
                    title = val;
                    break;

                case "manufacturer":
                    manufacturer = val;
                    break;

                case "description":
                    description = val;
                    break;

                case "attachRules":
                    try
                    {
                        comps = val.Split(',');

                        attachmentStack          = (comps[0].Trim() == "1");
                        attachmentSurf           = (comps[1].Trim() == "1");
                        attachmentAllowStack     = (comps[2].Trim() == "1");
                        attachmentAllowSurf      = (comps[3].Trim() == "1");
                        attachmentAllowCollision = (comps[4].Trim() == "1");
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("attachRules string '{0}' could not be parsed into valid attachment rules. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "mass":
                    try
                    {
                        mass = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("mass string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "dragModelType":
                    dragModelType = val;
                    break;

                case "maximum_drag":
                    try
                    {
                        maximum_drag = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("maximum_drag string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "minimum_drag":
                    try
                    {
                        minimum_drag = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("minimum_drag string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "angularDrag ":
                    try
                    {
                        angularDrag = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("angularDrag string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "crashTolerance":
                    try
                    {
                        crashTolerance = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("crashTolerance string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                case "maxTemp":
                    try
                    {
                        maxTemp = Double.Parse(val.Trim());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(String.Format("maxTemp string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                    }
                    break;

                default:
                    if (val.Substring(0, 4) == "node")
                    {
                        try{
                            comps = val.Split(',');

                            double x = Double.Parse(comps[0].Trim());
                            double y = Double.Parse(comps[1].Trim());
                            double z = Double.Parse(comps[2].Trim());

                            double vx = Double.Parse(comps[3].Trim());
                            double vy = Double.Parse(comps[4].Trim());
                            double vz = Double.Parse(comps[5].Trim());

                            nodeDefinitions.Add(new KSPAttribNodeDefinition()
                            {
                                Name = key, Position = new Point3()
                                {
                                    x = x, y = y, z = z
                                }, UpVector = new Point3()
                                {
                                    x = vx, y = vy, z = vz
                                }
                            });
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("node string '{0}' ({2}) could not be parsed into doubles. (Line {1})", val, lineIdx, key), e);
                        }
                    }
                    else if (val.Trim() != "")
                    {
                        extraLines.Add(new string[] { key, val });
                    }
                    break;
                }
            }
            switch (module)
            {
            case KSPPartModule.AdvSASModule:
                break;

            case KSPPartModule.FuelLine:
                break;

            case KSPPartModule.FuelTank:
                break;

            case KSPPartModule.LiquidEngine:
                break;

            case KSPPartModule.CommandPod:
                break;

            case KSPPartModule.Parachutes:
                break;

            case KSPPartModule.RadialDecoupler:
                break;

            case KSPPartModule.RCSModule:
                break;

            case KSPPartModule.RCSFuelTank:
                break;

            case KSPPartModule.SASModule:
                break;

            case KSPPartModule.SolidRocket:
                break;

            case KSPPartModule.Decoupler:
                break;

            case KSPPartModule.Strut:
                break;

            case KSPPartModule.StrutConnector:
                break;

            case KSPPartModule.Winglet:
                break;

            case KSPPartModule.ControlSurface:
                break;

            default:
                throw new Exception(String.Format("No specific part parser for module '{0}'. Well, that's awkward. (We're in KSPEdit.Model.KSPPartAttrib btw, if you feel like reporting this)", module.ToString()));
                break;
            }
        }
Beispiel #53
0
 public T GetElement <T>(COLLADA root, out string selector) where T : ISID
 => (T)GetElement(root, out selector);
Beispiel #54
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            COLLADA model = new COLLADA();

            // init new
            model.asset = new asset();
            model.asset.contributor[1] = new assetContributor();
            model.asset.contributor[0] = new assetContributor();

            model.asset.unit    = new assetUnit();
            model.asset.up_axis = new UpAxisType();

            model.Items = new object[1];

            // asset
            model.asset.contributor[0].author         = "caimagic";
            model.asset.contributor[0].authoring_tool = "FBX COLLADA exporter";
            model.asset.contributor[0].comments       = "hello world";
            model.asset.unit.meter = 0.01;
            model.asset.unit.name  = "centimer";
            model.asset.up_axis    = UpAxisType.Y_UP;

            // library_geometries
            library_geometries library_geom = new library_geometries();

            library_geom.geometry[1] = new geometry();
            library_geom.geometry[0] = new geometry();

            geometry geom = new geometry();

            mesh geomMesh = new mesh();

            geomMesh.source[3] = new source();
            geomMesh.source[0] = new source();
            geomMesh.source[1] = new source();
            geomMesh.source[2] = new source();

            float_array            position_float_array      = new float_array();
            float_array            normal_float_array        = new float_array();
            float_array            uv_float_array            = new float_array();
            sourceTechnique_common position_technique_common = new sourceTechnique_common();
            sourceTechnique_common normal_technique_common   = new sourceTechnique_common();
            sourceTechnique_common uv_technique_common       = new sourceTechnique_common();

            position_float_array.id    = "Plane001-POSITION-array";
            position_float_array.count = 9;
            //根据count创建一个数组
            position_float_array.Values    = new double[position_float_array.count];
            position_float_array.Values[0] = -49.719101f;
            position_float_array.Values[1] = -41.011238f;
            position_float_array.Values[2] = 0.000000f;
            position_float_array.Values[3] = 49.719101f;
            position_float_array.Values[4] = -41.011238f;
            position_float_array.Values[5] = 0.000000f;
            position_float_array.Values[6] = -49.719101f;
            position_float_array.Values[7] = 41.011238f;
            position_float_array.Values[8] = 0.000000f;

            position_technique_common.accessor = new accessor();

            /*
             * 创建数组的几种形式
             * double[] array = new double[10];
             * double[] array = { 0.0, 1.1, 2.2};
             * double[] array = new double[5]  { 99,  98, 92, 97, 95};
             * double[] array = new double[  ]  { 99,  98, 92, 97, 95};
             * double[] another_array = array;*/
            position_technique_common.accessor.param         = new param[3];
            position_technique_common.accessor.param[0]      = new param();
            position_technique_common.accessor.param[1]      = new param();
            position_technique_common.accessor.param[2]      = new param();
            position_technique_common.accessor.source        = "#" + position_float_array.id;
            position_technique_common.accessor.count         = 3;
            position_technique_common.accessor.stride        = 3;
            position_technique_common.accessor.param[0].name = "X";
            position_technique_common.accessor.param[0].type = "float";
            position_technique_common.accessor.param[1].name = "Y";
            position_technique_common.accessor.param[1].type = "float";
            position_technique_common.accessor.param[2].name = "Z";
            position_technique_common.accessor.param[2].type = "float";

            normal_float_array.id        = "Plane001-Normal0-array";
            normal_float_array.count     = 9;
            normal_float_array.Values    = new double[normal_float_array.count];
            normal_float_array.Values[0] = 0.0f;
            normal_float_array.Values[1] = 0.0f;
            normal_float_array.Values[2] = 1.0f;
            normal_float_array.Values[3] = 0.0f;
            normal_float_array.Values[4] = 0.0f;
            normal_float_array.Values[5] = 1.0f;
            normal_float_array.Values[6] = 0.0f;
            normal_float_array.Values[7] = 0.0f;
            normal_float_array.Values[8] = 1.0f;

            normal_technique_common.accessor               = new accessor();
            normal_technique_common.accessor.param         = new param[3];
            normal_technique_common.accessor.param[0]      = new param();
            normal_technique_common.accessor.param[1]      = new param();
            normal_technique_common.accessor.param[2]      = new param();
            normal_technique_common.accessor.source        = "#" + normal_float_array.id;
            normal_technique_common.accessor.count         = 3;
            normal_technique_common.accessor.stride        = 3;
            normal_technique_common.accessor.param[0].name = "X";
            normal_technique_common.accessor.param[0].type = "float";
            normal_technique_common.accessor.param[1].name = "Y";
            normal_technique_common.accessor.param[1].type = "float";
            normal_technique_common.accessor.param[2].name = "Z";
            normal_technique_common.accessor.param[2].type = "float";

            uv_float_array.id        = "Plane001-UV0-array";
            uv_float_array.count     = 6;
            uv_float_array.Values    = new double[uv_float_array.count];
            uv_float_array.Values[0] = 1.0000f;
            uv_float_array.Values[1] = 0.0000f;
            uv_float_array.Values[2] = 0.0000f;
            uv_float_array.Values[3] = 0.0000f;
            uv_float_array.Values[4] = 1.0000f;
            uv_float_array.Values[5] = 1.0000f;

            uv_technique_common.accessor               = new accessor();
            uv_technique_common.accessor.param         = new param[2];
            uv_technique_common.accessor.param[0]      = new param();
            uv_technique_common.accessor.param[1]      = new param();
            uv_technique_common.accessor.source        = "#" + uv_float_array.id;
            uv_technique_common.accessor.count         = 3;
            uv_technique_common.accessor.stride        = 2;
            uv_technique_common.accessor.param[0].name = "S";
            uv_technique_common.accessor.param[0].type = "float";
            uv_technique_common.accessor.param[1].name = "T";
            uv_technique_common.accessor.param[1].type = "float";

            geomMesh.source[0].id               = "Plane001-POSITION";
            geomMesh.source[0].Item             = position_float_array;
            geomMesh.source[0].technique_common = position_technique_common;
            geomMesh.source[1].id               = "Plane001-Normal0";
            geomMesh.source[1].Item             = normal_float_array;
            geomMesh.source[1].technique_common = normal_technique_common;
            geomMesh.source[2].id               = "Plane001-UV0";
            geomMesh.source[2].Item             = uv_float_array;
            geomMesh.source[2].technique_common = uv_technique_common;

            geomMesh.vertices                   = new vertices();
            geomMesh.vertices.input[0]          = new InputLocal();
            geomMesh.vertices.input[0].semantic = "POSITION";
            geomMesh.vertices.input[0].source   = "#Plane001-POSITION";
            geomMesh.vertices.id                = "Plane001-VERTEX";

            triangles meshTriangle = new triangles();

            meshTriangle.count             = 1;
            meshTriangle.input             = new InputLocalOffset[3];
            meshTriangle.input[0]          = new InputLocalOffset();
            meshTriangle.input[1]          = new InputLocalOffset();
            meshTriangle.input[2]          = new InputLocalOffset();
            meshTriangle.input[0].semantic = "VERTEX";
            meshTriangle.input[0].offset   = 0;
            meshTriangle.input[0].source   = "#Plane001-VERTEX";
            meshTriangle.input[1].semantic = "NORMAL";
            meshTriangle.input[1].offset   = 1;
            meshTriangle.input[1].source   = "#Plane001-Normal0";
            meshTriangle.input[2].semantic = "TEXCOORD";
            meshTriangle.input[2].offset   = 2;
            meshTriangle.input[2].set      = 0;
            meshTriangle.input[2].source   = "#Plane001-UV0";

            string p = "";

            int[] pArray = new int[9];
            pArray[0] = 0;
            pArray[1] = 0;
            pArray[2] = 0;
            pArray[3] = 1;
            pArray[4] = 1;
            pArray[5] = 1;
            pArray[6] = 2;
            pArray[7] = 2;
            pArray[8] = 2;
            foreach (var data in pArray)
            {
                if (data is int)
                {
                    p += " " + data.ToString();
                }
            }
            meshTriangle.p = p;

            geomMesh.Items    = new object[1];
            geomMesh.Items[0] = new object();
            geomMesh.Items[0] = meshTriangle;

            geom.Item = geomMesh;
            geom.id   = "Plane001-lib";
            geom.name = "Plane001Mesh";
            library_geom.geometry[0] = geom;

            // library_visual_scenes
            library_visual_scenes lib_visual_scene = new library_visual_scenes();

            lib_visual_scene.visual_scene    = new visual_scene[1];
            lib_visual_scene.visual_scene[0] = new visual_scene();

            visual_scene visaul = new visual_scene();

            visaul.node         = new node[1];
            visaul.node[0]      = new node();
            visaul.node[0].name = "Triangle001";
            visaul.node[0].id   = "Triangle001";
            visaul.node[0].sid  = "Triangle001";

            visaul.node[0].instance_geometry        = new instance_geometry[1];
            visaul.node[0].instance_geometry[0]     = new instance_geometry();
            visaul.node[0].instance_geometry[0].url = "#Plane001-lib";

            visaul.node[0].extra                         = new extra[1];
            visaul.node[0].extra[0]                      = new extra();
            visaul.node[0].extra[0].technique            = new technique[1];
            visaul.node[0].extra[0].technique[0]         = new technique();
            visaul.node[0].extra[0].technique[0].profile = "FCOLLADA";

            visaul.name = "cube";
            visaul.id   = "cube";

            lib_visual_scene.visual_scene[0] = visaul;

            model.Items    = new object[2];
            model.Items[0] = library_geom;
            model.Items[1] = lib_visual_scene;

            model.scene = new COLLADAScene();
            model.scene.instance_visual_scene     = new InstanceWithExtra();
            model.scene.instance_visual_scene.url = "#" + visaul.id;

            model.Save("C:\\ProgramData\\Autodesk\\revit\\Addins\\2020\\dd.dae");
            return(0);
        }
Beispiel #55
0
 public static void AddMaterial(COLLADA collada, String textureFileName)
 {
 }
        public static int Main(string[] args)
        {
            Utils.LogLevel   = LogLevelEnum.Warning;
            Utils.DebugLevel = LogLevelEnum.Debug;

            string oldTitle = Console.Title;

#if DEV_DOLKENSP
            Utils.LogLevel   = LogLevelEnum.None;    // Display NO error logs
            Utils.DebugLevel = LogLevelEnum.Debug;

            args = new String[] { @"C:\Users\PeterDolkens\Downloads\SOC'n'destroy\socpak\pisces_int.soc", "-objectdir", @"C:\Users\PeterDolkens\Downloads\SOC'n'destroy\socpak", "-obj", "-outdir", @"C:\Users\PeterDolkens\Downloads\SOC'n'destroy\socpak\out" };
#endif

#if DEV_MARKEMP
            Utils.LogLevel   = LogLevelEnum.Verbose; // Display ALL error logs in the console
            Utils.DebugLevel = LogLevelEnum.Debug;   // Send all to the IDE Output window

            //args = new String[] { @"D:\depot\mwo\Objects\mechs\catapult\body\catapult.chr", "-dds", "-dae", "-objectdir", @"d:\depot\mwo\" };
            //args = new String[] { @"D:\depot\mwo\Objects\environments\frontend\mechlab_a\mechbay_ceilings\mechbay_ceilinga.cgf", "-dds", "-dae", "-objectdir", @"d:\depot\mwo\" };
            //args = new String[] { @"D:\depot\mwo\Objects\environments\industrial\mf_maglev_loader_a.cgf", "-dds", "-dae", "-objectdir", @"d:\depot\mwo\" };
            //args = new String[] { @"D:\depot\MWO\Objects\characters\pilot\pilot_body.chr", "-dds", "-dae", "-objectdir", @"d:\blender projects\mechs\" };
            //args = new String[] { @"D:\depot\MWO\Objects\environments\city\im_roads_zone_05\im_zone05_block16.cgf", "-objectdir", @"d:\blender projects\mechs", "-dae" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\animals\fish\Fish_JellyFish_prop_animal_01.cga", "-objectdir", @"d:\depot\sc\data", "-dae" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\animals\fish\CleanerFish_clean_prop_animal_01.chr", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"d:\depot\SC\Data\Objects\Spaceships\Ships\AEGS\Gladius\AEGS_Gladius.cga", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"d:\depot\SC\Data\Objects\Spaceships\Ships\AEGS\Retaliator\AEGS_retaliator.cga", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\Spaceships\Ships\AEGS\Redeemer\AEGS_Redeemer.cga", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\Spaceships\Ships\DRAK\Cutlass\DRAK_Cutlass.cga", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"d:\depot\SC\Data\Objects\buildingsets\human\lowtech\bravo\grimhex\anchor\anchor_gun_a.cgf", "-objectdir", @"d:\depot\sc\data", "-dds", "-dae", "-tif" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\Characters\Human\heads\male\npc\male09\male09_t1_head.skin", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\Characters\Human\male_v7\export\bhm_skeleton_v7.chr", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\buildingsets\human\universal\org\trees\tree_ash_a.cgf", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\Characters\Human\male_v7\armor\rsi\m_rsi_pilot_flightsuit_01.skin", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"D:\depot\SC\Data\Objects\Characters\Human\male_v7\armor\slaver\m_slaver_medium_armor_01_core.skin", "-objectdir", @"d:\depot\sc\data", "-dae", "-tif" };
            //args = new String[] { @"d:\temp\prey\dahl_genmalebody01.skin", "-objectdir", @"d:\temp\prey", "-dae", "-dds" };
            //args = new string[] { @"c:\users\ggerb\source\repos\Cryengine-Converter\cgfconvertertests\resourcefiles\sonicboom\checkpoint.cgf" };
#endif


            CultureInfo customCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";

            Thread.CurrentThread.CurrentCulture = customCulture;
            ArgsHandler argsHandler = new ArgsHandler();
#if !DEBUG
            try
            {
#endif
            if (argsHandler.ProcessArgs(args) == 0)
            {
                foreach (String inputFile in argsHandler.InputFiles)
                {
                    try
                    {
                        // Read CryEngine Files
                        CryEngine cryData = new CryEngine(inputFile, argsHandler.DataDir.FullName);
                        cryData.ProcessCryengineFiles();

                        if (argsHandler.OutputBlender == true)
                        {
                            Blender blendFile = new Blender(argsHandler, cryData);

                            blendFile.Render(argsHandler.OutputDir, argsHandler.InputFiles.Count > 1);
                        }

                        if (argsHandler.OutputWavefront == true)
                        {
                            Wavefront objFile = new Wavefront(argsHandler, cryData);

                            objFile.Render(argsHandler.OutputDir, argsHandler.InputFiles.Count > 1);
                        }

                        if (argsHandler.OutputCryTek == true)
                        {
                            CryRender cryFile = new CryRender(argsHandler, cryData);

                            cryFile.Render(argsHandler.OutputDir, argsHandler.InputFiles.Count > 1);
                        }

                        if (argsHandler.OutputCollada == true)
                        {
                            COLLADA daeFile = new COLLADA(argsHandler, cryData);

                            daeFile.Render(argsHandler.OutputDir, argsHandler.InputFiles.Count > 1);
                        }
                    }
                    catch (Exception ex)
                    {
                        Utils.Log(LogLevelEnum.Critical);
                        Utils.Log(LogLevelEnum.Critical, "********************************************************************************");
                        Utils.Log(LogLevelEnum.Critical, "There was an error rendering {0}", inputFile);
                        Utils.Log(LogLevelEnum.Critical);
                        Utils.Log(LogLevelEnum.Critical, ex.Message);
                        Utils.Log(LogLevelEnum.Critical);
                        Utils.Log(LogLevelEnum.Critical, ex.StackTrace);
                        Utils.Log(LogLevelEnum.Critical, "********************************************************************************");
                        Utils.Log(LogLevelEnum.Critical);
                        return(1);
                    }
                }
            }

#if !DEBUG
        }

        catch (Exception)
        {
            if (argsHandler.Throw)
            {
                throw;
            }
        }
#endif

            Console.Title = oldTitle;

#if (DEV_DOLKENSP || DEV_MARKEMP)
            Console.WriteLine("Done...");
            Console.ReadKey();
#endif
            return(0);
        }
Beispiel #57
0
        private void button3_Click(object sender, EventArgs e)
        {
            if (!File.Exists(sFileName))
            {
                MessageBox.Show("Unable to access " + sFileName + "!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            bool   rep        = false;
            int    offsets    = 0;
            string trisall    = "";
            string vertstring = "";

            string[] vertexids        = { };
            string   normalsid        = "";
            string   normalsstring    = "";
            string   texcoordid       = "";
            string   texcoordstring   = "";
            int      textriarraycount = 0;
            int      textricount      = 0;

            int[] textriarray = new int[File.ReadAllLines("settings.bmfo")[2].Split().Length];
            int[,] tris = new int[0, 0];
            int vertexoffset   = 0;
            int texcoordoffset = 0;
            int normaloffset   = 0;
            int coloroffset    = 0;

            float[,] bind_float_matrix = new float[0, 0];
            byte[,] output             = new byte[0, 0];
            COLLADA model = COLLADA.Load(sFileName);

            foreach (var item in model.Items)
            {
                var geometries = item as library_geometries;
                if (geometries == null)
                {
                    continue;
                }
                foreach (var geom in geometries.geometry)
                {
                    var mesh = geom.Item as mesh;
                    if (mesh == null)
                    {
                        continue;
                    }
                    if (1 != 0)
                    {
                        var meshItem        = mesh.vertices;
                        var vertices        = meshItem as vertices;
                        var inputs          = vertices.input;
                        int vertexidnumbers = inputs.Length;
                        vertexids       = new string[vertexidnumbers];
                        vertexidnumbers = 0;
                        foreach (var input in inputs)
                        {
                            vertexids[vertexidnumbers] = input.source;
                        }
                        vertexidnumbers++;
                    }
                    foreach (var meshItem in mesh.Items)
                    {
                        try
                        {
                            textriarray[textriarraycount] = textricount / 3;
                        }
                        catch
                        {
                            break;
                        }
                        textriarraycount++;
                        var triangles = meshItem as polylist;
                        var inputs    = triangles.input;
                        offsets = 0;
                        foreach (var input in inputs)
                        {
                            if (input.semantic == "VERTEX")
                            {
                                vertexoffset = offsets;
                            }
                            else if (input.semantic == "TEXCOORD")
                            {
                                texcoordid     = input.source;
                                texcoordoffset = offsets;
                            }
                            else if (input.semantic == "NORMAL")
                            {
                                normalsid    = input.source;
                                normaloffset = offsets;
                            }

                            offsets++;
                        }
                        trisall = trisall + triangles.p + " ";
                        foreach (var hmmm in triangles.p.Split())
                        {
                            textricount++;
                        }
                    }
                    foreach (var source in mesh.source)
                    {
                        foreach (var vertexid in vertexids)
                        {
                            if (vertexid == "#" + source.id)
                            {
                                var verts = source.Item as float_array;
                                foreach (var vert in verts.Values)
                                {
                                    vertstring = vertstring + vert + " ";
                                }
                            }
                        }
                        if (normalsid == "#" + source.id)
                        {
                            var normalsarray = source.Item as float_array;
                            foreach (var normal in normalsarray.Values)
                            {
                                normalsstring = normalsstring + normal + " ";
                            }
                        }
                        else if (texcoordid == "#" + source.id)
                        {
                            var texcoordsarray = source.Item as float_array;
                            foreach (var texcoord in texcoordsarray.Values)
                            {
                                texcoordstring = texcoordstring + texcoord + " ";
                            }
                        }
                    }
                    foreach (var meshItem in mesh.Items)
                    {
                        if (meshItem is polylist && rep == false)
                        {
                            string   trisold2 = trisall;
                            string[] trisold  = trisold2.Split();
                            tris = new int[offsets, (trisold.Length + 1 / (offsets + 1))];
                            int currenttri   = 0;
                            int currentelem  = 0;
                            int currentelem2 = 0;
                            foreach (string elem in trisold)
                            {
                                if (currentelem == offsets - 1)
                                {
                                    currentelem2++;
                                }
                                if (int.TryParse(elem, out int result))
                                {
                                    tris[currenttri % offsets, currentelem2] = result;
                                    //MessageBox.Show("tris[" + (currenttri%offsets).ToString() + ", " + currentelem2 + "] = " + result.ToString());
                                }
                                currentelem = currenttri % offsets;
                                currenttri++;
                            }
                            rep = true;
                        }
                    }
                }

                var controllers = item as library_controllers;
                if (controllers == null)
                {
                    continue;
                }
                foreach (var control in controllers.controller)
                {
                    string bind_name = "";
                    var    skins     = item as skin;
                    if (skins == null)
                    {
                        continue;
                    }
                    var joints = item as skinJoints;
                    foreach (var joint in joints.input)
                    {
                        if (joint.semantic == "INV_BIND_MATRIX")
                        {
                            bind_name = joint.source;
                        }
                    }
                    foreach (var source in skins.source)
                    {
                        if (bind_name == "#" + source.id)
                        {
                            var bind_poses = source.Item as float_array;
                            bind_float_matrix = new float[16, bind_poses.count / 16];
                            int iter  = 0;
                            int iter2 = 0;
                            foreach (var poses in bind_poses.Values)
                            {
                                bind_float_matrix[iter, iter2] = (float)poses;
                                iter++;
                                if (iter == 16)
                                {
                                    iter2++;
                                    iter = 0;
                                }
                            }
                        }
                    }
                }

                output = new byte[16, bind_float_matrix.GetLength(1)];
                var visual_scenes = item as library_visual_scenes;
                if (visual_scenes == null)
                {
                    continue;
                }
                foreach (var visual_scene in visual_scenes.visual_scene)
                {
                    var nodes = visual_scene.node as node[];
                    if (nodes == null)
                    {
                        continue;
                    }
                    foreach (var node in nodes)
                    {
                        if (node.id == "Armature")
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load(sFileName);
                            XmlNodeList list      = doc.SelectNodes("library_visual_scenes/visual_scene/node[@id=\"Armature\"]");
                            string      nodething = "library_visual_scenes/visual_scene/node";
                            int         nodecount = list.Count;
                            int         iterthing = 0;
                            for (int j = 0; j < nodecount; j++)
                            {
                                XmlNode elem = list[j];
                                if (1 > 0)
                                {
                                    string childid    = elem.Name;
                                    int    countchild = doc.SelectNodes(nodething + "[@name=\"" + childid + "\"]").Count;
                                    byte[] toBytes    = new byte[16];
                                    byte[] toBytes3   = Encoding.ASCII.GetBytes(childid);
                                    int    iter1      = 0;
                                    foreach (byte bytee in toBytes3)
                                    {
                                        toBytes[iter1] = bytee;
                                        iter1++;
                                    }
                                    output[0, iterthing]  = (byte)((countchild >> 8) & 0xff);
                                    output[1, iterthing]  = (byte)(countchild & 0xff);
                                    output[2, iterthing]  = toBytes[0];
                                    output[3, iterthing]  = toBytes[1];
                                    output[4, iterthing]  = toBytes[2];
                                    output[5, iterthing]  = toBytes[3];
                                    output[6, iterthing]  = toBytes[4];
                                    output[7, iterthing]  = toBytes[5];
                                    output[8, iterthing]  = toBytes[6];
                                    output[9, iterthing]  = toBytes[7];
                                    output[10, iterthing] = toBytes[8];
                                    output[11, iterthing] = toBytes[9];
                                    output[12, iterthing] = toBytes[10];
                                    output[13, iterthing] = toBytes[11];
                                    output[14, iterthing] = toBytes[12];
                                    output[15, iterthing] = toBytes[13];
                                    iterthing++;
                                }
                                while (1 > 0)
                                {
                                    nodething = nodething + "/node";
                                    if (doc.SelectNodes(nodething).Count != 0)
                                    {
                                        string childid    = doc.SelectSingleNode(nodething).Name;
                                        int    countchild = doc.SelectNodes(nodething + "[@name=\"" + childid + "\"]").Count;
                                        byte[] toBytes    = new byte[16];
                                        byte[] toBytes3   = Encoding.ASCII.GetBytes(childid);
                                        int    iter1      = 0;
                                        foreach (byte bytee in toBytes3)
                                        {
                                            toBytes[iter1] = bytee;
                                            iter1++;
                                        }
                                        output[0, iterthing]  = (byte)((countchild >> 8) & 0xff);
                                        output[1, iterthing]  = (byte)(countchild & 0xff);
                                        output[2, iterthing]  = toBytes[0];
                                        output[3, iterthing]  = toBytes[1];
                                        output[4, iterthing]  = toBytes[2];
                                        output[5, iterthing]  = toBytes[3];
                                        output[6, iterthing]  = toBytes[4];
                                        output[7, iterthing]  = toBytes[5];
                                        output[8, iterthing]  = toBytes[6];
                                        output[9, iterthing]  = toBytes[7];
                                        output[10, iterthing] = toBytes[8];
                                        output[11, iterthing] = toBytes[9];
                                        output[12, iterthing] = toBytes[10];
                                        output[13, iterthing] = toBytes[11];
                                        output[14, iterthing] = toBytes[12];
                                        output[15, iterthing] = toBytes[13];
                                        iterthing++;
                                    }
                                    else
                                    {
                                        nodething = "library_visual_scenes/visual_scene/node";
                                        string childid  = doc.SelectSingleNode(nodething).Name;
                                        byte[] toBytes  = new byte[16];
                                        byte[] toBytes3 = Encoding.ASCII.GetBytes(childid);
                                        int    iter1    = 0;
                                        foreach (byte bytee in toBytes3)
                                        {
                                            toBytes[iter1] = bytee;
                                            iter1++;
                                        }
                                        output[0, iterthing]  = 0;
                                        output[1, iterthing]  = 0;
                                        output[2, iterthing]  = toBytes[0];
                                        output[3, iterthing]  = toBytes[1];
                                        output[4, iterthing]  = toBytes[2];
                                        output[5, iterthing]  = toBytes[3];
                                        output[6, iterthing]  = toBytes[4];
                                        output[7, iterthing]  = toBytes[5];
                                        output[8, iterthing]  = toBytes[6];
                                        output[9, iterthing]  = toBytes[7];
                                        output[10, iterthing] = toBytes[8];
                                        output[11, iterthing] = toBytes[9];
                                        output[12, iterthing] = toBytes[10];
                                        output[13, iterthing] = toBytes[11];
                                        output[14, iterthing] = toBytes[12];
                                        output[15, iterthing] = toBytes[13];
                                        break;
                                    }
                                }
                                iterthing++;
                            }
                        }
                    }
                }
            }

            int scaling = int.Parse(File.ReadAllLines("settings.bmfo")[4]);

            string[]     vertarray     = vertstring.Split();
            string[]     normalarray   = normalsstring.Split();
            string[]     texcoordarray = texcoordstring.Split();
            MemoryStream BMF           = new MemoryStream();
            int          vertheader    = 0;
            string       FileName      = File.ReadAllLines("settings.bmfo")[1] + "/" + Path.GetFileNameWithoutExtension(sFileName).Replace(' ', '_') + ".bmf";

            using (FileStream fs = File.Create(FileName))
            {
            }
            BMF.Write(new byte[] {
                0x00,
                0x00,
                0x00,
                0x28,
                //adding this if i ever want to change this part
                0x00,
                0x00,
                0x00,
                0x00,
                //(byte)((tricount >> 8) & 0xff),
                //(byte)(tricount & 0xff),
                //(byte)((trioffset >> 8) & 0xff),
                //(byte)(trioffset & 0xff),
                0x00,
                0x00,
                0xFF,
                0xFF,
                0x00,
                0x00,
                0xFF,
                0xFF
            }, 0, 16);
            BMF.Write(new byte[] {
                0x00,
                0x00,
                0xFF,
                0xFF,
                0x00,
                0x00,
                0xFF,
                0xFF,
                0x00,
                0x00,
                0xFF,
                0xFF,
                0x00,
                0x00,
                0xFF,
                0xFF
            }, 0, 16);
            BMF.Write(new byte[] {
                0x00,
                0x00,
                0xFF,
                0xFF,
                0x00,
                0x00,
                0xFF,
                0xFF,
                0x00,
                0x00,
                0xFF,
                0xFF,
                0x00,
                0x00,
                0xFF,
                0xFF
            }, 0, 16);
            BMF.Write(new byte[] {
                0x47,
                0x45,
                0x4E,
                0x45,
                0x52,
                0x41,
                0x54,
                0x45,
                0x44,
                0x00,
                0x42,
                0x59,
                0x00,
                0x00,
                0x00,
                0x00
            }, 0, 16);
            BMF.Write(new byte[] {
                0x44,
                0x41,
                0x45,
                0x32,
                0x42,
                0x4D,
                0x46,
                0x00,
                0x00,
                0x00,
                0x56,
                0x45,
                0x52,
                0x54,
                0x53,
                0x3A
            }, 0, 16);
            int i         = 0;
            int iterb     = 0;
            int iterrerew = 0;

            while (1 < 2)
            {
                //cheap texcord fix
                if (iterrerew < textriarray.Length && iterb == textriarray[iterrerew] / 3)
                {
                    iterrerew++;
                }
                iterb++;

                //vertex1
                int    vtxx1, vtxy1, vtxz1;
                double dvtxx1 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i] * 3]) * scaling);
                if (dvtxx1 > -1)
                {
                    vtxx1 = (int)dvtxx1;
                }
                else
                {
                    vtxx1 = (int)(65535 + dvtxx1);
                }
                double dvtxy1 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i] * 3 + 1]) * scaling);
                if (dvtxy1 > -1)
                {
                    vtxy1 = (int)dvtxy1;
                }
                else
                {
                    vtxy1 = (int)(65535 + dvtxy1);
                }
                double dvtxz1 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i] * 3 + 2]) * scaling);
                if (dvtxz1 > -1)
                {
                    vtxz1 = (int)dvtxz1;
                }
                else
                {
                    vtxz1 = (int)(65535 + dvtxz1);
                }
                //texcoord1
                float tcu11 = float.Parse(texcoordarray[tris[texcoordoffset, i] * 2]);
                short tcu1  = Convert.ToInt16(tcu11 * (xy[iterrerew - 1] >> 16) * 32);
                float tcv11 = float.Parse(texcoordarray[tris[texcoordoffset, i] * 2 + 1]);
                short tcv1  = Convert.ToInt16(tcv11 * (xy[iterrerew - 1] & 0xFFFF) * 32);
                //normals1
                double dn11 = Math.Round(float.Parse(normalarray[tris[normaloffset, i] * 3]) * 127);
                double dn21 = Math.Round(float.Parse(normalarray[tris[normaloffset, i] * 3 + 1]) * 127);
                double dn31 = Math.Round(float.Parse(normalarray[tris[normaloffset, i] * 3 + 2]) * 127);


                //vertex2
                int    vtxx2, vtxy2, vtxz2;
                double dvtxx2 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i + 1] * 3]) * scaling);
                if (dvtxx2 > -1)
                {
                    vtxx2 = (int)dvtxx2;
                }
                else
                {
                    vtxx2 = (int)(65535 + dvtxx2);
                }
                double dvtxy2 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i + 1] * 3 + 1]) * scaling);
                if (dvtxy2 > -1)
                {
                    vtxy2 = (int)dvtxy2;
                }
                else
                {
                    vtxy2 = (int)(65535 + dvtxy2);
                }
                double dvtxz2 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i + 1] * 3 + 2]) * scaling);
                if (dvtxz2 > -1)
                {
                    vtxz2 = (int)dvtxz2;
                }
                else
                {
                    vtxz2 = (int)(65535 + dvtxz2);
                }
                //texcoord2
                float tcu12 = float.Parse(texcoordarray[tris[texcoordoffset, i + 1] * 2]);
                short tcu2  = Convert.ToInt16(tcu12 * (xy[iterrerew - 1] >> 16) * 32);
                float tcv12 = float.Parse(texcoordarray[tris[texcoordoffset, i + 1] * 2 + 1]);
                short tcv2  = Convert.ToInt16(tcv12 * (xy[iterrerew - 1] & 0xFFFF) * 32);
                //normals2
                double dn12 = Math.Round(float.Parse(normalarray[tris[normaloffset, i + 1] * 3]) * 127);
                double dn22 = Math.Round(float.Parse(normalarray[tris[normaloffset, i + 1] * 3 + 1]) * 127);
                double dn32 = Math.Round(float.Parse(normalarray[tris[normaloffset, i + 1] * 3 + 2]) * 127);


                //vertex3
                int    vtxx3, vtxy3, vtxz3;
                double dvtxx3 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i + 2] * 3]) * scaling);
                if (dvtxx3 > -1)
                {
                    vtxx3 = (int)dvtxx3;
                }
                else
                {
                    vtxx3 = (int)(65535 + dvtxx3);
                }
                double dvtxy3 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i + 2] * 3 + 1]) * scaling);
                if (dvtxy3 > -1)
                {
                    vtxy3 = (int)dvtxy3;
                }
                else
                {
                    vtxy3 = (int)(65535 + dvtxy3);
                }
                double dvtxz3 = Math.Round(float.Parse(vertarray[tris[vertexoffset, i + 2] * 3 + 2]) * scaling);
                if (dvtxz2 > -1)
                {
                    vtxz3 = (int)dvtxz3;
                }
                else
                {
                    vtxz3 = (int)(65535 + dvtxz3);
                }
                //texcoord2
                float tcu13 = float.Parse(texcoordarray[tris[texcoordoffset, i + 2] * 2]);
                short tcu3  = Convert.ToInt16(tcu13 * (xy[iterrerew - 1] >> 16) * 32);
                float tcv13 = float.Parse(texcoordarray[tris[texcoordoffset, i + 2] * 2 + 1]);
                short tcv3  = Convert.ToInt16(tcv13 * (xy[iterrerew - 1] & 0xFFFF) * 32);
                //normals2
                double dn13 = Math.Round(float.Parse(normalarray[tris[normaloffset, i + 2] * 3]) * 127);
                double dn23 = Math.Round(float.Parse(normalarray[tris[normaloffset, i + 2] * 3 + 1]) * 127);
                double dn33 = Math.Round(float.Parse(normalarray[tris[normaloffset, i + 2] * 3 + 2]) * 127);



                byte[] vert1 =
                {
                    (byte)((vtxx1 >> 8) & 0xff),
                    (byte)(vtxx1 & 0xff),
                    (byte)((vtxy1 >> 8) & 0xff),
                    (byte)(vtxy1 & 0xff),
                    (byte)((vtxz1 >> 8) & 0xff),
                    (byte)(vtxz1 & 0xff),
                    0x00,
                    0x00,
                    (byte)((tcu1 >> 8) & 0xff),
                    (byte)(tcu1 & 0xff),
                    (byte)((tcv1 >> 8) & 0xff),
                    (byte)(tcv1 & 0xff),
                    (byte)dn11,
                    (byte)dn21,
                    (byte)dn31,
                    0xFF
                };

                byte[] vert2 =
                {
                    (byte)((vtxx2 >> 8) & 0xff),
                    (byte)(vtxx2 & 0xff),
                    (byte)((vtxy2 >> 8) & 0xff),
                    (byte)(vtxy2 & 0xff),
                    (byte)((vtxz2 >> 8) & 0xff),
                    (byte)(vtxz2 & 0xff),
                    0x00,
                    0x00,
                    (byte)((tcu2 >> 8) & 0xff),
                    (byte)(tcu2 & 0xff),
                    (byte)((tcv2 >> 8) & 0xff),
                    (byte)(tcv2 & 0xff),
                    (byte)dn12,
                    (byte)dn22,
                    (byte)dn32,
                    0xFF
                };

                byte[] vert3 =
                {
                    (byte)((vtxx3 >> 8) & 0xff),
                    (byte)(vtxx3 & 0xff),
                    (byte)((vtxy3 >> 8) & 0xff),
                    (byte)(vtxy3 & 0xff),
                    (byte)((vtxz3 >> 8) & 0xff),
                    (byte)(vtxz3 & 0xff),
                    0x00,
                    0x00,
                    (byte)((tcu3 >> 8) & 0xff),
                    (byte)(tcu3 & 0xff),
                    (byte)((tcv3 >> 8) & 0xff),
                    (byte)(tcv3 & 0xff),
                    (byte)dn13,
                    (byte)dn23,
                    (byte)dn33,
                    0xFF
                };
                if (Enumerable.SequenceEqual(vert1, vert2) && Enumerable.SequenceEqual(vert2, vert3))
                {
                }
                else
                {
                    BMF.Write(new byte[] {
                        //vert1
                        (byte)((vtxx1 >> 8) & 0xff),
                        (byte)(vtxx1 & 0xff),
                        (byte)((vtxy1 >> 8) & 0xff),
                        (byte)(vtxy1 & 0xff),
                        (byte)((vtxz1 >> 8) & 0xff),
                        (byte)(vtxz1 & 0xff),
                        0x00,
                        0x00,
                        (byte)((tcu1 >> 8) & 0xff),
                        (byte)(tcu1 & 0xff),
                        (byte)((tcv1 >> 8) & 0xff),
                        (byte)(tcv1 & 0xff),
                        (byte)dn11,
                        (byte)dn21,
                        (byte)dn31,
                        0xFF,

                        //vert2
                        (byte)((vtxx2 >> 8) & 0xff),
                        (byte)(vtxx2 & 0xff),
                        (byte)((vtxy2 >> 8) & 0xff),
                        (byte)(vtxy2 & 0xff),
                        (byte)((vtxz2 >> 8) & 0xff),
                        (byte)(vtxz2 & 0xff),
                        0x00,
                        0x00,
                        (byte)((tcu2 >> 8) & 0xff),
                        (byte)(tcu2 & 0xff),
                        (byte)((tcv2 >> 8) & 0xff),
                        (byte)(tcv2 & 0xff),
                        (byte)dn12,
                        (byte)dn22,
                        (byte)dn32,
                        0xFF,

                        //vert3
                        (byte)((vtxx3 >> 8) & 0xff),
                        (byte)(vtxx3 & 0xff),
                        (byte)((vtxy3 >> 8) & 0xff),
                        (byte)(vtxy3 & 0xff),
                        (byte)((vtxz3 >> 8) & 0xff),
                        (byte)(vtxz3 & 0xff),
                        0x00,
                        0x00,
                        (byte)((tcu3 >> 8) & 0xff),
                        (byte)(tcu3 & 0xff),
                        (byte)((tcv3 >> 8) & 0xff),
                        (byte)(tcv3 & 0xff),
                        (byte)dn13,
                        (byte)dn23,
                        (byte)dn33,
                        0xFF
                    }, 0, 48);
                    vertheader++;
                }
                i += 3;
                if (i >= tris.GetLength(1) - 2)
                {
                    break;
                }
            }
            if (File.ReadAllLines("settings.bmfo")[5] == "YES")
            {
            }
            if (File.ReadAllLines("settings.bmfo")[2] != "")
            {
                string[] textures     = File.ReadAllLines("settings.bmfo")[2].Split();
                int      iterationals = 0;
                foreach (string texture in textures)
                {
                    byte[] toBytes  = new byte[16];
                    byte[] toBytes3 = Encoding.ASCII.GetBytes(Path.GetFileNameWithoutExtension(texture));
                    int    iter1    = 0;
                    foreach (byte bytee in toBytes3)
                    {
                        toBytes[iter1] = bytee;
                        iter1++;
                    }
                    BMF.Write(new byte[] {
                        (byte)((textriarray[iterationals] / 3 >> 8) & 0xff),
                        (byte)(textriarray[iterationals] / 3 & 0xff),
                        toBytes[0],
                        toBytes[1],
                        toBytes[2],
                        toBytes[3],
                        toBytes[4],
                        toBytes[5],
                        toBytes[6],
                        toBytes[7],
                        toBytes[8],
                        toBytes[9],
                        toBytes[0xa],
                        toBytes[0xb],
                        toBytes[0xc],
                        toBytes[0xd]
                    }, 0, 16);
                    iterationals++;
                }
                byte[] toBytes1 = new byte[16];
                byte[] toBytes4 = Encoding.ASCII.GetBytes("texturedUnlit");
                int    iter2    = 0;
                foreach (byte bytee in toBytes4)
                {
                    toBytes1[iter2] = bytee;
                    iter2++;
                }
                BMF.Write(new byte[] {
                    0x00,
                    0x00,
                    toBytes1[0],
                    toBytes1[1],
                    toBytes1[2],
                    toBytes1[3],
                    toBytes1[4],
                    toBytes1[5],
                    toBytes1[6],
                    toBytes1[7],
                    toBytes1[8],
                    toBytes1[9],
                    toBytes1[0xa],
                    toBytes1[0xb],
                    toBytes1[0xc],
                    0x00
                }, 0, 16);
            }
            //write triangles

            /*
             *
             * gotta remember re adding this code generator as an option later on
             *
             * BMF.Write(new byte[] {
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x00,
             *  0x54,
             *  0x52,
             *  0x49,
             *  0x53,
             *  0x3A
             * }, 0, 16);
             * if (texcoords == true)
             * {
             *  float[] tridata = new float[tricount/2];
             *  int valz = 0;
             *  foreach(float td in tridata)
             *  {
             *      BMF.Write(new byte[] {
             *              (byte)((valz >> 8) & 0xff),
             *              (byte)(valz & 0xff),
             *              (byte)((valz + 1 >> 8) & 0xff),
             *              (byte)(valz + 1 & 0xff),
             *              (byte)((valz + 2 >> 8) & 0xff),
             *              (byte)(valz + 2 & 0xff),
             *              0x00,
             *              0x00,
             *              (byte)((valz + 3 >> 8) & 0xff),
             *              (byte)(valz + 3 & 0xff),
             *              (byte)((valz + 4 >> 8) & 0xff),
             *              (byte)(valz + 4 & 0xff),
             *              (byte)((valz + 5 >> 8) & 0xff),
             *              (byte)(valz + 5 & 0xff),
             *              0x00,
             *              0x00
             * }, 0, 16);
             *      valz += 6;
             *  }
             * }*/
            for (int j = 0; j < output.GetLength(1); j++)
            {
                BMF.Write(new byte[] {
                    output[0, j],
                    output[1, j],
                    output[2, j],
                    output[3, j],
                    output[4, j],
                    output[5, j],
                    output[6, j],
                    output[7, j],
                    output[8, j],
                    output[9, j],
                    output[10, j],
                    output[11, j],
                    output[12, j],
                    output[13, j],
                    output[14, j],
                    output[15, j],
                }, 0, 16);
            }

            FileStream bmffile = new FileStream(FileName, FileMode.Open);

            BMF.WriteTo(bmffile);
            bmffile.Dispose();
            //fix verts (temp)
            vertheader = vertheader * 3;
            byte[] array = File.ReadAllBytes(FileName);
            array[0] = (byte)((vertheader >> 8) & 0xff);
            array[1] = (byte)(vertheader & 0xff);
            File.WriteAllBytes(FileName, array);
        }
Beispiel #58
0
 protected virtual void InitChildNode(COLLADA Doc,XmlNode Child)
 {
     throw new NotImplementedException();
 }
Beispiel #59
0
        public void Export(string filePath)
        {
            PalletProperties palletProperties = _palletSolution.Analysis.PalletProperties;

            COLLADA model = new COLLADA();

            // asset
            model.asset = new asset()
            {
                created  = DateTime.Now,
                modified = DateTime.Now
            };
            model.asset.keywords = "StackBuilder Pallet Case";
            model.asset.title    = _palletSolution.Title;
            model.asset.unit     = new assetUnit()
            {
                name = "millimeters", meter = 0.001
            };
            model.asset.up_axis = UpAxisType.Z_UP;

            library_images        images     = new library_images();
            library_materials     materials  = new library_materials();
            library_effects       effects    = new library_effects();
            library_geometries    geometries = new library_geometries();
            library_nodes         nodes      = new library_nodes();
            library_cameras       cameras    = new library_cameras();
            library_animations    animations = new library_animations();
            library_visual_scenes scenes     = new library_visual_scenes();

            COLLADAScene colladaScene = new COLLADAScene();

            model.Items = new Object[] { images, materials, effects, geometries, nodes, cameras, animations, scenes };
            model.scene = colladaScene;

            // colors and materials
            List <effect>   listEffects   = new List <effect>();
            List <material> listMaterials = new List <material>();
            List <image>    listImages    = new List <image>();

            // effects
            effect   effectPallet;
            material materialPallet;

            CreateMaterial(palletProperties.Color, null, null, "Pallet", out effectPallet, out materialPallet);
            listEffects.Add(effectPallet);
            listMaterials.Add(materialPallet);

            Box box = new Box(0, _palletSolution.Analysis.BProperties);

            // build list of effects / materials / images
            uint faceIndex = 0;

            foreach (Face face in box.Faces)
            {
                // build texture image if any
                string textureName = null;
                if (face.HasBitmap)
                {
                    textureName = string.Format("textureFace_{0}", faceIndex);
                    string texturePath = System.IO.Path.Combine(
                        System.IO.Path.GetDirectoryName(filePath)
                        , textureName + ".jpg");

                    double dimX = 0.0, dimY = 0.0;

                    switch (faceIndex)
                    {
                    case 0: dimX = box.Width; dimY = box.Height; break;

                    case 1: dimX = box.Width; dimY = box.Height; break;

                    case 2: dimX = box.Length; dimY = box.Height; break;

                    case 3: dimX = box.Length; dimY = box.Height; break;

                    case 4: dimX = box.Length; dimY = box.Width; break;

                    case 5: dimX = box.Length; dimY = box.Width; break;

                    default: break;
                    }
                    face.ExtractFaceBitmap(dimX, dimY, _bmpWidth, texturePath);
                    // create image
                    listImages.Add(
                        new image()
                    {
                        id   = textureName + ".jpg",
                        name = textureName + ".jpg",
                        Item = @".\" + textureName + @".jpg"
                    }
                        );
                }
                material materialCase;
                effect   effectCase;
                CreateMaterial(face.ColorFill, textureName, "0", string.Format("Case{0}", faceIndex), out effectCase, out materialCase);
                listEffects.Add(effectCase);
                listMaterials.Add(materialCase);

                ++faceIndex;
            }

            // add to image list
            images.image = listImages.ToArray();

            // case lines material
            effect   effectCaseLines;
            material materialCaseLines;

            CreateMaterial(Color.Black, null, null, "CaseLines", out effectCaseLines, out materialCaseLines);
            listEffects.Add(effectCaseLines);
            listMaterials.Add(materialCaseLines);
            effects.effect     = listEffects.ToArray();
            materials.material = listMaterials.ToArray();

            // geometries
            geometry geomPallet = new geometry()
            {
                id = "palletGeometry", name = "palletGeometry"
            };
            geometry geomCase = new geometry()
            {
                id = "caseGeometry", name = "caseGeometry"
            };

            geometries.geometry = new geometry[] { geomPallet, geomCase };
            // pallet
            mesh meshPallet = CreatePalletMesh(palletProperties);

            geomPallet.Item = meshPallet;
            // case
            mesh meshCase = CreateCaseMesh(_palletSolution.Analysis.BProperties as BoxProperties);

            geomCase.Item = meshCase;
            // library_animations
            animation animationMain = new animation()
            {
                id = "animationMain_ID", name = "animationMain"
            };

            animations.animation = new animation[] { animationMain };

            List <object> listAnimationSource = new List <object>();

            // library_visual_scenes
            visual_scene mainScene = new visual_scene()
            {
                id = "MainScene", name = "MainScene"
            };

            scenes.visual_scene = new visual_scene[] { mainScene };

            List <node> sceneNodes = new List <node>();

            sceneNodes.Add(new node()
            {
                id   = "PalletNode",
                name = "PalletNode",
                instance_geometry = new instance_geometry[]
                {
                    new instance_geometry()
                    {
                        url           = "#palletGeometry",
                        bind_material = new bind_material()
                        {
                            technique_common = new instance_material[]
                            {
                                new instance_material()
                                {
                                    symbol = "materialPallet",
                                    target = string.Format("#{0}", materialPallet.id)
                                }
                            }
                        }
                    }
                }
            });
            uint caseIndex = 0;

            foreach (ILayer layer in _palletSolution)
            {
                BoxLayer bLayer = layer as BoxLayer;
                if (null == bLayer)
                {
                    continue;
                }

                foreach (BoxPosition bp in bLayer)
                {
                    Vector3D translation = bp.Position;
                    Vector3D rotations   = bp.Transformation.Rotations;

                    node caseNode = new node()
                    {
                        id               = string.Format("CaseNode_{0}_ID", caseIndex),
                        name             = string.Format("CaseNode_{0}", caseIndex),
                        ItemsElementName = new ItemsChoiceType2[]
                        {
                            ItemsChoiceType2.translate,
                            ItemsChoiceType2.rotate,
                            ItemsChoiceType2.rotate,
                            ItemsChoiceType2.rotate
                        },
                        Items = new object[]
                        {
                            new TargetableFloat3()
                            {
                                Values = new double[] { translation.X, translation.Y, translation.Z },
                                sid    = "t",
                            },
                            new rotate()
                            {
                                Values = new double[] { 1.0, 0.0, 0.0, rotations.X },
                                sid    = "rx"
                            },
                            new rotate()
                            {
                                Values = new double[] { 0.0, 1.0, 0.0, rotations.Y },
                                sid    = "ry"
                            },
                            new rotate()
                            {
                                Values = new double[] { 0.0, 0.0, 1.0, rotations.Z },
                                sid    = "rz"
                            }
                        },

                        instance_geometry = new instance_geometry[]
                        {
                            new instance_geometry()
                            {
                                url           = "#caseGeometry",
                                bind_material = new bind_material()
                                {
                                    technique_common = new instance_material[]
                                    {
                                        new instance_material()
                                        {
                                            symbol = "materialCase0", target = "#material_Case0_ID"
                                        },
                                        new instance_material()
                                        {
                                            symbol = "materialCase1", target = "#material_Case1_ID"
                                        },
                                        new instance_material()
                                        {
                                            symbol = "materialCase2", target = "#material_Case2_ID"
                                        },
                                        new instance_material()
                                        {
                                            symbol = "materialCase3", target = "#material_Case3_ID"
                                        },
                                        new instance_material()
                                        {
                                            symbol = "materialCase4", target = "#material_Case4_ID"
                                        },
                                        new instance_material()
                                        {
                                            symbol = "materialCase5", target = "#material_Case5_ID"
                                        },
                                        new instance_material()
                                        {
                                            symbol = "materialCaseLines", target = "#material_CaseLines_ID"
                                        }
                                    }
                                }
                            }
                        }
                    };
                    sceneNodes.Add(caseNode);

                    // animations
                    CreateAnimation(caseIndex, (uint)_palletSolution.CaseCount, listAnimationSource, bp);

                    // increment case index
                    ++caseIndex;
                }
            }

            // add nodes
            mainScene.node = sceneNodes.ToArray();

            animationMain.Items = listAnimationSource.ToArray();

            // library_cameras
            camera cameraCamera = new camera()
            {
                id = "Camera-Camera", name = "Camera-Camera"
            };
            cameraOpticsTechnique_commonPerspective cameraPerspective = new cameraOpticsTechnique_commonPerspective()
            {
                znear = new TargetableFloat()
                {
                    sid = "znear", Value = 1.0
                },
                zfar = new TargetableFloat()
                {
                    sid = "zfar", Value = 10000.0
                }
            };

            cameraCamera.optics = new cameraOptics()
            {
                technique_common = new cameraOpticsTechnique_common()
                {
                    Item = cameraPerspective
                }
            };
            cameras.camera = new camera[] { cameraCamera };

            // colladaScene
            colladaScene.instance_visual_scene = new InstanceWithExtra()
            {
                url = "#MainScene"
            };

            model.Save(filePath);
            model.Save(System.IO.Path.ChangeExtension(filePath, "xml"));
        }
Beispiel #60
0
        /// <summary>
        ///     Exports a Model to the Collada format.
        ///     See: https://www.khronos.org/files/collada_spec_1_4.pdf for more information.
        /// </summary>
        /// <param name="model">The Model that will be exported</param>
        /// <param name="fileName">The output File Name</param>
        /// <param name="modelIndex">Index of the model to be exported</param>
        /// <param name="skeletalAnimationIndex">(Optional) Index of the skeletal animation</param>
        public static void export(RenderBase.OModelGroup model, string fileName, int modelIndex, int skeletalAnimationIndex = -1)
        {
            RenderBase.OModel mdl = model.model[modelIndex];
            COLLADA           dae = new COLLADA();

            dae.asset.created  = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ssZ");
            dae.asset.modified = dae.asset.created;

            foreach (RenderBase.OTexture tex in model.texture)
            {
                daeImage img = new daeImage();
                img.id        = tex.name + "_id";
                img.name      = tex.name;
                img.init_from = "./" + tex.name + ".png";

                dae.library_images.Add(img);
            }

            foreach (RenderBase.OMaterial mat in mdl.material)
            {
                daeMaterial mtl = new daeMaterial();
                mtl.name = mat.name + "_mat";
                mtl.id   = mtl.name + "_id";
                mtl.instance_effect.url = "#eff_" + mat.name + "_id";

                dae.library_materials.Add(mtl);

                daeEffect eff = new daeEffect();
                eff.id   = "eff_" + mat.name + "_id";
                eff.name = "eff_" + mat.name;

                daeParam surface = new daeParam();
                surface.surface           = new daeParamSurfaceElement();
                surface.sid               = "img_surface";
                surface.surface.type      = "2D";
                surface.surface.init_from = mat.name0 + "_id";
                surface.surface.format    = "PNG";
                eff.profile_COMMON.newparam.Add(surface);

                daeParam sampler = new daeParam();
                sampler.sampler2D        = new daeParamSampler2DElement();
                sampler.sid              = "img_sampler";
                sampler.sampler2D.source = "img_surface";

                switch (mat.textureMapper[0].wrapU)
                {
                case RenderBase.OTextureWrap.repeat: sampler.sampler2D.wrap_s = "WRAP"; break;

                case RenderBase.OTextureWrap.mirroredRepeat: sampler.sampler2D.wrap_s = "MIRROR"; break;

                case RenderBase.OTextureWrap.clampToEdge: sampler.sampler2D.wrap_s = "CLAMP"; break;

                case RenderBase.OTextureWrap.clampToBorder: sampler.sampler2D.wrap_s = "BORDER"; break;

                default: sampler.sampler2D.wrap_s = "NONE"; break;
                }

                switch (mat.textureMapper[0].wrapV)
                {
                case RenderBase.OTextureWrap.repeat: sampler.sampler2D.wrap_t = "WRAP"; break;

                case RenderBase.OTextureWrap.mirroredRepeat: sampler.sampler2D.wrap_t = "MIRROR"; break;

                case RenderBase.OTextureWrap.clampToEdge: sampler.sampler2D.wrap_t = "CLAMP"; break;

                case RenderBase.OTextureWrap.clampToBorder: sampler.sampler2D.wrap_t = "BORDER"; break;

                default: sampler.sampler2D.wrap_t = "NONE"; break;
                }

                switch (mat.textureMapper[0].minFilter)
                {
                case RenderBase.OTextureMinFilter.linearMipmapLinear: sampler.sampler2D.minfilter = "LINEAR_MIPMAP_LINEAR"; break;

                case RenderBase.OTextureMinFilter.linearMipmapNearest: sampler.sampler2D.minfilter = "LINEAR_MIPMAP_NEAREST"; break;

                case RenderBase.OTextureMinFilter.nearestMipmapLinear: sampler.sampler2D.minfilter = "NEAREST_MIPMAP_LINEAR"; break;

                case RenderBase.OTextureMinFilter.nearestMipmapNearest: sampler.sampler2D.minfilter = "NEAREST_MIPMAP_NEAREST"; break;

                default: sampler.sampler2D.minfilter = "NONE"; break;
                }

                switch (mat.textureMapper[0].magFilter)
                {
                case RenderBase.OTextureMagFilter.linear: sampler.sampler2D.magfilter = "LINEAR"; break;

                case RenderBase.OTextureMagFilter.nearest: sampler.sampler2D.magfilter = "NEAREST"; break;

                default: sampler.sampler2D.magfilter = "NONE"; break;
                }

                sampler.sampler2D.mipfilter = sampler.sampler2D.magfilter;

                eff.profile_COMMON.newparam.Add(sampler);

                eff.profile_COMMON.technique.sid = "img_technique";
                eff.profile_COMMON.technique.phong.emission.set(Color.Black);
                eff.profile_COMMON.technique.phong.ambient.set(Color.Black);
                eff.profile_COMMON.technique.phong.specular.set(Color.White);
                eff.profile_COMMON.technique.phong.diffuse.texture.texture = "img_sampler";

                dae.library_effects.Add(eff);
            }

            string jointNames   = null;
            string invBindPoses = null;

            for (int index = 0; index < mdl.skeleton.Count; index++)
            {
                RenderBase.OMatrix transform = new RenderBase.OMatrix();
                transformSkeleton(mdl.skeleton, index, ref transform);

                jointNames += mdl.skeleton[index].name;
                daeMatrix mtx = new daeMatrix();
                mtx.set(transform.invert());
                invBindPoses += mtx.data;
                if (index < mdl.skeleton.Count - 1)
                {
                    jointNames   += " ";
                    invBindPoses += " ";
                }
            }

            int            meshIndex = 0;
            daeVisualScene vs        = new daeVisualScene();

            vs.name = "vs_" + mdl.name;
            vs.id   = vs.name + "_id";
            if (mdl.skeleton.Count > 0)
            {
                writeSkeleton(mdl.skeleton, 0, ref vs.node);
            }
            foreach (RenderBase.OMesh obj in mdl.mesh)
            {
                //Geometry
                daeGeometry geometry = new daeGeometry();

                string meshName = "mesh_" + meshIndex++ + "_" + obj.name;
                geometry.id   = meshName + "_id";
                geometry.name = meshName;

                MeshUtils.optimizedMesh mesh      = MeshUtils.optimizeMesh(obj);
                List <float>            positions = new List <float>();
                List <float>            normals   = new List <float>();
                List <float>            uv0       = new List <float>();
                List <float>            uv1       = new List <float>();
                List <float>            uv2       = new List <float>();
                List <float>            colors    = new List <float>();
                foreach (RenderBase.OVertex vtx in mesh.vertices)
                {
                    positions.Add(vtx.position.x);
                    positions.Add(vtx.position.y);
                    positions.Add(vtx.position.z);

                    if (mesh.hasNormal)
                    {
                        normals.Add(vtx.normal.x);
                        normals.Add(vtx.normal.y);
                        normals.Add(vtx.normal.z);
                    }

                    if (mesh.texUVCount > 0)
                    {
                        uv0.Add(vtx.texture0.x);
                        uv0.Add(vtx.texture0.y);
                    }

                    if (mesh.texUVCount > 1)
                    {
                        uv1.Add(vtx.texture1.x);
                        uv1.Add(vtx.texture1.y);
                    }

                    if (mesh.texUVCount > 2)
                    {
                        uv2.Add(vtx.texture2.x);
                        uv2.Add(vtx.texture2.y);
                    }

                    if (mesh.hasColor)
                    {
                        colors.Add(((vtx.diffuseColor >> 16) & 0xff) / 255f);
                        colors.Add(((vtx.diffuseColor >> 8) & 0xff) / 255f);
                        colors.Add((vtx.diffuseColor & 0xff) / 255f);
                        colors.Add(((vtx.diffuseColor >> 24) & 0xff) / 255f);
                    }
                }

                daeSource position = new daeSource();
                position.name           = meshName + "_position";
                position.id             = position.name + "_id";
                position.float_array    = new daeFloatArray();
                position.float_array.id = position.name + "_array_id";
                position.float_array.set(positions);
                position.technique_common.accessor.source = "#" + position.float_array.id;
                position.technique_common.accessor.count  = (uint)mesh.vertices.Count;
                position.technique_common.accessor.stride = 3;
                position.technique_common.accessor.addParam("X", "float");
                position.technique_common.accessor.addParam("Y", "float");
                position.technique_common.accessor.addParam("Z", "float");

                geometry.mesh.source.Add(position);

                daeSource normal = new daeSource();
                if (mesh.hasNormal)
                {
                    normal.name           = meshName + "_normal";
                    normal.id             = normal.name + "_id";
                    normal.float_array    = new daeFloatArray();
                    normal.float_array.id = normal.name + "_array_id";
                    normal.float_array.set(normals);
                    normal.technique_common.accessor.source = "#" + normal.float_array.id;
                    normal.technique_common.accessor.count  = (uint)mesh.vertices.Count;
                    normal.technique_common.accessor.stride = 3;
                    normal.technique_common.accessor.addParam("X", "float");
                    normal.technique_common.accessor.addParam("Y", "float");
                    normal.technique_common.accessor.addParam("Z", "float");

                    geometry.mesh.source.Add(normal);
                }

                daeSource[] texUV = new daeSource[3];
                for (int i = 0; i < mesh.texUVCount; i++)
                {
                    texUV[i] = new daeSource();

                    texUV[i].name           = meshName + "_uv" + i;
                    texUV[i].id             = texUV[i].name + "_id";
                    texUV[i].float_array    = new daeFloatArray();
                    texUV[i].float_array.id = texUV[i].name + "_array_id";
                    texUV[i].technique_common.accessor.source = "#" + texUV[i].float_array.id;
                    texUV[i].technique_common.accessor.count  = (uint)mesh.vertices.Count;
                    texUV[i].technique_common.accessor.stride = 2;
                    texUV[i].technique_common.accessor.addParam("S", "float");
                    texUV[i].technique_common.accessor.addParam("T", "float");

                    geometry.mesh.source.Add(texUV[i]);
                }

                daeSource color = new daeSource();
                if (mesh.hasColor)
                {
                    color.name           = meshName + "_color";
                    color.id             = color.name + "_id";
                    color.float_array    = new daeFloatArray();
                    color.float_array.id = color.name + "_array_id";
                    color.float_array.set(colors);
                    color.technique_common.accessor.source = "#" + color.float_array.id;
                    color.technique_common.accessor.count  = (uint)mesh.vertices.Count;
                    color.technique_common.accessor.stride = 4;
                    color.technique_common.accessor.addParam("R", "float");
                    color.technique_common.accessor.addParam("G", "float");
                    color.technique_common.accessor.addParam("B", "float");
                    color.technique_common.accessor.addParam("A", "float");

                    geometry.mesh.source.Add(color);
                }

                geometry.mesh.vertices.id = meshName + "_vertices_id";
                geometry.mesh.vertices.addInput("POSITION", "#" + position.id);


                geometry.mesh.triangles.material = mdl.material[obj.materialId].name;
                geometry.mesh.triangles.addInput("VERTEX", "#" + geometry.mesh.vertices.id);
                if (mesh.hasNormal)
                {
                    geometry.mesh.triangles.addInput("NORMAL", "#" + normal.id);
                }
                if (mesh.hasColor)
                {
                    geometry.mesh.triangles.addInput("COLOR", "#" + color.id);
                }
                if (mesh.texUVCount > 0)
                {
                    texUV[0].float_array.set(uv0);
                    geometry.mesh.triangles.addInput("TEXCOORD", "#" + texUV[0].id);
                }
                if (mesh.texUVCount > 1)
                {
                    texUV[1].float_array.set(uv1);
                    geometry.mesh.triangles.addInput("TEXCOORD", "#" + texUV[1].id, 0, 1);
                }
                if (mesh.texUVCount > 2)
                {
                    texUV[2].float_array.set(uv2);
                    geometry.mesh.triangles.addInput("TEXCOORD", "#" + texUV[2].id, 0, 2);
                }
                geometry.mesh.triangles.set(mesh.indices);

                dae.library_geometries.Add(geometry);

                bool hasNode       = obj.vertices[0].node.Count > 0;
                bool hasWeight     = obj.vertices[0].weight.Count > 0;
                bool hasController = hasNode && hasWeight;

                //Controller
                daeController controller = new daeController();
                if (hasController)
                {
                    controller.id = meshName + "_ctrl_id";

                    controller.skin.source = "#" + geometry.id;
                    controller.skin.bind_shape_matrix.set(new RenderBase.OMatrix());

                    daeSource joints = new daeSource();
                    joints.id               = meshName + "_ctrl_joint_names_id";
                    joints.Name_array       = new daeNameArray();
                    joints.Name_array.id    = meshName + "_ctrl_joint_names_array_id";
                    joints.Name_array.count = (uint)mdl.skeleton.Count;
                    joints.Name_array.data  = jointNames;
                    joints.technique_common.accessor.source = "#" + joints.Name_array.id;
                    joints.technique_common.accessor.count  = joints.Name_array.count;
                    joints.technique_common.accessor.stride = 1;
                    joints.technique_common.accessor.addParam("JOINT", "Name");

                    controller.skin.src.Add(joints);

                    daeSource bindPoses = new daeSource();
                    bindPoses.id                = meshName + "_ctrl_inv_bind_poses_id";
                    bindPoses.float_array       = new daeFloatArray();
                    bindPoses.float_array.id    = meshName + "_ctrl_inv_bind_poses_array_id";
                    bindPoses.float_array.count = (uint)(mdl.skeleton.Count * 16);
                    bindPoses.float_array.data  = invBindPoses;
                    bindPoses.technique_common.accessor.source = "#" + bindPoses.float_array.id;
                    bindPoses.technique_common.accessor.count  = (uint)mdl.skeleton.Count;
                    bindPoses.technique_common.accessor.stride = 16;
                    bindPoses.technique_common.accessor.addParam("TRANSFORM", "float4x4");

                    controller.skin.src.Add(bindPoses);

                    daeSource weights = new daeSource();
                    weights.id             = meshName + "_ctrl_weights_id";
                    weights.float_array    = new daeFloatArray();
                    weights.float_array.id = meshName + "_ctrl_weights_array_id";
                    weights.technique_common.accessor.source = "#" + weights.float_array.id;
                    weights.technique_common.accessor.stride = 1;
                    weights.technique_common.accessor.addParam("WEIGHT", "float");

                    StringBuilder w      = new StringBuilder();
                    StringBuilder vcount = new StringBuilder();
                    StringBuilder v      = new StringBuilder();

                    float[] wLookBack      = new float[32];
                    uint    wLookBackIndex = 0;
                    int     buffLen        = 0;

                    int wIndex = 0;
                    int wCount = 0;
                    foreach (RenderBase.OVertex vtx in mesh.vertices)
                    {
                        int count = Math.Min(vtx.node.Count, vtx.weight.Count);

                        vcount.Append(count + " ");
                        for (int n = 0; n < count; n++)
                        {
                            v.Append(vtx.node[n] + " ");
                            bool found = false;
                            uint bPos  = (wLookBackIndex - 1) & 0x1f;
                            for (int i = 0; i < buffLen; i++)
                            {
                                if (wLookBack[bPos] == vtx.weight[n])
                                {
                                    v.Append(wIndex - (i + 1) + " ");
                                    found = true;
                                    break;
                                }
                                bPos = (bPos - 1) & 0x1f;
                            }

                            if (!found)
                            {
                                v.Append(wIndex++ + " ");
                                w.Append(vtx.weight[n].ToString(CultureInfo.InvariantCulture) + " ");
                                wCount++;

                                wLookBack[wLookBackIndex] = vtx.weight[n];
                                wLookBackIndex            = (wLookBackIndex + 1) & 0x1f;
                                if (buffLen < wLookBack.Length)
                                {
                                    buffLen++;
                                }
                            }
                        }
                    }

                    weights.float_array.data  = w.ToString().TrimEnd();
                    weights.float_array.count = (uint)wCount;
                    weights.technique_common.accessor.count = (uint)wCount;

                    controller.skin.src.Add(weights);
                    controller.skin.vertex_weights.vcount = vcount.ToString().TrimEnd();
                    controller.skin.vertex_weights.v      = v.ToString().TrimEnd();
                    controller.skin.vertex_weights.count  = (uint)mesh.vertices.Count;
                    controller.skin.joints.addInput("JOINT", "#" + joints.id);
                    controller.skin.joints.addInput("INV_BIND_MATRIX", "#" + bindPoses.id);

                    controller.skin.vertex_weights.addInput("JOINT", "#" + joints.id);
                    controller.skin.vertex_weights.addInput("WEIGHT", "#" + weights.id, 1);

                    if (dae.library_controllers == null)
                    {
                        dae.library_controllers = new List <daeController>();
                    }
                    dae.library_controllers.Add(controller);
                }

                //Visual scene node
                daeNode node = new daeNode();
                node.name = "vsn_" + meshName;
                node.id   = node.name + "_id";
                node.matrix.set(new RenderBase.OMatrix());
                if (hasController)
                {
                    node.instance_controller          = new daeInstanceController();
                    node.instance_controller.url      = "#" + controller.id;
                    node.instance_controller.skeleton = "#" + mdl.skeleton[0].name + "_bone_id";
                    node.instance_controller.bind_material.technique_common.instance_material.symbol = mdl.material[obj.materialId].name;
                    node.instance_controller.bind_material.technique_common.instance_material.target = "#" + mdl.material[obj.materialId].name + "_mat_id";
                }
                else
                {
                    node.instance_geometry     = new daeInstanceGeometry();
                    node.instance_geometry.url = "#" + geometry.id;
                    node.instance_geometry.bind_material.technique_common.instance_material.symbol = mdl.material[obj.materialId].name;
                    node.instance_geometry.bind_material.technique_common.instance_material.target = "#" + mdl.material[obj.materialId].name + "_mat_id";
                }

                vs.node.Add(node);
            }
            dae.library_visual_scenes.Add(vs);

            daeInstaceVisualScene scene = new daeInstaceVisualScene();

            scene.url = "#" + vs.id;
            dae.scene.Add(scene);

            XmlWriterSettings settings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                Indent   = true
            };

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "http://www.collada.org/2005/11/COLLADASchema");
            XmlSerializer serializer = new XmlSerializer(typeof(COLLADA));
            XmlWriter     output     = XmlWriter.Create(new FileStream(fileName, FileMode.Create), settings);

            serializer.Serialize(output, dae, ns);
            output.Close();
        }