示例#1
0
        public void ExportBMD(string fileName, bool isBDL)
        {
            string outDir        = Path.GetDirectoryName(fileName);
            string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);

            fileNameNoExt = fileNameNoExt.Split('.')[0];
            if (isBDL)
            {
                fileName = Path.Combine(outDir, fileNameNoExt + ".bdl");
            }
            else
            {
                fileName = Path.Combine(outDir, fileNameNoExt + ".bmd");
            }

            using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                EndianBinaryWriter writer = new EndianBinaryWriter(stream, Endian.Big);

                if (isBDL)
                {
                    writer.Write("J3D2bdl4".ToCharArray());
                }
                else
                {
                    writer.Write("J3D2bmd3".ToCharArray());
                }

                writer.Write(0); // Placeholder for file size

                if (isBDL)
                {
                    writer.Write(9); // Number of sections; bmd has 8, bdl has 9
                }
                else
                {
                    writer.Write(8);
                }

                writer.Write("SuperBMD - Gamma".ToCharArray());

                Scenegraph.Write(writer, packetCount, vertexCount);
                VertexData.Write(writer);
                SkinningEnvelopes.Write(writer);
                PartialWeightData.Write(writer);
                Joints.Write(writer);
                Shapes.Write(writer);
                Materials.Write(writer);

                if (isBDL)
                {
                    MatDisplayList.Write(writer);
                }

                Textures.Write(writer);

                writer.Seek(8, SeekOrigin.Begin);
                writer.Write((int)writer.BaseStream.Length);
            }
        }
示例#2
0
        public void Export(string fileName)
        {
            using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                EndianBinaryWriter writer = new EndianBinaryWriter(stream, Endian.Big);

                writer.Write("J3D2bmd3".ToCharArray());
                writer.Write(0); // Placeholder for file size
                writer.Write(8); // Number of sections; bmd has 8, bdl has 9

                writer.Write("SVR3".ToCharArray());
                writer.Write(-1);
                writer.Write((long)-1);

                Scenegraph.Write(writer, packetCount, vertexCount);
                VertexData.Write(writer);
                SkinningEnvelopes.Write(writer);
                PartialWeightData.Write(writer);
                Joints.Write(writer);
                Shapes.Write(writer);
                Materials.Write(writer);
                Textures.Write(writer);

                writer.Seek(8, SeekOrigin.Begin);
                writer.Write((int)writer.BaseStream.Length);
            }
        }
示例#3
0
        internal void Load(XmlReader reader, GameObject parent, ComponentIndexer componentIndexer, Scenegraph scenegraph)
        {
            transform.Scenegraph = scenegraph;
            AddSubscriptions(null);
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "GameObject")
                {
                    return;
                }

                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "Children")
                    {
                        LoadChildren(reader, componentIndexer);
                    }
                    else
                    {
                        Component c = componentIndexer.GetComponentByName(reader.Name, this);
                        if (c == null)
                        {
                            throw new ParseException(reader.Name);
                        }

                        if (c is Transform)
                        {
                            transform.Load(reader);
                            if (parent != null)
                            {
                                transform.Parent = parent.transform;
                            }
                        }
                        else
                        {
                            c.Load(reader);
                            components.Add(c);
                        }
                    }
                }
            }
        }
示例#4
0
 /// <summary>
 /// currently does nothing
 /// </summary>
 /// <param name="gameTime"></param>
 /// <param name="graph"></param>
 protected override void UpdateMe(GameTime gameTime, Scenegraph graph)
 {
     //TODO Could put support for animated tiles here...
 }
示例#5
0
        public void ExportAssImp(string fileName, string modelType, ExportSettings settings)
        {
            fileName = Path.GetFullPath(fileName); // Get absolute path instead of relative
            string outDir        = Path.GetDirectoryName(fileName);
            string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);

            fileName = Path.Combine(outDir, fileNameNoExt + ".dae");

            Scene outScene = new Scene();

            outScene.RootNode = new Node("RootNode");

            Materials.FillScene(outScene, Textures, outDir);
            Shapes.FillScene(outScene, VertexData.Attributes, Joints.FlatSkeleton, SkinningEnvelopes.InverseBindMatrices);
            Scenegraph.FillScene(outScene, Joints.FlatSkeleton, settings.UseSkeletonRoot);
            Scenegraph.CorrectMaterialIndices(outScene, Materials);
            Textures.DumpTextures(outDir);


            foreach (Mesh mesh in outScene.Meshes)
            {
                // Assimp has a JoinIdenticalVertices post process step, but we can't use that or the skinning info we manually add won't take it into account.
                RemoveDuplicateVertices(mesh);
            }


            AssimpContext cont = new AssimpContext();

            cont.ExportFile(outScene, fileName, "collada", PostProcessSteps.ValidateDataStructure);


            //if (SkinningEnvelopes.Weights.Count == 0)
            //    return; // There's no skinning information, so we can stop here

            // Now we need to add some skinning info, since AssImp doesn't do it for some bizarre reason

            StreamWriter test = new StreamWriter(fileName + ".tmp");
            StreamReader dae  = File.OpenText(fileName);

            while (!dae.EndOfStream)
            {
                string line = dae.ReadLine();

                if (line == "  <library_visual_scenes>")
                {
                    AddControllerLibrary(outScene, test);
                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<node"))
                {
                    Regex reg   = new Regex("^( +)<node id=\"([^\"]+)\" +name=\"[^\"]+\" +type=\"NODE\">$");
                    Match match = reg.Match(line);

                    if (match.Success)
                    {
                        string indentation = match.Groups[1].Value;
                        string joint_name  = match.Groups[2].Value;
                        if (Joints.FlatSkeleton.Exists(x => x.Name == joint_name))
                        {
                            string jointLine = indentation + $"<node id=\"{joint_name}\" name=\"{joint_name}\" sid=\"{joint_name}\" type=\"JOINT\">";
                            test.WriteLine(jointLine);
                        }
                        else
                        {
                            test.WriteLine(line);
                        }
                    }
                    else
                    {
                        test.WriteLine(line);
                    }
                    test.Flush();
                }
                else if (line.Contains("<material id=\""))
                {
                    Regex reg   = new Regex("^    <material id=\"([^\"]+)\" name=\"[^\"]+\">$");
                    Match match = reg.Match(line);
                    if (match.Success)
                    {
                        string mat_name_sanitized = match.Groups[1].Value;
                        int    mat_index          = Materials.GetMaterialIndexFromSanitizedMaterialName(mat_name_sanitized);
                        string mat_name           = Materials.m_Materials[mat_index].Name;
                        string matLine            = $"    <material id=\"{mat_name_sanitized}\" name=\"{mat_name}\">";
                        test.WriteLine(matLine);
                    }
                    else
                    {
                        test.WriteLine(line);
                    }
                    test.Flush();
                }
                else if (line.Contains("</visual_scene>"))
                {
                    foreach (Mesh mesh in outScene.Meshes)
                    {
                        test.WriteLine($"      <node id=\"{ mesh.Name }\" name=\"{ mesh.Name }\" type=\"NODE\">");

                        test.WriteLine($"       <instance_controller url=\"#{ mesh.Name }-skin\">");
                        test.WriteLine("        <skeleton>#skeleton_root</skeleton>");
                        test.WriteLine("        <bind_material>");
                        test.WriteLine("         <technique_common>");
                        test.WriteLine($"          <instance_material symbol=\"{ Materials.m_Materials[mesh.MaterialIndex].Name }\" target=\"#{ Materials.m_Materials[mesh.MaterialIndex].Name.Replace("(", "_").Replace(")", "_") }\" />");
                        test.WriteLine("         </technique_common>");
                        test.WriteLine("        </bind_material>");
                        test.WriteLine("       </instance_controller>");

                        test.WriteLine("      </node>");
                        test.Flush();
                    }

                    test.WriteLine(line);
                    test.Flush();
                }
                else
                {
                    test.WriteLine(line);
                    test.Flush();
                }
            }

            test.Close();
            dae.Close();

            File.Copy(fileName + ".tmp", fileName, true);
            File.Delete(fileName + ".tmp");
        }
示例#6
0
 public Transform(GameObject gameObject) : base(gameObject)
 {
     scenegraph = SceneManager.CurrentScene?.Scenegraph;
     children   = new List <Transform>();
 }
示例#7
0
        public void ExportAssImp(string fileName, string modelType, ExportSettings settings)
        {
            string outDir        = Path.GetDirectoryName(fileName);
            string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);

            fileName = Path.Combine(outDir, fileNameNoExt + ".dae");

            Scene outScene = new Scene();

            outScene.RootNode = new Node("RootNode");

            Scenegraph.FillScene(outScene, Joints.FlatSkeleton, settings.UseSkeletonRoot);
            Materials.FillScene(outScene, Textures, outDir);
            Shapes.FillScene(outScene, VertexData.Attributes, Joints.FlatSkeleton, SkinningEnvelopes.InverseBindMatrices);
            Scenegraph.CorrectMaterialIndices(outScene, Materials);

            if (SkinningEnvelopes.Weights.Count == 0)
            {
                Assimp.Node geomNode = new Node(Path.GetFileNameWithoutExtension(fileName), outScene.RootNode);

                for (int i = 0; i < Shapes.Shapes.Count; i++)
                {
                    geomNode.MeshIndices.Add(i);
                }

                outScene.RootNode.Children.Add(geomNode);
            }

            AssimpContext cont = new AssimpContext();

            cont.ExportFile(outScene, fileName, "collada", PostProcessSteps.ValidateDataStructure);

            if (SkinningEnvelopes.Weights.Count == 0)
            {
                return; // There's no skinning information, so we can stop here
            }
            // Now we need to add some skinning info, since AssImp doesn't do it for some bizarre reason

            StreamWriter test = new StreamWriter(fileName + ".tmp");
            StreamReader dae  = File.OpenText(fileName);

            while (!dae.EndOfStream)
            {
                string line = dae.ReadLine();

                if (line == "  <library_visual_scenes>")
                {
                    AddControllerLibrary(outScene, test);
                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<node"))
                {
                    string[] testLn = line.Split('\"');
                    string   name   = testLn[3];

                    if (Joints.FlatSkeleton.Exists(x => x.Name == name))
                    {
                        string jointLine = line.Replace(">", $" sid=\"{ name }\" type=\"JOINT\">");
                        test.WriteLine(jointLine);
                        test.Flush();
                    }
                    else
                    {
                        test.WriteLine(line);
                        test.Flush();
                    }
                }
                else if (line.Contains("</visual_scene>"))
                {
                    foreach (Mesh mesh in outScene.Meshes)
                    {
                        test.WriteLine($"      <node id=\"{ mesh.Name }\" name=\"{ mesh.Name }\" type=\"NODE\">");

                        test.WriteLine($"       <instance_controller url=\"#{ mesh.Name }-skin\">");
                        test.WriteLine("        <skeleton>#skeleton_root</skeleton>");
                        test.WriteLine("        <bind_material>");
                        test.WriteLine("         <technique_common>");
                        test.WriteLine($"          <instance_material symbol=\"theresonlyone\" target=\"#m{ mesh.MaterialIndex }mat\" />");
                        test.WriteLine("         </technique_common>");
                        test.WriteLine("        </bind_material>");
                        test.WriteLine("       </instance_controller>");

                        test.WriteLine("      </node>");
                        test.Flush();
                    }

                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<matrix"))
                {
                    string matLine = line.Replace("<matrix>", "<matrix sid=\"matrix\">");
                    test.WriteLine(matLine);
                    test.Flush();
                }
                else
                {
                    test.WriteLine(line);
                    test.Flush();
                }
            }

            test.Close();
            dae.Close();

            File.Copy(fileName + ".tmp", fileName, true);
            File.Delete(fileName + ".tmp");
        }
示例#8
0
文件: Model.cs 项目: kai13xd/SuperBMD
        public void ExportAssImp(string fileName, string outFilepath, string modelType, ExportSettings settings, bool keepmatnames = true)
        {
            string outDir = Path.GetDirectoryName(outFilepath);

            //string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);
            fileName = outFilepath;//Path.Combine(outDir, fileNameNoExt + ".dae");

            Scene outScene = new Scene();

            outScene.RootNode = new Node("RootNode");

            Scenegraph.FillScene(outScene, Joints.FlatSkeleton, settings.UseSkeletonRoot);
            Dictionary <string, int> slots_to_uvindex = Materials.FillScene(outScene, Textures, outDir, keepmatnames);

            Shapes.FillScene(outScene, VertexData.Attributes, Joints.FlatSkeleton, SkinningEnvelopes.InverseBindMatrices);
            Scenegraph.CorrectMaterialIndices(outScene, Materials);
            Textures.DumpTextures(outDir);

            foreach (Mesh mesh in outScene.Meshes)
            {
                Console.WriteLine(String.Format("Texcoord count: {0}", mesh.TextureCoordinateChannelCount));
            }

            if (true)  //(SkinningEnvelopes.Weights.Count == 0)
            {
                Assimp.Node geomNode = new Node(Path.GetFileNameWithoutExtension(fileName), outScene.RootNode);

                for (int i = 0; i < Shapes.Shapes.Count; i++)
                {
                    geomNode.MeshIndices.Add(i);
                }

                outScene.RootNode.Children.Add(geomNode);
            }

            AssimpContext cont = new AssimpContext();

            cont.ExportFile(outScene, fileName, "collada", PostProcessSteps.ValidateDataStructure | PostProcessSteps.JoinIdenticalVertices);
            //cont.ExportFile(outScene, fileName, "collada");


            List <string> a;

            //if (SkinningEnvelopes.Weights.Count == 0)
            //    return; // There's no skinning information, so we can stop here

            //return; // adding skinning info is buggy so we won't do it
            // Now we need to add some skinning info, since AssImp doesn't do it for some bizarre reason

            bool hasWeights = SkinningEnvelopes.Weights.Count != 0;

            hasWeights = false;
            StreamWriter test      = new StreamWriter(fileName + ".tmp");
            StreamReader dae       = File.OpenText(fileName);
            bool         dontWrite = false;

            while (!dae.EndOfStream)
            {
                string line = dae.ReadLine();

                //if (SkinningEnvelopes.Weights.Count != 0) {
                if (hasWeights && line == "  <library_visual_scenes>")
                {
                    AddControllerLibrary(outScene, test);
                    test.WriteLine(line);
                    test.Flush();
                }
                else if (hasWeights && line.Contains("<node"))
                {
                    string[] testLn = line.Split('\"');
                    string   name   = testLn[3];

                    if (Joints.FlatSkeleton.Exists(x => x.Name == name))
                    {
                        string jointLine = line.Replace(">", $" sid=\"{ name }\" type=\"JOINT\">");
                        test.WriteLine(jointLine);
                        test.Flush();
                    }
                    else
                    {
                        test.WriteLine(line);
                        test.Flush();
                    }
                }
                else if (hasWeights && line.Contains("</visual_scene>"))
                {
                    foreach (Mesh mesh in outScene.Meshes)
                    {
                        string matname = "mat";
                        if (keepmatnames == true)
                        {
                            matname = AssimpMatnameSanitize(mesh.MaterialIndex, outScene.Materials[mesh.MaterialIndex].Name);
                        }
                        else
                        {
                            matname = AssimpMatnameSanitize(mesh.MaterialIndex, matname);
                        }

                        test.WriteLine($"      <node id=\"{ mesh.Name }\" name=\"{ mesh.Name }\" type=\"NODE\">");

                        test.WriteLine($"       <instance_controller url=\"#{ mesh.Name }-skin\">");
                        test.WriteLine("        <skeleton>#skeleton_root</skeleton>");
                        test.WriteLine("        <bind_material>");
                        test.WriteLine("         <technique_common>");
                        test.WriteLine($"          <instance_material symbol=\"theresonlyone\" target=\"#{matname}\" />");
                        test.WriteLine("         </technique_common>");
                        test.WriteLine("        </bind_material>");
                        test.WriteLine("       </instance_controller>");

                        test.WriteLine("      </node>");
                        test.Flush();
                    }

                    test.WriteLine(line);
                    test.Flush();
                }
                else if (hasWeights && line.Contains("<matrix"))
                {
                    string matLine = line.Replace("<matrix>", "<matrix sid=\"matrix\">");
                    test.WriteLine(matLine);
                    test.Flush();
                }
                else if (line.Contains("<library_images>"))
                {
                    dontWrite = true;
                    Console.WriteLine("Hello Hallo");
                }
                else if (line.Contains("</library_images>"))
                {
                    dontWrite = false;
                    Console.WriteLine("Hello Hallo2");
                    // Add our own images here
                    test.WriteLine("  <library_images>");
                    WriteTexturesToStream(outScene, test);
                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<library_effects>"))
                {
                    dontWrite = true;
                    Console.WriteLine("Hello Hallo3");
                    // We get rid of the existing library effects
                }
                else if (line.Contains("</library_effects>"))
                {
                    dontWrite = false;
                    Console.WriteLine("Hello Hallo4");
                    // Add our own library_effects here
                    test.WriteLine("    <library_effects>");
                    WriteMaterialsToStream(outScene, test, slots_to_uvindex);
                    test.WriteLine(line);
                    test.Flush();
                }
                else if (!dontWrite)
                {
                    test.WriteLine(line);
                    test.Flush();
                }
            }
            test.Close();
            dae.Close();

            File.Copy(fileName + ".tmp", fileName, true);
            File.Delete(fileName + ".tmp");
        }
示例#9
0
 /// <summary>
 /// This update just advances frames and checks for collisions
 /// </summary>
 /// <param name="gameTime"> the elapsed time since last call</param>
 /// <param name="graph">the scenegraph this SceneObject is attached to</param>
 protected override void UpdateMe(GameTime gameTime, Scenegraph graph)
 {
     if (image != null)
     {
         image.Update(gameTime, graph);
     }
     List<CollisionRecord> removalList= new List<CollisionRecord>();
     foreach (CollisionRecord rec in collisionList)
     {
         BasicSprite other = rec.sprite;
         if (other.IsDestroyed())
         {
             removalList.Add(rec);
         }
         else
         {
             if (GetCollider().CollidesWith(other.GetCollider()))
             {
                 if (!rec.collidedWith)
                 {
                     rec.collidedWith = true;
                     OnCollisionEnterWith(other);
                 }
                 OnCollisionWith(other);
             }
             else
             {
                 if (rec.collidedWith)
                 {
                     rec.collidedWith = false;
                     OnCollisionExitWith(other);
                 }
             }
         }
     }
     foreach (CollisionRecord r in removalList)
     {
         collisionList.Remove(r);
     }
 }
示例#10
0
        /// <summary>
        /// Clone an object based on way Files are linked
        /// </summary>
        /// <param name="pfd"></param>
        /// <param name="localgroup"></param>
        /// <param name="onlydefault"></param>
        protected static SimPe.Packages.GeneratableFile RecolorClone(CloneSettings.BaseResourceType br, SimPe.Packages.GeneratableFile ppkg, Interfaces.Files.IPackedFileDescriptor pfd, uint localgroup, ObjectWorkshopSettings settings, bool pkgcontainsonlybase)
        {
            SimPe.Packages.GeneratableFile package = null;
            if (ppkg != null)
            {
                package = (SimPe.Packages.GeneratableFile)ppkg.Clone();
            }
            if (ppkg == null || pkgcontainsonlybase)
            {
                if (!pkgcontainsonlybase)
                {
                    package = SimPe.Packages.GeneratableFile.CreateNew();
                }
                //Get the Base Object Data from the Objects.package File
                string[] modelname = new string[0];
                if (br == CloneSettings.BaseResourceType.Objd)
                {
                    modelname = BaseClone(localgroup, package, pkgcontainsonlybase);
                }
                else
                {
                    SimPe.Interfaces.Scenegraph.IScenegraphFileIndexItem[] fii = FileTable.FileIndex.FindFile(pfd, null);
                    if (fii.Length > 0)
                    {
                        SimPe.Interfaces.Files.IPackedFileDescriptor cpfd = fii[0].FileDescriptor.Clone();
                        cpfd          = cpfd.Clone();
                        cpfd.UserData = fii[0].Package.Read(fii[0].FileDescriptor).UncompressedData;
                        package.Add(cpfd);
                    }
                }
                ObjectCloner objclone = new ObjectCloner(package);
                ArrayList    exclude  = new ArrayList();



                //allways for recolors
                if (settings is OWRecolorSettings)
                {
                    exclude.Add("stdMatEnvCubeTextureName");
                    exclude.Add("TXTR");
                }
                else
                {
                    exclude.Add("tsMaterialsMeshName");
                    exclude.Add("TXTR");
                    exclude.Add("stdMatEnvCubeTextureName");
                }

                //do the recolor
                objclone.Setup = settings;
                objclone.Setup.BaseResource     = br;
                objclone.Setup.OnlyDefaultMmats = (settings.OnlyDefaultMmats && br != CloneSettings.BaseResourceType.Xml);
                objclone.Setup.UpdateMmatGuids  = objclone.Setup.OnlyDefaultMmats;

                /*objclone.Setup.IncludeWallmask = settings.IncludeWallmask;
                 * objclone.Setup.IncludeAnimationResources = settings.IncludeAnimationResources;
                 * objclone.Setup.KeepOriginalMesh = settings.KeepOriginalMesh;
                 * objclone.Setup.PullResourcesByStr = settings.PullResourcesByStr;
                 * objclone.Setup.StrInstances = settings.StrInstances;*/


                objclone.RcolModelClone(modelname, exclude);

                //for clones only when cbparent is checked
                if (settings is OWCloneSettings)
                {
                    if (((OWCloneSettings)settings).StandAloneObject || br == CloneSettings.BaseResourceType.Xml)
                    {
                        string[]            names = Scenegraph.LoadParentModelNames(package, true);
                        SimPe.Packages.File pkg   = SimPe.Packages.File.LoadFromFile(null);

                        ObjectCloner pobj = new ObjectCloner(pkg);
                        pobj.Setup = settings;
                        pobj.Setup.BaseResource     = br;
                        pobj.Setup.OnlyDefaultMmats = (settings.OnlyDefaultMmats && br != CloneSettings.BaseResourceType.Xml);;
                        pobj.Setup.UpdateMmatGuids  = pobj.Setup.OnlyDefaultMmats;

                        /*pobj.Setup.IncludeWallmask = settings.IncludeWallmask;
                         * pobj.Setup.IncludeAnimationResources = settings.IncludeAnimationResources;
                         * pobj.Setup.KeepOriginalMesh = settings.KeepOriginalMesh;
                         * pobj.Setup.PullResourcesByStr = settings.PullResourcesByStr;
                         * pobj.Setup.StrInstances = settings.StrInstances;*/


                        pobj.RcolModelClone(names, exclude);
                        pobj.AddParentFiles(modelname, package);
                    }
                    else
                    {
                        string[] modelnames = modelname;
                        if (!((OWCloneSettings)settings).RemoveUselessResource)
                        {
                            modelnames = null;
                        }
                        objclone.RemoveSubsetReferences(Scenegraph.GetParentSubsets(package), modelnames);
                    }
                }
            }

            return(package);
        }
示例#11
0
 /// <summary>
 /// Called to update the image for the passage of time.  
 /// Since a SimpleSpriteImage represents a single static image, it is a NOP
 /// </summary>
 /// <param name="gameTime">elapsed time since last call</param>
 /// <param name="graph">the scene graph that is controlling the render of this sprite image</param>
 public void Update(GameTime gameTime, Scenegraph graph)
 {
     //does nothing in a  simple sprite image
 }
示例#12
0
        /// <summary>
        /// This update just advances frames.
        /// </summary>
        /// <param name="gameTime"> the elapsed time since last call</param>
        /// <param name="graph">the scenegraph this SceneObject is attached to</param>
        public void Update(GameTime gameTime, Scenegraph graph)
        {
            elapsedFrameTime += gameTime.ElapsedGameTime.TotalSeconds;

            while (elapsedFrameTime >= secPerFrame)
            {
                elapsedFrameTime -= secPerFrame;
                frameIndex = (frameIndex + 1) % frames.Length;
                ResetColliderSize();
            }
        }
示例#13
0
        public void ExportAssImp(string fileName, string modelType, ExportSettings settings, Arguments cmdargs)
        {
            fileName = Path.GetFullPath(fileName); // Get absolute path instead of relative
            string outDir        = Path.GetDirectoryName(fileName);
            string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);

            if (modelType == "obj")
            {
                fileName = Path.Combine(outDir, fileNameNoExt + ".obj");
            }
            else
            {
                fileName = Path.Combine(outDir, fileNameNoExt + ".dae");
            }
            Scene outScene = new Scene {
                RootNode = new Node("RootNode")
            };

            Console.WriteLine();
            Console.WriteLine("Processing Materials ->");
            Materials.FillScene(outScene, Textures, outDir);
            Console.WriteLine();
            Console.WriteLine("Processing Meshes ->");
            Shapes.FillScene(outScene, VertexData.Attributes, Joints.FlatSkeleton, SkinningEnvelopes.InverseBindMatrices);
            Console.WriteLine();
            Console.Write("Processing Skeleton");
            Scenegraph.FillScene(outScene, Joints.FlatSkeleton, settings.UseSkeletonRoot);
            Scenegraph.CorrectMaterialIndices(outScene, Materials);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Processing Textures ->");
            Textures.DumpTextures(outDir, fileNameNoExt + "_tex_headers.json", true, cmdargs.readMipmaps);

            string infPath = Path.Combine(outDir, fileNameNoExt + "_hierarchy.json");

            this.Scenegraph.DumpJson(infPath);

            Console.WriteLine();
            Console.WriteLine("Removing Duplicate Verticies ->");
            foreach (Mesh mesh in outScene.Meshes)
            {
                Console.Write(mesh.Name.Replace('_', ' ') + ": ");
                // Assimp has a JoinIdenticalVertices post process step, but we can't use that or the skinning info we manually add won't take it into account.
                RemoveDuplicateVertices(mesh);
                Console.Write("✓");
                Console.WriteLine();
            }


            AssimpContext cont = new AssimpContext();

            if (modelType == "obj")
            {
                Console.WriteLine("Writing the OBJ file...");
                cont.ExportFile(outScene, fileName, "obj");//, PostProcessSteps.ValidateDataStructure);
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName)) {
                    string mtllibname = fileName.Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries).Last() + ".mtl";
                    file.WriteLine(String.Format("mtllib {0}", mtllibname));
                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        foreach (Assimp.Vector3D vertex in mesh.Vertices)
                        {
                            file.WriteLine(String.Format("v {0} {1} {2}", vertex.X, vertex.Y, vertex.Z));
                        }
                    }

                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        foreach (Assimp.Vector3D normal in mesh.Normals)
                        {
                            file.WriteLine(String.Format("vn {0} {1} {2}", normal.X, normal.Y, normal.Z));
                        }
                    }

                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        if (mesh.HasTextureCoords(0))
                        {
                            foreach (Assimp.Vector3D uv in mesh.TextureCoordinateChannels[0])
                            {
                                file.WriteLine(String.Format("vt {0} {1}", uv.X, uv.Y));
                            }
                        }
                    }

                    int vertex_offset = 1;

                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        string material_name = outScene.Materials[mesh.MaterialIndex].Name;
                        file.WriteLine(String.Format("usemtl {0}", material_name));



                        foreach (Assimp.Face face in mesh.Faces)
                        {
                            file.Write("f ");
                            foreach (int index in face.Indices)
                            {
                                file.Write(index + vertex_offset);
                                if (mesh.HasTextureCoords(0))
                                {
                                    file.Write("/");
                                    file.Write(index + vertex_offset);
                                }
                                if (!mesh.HasTextureCoords(0) && mesh.HasNormals)
                                {
                                    file.Write("//");
                                    file.Write(index + vertex_offset);
                                }
                                else if (mesh.HasNormals)
                                {
                                    file.Write("/");
                                    file.Write(index + vertex_offset);
                                }
                                file.Write(" ");
                            }
                            file.Write("\n");
                        }

                        vertex_offset += mesh.VertexCount;
                    }
                }
                return;
            }
            else
            {
                cont.ExportFile(outScene, fileName, "collada", PostProcessSteps.ValidateDataStructure);
            }

            //if (SkinningEnvelopes.Weights.Count == 0)
            //    return; // There's no skinning information, so we can stop here

            // Now we need to add some skinning info, since AssImp doesn't do it for some bizarre reason

            StreamWriter test = new StreamWriter(fileName + ".tmp");
            StreamReader dae  = File.OpenText(fileName);

            Console.WriteLine();
            Console.Write("Finalizing the Mesh");
            while (!dae.EndOfStream)
            {
                string line = dae.ReadLine();

                if (line == "  <library_visual_scenes>")
                {
                    AddControllerLibrary(outScene, test);
                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<node"))
                {
                    string[] testLn = line.Split('\"');
                    string   name   = testLn[3];

                    if (Joints.FlatSkeleton.Exists(x => x.Name == name))
                    {
                        string jointLine = line.Replace(">", $" sid=\"{ name }\" type=\"JOINT\">");
                        test.WriteLine(jointLine);
                        test.Flush();
                    }
                    else
                    {
                        test.WriteLine(line);
                        test.Flush();
                    }
                }
                else if (line.Contains("</visual_scene>"))
                {
                    foreach (Mesh mesh in outScene.Meshes)
                    {
                        string matname      = "mat";
                        bool   keepmatnames = false;
                        if (keepmatnames == true)
                        {
                            matname = AssimpMatnameSanitize(mesh.MaterialIndex, outScene.Materials[mesh.MaterialIndex].Name);
                        }
                        else
                        {
                            matname = AssimpMatnameSanitize(mesh.MaterialIndex, Materials.m_Materials[mesh.MaterialIndex].Name);
                        }

                        test.WriteLine($"      <node id=\"{ mesh.Name }\" name=\"{ mesh.Name }\" type=\"NODE\">");

                        test.WriteLine($"       <instance_controller url=\"#{ mesh.Name }-skin\">");
                        test.WriteLine("        <skeleton>#skeleton_root</skeleton>");
                        test.WriteLine("        <bind_material>");
                        test.WriteLine("         <technique_common>");
                        test.WriteLine($"          <instance_material symbol=\"m{matname}\" target=\"#{matname}\" />");
                        test.WriteLine("         </technique_common>");
                        test.WriteLine("        </bind_material>");
                        test.WriteLine("       </instance_controller>");

                        test.WriteLine("      </node>");
                        test.Flush();
                    }

                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<matrix"))
                {
                    string matLine = line.Replace("<matrix>", "<matrix sid=\"matrix\">");
                    test.WriteLine(matLine);
                    test.Flush();
                }
                else
                {
                    test.WriteLine(line);
                    test.Flush();
                }
                Console.Write(".");
            }

            Console.Write("✓");
            Console.WriteLine();

            test.Close();
            dae.Close();

            File.Copy(fileName + ".tmp", fileName, true);
            File.Delete(fileName + ".tmp");
        }
示例#14
0
 protected override void UpdateMe(GameTime gameTime, Scenegraph graph)
 {
     base.UpdateMe(gameTime, graph);
     Vector2 newCell = GetLocalCellPosition();
     if (lastCell != newCell)
     {
         ExitedCell(lastCell);
         EnteredCell(newCell);
     }
     lastCell = newCell;
 }
示例#15
0
        /// <summary>
        /// This method is responsible for the update of the MOB. It adds movement
        /// behavior to the  BasicTilemapSprite beahvior
        /// </summary>
        /// <param name="gameTime">elapsed tiem since last call</param>
        /// <param name="graph">scenegraph this MOb is (potentially indirectly) parented to</param>
        protected override void UpdateMe(GameTime gameTime, Scenegraph graph)
        {
            base.UpdateMe(gameTime, graph); // let any base classes do their updating

            // now do motion
            double deltaT = gameTime.ElapsedGameTime.TotalSeconds;
            if (moving)
            {

                // check to see if we overshot and end motion
                // calculate distance to goal from where we are
                // We use a trick to avoid the square root in the distance claculation
                // movement speed is always >=0
                // if X& Y are both >=0  then IFF (X*X)>(Y*Y) THEN X>Y
                // so the comaprison is the same whether we take the quare root or not
                // as long as we comapre against another squred value
                Vector2 pos = GetLocalPosition();
                float dx = destinationPixel.X - pos.X;
                float dy = destinationPixel.Y - pos.Y;
                // Note this is a distance claculation without the final SQRT
                float distanceToGoalSqd = (dx * dx) + (dy * dy);
                // find the distance traveled since last update
                float distanceTraveled = (float)(deltaT * pixelPerSecSpeed);
                // calculate the distance squared for comparesion (much cheaper then SQRT)
                float distanceTraveledSqd = distanceTraveled * distanceTraveled;
                // compare.  If we moved a distance equal to or greater then the distance to the goal
                // for our last position, then we have reached our goal so just set us there and
                //end the move
                if (distanceToGoalSqd <= distanceTraveledSqd)
                {
                    SetLocalPosition(destinationPixel);
                    moving = false;
                }
                else
                {
                    // otehrwise move closer
                    SetLocalPosition(new Vector2(
                        pos.X + (float)(velocityPixPerSec.X * deltaT),
                        pos.Y + (float)(velocityPixPerSec.Y * deltaT)));
                }

            }
        }