示例#1
0
        public ExtendedView(Settings settings,
            GameState gameState,
			ITobiiTracker tobiiTracker,
            Aiming aiming,
            DebugOutput debugOutput
            )
        {
            _settings = settings;
            _gameState = gameState;
            _aiming = aiming;
            _debugOutput = debugOutput;
            _tobiiTracker = tobiiTracker;

            _aimTransitionState = 1;

            _extendedViewCamera = World.CreateCamera(new Vector3(), Vector3.Zero, 60f);
            _forwardCamera = World.CreateCamera(new Vector3(), Vector3.Zero, 60f);
        }
示例#2
0
        private void importLODToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ME3Package pcc = null;

            try
            {
                int n = listBox1.SelectedIndex;
                if (n == -1)
                {
                    return;
                }
                int m = listBox2.SelectedIndex;
                if (m == -1)
                {
                    return;
                }
                TreeNode t1 = treeView1.SelectedNode;
                if (t1 == null || t1.Parent == null || t1.Name == "")
                {
                    return;
                }
                SkeletalMesh skm = new SkeletalMesh();
                EntryStruct  en;
                string       loc = Path.GetDirectoryName(Application.ExecutablePath) + "\\exec\\";
                if (DisplayStyle == 0)
                {
                    int o = 0;
                    if (!Int32.TryParse(t1.Name, out o))
                    {
                        return;
                    }
                    en = Entries[o];
                    if (!en.isDLC)
                    {
                        if (en.isSkeletal)
                        {
                            pcc = MEPackageHandler.OpenME3Package(ME3Directory.cookedPath + en.Filename);
                            skm = new SkeletalMesh(pcc, en.Index);
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        string dirDLC = ME3Directory.DLCPath;
                        dirDLC += en.DLCName;
                        dirDLC += "\\CookedPCConsole\\Default.sfar";
                        DLCBase dlc = new DLCBase(dirDLC);
                        foreach (sfarFile file in dlc.fileList)
                        {
                            try
                            {
                                string filename = Path.GetFileName(file.fileName);
                                if (Path.GetExtension(filename).ToLower().EndsWith(".pcc") && filename == en.Filename)
                                {
                                    if (File.Exists(loc + "dlc.pcc"))
                                    {
                                        File.Delete(loc + "dlc.pcc");
                                    }
                                    using (Stream input = File.OpenRead(dirDLC), output = File.Create(loc + "dlc.pcc"))
                                    {
                                        AmaroK86.MassEffect3.DLCUnpack.DecompressEntry(file, input, output, dlc.CompressionScheme);
                                    }
                                    if (File.Exists(loc + "dlc.pcc"))
                                    {
                                        try
                                        {
                                            if (en.isSkeletal)
                                            {
                                                pcc = MEPackageHandler.OpenME3Package(loc + "dlc.pcc");
                                                skm = new SkeletalMesh(pcc, en.Index);
                                                break;
                                            }
                                            else
                                            {
                                                return;
                                            }
                                        }
                                        catch (Exception)
                                        {
                                            return;
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                return;
                            }
                        }
                    }
                }
                else
                {
                    return;
                }
                if (!skm.Loaded || pcc == null)
                {
                    return;
                }
                SkeletalMesh.LODModelStruct          lodpcc = skm.LODModels[0];
                UDKExplorer.UDK.Classes.SkeletalMesh skmudk = new UDKExplorer.UDK.Classes.SkeletalMesh(udk, Objects[n]);
                UDKExplorer.UDK.Classes.SkeletalMesh.LODModelStruct lodudk = skmudk.LODModels[m];
                lodpcc.Sections = new List <SkeletalMesh.SectionStruct>();
                foreach (UDKExplorer.UDK.Classes.SkeletalMesh.SectionStruct secudk in lodudk.Sections)
                {
                    SkeletalMesh.SectionStruct secpcc = new SkeletalMesh.SectionStruct();
                    secpcc.BaseIndex     = secudk.BaseIndex;
                    secpcc.ChunkIndex    = secudk.ChunkIndex;
                    secpcc.MaterialIndex = secudk.MaterialIndex;
                    secpcc.NumTriangles  = secudk.NumTriangles;
                    lodpcc.Sections.Add(secpcc);
                }
                lodpcc.IndexBuffer            = new SkeletalMesh.MultiSizeIndexContainerStruct();
                lodpcc.IndexBuffer.IndexCount = lodudk.IndexBuffer.IndexCount;
                lodpcc.IndexBuffer.IndexSize  = lodudk.IndexBuffer.IndexSize;
                lodpcc.IndexBuffer.Indexes    = new List <ushort>();
                foreach (ushort Idx in lodudk.IndexBuffer.Indexes)
                {
                    lodpcc.IndexBuffer.Indexes.Add(Idx);
                }
                List <int> BoneMap = new List <int>();
                for (int i = 0; i < skmudk.Bones.Count; i++)
                {
                    string udkb  = udk.GetName(skmudk.Bones[i].Name);
                    bool   found = false;
                    for (int j = 0; j < skm.Bones.Count; j++)
                    {
                        string pccb = pcc.getNameEntry(skm.Bones[j].Name);
                        if (pccb == udkb)
                        {
                            found = true;
                            BoneMap.Add(j);
                            if (importBonesToolStripMenuItem.Checked)
                            {
                                SkeletalMesh.BoneStruct bpcc = skm.Bones[j];
                                UDKExplorer.UDK.Classes.SkeletalMesh.BoneStruct budk = skmudk.Bones[i];
                                bpcc.Orientation = budk.Orientation;
                                bpcc.Position    = budk.Position;
                                skm.Bones[j]     = bpcc;
                            }
                        }
                    }
                    if (!found)
                    {
                        DebugOutput.PrintLn("ERROR: Cant Match Bone \"" + udkb + "\"");
                        BoneMap.Add(0);
                    }
                }

                lodpcc.ActiveBones = new List <ushort>();
                foreach (ushort Idx in lodudk.ActiveBones)
                {
                    lodpcc.ActiveBones.Add((ushort)BoneMap[Idx]);
                }
                lodpcc.Chunks = new List <SkeletalMesh.SkelMeshChunkStruct>();
                foreach (UDKExplorer.UDK.Classes.SkeletalMesh.SkelMeshChunkStruct chunkudk in lodudk.Chunks)
                {
                    SkeletalMesh.SkelMeshChunkStruct chunkpcc = new SkeletalMesh.SkelMeshChunkStruct();
                    chunkpcc.BaseVertexIndex   = chunkudk.BaseVertexIndex;
                    chunkpcc.MaxBoneInfluences = chunkudk.MaxBoneInfluences;
                    chunkpcc.NumRigidVertices  = chunkudk.NumRigidVertices;
                    chunkpcc.NumSoftVertices   = chunkudk.NumSoftVertices;
                    chunkpcc.BoneMap           = new List <ushort>();
                    chunkpcc.RiginSkinVertices = new List <SkeletalMesh.RigidSkinVertexStruct>();
                    chunkpcc.SoftSkinVertices  = new List <SkeletalMesh.SoftSkinVertexStruct>();
                    foreach (ushort Idx in chunkudk.BoneMap)
                    {
                        chunkpcc.BoneMap.Add((ushort)BoneMap[Idx]);
                    }
                    lodpcc.Chunks.Add(chunkpcc);
                }
                lodpcc.Size          = lodudk.Size;
                lodpcc.NumVertices   = lodudk.NumVertices;
                lodpcc.RequiredBones = new List <byte>();
                foreach (byte b in lodudk.RequiredBones)
                {
                    lodpcc.RequiredBones.Add(b);
                }
                lodpcc.VertexBufferGPUSkin = new SkeletalMesh.VertexBufferGPUSkinStruct();
                lodpcc.VertexBufferGPUSkin.NumTexCoords = lodudk.VertexBufferGPUSkin.NumTexCoords;
                lodpcc.VertexBufferGPUSkin.Extension    = lodudk.VertexBufferGPUSkin.Extension;
                lodpcc.VertexBufferGPUSkin.Origin       = lodudk.VertexBufferGPUSkin.Origin;
                lodpcc.VertexBufferGPUSkin.VertexSize   = lodudk.VertexBufferGPUSkin.VertexSize;
                lodpcc.VertexBufferGPUSkin.Vertices     = new List <SkeletalMesh.GPUSkinVertexStruct>();
                foreach (UDKExplorer.UDK.Classes.SkeletalMesh.GPUSkinVertexStruct vudk in lodudk.VertexBufferGPUSkin.Vertices)
                {
                    SkeletalMesh.GPUSkinVertexStruct vpcc = new SkeletalMesh.GPUSkinVertexStruct();
                    vpcc.TangentX         = vudk.TangentX;
                    vpcc.TangentZ         = vudk.TangentZ;
                    vpcc.Position         = vudk.Position;
                    vpcc.InfluenceBones   = vudk.InfluenceBones;
                    vpcc.InfluenceWeights = vudk.InfluenceWeights;
                    vpcc.U = vudk.U;
                    vpcc.V = vudk.V;
                    lodpcc.VertexBufferGPUSkin.Vertices.Add(vpcc);
                }
                for (int i = 0; i < skm.LODModels.Count; i++)
                {
                    skm.LODModels[i] = lodpcc;
                }
                SerializingContainer con = new SerializingContainer();
                con.Memory    = new MemoryStream();
                con.isLoading = false;
                skm.Serialize(con);
                int          end = skm.GetPropertyEnd();
                MemoryStream mem = new MemoryStream();
                mem.Write(pcc.Exports[en.Index].Data, 0, end);
                mem.Write(con.Memory.ToArray(), 0, (int)con.Memory.Length);
                pcc.Exports[en.Index].Data = mem.ToArray();
                pcc.save();
                if (!en.isDLC)
                {
                    MessageBox.Show("Done");
                }
                else
                {
                    MessageBox.Show("Done. The file is now in following folder, please replace it back to DLC :\n" + loc + "dlc.pcc");
                }
                globalTreeToolStripMenuItem.Visible       =
                    optionsToolStripMenuItem.Visible      =
                        transferToolStripMenuItem.Visible =
                            splitContainer1.Visible       = true;
                fileToolStripMenuItem.Visible             =
                    importLODToolStripMenuItem.Visible    =
                        splitContainer3.Visible           = false;
            }
            finally
            {
                pcc?.Dispose();
            }
        }
示例#3
0
        public TreeNode ToTree(int nr)
        {
            TreeNode t = new TreeNode("#" + nr + " Level");

            DebugOutput.PrintLn("Generating Tree...");
            for (int i = 0; i < Objects.Count(); i++)
            {
                int index = Objects[i];
                if (index > 0)
                {
                    IExportEntry e = pcc.Exports[index];
                    DebugOutput.PrintLn((i + 1) + " / " + Objects.Count + " : \"" + e.ObjectName + "\" - \"" + e.ClassName + "\"");
                    switch (e.ClassName)
                    {
                    case "WwiseEnvironmentVolume":
                        foreach (WwiseEnvironmentVolume wev in WEV)
                        {
                            if (wev.MyIndex == index)
                            {
                                t.Nodes.Add(wev.ToTree());
                            }
                        }
                        break;

                    case "WwiseAudioVolume":
                        foreach (WwiseAudioVolume wav in WAV)
                        {
                            if (wav.MyIndex == index)
                            {
                                t.Nodes.Add(wav.ToTree());
                            }
                        }
                        break;

                    case "WwiseAmbientSound":
                        foreach (WwiseAmbientSound was in WAS)
                        {
                            if (was.MyIndex == index)
                            {
                                t.Nodes.Add(was.ToTree());
                            }
                        }
                        break;

                    case "BioPathPoint":
                        foreach (BioPathPoint bpp in BPP)
                        {
                            if (bpp.MyIndex == index)
                            {
                                t.Nodes.Add(bpp.ToTree());
                            }
                        }
                        break;

                    case "BioTriggerVolume":
                        foreach (BioTriggerVolume btv in BTV)
                        {
                            if (btv.MyIndex == index)
                            {
                                t.Nodes.Add(btv.ToTree());
                            }
                        }
                        break;

                    case "BioPlaypenVolumeAdditive":
                        foreach (BioPlaypenVolumeAdditive bpva in BPVA)
                        {
                            if (bpva.MyIndex == index)
                            {
                                t.Nodes.Add(bpva.ToTree());
                            }
                        }
                        break;

                    case "BlockingVolume":
                        foreach (BlockingVolume bv in BV)
                        {
                            if (bv.MyIndex == index)
                            {
                                t.Nodes.Add(bv.ToTree());
                            }
                        }
                        break;

                    case "MantleMarker":
                        foreach (MantleMarker mm in MM)
                        {
                            if (mm.MyIndex == index)
                            {
                                t.Nodes.Add(mm.ToTree());
                            }
                        }
                        break;

                    case "PathNode":
                        foreach (PathNode pn in PN)
                        {
                            if (pn.MyIndex == index)
                            {
                                t.Nodes.Add(pn.ToTree());
                            }
                        }
                        break;

                    case "SplineActor":
                        foreach (SplineActor sp in SPA)
                        {
                            if (sp.MyIndex == index)
                            {
                                t.Nodes.Add(sp.ToTree());
                            }
                        }
                        break;

                    case "TargetPoint":
                        foreach (TargetPoint tp in TP)
                        {
                            if (tp.MyIndex == index)
                            {
                                t.Nodes.Add(tp.ToTree());
                            }
                        }
                        break;

                    case "LightVolume":
                        foreach (LightVolume lv in LV)
                        {
                            if (lv.MyIndex == index)
                            {
                                t.Nodes.Add(lv.ToTree());
                            }
                        }
                        break;

                    case "StaticMeshActor":
                        foreach (StaticMeshActor stma in STM_A)
                        {
                            if (stma.MyIndex == index)
                            {
                                t.Nodes.Add(stma.ToTree());
                            }
                        }
                        break;

                    case "DecalActor":
                        foreach (DecalActor da in DA)
                        {
                            if (da.MyIndex == index)
                            {
                                t.Nodes.Add(da.ToTree());
                            }
                        }
                        break;

                    case "InterpActor":
                        foreach (InterpActor ia in IA)
                        {
                            if (ia.MyIndex == index)
                            {
                                t.Nodes.Add(ia.ToTree());
                            }
                        }
                        break;

                    case "StaticMeshCollectionActor":
                        foreach (StaticMeshCollectionActor stmca in STM_CA)
                        {
                            if (stmca.MyIndex == index)
                            {
                                t.Nodes.Add(stmca.ToTree());
                            }
                        }
                        break;

                    case "CoverLink":
                        foreach (CoverLink cl in CL)
                        {
                            if (cl.MyIndex == index)
                            {
                                t.Nodes.Add(cl.ToTree());
                            }
                        }
                        break;

                    case "CoverSlotMarker":
                        foreach (CoverSlotMarker csm in CSM)
                        {
                            if (csm.MyIndex == index)
                            {
                                t.Nodes.Add(csm.ToTree());
                            }
                        }
                        break;

                    case "Emitter":
                        foreach (Emitter em in EM)
                        {
                            if (em.MyIndex == index)
                            {
                                t.Nodes.Add(em.ToTree());
                            }
                        }
                        break;

                    default:
                        string s = "#" + index + " : \"";
                        s += e.ObjectName + "\" CLASS : \"";
                        s += e.ClassName + "\"";
                        TreeNode t1 = new TreeNode(s);
                        t.Nodes.Add(t1);
                        break;
                    }
                }
                else
                {
                    TreeNode t1 = new TreeNode("#" + index + " : NOT IMPLEMENTED");
                    t.Nodes.Add(t1);
                }
            }
            return(t);
        }
示例#4
0
        private void importLODToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int n = listBox1.SelectedIndex;

            if (n == -1)
            {
                return;
            }
            int m = listBox2.SelectedIndex;

            if (m == -1)
            {
                return;
            }
            SkeletalMesh skm = new SkeletalMesh(pcc, SelectedObject);

            SkeletalMesh.LODModelStruct          lodpcc = skm.LODModels[SelectedLOD];
            UDKExplorer.UDK.Classes.SkeletalMesh skmudk = new UDKExplorer.UDK.Classes.SkeletalMesh(udk, Objects[n]);
            if (skm.Bones.Count != skmudk.Bones.Count)
            {
                MessageBox.Show("Your imported mesh has a different count of Bones! This would crash your game, stopping now.");
                return;
            }
            UDKExplorer.UDK.Classes.SkeletalMesh.LODModelStruct lodudk = skmudk.LODModels[m];
            lodpcc.Sections = new List <SkeletalMesh.SectionStruct>();
            foreach (UDKExplorer.UDK.Classes.SkeletalMesh.SectionStruct secudk in lodudk.Sections)
            {
                SkeletalMesh.SectionStruct secpcc = new SkeletalMesh.SectionStruct();
                secpcc.BaseIndex     = secudk.BaseIndex;
                secpcc.ChunkIndex    = secudk.ChunkIndex;
                secpcc.MaterialIndex = secudk.MaterialIndex;
                secpcc.NumTriangles  = secudk.NumTriangles;
                lodpcc.Sections.Add(secpcc);
            }
            lodpcc.IndexBuffer            = new SkeletalMesh.MultiSizeIndexContainerStruct();
            lodpcc.IndexBuffer.IndexCount = lodudk.IndexBuffer.IndexCount;
            lodpcc.IndexBuffer.IndexSize  = lodudk.IndexBuffer.IndexSize;
            lodpcc.IndexBuffer.Indexes    = new List <ushort>();
            foreach (ushort Idx in lodudk.IndexBuffer.Indexes)
            {
                lodpcc.IndexBuffer.Indexes.Add(Idx);
            }
            List <int> BoneMap = new List <int>();

            for (int i = 0; i < skmudk.Bones.Count; i++)
            {
                string udkb  = udk.GetName(skmudk.Bones[i].Name);
                bool   found = false;
                for (int j = 0; j < skm.Bones.Count; j++)
                {
                    string pccb = pcc.getNameEntry(skm.Bones[j].Name);
                    if (pccb == udkb)
                    {
                        found = true;
                        BoneMap.Add(j);
                        if (MPOpt.SKM_importbones)
                        {
                            SkeletalMesh.BoneStruct bpcc = skm.Bones[j];
                            UDKExplorer.UDK.Classes.SkeletalMesh.BoneStruct budk = skmudk.Bones[i];
                            bpcc.Orientation = budk.Orientation;
                            bpcc.Position    = budk.Position;
                            skm.Bones[j]     = bpcc;
                        }
                    }
                }
                if (!found)
                {
                    DebugOutput.PrintLn("ERROR: Cant Match Bone \"" + udkb + "\"");
                    BoneMap.Add(0);
                }
            }

            lodpcc.ActiveBones = new List <ushort>();
            foreach (ushort Idx in lodudk.ActiveBones)
            {
                lodpcc.ActiveBones.Add((ushort)BoneMap[Idx]);
            }
            lodpcc.Chunks = new List <SkeletalMesh.SkelMeshChunkStruct>();
            foreach (UDKExplorer.UDK.Classes.SkeletalMesh.SkelMeshChunkStruct chunkudk in lodudk.Chunks)
            {
                SkeletalMesh.SkelMeshChunkStruct chunkpcc = new SkeletalMesh.SkelMeshChunkStruct();
                chunkpcc.BaseVertexIndex   = chunkudk.BaseVertexIndex;
                chunkpcc.MaxBoneInfluences = chunkudk.MaxBoneInfluences;
                chunkpcc.NumRigidVertices  = chunkudk.NumRigidVertices;
                chunkpcc.NumSoftVertices   = chunkudk.NumSoftVertices;
                chunkpcc.BoneMap           = new List <ushort>();
                chunkpcc.RiginSkinVertices = new List <SkeletalMesh.RigidSkinVertexStruct>();
                chunkpcc.SoftSkinVertices  = new List <SkeletalMesh.SoftSkinVertexStruct>();
                foreach (ushort Idx in chunkudk.BoneMap)
                {
                    chunkpcc.BoneMap.Add((ushort)BoneMap[Idx]);
                }
                lodpcc.Chunks.Add(chunkpcc);
            }
            lodpcc.Size          = lodudk.Size;
            lodpcc.NumVertices   = lodudk.NumVertices;
            lodpcc.RequiredBones = new List <byte>();
            foreach (byte b in lodudk.RequiredBones)
            {
                lodpcc.RequiredBones.Add(b);
            }
            lodpcc.VertexBufferGPUSkin = new SkeletalMesh.VertexBufferGPUSkinStruct();
            lodpcc.VertexBufferGPUSkin.NumTexCoords = lodudk.VertexBufferGPUSkin.NumTexCoords;
            lodpcc.VertexBufferGPUSkin.Extension    = lodudk.VertexBufferGPUSkin.Extension;
            lodpcc.VertexBufferGPUSkin.Origin       = lodudk.VertexBufferGPUSkin.Origin;
            lodpcc.VertexBufferGPUSkin.VertexSize   = lodudk.VertexBufferGPUSkin.VertexSize;
            lodpcc.VertexBufferGPUSkin.Vertices     = new List <SkeletalMesh.GPUSkinVertexStruct>();
            foreach (UDKExplorer.UDK.Classes.SkeletalMesh.GPUSkinVertexStruct vudk in lodudk.VertexBufferGPUSkin.Vertices)
            {
                SkeletalMesh.GPUSkinVertexStruct vpcc = new SkeletalMesh.GPUSkinVertexStruct();
                vpcc.TangentX         = vudk.TangentX;
                vpcc.TangentZ         = vudk.TangentZ;
                vpcc.Position         = vudk.Position;
                vpcc.InfluenceBones   = vudk.InfluenceBones;
                vpcc.InfluenceWeights = vudk.InfluenceWeights;
                vpcc.U = vudk.U;
                vpcc.V = vudk.V;
                lodpcc.VertexBufferGPUSkin.Vertices.Add(vpcc);
            }
            skm.LODModels[SelectedLOD] = lodpcc;
            SerializingContainer con = new SerializingContainer();

            con.Memory    = new MemoryStream();
            con.isLoading = false;
            skm.Serialize(con);
            int          end = skm.GetPropertyEnd();
            MemoryStream mem = new MemoryStream();

            mem.Write(pcc.Exports[SelectedObject].Data, 0, end);
            mem.Write(con.Memory.ToArray(), 0, (int)con.Memory.Length);
            pcc.Exports[SelectedObject].Data = mem.ToArray();
            MessageBox.Show("Done");
            Close();
        }
示例#5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DebuggerTextWriter" /> class.
 /// </summary>
 /// <param name="dbgEngDll">The DbgEngDll debugger engine.</param>
 /// <param name="outputType">Type of the output.</param>
 public DebuggerTextWriter(DbgEngDll dbgEngDll, DebugOutput outputType)
 {
     OutputType          = outputType;
     outputCallbacksWide = dbgEngDll.Client.GetOutputCallbacksWide();
     outputCallbacks     = dbgEngDll.Client.GetOutputCallbacks();
 }
        private string relinkObjectProperty(IMEPackage importingPCC, IMEPackage destinationPCC, ObjectProperty objProperty, List <KeyValuePair <int, int> > crossPCCObjectMappingList)
        {
            if (objProperty.Value == 0)
            {
                return(null); //do not relink 0
            }
            if (importingPCC == destinationPCC && objProperty.Value < 0)
            {
                return(null); //do not relink same-pcc imports.
            }
            int sourceObjReference = objProperty.Value;

            if (sourceObjReference > 0)
            {
                sourceObjReference--; //make 0 based for mapping.
            }
            if (sourceObjReference < 0)
            {
                sourceObjReference++; //make 0 based for mapping.
            }
            //if (objProperty.Name != null)
            //{
            //    Debug.WriteLine(objProperty.Name);
            //}
            KeyValuePair <int, int> mapping = crossPCCObjectMappingList.Where(pair => pair.Key == sourceObjReference).FirstOrDefault();
            var defaultKVP = default(KeyValuePair <int, int>); //struct comparison

            if (!mapping.Equals(defaultKVP))
            {
                //relink
                int newval = 0;
                if (mapping.Value > 0)
                {
                    newval = mapping.Value + 1; //reincrement
                }
                else if (mapping.Value < 0)
                {
                    newval = mapping.Value - 1; //redecrement
                }
                objProperty.Value = (newval);
                IEntry entry = destinationPCC.getEntry(newval);
                string s     = "";
                if (entry != null)
                {
                    s = entry.GetFullPath;
                }
                Debug.WriteLine("Relink hit: " + sourceObjReference + objProperty.Name + ": " + s);
            }
            else if (objProperty.Value < 0) //It's an unmapped import
            {
                //objProperty is currently pointing to importingPCC as that is where we read the properties from
                int n               = objProperty.Value;
                int origvalue       = n;
                int importZeroIndex = Math.Abs(n) - 1;
                //Debug.WriteLine("Relink miss, attempting JIT relink on " + n + " " + rootNode.Text);
                if (n < 0 && importZeroIndex < importingPCC.ImportCount)
                {
                    //Get the original import
                    ImportEntry origImport         = importingPCC.getImport(importZeroIndex);
                    string      origImportFullName = origImport.GetFullPath;
                    //Debug.WriteLine("We should import " + origImport.GetFullPath);

                    ImportEntry crossImport          = null;
                    string      linkFailedDueToError = null;
                    try
                    {
                        crossImport = getOrAddCrossImport(origImportFullName, importingPCC, destinationPCC);
                    }
                    catch (Exception e)
                    {
                        //Error during relink
                        KFreonLib.Debugging.DebugOutput.StartDebugger("PCC Relinker");
                        DebugOutput.PrintLn("Exception occured during relink: ");
                        DebugOutput.PrintLn(ExceptionHandlerDialogWPF.FlattenException(e));
                        DebugOutput.PrintLn("You may want to consider discarding this sessions' changes as relinking was not able to properly finish.");
                        linkFailedDueToError = e.Message;
                    }
                    if (crossImport != null)
                    {
                        //cache item. Imports are stored +1, Exports-1. Someday I will go back and make this just 0 indexed
                        crossPCCObjectMappingList.Add(new KeyValuePair <int, int>(sourceObjReference, crossImport.UIndex + 1)); //add to mapping to speed up future relinks
                        objProperty.Value = crossImport.UIndex;
                        Debug.WriteLine("Relink hit: Dynamic CrossImport for " + origvalue + " " + importingPCC.getEntry(origvalue).GetFullPath + " -> " + objProperty.Value);
                    }
                    else
                    {
                        if (linkFailedDueToError != null)
                        {
                            Debug.WriteLine("Relink failed: CrossImport porting failed for " + objProperty.Name + " " + objProperty.Value + ": " + importingPCC.getEntry(origvalue).GetFullPath);
                            return("Relink failed for " + objProperty.Name + " " + objProperty.Value + ": " + linkFailedDueToError);
                        }
                        else
                        if (destinationPCC.getEntry(objProperty.Value) != null)
                        {
                            Debug.WriteLine("Relink failed: CrossImport porting failed for " + objProperty.Name + " " + objProperty.Value + ": " + importingPCC.getEntry(origvalue).GetFullPath);
                            return("Relink failed: CrossImport porting failed for " + objProperty.Name + " " + objProperty.Value + " " + destinationPCC.getEntry(objProperty.Value).GetFullPath);
                        }
                        else
                        {
                            return("Relink failed: New export does not exist - this is probably a bug in cross import code for " + objProperty.Name + " " + objProperty.Value);
                        }
                    }
                }
            }
            else
            {
                string path = importingPCC.getEntry(objProperty.Value) != null?importingPCC.getEntry(objProperty.Value).GetFullPath : "Entry not found: " + objProperty.Value;

                Debug.WriteLine("Relink failed: " + objProperty.Name + " " + objProperty.Value + " " + path);
                return("Relink failed: " + objProperty.Name + " " + objProperty.Value + " " + path);
            }
            return(null);
        }
示例#7
0
 /// <summary>Write the debug text to the output.</summary>
 /// <param name="exception">The exception.</param>
 /// <param name="output">The output method to use.</param>
 public static void WriteDebug(Exception exception, DebugOutput output = DebugOutput.TraceListener)
 {
     WriteLog(Generate(exception), false, output);
 }
示例#8
0
        /// <summary>Write the debug bool to the output.</summary>
        /// <param name="value">The value.</param>
        /// <param name="formatted">The toggle.</param>
        /// <param name="output">The output method to use.</param>
        public static void WriteDebug(bool value, bool formatted = true, DebugOutput output = DebugOutput.TraceListener)
        {
            string generateObjectFormatting = Generate(value);

            WriteLog(generateObjectFormatting, formatted, output);
        }
示例#9
0
            private int GuessGame(List <string> pccs)
            {
                int[] NumFounds = { 0, 0, 0 };

                DebugOutput.PrintLn("Starting to guess game...");

                IEnumerable <string>[] GameFiles = new IEnumerable <string> [3];

                GameFiles[0] = ME1Directory.Files;
                if (GameFiles[0] == null)
                {
                    DebugOutput.PrintLn("Could not find ME1 files!");
                }
                else
                {
                    DebugOutput.PrintLn("Got ME1 files...");
                }

                GameFiles[1] = ME2Directory.Files;
                if (GameFiles[1] == null)
                {
                    DebugOutput.PrintLn("Could not find ME2 files!");
                }
                else
                {
                    DebugOutput.PrintLn("Got ME2 files...");
                }

                GameFiles[2] = ME3Directory.Files;
                if (GameFiles[2] == null)
                {
                    DebugOutput.PrintLn("Could not find ME3 files!");
                }
                else
                {
                    DebugOutput.PrintLn("Got ME3 files...");
                }
                //DebugOutput.PrintLn("List of gamefiles acquired with counts " + ME1Directory.Files.Count + "  " + ME2Directory.Files.Count + "  " + ME3Directory.Files.Count + ". Beginning search...");

                try
                {
                    int test = 0;
                    foreach (IEnumerable <string> gamefiles in GameFiles)
                    {
                        if (gamefiles == null)
                        {
                            DebugOutput.PrintLn("Gamefiles was null in GuessGame for ME" + test++ + 1);
                            continue;
                        }
                        int found = 0;
                        Parallel.ForEach(pccs, pcc =>
                        {
                            if (pcc == null)
                            {
                                DebugOutput.PrintLn("PCC was null in GuessGame related to ME" + test + 1);
                                return;
                            }
                            //DebugOutput.PrintLn("Searching for game in pcc: " + pcc);
                            string temp = pcc.Replace("\\\\", "\\");
                            if (gamefiles.FirstOrDefault(t => t.Contains(temp)) != null)
                            {
                                found++;
                            }
                        });

                        NumFounds[test++] = found;
                    }
                }
                catch (Exception e)
                {
                    DebugOutput.PrintLn("Error guessing game: " + e.ToString());
                }


                DebugOutput.PrintLn("Finished guessing game.");
                if (NumFounds.Sum() == 0)
                {
                    return(-1);
                }
                else
                {
                    int maxVal  = NumFounds.Max();
                    var indices = Enumerable.Range(0, NumFounds.Count())
                                  .Where(i => NumFounds[i] == maxVal)
                                  .ToList();

                    if (indices.Count > 1)
                    {
                        DebugOutput.PrintLn("Could not guess game, files were present in more than one!");
                        return(-2);
                    }
                    else
                    {
                        return(indices[0] + 1);
                    }
                }
            }
示例#10
0
            /// <summary>
            /// Gets details, like pcc's and expID's, from current script and sets local properties.
            /// Properties:
            ///     ExpID's, PCC's, Texname, WhichGame, JobType.
            /// </summary>
            public bool GetJobDetails(bool update, out bool versionConflict, int version)
            {
                JobType         = DetectJobType();
                versionConflict = false;

                DebugOutput.PrintLn(String.Format("Job: {0}  type: {1}", Name, JobType));

                bool isTexture = JobType == "TEXTURE" ? true : false;

                ExpIDs = ModMaker.GetExpIDsFromScript(Script, isTexture);

                //Heff: adjust script paths for legacy ME3 DLC mods that references un-extracted DLC's
                FixLegacyDLCPaths();

                PCCs      = ModMaker.GetPCCsFromScript(Script, isTexture);
                Texname   = ModMaker.GetObjectNameFromScript(Script, isTexture);
                WhichGame = version == -1 ? ModMaker.GetGameVersionFromScript(Script, isTexture) : version;

                DebugOutput.PrintLn(String.Format("Job: {0} Detected game version: {1}  Detected texname: {2}", Name, WhichGame, Texname));

                // KFreon: Extra stuff to guess various things - NEW rev696 - from the WPF builds. Maybe unstable.
                #region Extra stuff from WPF
                // KFreon: Guess game version if required
                if (WhichGame == -1 && update)
                {
                    DebugOutput.PrintLn("Attempting to guess game version...");

                    /*int index = PCCs[0].IndexOf("Mass Effect");
                     * char c = PCCs[0][index + 1];*/

                    DebugOutput.PrintLn("Found num PCCS: " + PCCs.Count);
                    WhichGame = GuessGame(PCCs);

                    if (WhichGame == -2)
                    {
                        versionConflict = true;
                        return(false);
                    }
                }

                if (WhichGame == -1)
                {
                    DebugOutput.PrintLn("ERROR: No game found matching the mod files!\n" +
                                        "Make sure that you have the proper game installed, and that the toolset has the correct path!\n" +
                                        "If the mod targets DLC files, make sure that you have extracted all relevant DLC's.");

                    MessageBox.Show("No game found matching the mod files!\n" +
                                    "Make sure that you have the proper game installed, and that the toolset has the correct path!\n" +
                                    "If the mod targets DLC files, make sure that you have extracted all relevant DLC's.", "Error!");
                    return(false);
                }
                else
                {
                    DebugOutput.PrintLn("Guessed gameversion: " + WhichGame);
                }

                // KFreon: Get ExpID's if required
                if (ExpIDs.Count == 0 && update)
                {
                    DebugOutput.PrintLn("Unable to find ExpID's in script. Attempting to find them manually. Game: " + WhichGame);

                    string        biogame   = MEDirectories.MEDirectories.GetDefaultBIOGame(WhichGame);
                    List <string> gameFiles = MEDirectories.MEDirectories.EnumerateGameFiles(WhichGame, biogame);
                    foreach (string pcc in PCCs)
                    {
                        //DebugOutput.PrintLn("Searching: " + pcc);
                        int index = -1;
                        if ((index = gameFiles.FindIndex(t => t.ToLower().Contains(pcc.ToLower()))) >= 0)
                        {
                            IPCCObject pccObject = PCCObjects.Creation.CreatePCCObject(gameFiles[index], WhichGame);
                            int        count     = 0;
                            foreach (IExportEntry export in pccObject.Exports)
                            {
                                //DebugOutput.PrintLn("Searching export: " + export.ObjectName);
                                if (export.ObjectName.Contains(Texname))
                                {
                                    ExpIDs.Add(count);
                                }
                                count++;
                            }
                        }
                    }
                    DebugOutput.PrintLn("Finished searching. Found: " + ExpIDs.Count + " matches.");
                }
                #endregion Extra Stuff from WPF

                OrigExpIDs     = new List <int>(ExpIDs);
                OrigPCCs       = new List <string>(PCCs);
                OriginalScript = Script;

                return(true);
            }
示例#11
0
 public SFAREditor2()
 {
     InitializeComponent();
     DebugOutput.StartDebugger("SFAR Editor 2");
 }
示例#12
0
        /// <summary>
        /// Extracts image from TPF or copies image data from external file. Also able to return a byte[] of image data.
        /// </summary>
        /// <param name="ExtractPath">Path to extract image to.</param>
        /// <param name="ToMemory">OPTIONAL: If true, byte[] of image data returned.</param>
        /// <returns>If ToMemory is true, returns byte[] of image data, otherwise null.</returns>
        public byte[] Extract(string ExtractPath, bool ToMemory = false)
        {
            byte[] retval = null;

            bool?temp = ExtractPath.isDirectory();

            if (temp == null)
            {
                return(null);
            }

            string extractName = ExtractPath;

            if (temp == true) // If given path is a directory
            {
                string hashString = KFreonLib.Textures.Methods.FormatTexmodHashAsString(Hash);
                if (String.IsNullOrEmpty(TexName))
                {
                    extractName = Path.GetFileNameWithoutExtension(FileName);
                }
                else
                {
                    extractName = TexName;
                }

                if (!isDef && !extractName.Contains(hashString))
                {
                    extractName += "_" + hashString;
                }

                extractName += Path.GetExtension(FileName);
            }


            // KFreon: Get byte[] of image data.
            if (ToMemory)
            {
                if (isExternal)
                {
                    retval = Textures.Methods.GetExternalData(Path.Combine(FilePath, FileName));
                }
                else
                {
                    retval = zippy.Entries[TPFInd].Extract(true);
                }
            }
            else    // KFreon: Extract image to disk
            {
                try
                {
                    if (isExternal)
                    {
                        File.Copy(Path.Combine(FilePath, FileName), Path.Combine(ExtractPath, extractName));
                    }
                    else
                    {
                        zippy.Entries[TPFInd].Extract(false, Path.Combine(ExtractPath, extractName));
                    }
                }
                catch (Exception e)
                {
                    DebugOutput.PrintLn("File already exists.   " + e.ToString());
                }
            }
            return(retval);
        }
示例#13
0
        public void CreateDataBase()
        {
            if (string.IsNullOrEmpty(ME3Directory.cookedPath))
            {
                MessageBox.Show("This functionality requires ME3 to be installed. Set its path at:\n Options > Set Custom Path > Mass Effect 3");
                return;
            }
            FileStream fs       = new FileStream(DatabaseFile, FileMode.Create, FileAccess.Write);
            string     pathcook = ME3Directory.cookedPath;

            DebugOutput.Clear();
            DebugOutput.PrintLn("Levelbase.cs: Loading files from :" + pathcook);
            string[] files = Directory.GetFiles(pathcook, "*.pcc");
            for (int i = 0; i < files.Length; i++)
            {
                string file = files[i];
                DebugOutput.PrintLn(i + "/" + (files.Length - 1) + " Scanning : " + Path.GetFileName(file));
                try
                {
                    using (ME3Package pcc = MEPackageHandler.OpenME3Package(file))
                    {
                        for (int j = 0; j < pcc.Exports.Count(); j++)
                        {
                            IExportEntry e = pcc.Exports[j];
                            if (e.ClassName == "Level")
                            {
                                Level   l     = new Level(pcc, j, true);
                                DBEntry entry = new DBEntry();
                                entry.filepath = file;
                                entry.index    = j;
                                entry.count    = l.Objects.Count();
                                database.Add(entry);
                                //foreach(int idx in l.Objects)
                                //    if (pcc.isExport(idx) && pcc.Exports[idx].ClassName == "BioPlaypenVolumeAdditive")
                                //        DebugOutput.PrintLn("#############################found");
                                DebugOutput.PrintLn("\tfound Level with " + entry.count + " Objects");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error:\n" + ex.Message);
                    DebugOutput.PrintLn("Could not open " + Path.GetFileName(file));
                }
            }
            database.Sort((a, b) => a.filepath.CompareTo(b.filepath));

            byte[] buff = BitConverter.GetBytes(database.Count());
            fs.Write(buff, 0, 4);
            foreach (DBEntry e in database)
            {
                buff = BitConverter.GetBytes(e.index);
                fs.Write(buff, 0, 4);
                buff = BitConverter.GetBytes(e.count);
                fs.Write(buff, 0, 4);
                buff = BitConverter.GetBytes(e.filepath.Length);
                fs.Write(buff, 0, 4);
                foreach (char c in e.filepath)
                {
                    fs.WriteByte((byte)c);
                }
            }
            fs.Close();
        }
示例#14
0
 public void Render(Device d)
 {
     try
     {
         foreach (StaticMeshCollectionActor stmca in STM_CA)
         {
             stmca.Render(d);
         }
         foreach (StaticMeshActor stma in STM_A)
         {
             stma.Render(d);
         }
         foreach (InterpActor ia in IA)
         {
             ia.Render(d);
         }
         foreach (BlockingVolume bv in BV)
         {
             bv.Render(d);
         }
         foreach (SplineActor s in SPA)
         {
             s.Render(d);
         }
         foreach (TargetPoint tp in TP)
         {
             tp.Render(d);
         }
         foreach (LightVolume lv in LV)
         {
             lv.Render(d);
         }
         foreach (MantleMarker mm in MM)
         {
             mm.Render(d);
         }
         foreach (PathNode pn in PN)
         {
             pn.Render(d);
         }
         foreach (CoverLink cl in CL)
         {
             cl.Render(d);
         }
         foreach (CoverSlotMarker csm in CSM)
         {
             csm.Render(d);
         }
         foreach (Emitter em in EM)
         {
             em.Render(d);
         }
         foreach (BioPlaypenVolumeAdditive bpva in BPVA)
         {
             bpva.Render(d);
         }
         foreach (BioTriggerVolume btv in BTV)
         {
             btv.Render(d);
         }
         foreach (BioPathPoint bpp in BPP)
         {
             bpp.Render(d);
         }
         foreach (WwiseAmbientSound was in WAS)
         {
             was.Render(d);
         }
         foreach (WwiseAudioVolume wav in WAV)
         {
             wav.Render(d);
         }
         foreach (WwiseEnvironmentVolume wev in WEV)
         {
             wev.Render(d);
         }
     }
     catch (Exception e)
     {
         DebugOutput.PrintLn("Level ERROR: " + e.Message);
     }
 }
        public override void Unpack(string[] keywords)
        {
            if (HasFeature(keywords, DefineFeature._MAX2LAYER))
            {
                perfMode = PerformanceMode.Fastest;
            }
            else if (HasFeature(keywords, DefineFeature._MAX3LAYER))
            {
                perfMode = PerformanceMode.Balanced;
            }
            else
            {
                perfMode = PerformanceMode.BestQuality;
            }

            emissiveArray = HasFeature(keywords, DefineFeature._USEEMISSIVEMETAL);
            samplerMode   = SamplerMode.Default;
            if (HasFeature(keywords, DefineFeature._USELODMIP))
            {
                samplerMode = SamplerMode.LODSampler;
            }
            else if (HasFeature(keywords, DefineFeature._USEGRADMIP))
            {
                samplerMode = SamplerMode.GradientSampler;
            }

            uvMode = HasFeature(keywords, DefineFeature._WORLDUV) ? UVMode.WorldSpace : UVMode.UV;



            if (HasFeature(keywords, DefineFeature._MAX4TEXTURES))
            {
                maxTextureCount = MaxTextureCount.Four;
            }
            else if (HasFeature(keywords, DefineFeature._MAX8TEXTURES))
            {
                maxTextureCount = MaxTextureCount.Eight;
            }
            else if (HasFeature(keywords, DefineFeature._MAX12TEXTURES))
            {
                maxTextureCount = MaxTextureCount.Twelve;
            }
            else
            {
                maxTextureCount = MaxTextureCount.Sixteen;
            }

            disableHeightBlend = HasFeature(keywords, DefineFeature._DISABLEHEIGHTBLENDING);

            lightingMode = LightingMode.Automatic;
            if (HasFeature(keywords, DefineFeature._BDRF1))
            {
                lightingMode = LightingMode.StandardShader;
            }
            else if (HasFeature(keywords, DefineFeature._BDRF2))
            {
                lightingMode = LightingMode.Simplified;
            }
            else if (HasFeature(keywords, DefineFeature._BDRF3))
            {
                lightingMode = LightingMode.BlinnPhong;
            }

            perTexUVScale        = (HasFeature(keywords, DefineFeature._PERTEXUVSCALEOFFSET));
            perTexInterpContrast = HasFeature(keywords, DefineFeature._PERTEXINTERPCONTRAST);
            perTexBrightness     = HasFeature(keywords, DefineFeature._PERTEXBRIGHTNESS);
            perTexContrast       = HasFeature(keywords, DefineFeature._PERTEXCONTRAST);
            perTexAOStr          = (HasFeature(keywords, DefineFeature._PERTEXAOSTR));
            perTexMetallic       = (HasFeature(keywords, DefineFeature._PERTEXMETALLIC));
            perTexNormStr        = (HasFeature(keywords, DefineFeature._PERTEXNORMSTR));
            perTexSmoothStr      = (HasFeature(keywords, DefineFeature._PERTEXSMOOTHSTR));
            perTexTint           = (HasFeature(keywords, DefineFeature._PERTEXTINT));

            shaderModel = ShaderModel.Automatic;
            if (HasFeature(keywords, DefineFeature._FORCEMODEL46))
            {
                shaderModel = ShaderModel.Force46;
            }
            if (HasFeature(keywords, DefineFeature._FORCEMODEL50))
            {
                shaderModel = ShaderModel.Force50;
            }

            debugOutput = DebugOutput.None;
            if (HasFeature(keywords, DefineFeature._DEBUG_OUTPUT_ALBEDO))
            {
                debugOutput = DebugOutput.Albedo;
            }
            else if (HasFeature(keywords, DefineFeature._DEBUG_OUTPUT_HEIGHT))
            {
                debugOutput = DebugOutput.Height;
            }
            else if (HasFeature(keywords, DefineFeature._DEBUG_OUTPUT_NORMAL))
            {
                debugOutput = DebugOutput.Normal;
            }
            else if (HasFeature(keywords, DefineFeature._DEBUG_OUTPUT_SMOOTHNESS))
            {
                debugOutput = DebugOutput.Smoothness;
            }
            else if (HasFeature(keywords, DefineFeature._DEBUG_OUTPUT_METAL))
            {
                debugOutput = DebugOutput.Metallic;
            }
            else if (HasFeature(keywords, DefineFeature._DEBUG_OUTPUT_AO))
            {
                debugOutput = DebugOutput.AO;
            }
            else if (HasFeature(keywords, DefineFeature._DEBUG_OUTPUT_EMISSION))
            {
                debugOutput = DebugOutput.Emission;
            }
        }
 /// <summary>
 /// Creates new debugger output capturer.
 /// </summary>
 /// <param name="textWriter">The text writer.</param>
 /// <param name="captureFlags">The capture flags.</param>
 public static DebuggerOutputToTextWriter Create(TextWriter textWriter, DebugOutput captureFlags)
 {
     return new DbgEngDebuggerOutputToTextWriter(textWriter, captureFlags);
 }
示例#17
0
 // Writes to Debug (raises event)
 protected void ToDebugWindow(string data)
 {
     Task nowait = Task.Run(() => { DebugOutput?.Invoke(this, data); });
 }
示例#18
0
            /// <summary>
            /// Updates current job script to new format. Returns true if all bits to udpdate are found. NOTE that true does not mean updated script works.
            /// </summary>
            /// <param name="BIOGames">List of BIOGame paths for the games. MUST have only 3 elements. Each can be null if game files not found.</param>
            /// <param name="ExecFolder">Path to the ME3Explorer \exec\ folder.</param>
            /// <returns>True if all bits to update are found in current script.</returns>
            public bool UpdateJob(List <string> BIOGames, string ExecFolder)
            {
                bool retval = true;

                // KFreon: Ensure game target known

                /*if (WhichGame == -1)
                 * {
                 *  // KFreon: See if given pcc's exist on disk, and if so which game to they belong to. All basegame pcc's must be part of the same game.
                 *  int game = PCCObjects.Misc.SearchForPCC(PCCs, BIOGames, ExpIDs, ObjectName, JobType =="TEXTURE");
                 *
                 *  DebugOutput.PrintLn("Got game: " + game);
                 *
                 *  if (game == -1)
                 *  {
                 *      DebugOutput.PrintLn("Unable to find pcc's for job: " + Name);
                 *      retval = false;
                 *      WhichGame = 0;
                 *  }
                 *  else
                 *      WhichGame = game;
                 * }*/

                // KFreon: Return if already failed
                if (!retval)
                {
                    return(retval);
                }


                // KFreon: If texture job, fix pcc pathing.

                //string pathBIOGame = WhichGame == 1 ? Path.GetDirectoryName(BIOGames[WhichGame - 1]) : BIOGames[WhichGame - 1];
                // Heff: Seems like we change the paths in so many places that it's bound to f**k up somewhere. Also VERY unfriendly to DLC mods, so chanigs this.
                string pathBIOGame = BIOGames[WhichGame - 1];

                /*if (WhichGame == 3)
                 *  pathBIOGame = Path.Combine(pathBIOGame, "CookedPCConsole");
                 * else
                 *  pathBIOGame = Path.Combine(pathBIOGame, "CookedPC");*/

                // KFreon: Deal with multiple files found during search
                List <string> multiples;
                List <int>    MultiInds;

                // KFreon: Must be the same number of pcc's and expID's
                if (PCCs.Count != ExpIDs.Count)
                {
                    DebugOutput.PrintLn("Job: " + Name + " has " + PCCs.Count + " PCC's and " + ExpIDs.Count + " ExpID's. Incorrect, so skipping...");
                }
                else
                {
                    string script = "";
                    DebugOutput.PrintLn("Validating pccs");
                    OrigPCCs = ValidateGivenModPCCs(ref PCCs, ExpIDs, WhichGame, pathBIOGame, out multiples, out MultiInds, ref retval, JobType == "TEXTURE");

                    // KFreon: Texture job
                    if (JobType == "TEXTURE")
                    {
                        DebugOutput.PrintLn(Name + " is a texture mod.");

                        // KFreon: Get script for job
                        script = ModMaker.GenerateTextureScript(ExecFolder, OrigPCCs, ExpIDs, Texname, WhichGame, pathBIOGame);
                    }
                    else
                    {
                        // KFreon: HOPEFULLY a mesh mod...
                        DebugOutput.PrintLn(Name + " is a mesh mod. Hopefully...");
                        script = ModMaker.GenerateMeshScript(ExpIDs[0].ToString(), PCCs[0]);

                        // SirCxyrtyx: Might be a pcc compare job, so check for added names
                        List <string> namesToAdd = GetNamesFromScript(Script);
                        if (namesToAdd.Count > 0)
                        {
                            string names = "";
                            foreach (var name in namesToAdd)
                            {
                                names += "names.Add(\"" + name + "\");" + Environment.NewLine;
                            }
                            script = script.Replace("// **KF_NAMES", names);
                        }
                    }
                    Script = script;
                }

                return(retval);
            }
示例#19
0
 /// <summary>Write the debug text to the output.</summary>
 /// <param name="text">The text to write.</param>
 /// <param name="formatted">The toggle.</param>
 /// <param name="output">The output method to use.</param>
 public static void WriteDebug(string text, bool formatted = true, DebugOutput output = DebugOutput.TraceListener)
 {
     WriteLog(text, formatted, output);
 }
示例#20
0
        private static List <string> ValidateGivenModPCCs(ref List <string> PCCs, List <int> ExpIDs, int WhichGame, string pathBIOGame, out List <string> multiples, out List <int> MultiInds, ref bool retval, bool isTexture)
        {
            multiples = new List <string>();
            MultiInds = new List <int>();

            var gameFiles = new List <String>();

            switch (WhichGame)
            {
            case 1:
                gameFiles = ME1Directory.Files;
                break;

            case 2:
                gameFiles = ME2Directory.Files;
                break;

            case 3:
                gameFiles = ME3Directory.Files;
                break;
            }

            // KFreon: Fix pccs
            List <string> pccs = new List <string>();

            for (int i = 0; i < PCCs.Count; i++)
            {
                // KFreon: Test if pcc naming is correct. If not, fix.
                string pcc  = PCCs[i];
                string test = pcc.Replace("\\\\", "\\");

                DebugOutput.PrintLn("About to begin validating");


                try
                {
                    var result = gameFiles.Where(p => p.Contains(test)).DefaultIfEmpty("none").FirstOrDefault();
                    if (result != "none")
                    {
                        test = result; // Heff: this can potentially be a problem for bad .mods that are for DLC's but only specify pcc name.
                    }
                    else
                    {
                        DebugOutput.PrintLn("File not found in game files:" + test + ". Continuing...");
                    }
                }
                catch
                {
                    DebugOutput.PrintLn("File not found in game files:" + test + ". Continuing...");
                }


                if (test.Contains("#"))
                {
                    string[] parts = test.Split('#');
                    multiples.AddRange(parts);
                    for (int m = 0; m < parts.Length; m++)
                    {
                        MultiInds.Add(pccs.Count);
                    }
                }
                else if (test != "")
                {
                    string temp = test;
                    if (test.Contains(pathBIOGame))
                    {
                        temp = test.Remove(0, pathBIOGame.Length + 1);
                    }
                    if (!temp.Contains("\\\\"))
                    {
                        temp = temp.Replace("\\", "\\\\");
                    }
                    pccs.Add(temp);
                }
                else
                {
                    DebugOutput.PrintLn("Unable to find path for: " + pcc + ". This WILL cause errors later.");
                    pccs.Add(pcc);
                    retval = false;
                }
            }

            // KFreon: Deal with multiples
            if (multiples.Count > 0)
            {
                int found = 0;
                for (int i = 0; i < multiples.Count; i++)
                {
                    // TODO KFREON Need both multiples here
                    string pcc1 = multiples[i];
                    for (int j = i + 1; j < multiples.Count; j++)
                    {
                        string pcc2 = multiples[j];
                        if (pcc1 == pcc2)
                        {
                            found++;

                            if (!pcc1.Contains("\\\\"))
                            {
                                pcc1 = pcc1.Replace("\\", "\\\\");
                            }

                            pccs.Insert(MultiInds[i], pcc1);
                        }
                    }
                }

                // KFreon: Multiples still unresolved
                if (found != 0)
                {
                    // TODO KFreon add check to look at the given name fisrst. Might have something in it to clarify.
                    // TODO:  KFreon add selection ability
                    DebugOutput.PrintLn("MULTIPLES STILL UNRESOLVED!!!");
                }
            }
            PCCs = new List <string>(pccs);
            return(new List <string>(pccs));
        }
示例#21
0
        private void startScanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(ME3Directory.cookedPath))
            {
                MessageBox.Show("This functionality requires ME3 to be installed. Set its path at:\n Options > Set Custom Path > Mass Effect 3");
                return;
            }
            string path = ME3Directory.cookedPath;

            string[] files = Directory.GetFiles(path, "*.pcc");
            pb1.Maximum = files.Length;
            DebugOutput.Clear();
            Classes = new List <ClassDef>();
            for (int i = 0; i < files.Length; i++)
            {
                string file = files[i];
                DebugOutput.PrintLn(i.ToString("d4")
                                    + "\\"
                                    + (files.Length - 1)
                                    + " : Loading file \""
                                    + file
                                    + "\"");
                PCCObject pcc = new PCCObject(file);
                pb2.Maximum = pcc.Exports.Count();
                {
                    pb1.Value = i;
                    RefreshLists();
                    Application.DoEvents();
                }
                for (int j = 0; j < pcc.Exports.Count(); j++)
                {
                    if (j % 100 == 0)//refresh
                    {
                        pb1.Value = i;
                        pb2.Value = j;
                        Application.DoEvents();
                    }
                    int f = -1;
                    for (int k = 0; k < Classes.Count(); k++)
                    {
                        if (Classes[k].name == pcc.Exports[j].ClassName)
                        {
                            f = k;
                            break;
                        }
                    }
                    if (f == -1)//New Class found, add
                    {
                        ClassDef tmp = new ClassDef();
                        tmp.name  = pcc.Exports[j].ClassName;
                        tmp.props = new List <PropDef>();
                        Classes.Add(tmp);
                        f = Classes.Count() - 1;
                        UpdateStatus();
                    }
                    List <PropertyReader.Property> props = PropertyReader.getPropList(pcc, pcc.Exports[j].Data);
                    ClassDef res = Classes[f];
                    foreach (PropertyReader.Property p in props)
                    {
                        int    f2   = -1;
                        string name = pcc.getNameEntry(p.Name);
                        for (int k = 0; k < res.props.Count(); k++)
                        {
                            if (res.props[k].name == name)
                            {
                                f2 = k;
                                break;
                            }
                        }
                        if (f2 == -1) //found new prop
                        {
                            PropDef ptmp = new PropDef();
                            ptmp.name   = name;
                            ptmp.type   = (int)p.TypeVal;
                            ptmp.ffpath = Path.GetFileName(file);
                            ptmp.ffidx  = j;
                            res.props.Add(ptmp);
                            //DebugOutput.PrintLn("\tin object #"
                            //                    + j
                            //                    + " class \""
                            //                    + pcc.Exports[j].ClassName
                            //                    + "\" found property \""
                            //                    + name
                            //                    + "\" type "
                            //                    + PropertyReader.TypeToString(ptmp.type));
                        }
                    }
                }
            }
            Sort();
            RefreshLists();
            UpdateStatus();
            MessageBox.Show("Done.");
        }
示例#22
0
        /// <summary>
        /// Loads a .mod file from given file and returns a nullable boolean (True, null, False).
        /// </summary>
        /// <param name="file">.mod file to load.</param>
        /// <param name="modCount">REF: Total number of jobs loaded.</param>
        /// <param name="progbar">ProgressBar to increment/change during method.</param>
        /// <param name="ExternalCall">If true, certain functions are disabled/automated.</param>
        /// <returns>True if update is to be done automatically, false if not, and null if user requests to stop loading .mod.</returns>
        public static bool?LoadDotMod(string file, ref int modCount, ToolStripProgressBar progbar, bool ExternalCall)
        {
            bool AutoUpdate = false;

            // KFreon: Load from file
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                // KFreon: Attempt to get version
                fs.Seek(0, SeekOrigin.Begin);
                int    versionLength    = fs.ReadValueS32();
                long   countOffset      = fs.Seek(0, SeekOrigin.Current); // Just in case
                string version          = "";
                int    count            = -1;
                string ExecutingVersion = null;
                bool   validVersion     = false;
                if (versionLength > 20)     // KFreon: Version is definitely wrong
                {
                    ExecutingVersion = "";
                }
                else
                {
                    // KFreon: Do version checking
                    for (int i = 0; i < versionLength; i++)
                    {
                        version += (char)fs.ReadByte();
                    }

                    // KFreon: Get Executing Version and check validity of read .mod version
                    string vers;
                    ExecutingVersion = GetVersion(version, out vers, out validVersion);
                    version          = vers;

                    count = fs.ReadValueS32();

                    // KFreon: Check if update required
                    if (version != ExecutingVersion)
                    {
                        if (ExternalCall)
                        {
                            AutoUpdate = true;
                        }
                    }
                    else   // KFreon: Reset to null to signify success
                    {
                        ExecutingVersion = null;
                    }
                }


                // KFreon: Ask what to do about version
                if (ExecutingVersion != null) //&& !ExternalCall) // Heff: do we want to suppress this for external calls? should they always autoupdate?
                {                             // Seems better to keep it the current way, so that users get prompted if they load old .mods.
                    DialogResult dr = MessageBox.Show(Path.GetFileName(file) + " is old and unsupported by this version of ME3Explorer." + Environment.NewLine + "Click Yes to update .mod now, No to continue loading .mod, or Cancel to stop loading .mod", "Ancient .mod detected.", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                    if (dr == System.Windows.Forms.DialogResult.Cancel)
                    {
                        return(null);
                    }
                    else if (dr == System.Windows.Forms.DialogResult.Yes)
                    {
                        AutoUpdate = true;
                    }
                }

                /*else if (ExecutingVersion != null) // Heff: could use this for always updating if its an external call:
                 *  AutoUpdate = true;*/

                // KFreon: Reset stream position if necessary
                if (!validVersion)
                {
                    count = versionLength;
                    fs.Seek(countOffset, SeekOrigin.Begin);
                }

                // KFreon: Increment progress bar
                if (progbar != null)
                {
                    progbar.GetCurrentParent().Invoke(new Action(() =>
                    {
                        progbar.Value   = 0;
                        progbar.Maximum = count;
                    }));
                }

                // KFreon: Read Data
                DebugOutput.PrintLn("Found " + count + " Jobs", true);
                modCount += count;
                for (int i = 0; i < count; i++)
                {
                    // KFreon: Read name
                    ModMaker.ModJob md  = new ModMaker.ModJob();
                    int             len = fs.ReadValueS32();
                    md.Name = "";
                    for (int j = 0; j < len; j++)
                    {
                        md.Name += (char)fs.ReadByte();
                    }

                    // KFreon: Read script
                    len       = fs.ReadValueS32();
                    md.Script = "";
                    for (int j = 0; j < len; j++)
                    {
                        md.Script += (char)fs.ReadByte();
                    }

                    // KFreon: Read data
                    len = fs.ReadValueS32();
                    byte[] buff = fs.ReadBytes(len);
                    md.data = buff;
                    ModMaker.JobList.Add(md);
                    DebugOutput.PrintLn("Add Job \"" + md.Name + "\"", true);

                    if (progbar != null)
                    {
                        progbar.GetCurrentParent().Invoke(new Action(() => progbar.Increment(1)));
                    }
                }
            }
            return(AutoUpdate);
        }
示例#23
0
        /*public class ImportEntry : IEntry
         * {
         *  public static int byteSize = 28;
         *  internal byte[] header = new byte[byteSize];
         *  internal UDKPackage udkRef;
         *
         *  public int idxPackageFile { get { return BitConverter.ToInt32(header, 0); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 0, sizeof(int)); } }
         *  public int idxClassName { get { return BitConverter.ToInt32(header, 8); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 8, sizeof(int)); } }
         *  public int idxLink { get { return BitConverter.ToInt32(header, 16); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 16, sizeof(int)); } }
         *  public int idxObjectName { get { return BitConverter.ToInt32(header, 20); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 20, sizeof(int)); } }
         *
         *  public string ClassName { get { return udkRef.getName(idxClassName); } }
         *  public string PackageFile { get { return udkRef.Names[idxPackageFile] + ".udk"; } }
         *  public string ObjectName { get { return udkRef.getName(idxObjectName); } }
         *  public string PackageName
         *  {
         *      get
         *      {
         *          int val = idxLink;
         *          if (val != 0)
         *          {
         *              IEntry entry = udkRef.getEntry(val);
         *              return udkRef.getName(entry.idxObjectName);
         *          }
         *          else return "Package";
         *      }
         *  }
         *  public string PackageFullName
         *  {
         *      get
         *      {
         *          string result = PackageName;
         *          int idxNewPackName = idxLink;
         *
         *          while (idxNewPackName != 0)
         *          {
         *              string newPackageName = udkRef.getEntry(idxNewPackName).PackageName;
         *              if (newPackageName != "Package")
         *                  result = newPackageName + "." + result;
         *              idxNewPackName = udkRef.getEntry(idxNewPackName).idxLink;
         *          }
         *          return result;
         *      }
         *  }
         *
         *  public string GetFullPath
         *  {
         *      get
         *      {
         *          string s = "";
         *          if (PackageFullName != "Class" && PackageFullName != "Package")
         *              s += PackageFullName + ".";
         *          s += ObjectName;
         *          return s;
         *      }
         *  }
         *
         *  public ImportEntry(UDKPackage UDKPackage, byte[] importData)
         *  {
         *      udkRef = UDKPackage;
         *      header = (byte[])importData.Clone();
         *  }
         *
         *  public ImportEntry(UDKPackage UDKPackage, Stream importData)
         *  {
         *      udkRef = UDKPackage;
         *      header = new byte[ImportEntry.byteSize];
         *      importData.Read(header, 0, header.Length);
         *  }
         *
         *  public ImportEntry Clone()
         *  {
         *      ImportEntry newImport = (ImportEntry)MemberwiseClone();
         *      newImport.header = (byte[])this.header.Clone();
         *      return newImport;
         *  }
         * } */

        /*
         * public class ExportEntry : IEntry // class containing info about export entry (header info + data)
         * {
         * internal byte[] header; // holds data about export header, not the export data.
         * public UDKPackage udkRef;
         * public uint offset { get; set; }
         *
         * public int idxClass { get { return BitConverter.ToInt32(header, 0); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 0, sizeof(int)); } }
         * public int idxClassParent { get { return BitConverter.ToInt32(header, 4); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 4, sizeof(int)); } }
         * public int idxLink { get { return BitConverter.ToInt32(header, 8); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 8, sizeof(int)); } }
         * public int idxPackageName { get { return BitConverter.ToInt32(header, 8) - 1; } set { Buffer.BlockCopy(BitConverter.GetBytes(value + 1), 0, header, 8, sizeof(int)); } }
         * public int idxObjectName { get { return BitConverter.ToInt32(header, 12); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 12, sizeof(int)); } }
         * public int indexValue { get { return BitConverter.ToInt32(header, 16); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 16, sizeof(int)); } }
         * public int idxArchtype { get { return BitConverter.ToInt32(header, 20); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 20, sizeof(int)); } }
         * public ulong ObjectFlags { get { return BitConverter.ToUInt64(header, 24); } set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 24, sizeof(long)); } }
         *
         * public string ObjectName { get { return udkRef.getName(idxObjectName); } }
         * public string ClassName { get { int val = idxClass; if (val != 0) return udkRef.getName(udkRef.getEntry(val).idxObjectName); else return "Class"; } }
         * public string ClassParent { get { int val = idxClassParent; if (val != 0) return udkRef.getName(udkRef.getEntry(val).idxObjectName); else return "Class"; } }
         * public string PackageName { get { int val = idxPackageName; if (val >= 0) return udkRef.getName(udkRef.Exports[val].idxObjectName); else return "Package"; } }
         * public string PackageFullName
         * {
         *  get
         *  {
         *      string result = PackageName;
         *      int idxNewPackName = idxPackageName;
         *
         *      while (idxNewPackName >= 0)
         *      {
         *          string newPackageName = udkRef.Exports[idxNewPackName].PackageName;
         *          if (newPackageName != "Package")
         *              result = newPackageName + "." + result;
         *          idxNewPackName = udkRef.Exports[idxNewPackName].idxPackageName;
         *      }
         *      return result;
         *  }
         * }
         *
         * public string ContainingPackage
         * {
         *  get
         *  {
         *      string result = PackageName;
         *      if (result.EndsWith(ObjectName))
         *      {
         *          result = "";
         *      }
         *      int idxNewPackName = idxPackageName;
         *
         *      while (idxNewPackName >= 0)
         *      {
         *          string newPackageName = udkRef.Exports[idxNewPackName].PackageName;
         *          if (newPackageName != "Package")
         *          {
         *              if (!result.Equals(""))
         *              {
         *                  result = newPackageName + "." + result;
         *              }
         *              else
         *              {
         *                  result = newPackageName;
         *              }
         *          }
         *          idxNewPackName = udkRef.Exports[idxNewPackName].idxPackageName;
         *      }
         *      return result;
         *  }
         * }
         *
         * public string GetFullPath
         * {
         *  get
         *  {
         *      string s = "";
         *      if (PackageFullName != "Class" && PackageFullName != "Package")
         *          s += PackageFullName + ".";
         *      s += ObjectName;
         *      return s;
         *  }
         * }
         * public string ArchtypeName { get { int val = idxArchtype; if (val != 0) return udkRef.(udkRef.getEntry(val).idxObjectName); else return "None"; } }
         *
         * public int DataSize { get { return BitConverter.ToInt32(header, 32); } internal set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 32, sizeof(int)); } }
         * public int DataOffset { get { return BitConverter.ToInt32(header, 36); } internal set { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, header, 36, sizeof(int)); } }
         * public int DataOffsetTmp;
         * byte[] _data = null;
         * public byte[] Data // holds data about export data
         * {
         *  get
         *  {
         *      // if data isn't loaded then fill it from udk file (load-on-demand)
         *      if (_data == null)
         *      {
         *          udkRef.getData(DataOffset, this);
         *      }
         *      return _data;
         *  }
         *
         *  set { _data = value; hasChanged = true; }
         * }
         * public bool likelyCoalescedVal
         * {
         *  get
         *  {
         *      return (Data.Length < 25) ? false : (Data[25] == 64); //0x40
         *  }
         *  set { }
         * }
         * public bool hasChanged { get; internal set; }
         *
         * public ExportEntry(UDKPackage UDKPackage, byte[] importData, uint exportOffset)
         * {
         *  udkRef = UDKPackage;
         *  header = (byte[])importData.Clone();
         *  offset = exportOffset;
         *  hasChanged = false;
         * }
         *
         * public ExportEntry()
         * {
         *  // TODO: Complete member initialization
         * }
         *
         * public ExportEntry Clone()
         * {
         *  ExportEntry newExport = (ExportEntry)this.MemberwiseClone(); // copy all reference-types vars
         *                                                               // now creates new copies of referenced objects
         *  newExport.header = (byte[])this.header.Clone();
         *  newExport.Data = (byte[])this.Data.Clone();
         *  int index = 0;
         *  string name = ObjectName;
         *  foreach (ExportEntry ent in udkRef.Exports)
         *  {
         *      if (name == ent.ObjectName && ent.indexValue > index)
         *      {
         *          index = ent.indexValue;
         *      }
         *  }
         *  index++;
         *  newExport.indexValue = index;
         *  return newExport;
         * }
         * }*/

        /// <summary>
        ///     UDKPackage class constructor. It also load namelist, importlist and exportinfo (not exportdata) from udk file
        /// </summary>
        /// <param name="UDKPackagePath">full path + file name of desired udk file.</param>
        public UDKPackage(string UDKPackagePath, bool fullFileInMemory = false)
        {
            string path = UDKPackagePath;

            DebugOutput.PrintLn("Load file : " + path);
            FileName = Path.GetFullPath(path);
            MemoryStream tempStream = new MemoryStream();

            if (!File.Exists(FileName))
            {
                throw new FileNotFoundException("UPK file not found");
            }
            using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read))
            {
                FileInfo tempInfo = new FileInfo(FileName);
                tempStream.WriteFromStream(fs, tempInfo.Length);
                if (tempStream.Length != tempInfo.Length)
                {
                    throw new FileLoadException("File not fully read in. Try again later");
                }
            }

            //tempStream.Seek(12, SeekOrigin.Begin);
            //int tempNameSize = tempStream.ReadValueS32();
            //tempStream.Seek(64 + tempNameSize, SeekOrigin.Begin);
            //int tempGenerations = tempStream.ReadValueS32();
            //tempStream.Seek(36 + tempGenerations * 12, SeekOrigin.Current);
            //int tempPos = (int)tempStream.Position;
            tempStream.Seek(0, SeekOrigin.Begin);
            header = tempStream.ReadBytes(headerSize);
            tempStream.Seek(0, SeekOrigin.Begin);

            MemoryStream listsStream;

            if (IsCompressed)
            {
                /*DebugOutput.PrintLn("File is compressed");
                 * {
                 *  listsStream = CompressionHelper.DecompressME1orME2(tempStream);
                 *
                 *  //Correct the header
                 *  IsCompressed = false;
                 *  listsStream.Seek(0, SeekOrigin.Begin);
                 *  listsStream.WriteBytes(header);
                 *
                 *  //Set numblocks to zero
                 *  listsStream.WriteValueS32(0);
                 *  //Write the magic number
                 *  listsStream.WriteValueS32(1026281201);
                 *  //Write 8 bytes of 0
                 *  listsStream.WriteValueS32(0);
                 *  listsStream.WriteValueS32(0);
                 * }*/
                throw new FileLoadException("Compressed UPK packages are not supported.");
            }
            else
            {
                DebugOutput.PrintLn("File already decompressed. Reading decompressed data.");
                listsStream = tempStream;
            }

            names = new List <string>();
            listsStream.Seek(NameOffset, SeekOrigin.Begin);

            for (int i = 0; i < NameCount; i++)
            {
                try
                {
                    int    len = listsStream.ReadValueS32();
                    string s   = listsStream.ReadString((uint)(len - 1));
                    //skipping irrelevant data

                    listsStream.Seek(9, SeekOrigin.Current); // 8 + 1 for terminator character
                    names.Add(s);
                }
                catch (Exception e)
                {
                    Debugger.Break();
                    throw e;
                }
            }

            imports = new List <ImportEntry>();
            listsStream.Seek(ImportOffset, SeekOrigin.Begin);
            for (int i = 0; i < ImportCount; i++)
            {
                ImportEntry import = new ImportEntry(this, listsStream);
                import.Index            = i;
                import.PropertyChanged += importChanged;
                imports.Add(import);
            }

            exports = new List <IExportEntry>();
            listsStream.Seek(ExportOffset, SeekOrigin.Begin);
            for (int i = 0; i < ExportCount; i++)
            {
                UDKExportEntry exp = new UDKExportEntry(this, listsStream);
                exp.Index            = i;
                exp.PropertyChanged += exportChanged;
                exports.Add(exp);
            }
        }
示例#24
0
        protected override void OnExecuteCSharpScript()
        {
            BackgroundExecute((string _documentText, out string _textOutput, out string _errorOutput, out IEnumerable <object> _result) =>
            {
                BackgroundExecuteDelegate scriptExecution = (string documentText, out string textOutput, out string errorOutput, out IEnumerable <object> result) =>
                {
                    // Setting results
                    textOutput  = "";
                    errorOutput = "";

                    // Execution code
                    var oldOut   = Console.Out;
                    var oldError = Console.Error;

                    try
                    {
                        using (StringWriter writer = new StringWriter())
                        {
                            Console.SetOut(writer);
                            Console.SetError(writer);

                            DebugOutput captureFlags = DebugOutput.Normal | DebugOutput.Error | DebugOutput.Warning | DebugOutput.Verbose
                                                       | DebugOutput.Prompt | DebugOutput.PromptRegisters | DebugOutput.ExtensionWarning | DebugOutput.Debuggee
                                                       | DebugOutput.DebuggeePrompt | DebugOutput.Symbols | DebugOutput.Status;
                            var callbacks = DebuggerOutputToTextWriter.Create(Console.Out, captureFlags);

                            interactiveExecution.scriptBase._UiActionExecutor_ = (action) => Dispatcher.Invoke(action);
                            using (OutputCallbacksSwitcher switcher = OutputCallbacksSwitcher.Create(callbacks))
                            {
                                interactiveExecution.UnsafeInterpret(documentText);
                                writer.Flush();
                                textOutput = writer.GetStringBuilder().ToString();
                            }
                        }

                        UpdateScriptCode();
                    }
                    catch (Microsoft.CodeAnalysis.Scripting.CompilationErrorException ex)
                    {
                        StringBuilder sb = new StringBuilder();

                        sb.AppendLine("Compile errors:");
                        foreach (var error in ex.Diagnostics)
                        {
                            sb.AppendLine(error.ToString());
                        }

                        errorOutput = sb.ToString();
                    }
                    catch (ExitRequestedException)
                    {
                        throw;
                    }
                    catch (AggregateException ex)
                    {
                        if (ex.InnerException is ExitRequestedException)
                        {
                            throw ex.InnerException;
                        }
                        errorOutput = ex.ToString();
                    }
                    catch (TargetInvocationException ex)
                    {
                        if (ex.InnerException is ExitRequestedException)
                        {
                            throw ex.InnerException;
                        }
                        errorOutput = ex.InnerException.ToString();
                    }
                    catch (Exception ex)
                    {
                        errorOutput = ex.ToString();
                    }
                    finally
                    {
                        Console.SetError(oldError);
                        Console.SetOut(oldOut);
                        result  = results;
                        results = new List <object>();
                        interactiveExecution.scriptBase._UiActionExecutor_ = null;
                    }
                };

                // Check if we should execute script code in STA thread
                if (interactiveExecution.scriptBase.ForceStaExecution)
                {
                    string tempTextOutput           = null;
                    string tempErrorOutput          = null;
                    IEnumerable <object> tempResult = null;

                    InteractiveWindow.ExecuteInSTA(() =>
                    {
                        scriptExecution(_documentText, out tempTextOutput, out tempErrorOutput, out tempResult);
                    });
                    _textOutput  = tempTextOutput;
                    _errorOutput = tempErrorOutput;
                    _result      = tempResult;
                }
                else
                {
                    scriptExecution(_documentText, out _textOutput, out _errorOutput, out _result);
                }
            }, true);
        }
示例#25
0
        /// <summary>
        ///     save PCCObject to file.
        /// </summary>
        /// <param name="newFileName">set full path + file name.</param>
        /// <param name="saveCompress">set true if you want a zlib compressed pcc file.</param>
        public void saveToCprFile(string newFileName = null, bool saveCompress = false)
        {
            bool bOverwriteFile = false;

            if (string.IsNullOrWhiteSpace(newFileName) || newFileName == pccFileName)
            {
                bOverwriteFile = true;
                newFileName    = Path.GetFullPath(pccFileName) + ".tmp";
            }

            if (bDLCStored)
            {
                saveCompress = false;
            }

            using (MemoryStream newPccStream = new MemoryStream())
            {
                //ME3Explorer.DebugOutput.Clear();
                DebugOutput.PrintLn("Saving file...");

                DebugOutput.PrintLn("writing names list...");

                // this condition needs a deeper check. todo...
                if (bExtraNamesList)
                {
                    //MessageBox.Show("sono dentro, dimensione extranamelist: " + extraNamesList.Length + " bytes");
                    newPccStream.Seek(headerSize, SeekOrigin.Begin);
                    newPccStream.Write(extraNamesList, 0, extraNamesList.Length);
                }

                //writing names list
                newPccStream.Seek(NameOffset, SeekOrigin.Begin);
                NameCount = Names.Count;
                foreach (string name in Names)
                {
                    newPccStream.WriteValueS32(-(name.Length + 1));
                    newPccStream.WriteString(name + "\0", (uint)(name.Length + 1) * 2, Encoding.Unicode);
                }

                DebugOutput.PrintLn("writing imports list...");

                //writing import infos
                ImportOffset = (int)newPccStream.Position;
                ImportCount  = Imports.Count;
                foreach (ME3ImportEntry import in Imports)
                {
                    newPccStream.Write(import.data, 0, import.data.Length);
                }

                //updating general export infos
                ExportOffset     = (int)newPccStream.Position;
                ExportCount      = Exports.Count;
                expInfoEndOffset = ExportOffset + Exports.Sum(export => export.info.Length);
                expDataBegOffset = expInfoEndOffset;

                // WV code stuff...
                DebugOutput.PrintLn("writing export data...");
                int counter = 0;
                int breaker = Exports.Count / 100;
                if (breaker == 0)
                {
                    breaker = 1;
                }

                //updating general export infos
                ExportOffset     = (int)newPccStream.Position;
                ExportCount      = Exports.Count;
                expInfoEndOffset = ExportOffset + Exports.Sum(export => export.info.Length);
                if (expDataBegOffset < expInfoEndOffset)
                {
                    expDataBegOffset = expInfoEndOffset;
                }

                //writing export data

                /*newPccStream.Seek(expDataBegOffset, SeekOrigin.Begin);
                 * foreach (ExportEntry export in Exports)
                 * {
                 *  //updating info values
                 *  export.DataSize = export.Data.Length;
                 *  export.DataOffset = (int)newPccStream.Position;
                 *
                 *  //writing data
                 *  newPccStream.Write(export.Data, 0, export.Data.Length);
                 * }*/
                //writing export data
                List <ME3ExportEntry> unchangedExports = Exports.Where(export => !export.hasChanged || (export.hasChanged && export.Data.Length <= export.DataSize)).ToList();
                List <ME3ExportEntry> changedExports   = Exports.Where(export => export.hasChanged && export.Data.Length > export.DataSize).ToList();

                foreach (ME3ExportEntry export in unchangedExports)
                {
                    newPccStream.Seek(export.DataOffset, SeekOrigin.Begin);
                    //updating info values
                    export.DataSize = export.Data.Length;
                    //export.DataOffset = (int)newPccStream.Position;
                    export.DataOffset = (uint)newPccStream.Position;

                    //writing data
                    newPccStream.Write(export.Data, 0, export.Data.Length);
                }

                ME3ExportEntry lastExport     = unchangedExports.Find(export => export.DataOffset == unchangedExports.Max(maxExport => maxExport.DataOffset));
                int            lastDataOffset = (int)(lastExport.DataOffset + lastExport.DataSize);

                newPccStream.Seek(lastDataOffset, SeekOrigin.Begin);
                foreach (ME3ExportEntry export in changedExports)
                {
                    //updating info values
                    export.DataSize   = export.Data.Length;
                    export.DataOffset = (uint)newPccStream.Position;

                    //writing data
                    newPccStream.Write(export.Data, 0, export.Data.Length);
                }

                //if (Exports.Any(x => x.Data == null))
                //    throw new Exception("values null!!");

                //writing export info
                newPccStream.Seek(ExportOffset, SeekOrigin.Begin);
                foreach (ME3ExportEntry export in Exports)
                {
                    newPccStream.Write(export.info, 0, export.info.Length);
                }

                /*foreach (ExportEntry export in unchangedExports)
                 * {
                 *  newPccStream.Write(export.info, 0, export.info.Length);
                 * }
                 * foreach (ExportEntry export in changedExports)
                 * {
                 *  newPccStream.Write(export.info, 0, export.info.Length);
                 * }*/

                DebugOutput.PrintLn("writing header file...");

                //writing header
                bCompressed = false;
                newPccStream.Seek(0, SeekOrigin.Begin);
                newPccStream.Write(header, 0, header.Length);
                newPccStream.Seek(0, SeekOrigin.Begin);

                if (saveCompress)
                {
                    DebugOutput.PrintLn("compressing in zlib format, it may take a while...");
                    PCCHandler.CompressAndSave(newPccStream, newFileName);
                }
                else
                {
                    using (FileStream outputStream = File.Create(newFileName))
                    {
                        newPccStream.CopyTo(outputStream);
                    }
                }
            }

            if (bOverwriteFile)
            {
                File.Delete(pccFileName);
                File.Move(newFileName, pccFileName);
            }
            DebugOutput.PrintLn(Path.GetFileName(pccFileName) + " has been saved.");
        }
示例#26
0
        private void startScanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(ME3Directory.cookedPath))
            {
                MessageBox.Show("This functionality requires ME3 to be installed. Set its path at:\n Options > Set Custom Path > Mass Effect 3");
                return;
            }
            string path = ME3Directory.cookedPath;

            string[] files = Directory.GetFiles(path, "*.pcc");
            pb1.Maximum = files.Length;
            DebugOutput.Clear();
            database = new List <DBEntry>();
            int count = 0;

            foreach (string file in files)
            {
                pb1.Value = count++;
                DebugOutput.PrintLn("Scanning file : " + Path.GetFileName(file) + " ...");
                try
                {
                    PCCObject pcc = new PCCObject(file);
                    DBEntry   ent = new DBEntry();
                    ent.filename = Path.GetFileName(file);
                    ent.Objects  = new List <ObjInf>();
                    for (int i = 0; i < pcc.Exports.Count; i++)
                    {
                        PCCObject.ExportEntry ex = pcc.Exports[i];
                        ObjInf obj;
                        switch (ex.ClassName)
                        {
                        case "StaticMesh":
                            obj       = new ObjInf();
                            obj.Index = i;
                            obj.Type  = 0;
                            obj.name  = ex.ObjectName;
                            ent.Objects.Add(obj);
                            break;

                        case "SkeletalMesh":
                            obj       = new ObjInf();
                            obj.Index = i;
                            obj.Type  = 1;
                            obj.name  = ex.ObjectName;
                            ent.Objects.Add(obj);
                            break;
                        }
                    }
                    if (ent.Objects.Count != 0)
                    {
                        DebugOutput.PrintLn("Found " + ent.Objects.Count + " Objects:", false);
                        //foreach (ObjInf o in ent.Objects)
                        //    DebugOutput.PrintLn("\t" + o.Index + " : " + o.name + " (" + TypeToString(o.Type) + ")", false);
                        //DebugOutput.Update();
                        database.Add(ent);
                    }
                    else
                    {
                        DebugOutput.PrintLn("Nothing...", false);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error:\n" + ex.Message);
                    DebugOutput.PrintLn("Could not open file : " + Path.GetFileName(file));
                }
            }
            RefreshLists();
            pb1.Value = 0;
        }
示例#27
0
 public void SaveChanges()
 {
     foreach (StaticMeshCollectionActor stmca in STM_CA)
     {
         stmca.SaveChanges();
     }
     foreach (StaticMeshActor stma in STM_A)
     {
         stma.SaveChanges();
     }
     foreach (InterpActor ia in IA)
     {
         ia.SaveChanges();
     }
     foreach (BlockingVolume bv in BV)
     {
         bv.SaveChanges();
     }
     foreach (SplineActor sp in SPA)
     {
         sp.SaveChanges();
     }
     foreach (TargetPoint tp in TP)
     {
         tp.SaveChanges();
     }
     foreach (LightVolume lv in LV)
     {
         lv.SaveChanges();
     }
     foreach (MantleMarker mm in MM)
     {
         mm.SaveChanges();
     }
     foreach (PathNode pn in PN)
     {
         pn.SaveChanges();
     }
     foreach (CoverLink cl in CL)
     {
         cl.SaveChanges();
     }
     foreach (CoverSlotMarker csm in CSM)
     {
         csm.SaveChanges();
     }
     foreach (Emitter em in EM)
     {
         em.SaveChanges();
     }
     foreach (BioPlaypenVolumeAdditive bpva in BPVA)
     {
         bpva.SaveChanges();
     }
     foreach (BioTriggerVolume btv in BTV)
     {
         btv.SaveChanges();
     }
     foreach (BioPathPoint bpp in BPP)
     {
         bpp.SaveChanges();
     }
     foreach (WwiseAmbientSound was in WAS)
     {
         was.SaveChanges();
     }
     foreach (WwiseAudioVolume wav in WAV)
     {
         wav.SaveChanges();
     }
     foreach (WwiseEnvironmentVolume wev in WEV)
     {
         wev.SaveChanges();
     }
     DebugOutput.PrintLn("Saving \"" + Path.GetFileName(pcc.FileName) + "\" ...");
     pcc.save();
 }
示例#28
0
        public DLCEditor2()
        {
            InitializeComponent();

            //FemShep's Mod Manager 3 automator for DLCEditor2.
            string[] arguments = Environment.GetCommandLineArgs();
            if (arguments.Length > 2)
            {
                try
                {
                    string cmdCommand = arguments[1];
                    if (cmdCommand.Equals("-dlcinject", StringComparison.Ordinal))
                    {
                        if (arguments.Length % 2 != 1 || arguments.Length < 5)
                        {
                            MessageBox.Show("Wrong number of arguments for the -dlcinject switch.:\nSyntax is: <exe> -dlcinject SFARPATH SEARCHTERM NEWFILEPATH [SEARCHTERM2 NEWFILEPATH2]...", "ME3 DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        string dlcFileName = arguments[2];
                        int    numfiles    = (arguments.Length - 3) / 2;

                        string[] filesToReplace = new String[numfiles];
                        string[] newFiles       = new String[numfiles];

                        int argnum = 3; //starts at 3
                        for (int i = 0; i < filesToReplace.Length; i++)
                        {
                            filesToReplace[i] = arguments[argnum];
                            argnum++;
                            newFiles[i] = arguments[argnum];
                            argnum++;
                        }
                        automated = true;
                        if (File.Exists(dlcFileName))
                        {
                            openSFAR(dlcFileName);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("dlcFilename does not exist: " + dlcFileName);
                            MessageBox.Show("Failed to autoinject: DLC file does not exist: " + dlcFileName, "ME3Explorer DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        //SFAR was opened.
                        //Now we search for the element to replace so it is selected...
                        for (int i = 0; i < numfiles; i++)
                        {
                            selectSearchedElement(filesToReplace[i]);
                            //the element is now selected, hopefully.
                            TreeNode t = treeView1.SelectedNode;
                            if (DLC == null || t == null || t.Parent == null || t.Parent.Text != "FileEntries")
                            {
                                MessageBox.Show("DLCEditor2 automator encountered an error: the file to replace does not exist or the tree has not been initialized.", "ME3 DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            replaceFile(newFiles[i], t.Index);
                        }
                    }
                    else if (cmdCommand.Equals("-dlcextract", StringComparison.Ordinal))
                    {
                        if (arguments.Length != 5)
                        {
                            //-2 for me3explorer & -dlcextract
                            MessageBox.Show("Wrong number of arguments for the -dlcinject switch.:\nSyntax is: <exe> -dlcextract SFARPATH SEARCHTERM EXTRACTIONPATH", "ME3 DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        automated = true;
                        string dlcFileName    = arguments[2];
                        string searchTerm     = arguments[3];
                        string extractionPath = arguments[4];
                        if (File.Exists(dlcFileName))
                        {
                            openSFAR(dlcFileName);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("dlcFilename does not exist: " + dlcFileName);
                            MessageBox.Show("Failed to autoextract: DLC file does not exist: " + dlcFileName, "ME3Explorer DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        //SFAR was opened.
                        //Now we search for the element to extract so it is selected...
                        selectSearchedElement(searchTerm);
                        //the element is now selected, hopefully.
                        TreeNode t = treeView1.SelectedNode;
                        if (DLC == null || t == null || t.Parent == null || t.Parent.Text != "FileEntries")
                        {
                            MessageBox.Show("DLCEditor2 extraction automator encountered an error:\nThe file to replace does not exist or the tree has not been initialized.", "DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        extractFile(t.Index, extractionPath);
                    }
                    else if (cmdCommand.Equals("-dlcaddfiles", StringComparison.Ordinal))
                    {
                        if (arguments.Length % 2 != 1 || arguments.Length < 5)
                        {
                            MessageBox.Show("Wrong number of arguments for the -dlcaddfiles switch.:\nSyntax is: <exe> -dlcinject SFARPATH INTERNALPATH NEWFILEPATH [INTERNALPATH2 NEWFILEPATH2]...", "ME3 DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }

                        automated = true;
                        string dlcFileName = arguments[2];

                        int      numfiles      = (arguments.Length - 3) / 2;
                        string[] internalPaths = new String[numfiles];
                        string[] sourcePaths   = new String[numfiles];

                        int argnum = 3; //starts at 3
                        for (int i = 0; i < internalPaths.Length; i++)
                        {
                            internalPaths[i] = arguments[argnum];
                            argnum++;
                            sourcePaths[i] = arguments[argnum];
                            argnum++;
                        }

                        if (File.Exists(dlcFileName))
                        {
                            openSFAR(dlcFileName);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("DLC does not exist: " + dlcFileName);
                            MessageBox.Show("Failed to autoadd: DLC file does not exist: " + dlcFileName, "ME3Explorer DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        //SFAR was opened.
                        for (int i = 0; i < internalPaths.Length; i++)
                        {
                            System.Diagnostics.Debug.WriteLine("Adding file quick: " + sourcePaths[i] + " " + internalPaths[i]);
                            DLC.AddFileQuick(sourcePaths[i], internalPaths[i]);
                            DLC = new DLCPackage(DLC.MyFileName);
                            treeView1.Nodes.Clear();
                            treeView1.Nodes.Add(DLC.ToTree());
                        }
                    }
                    else if (cmdCommand.Equals("-dlcremovefiles", StringComparison.Ordinal))
                    {
                        if (arguments.Length < 4)
                        {
                            //-2 for me3explorer & -dlcextract
                            MessageBox.Show("Wrong number of arguments for the -dlcremovefiles switch.:\nSyntax is: <exe> -dlcinject SFARPATH INTERNALPATH [INTERNALPATH2]...", "ME3 DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        automated = true;
                        string dlcFileName = arguments[2];

                        int numfiles = (arguments.Length - 3);

                        string[] filesToRemove = new String[numfiles];

                        int argnum = 3; //starts at 3
                        for (int i = 0; i < filesToRemove.Length; i++)
                        {
                            filesToRemove[i] = arguments[argnum];
                            argnum++;
                        }

                        if (File.Exists(dlcFileName))
                        {
                            openSFAR(dlcFileName);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("DLC does not exist: " + dlcFileName);
                            MessageBox.Show("Failed to autoremove: DLC file does not exist: " + dlcFileName, "ME3Explorer DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        //SFAR was opened.
                        for (int i = 0; i < filesToRemove.Length; i++)
                        {
                            selectSearchedElement(filesToRemove[i]);
                            //the element is now selected, hopefully.
                            TreeNode t = treeView1.SelectedNode;
                            if (DLC == null || t == null || t.Parent == null || t.Parent.Text != "FileEntries")
                            {
                                MessageBox.Show("DLCEditor2 file removal automator encountered an error:\nThe file to remove does not exist or the tree has not been initialized.", "DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Application.Exit();
                                return;
                            }
                            DLC.DeleteEntry(t.Index);
                            DLC = new DLCPackage(DLC.MyFileName);
                            treeView1.Nodes.Clear();
                            treeView1.Nodes.Add(DLC.ToTree());
                        }
                    }
                    else if (cmdCommand.Equals("-dlcunpack", StringComparison.Ordinal) || cmdCommand.Equals("-dlcunpack-nodebug", StringComparison.Ordinal))
                    {
                        if (arguments.Length != 4)
                        {
                            MessageBox.Show("Wrong number of arguments for automated DLC unpacking:\nSyntax is: <exe> -dlcinject SFARPATH EXTRACTIONPATH", "ME3 DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }


                        string sfarPath = arguments[2];
                        autoUnpackFolder = arguments[3];

                        automated = true;
                        if (File.Exists(sfarPath))
                        {
                            openSFAR(sfarPath);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("DLC does not exist: " + sfarPath);
                            MessageBox.Show("Failed to autounpack: DLC file does not exist: " + sfarPath, "ME3Explorer DLCEditor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Application.Exit();
                            return;
                        }
                        //SFAR was opened.
                        if (cmdCommand.Equals("-dlcunpack"))
                        {
                            DebugOutput.StartDebugger("DLC Editor 2"); //open debugging window since this operation takes a long time. The main debugger won't start as this will exit before that code can be reached
                        }
                        //Simulate Unpack operation click.
                        unpackSFARToolStripMenuItem.PerformClick();
                    }
                }
                catch (FileNotFoundException exc)
                {
                    MessageBox.Show("Failed to run DLCEditor2 Automator with the specified parameters.\n\nA file not found error occured while trying to automate a task.\n" + exc.Message, "DLC Editor2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(1);
                    Application.Exit();
                }
                Environment.Exit(0);
                Application.Exit();
            }
            DebugOutput.StartDebugger("DLC Editor 2"); //open debugging window AFTER automation. Otherwise it pops up all weirdlike.
        }
示例#29
0
        private void scanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ME3Directory.cookedPath))
            {
                MessageBox.Show("This functionality requires ME3 to be installed. Set its path at:\n Options > Set Custom Path > Mass Effect 3");
                return;
            }
            DebugOutput.StartDebugger("Meshplorer2");
            int count = 0;

            timer1.Enabled = false;
            Entries        = new List <EntryStruct>();
            bool ScanDLC = false;

            if (MessageBox.Show("Scan DLCs too?", "Meshplorer 2", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                ScanDLC = true;
            }
            if (ScanDLC)
            {
                #region DLC Stuff
                string dirDLC = ME3Directory.DLCPath;
                if (!Directory.Exists(dirDLC))
                {
                    DebugOutput.PrintLn("No DLC Folder found!");
                }
                else
                {
                    string[] subdirs = Directory.GetDirectories(dirDLC);
                    string   loc     = Path.GetDirectoryName(Application.ExecutablePath) + "\\exec\\";
                    Directory.CreateDirectory(loc + "temp");
                    foreach (string DLCpath in subdirs)
                    {
                        if (!DLCpath.StartsWith("__") && !DLCpath.StartsWith("DLC_UPD"))
                        {
                            string  path = DLCpath + "\\CookedPCConsole\\Default.sfar";
                            DLCBase dlcbase;
                            try
                            {
                                dlcbase       = new DLCBase(path);
                                count         = 0;
                                pbar1.Maximum = dlcbase.fileList.Count;
                                foreach (sfarFile file in dlcbase.fileList)
                                {
                                    try
                                    {
                                        string filename = Path.GetFileName(file.fileName);
                                        if (Path.GetExtension(filename).ToLower().EndsWith(".pcc"))
                                        {
                                            using (Stream input = File.OpenRead(path), output = File.Create(loc + "temp\\" + filename))
                                            {
                                                AmaroK86.MassEffect3.DLCUnpack.DecompressEntry(file, input, output, dlcbase.CompressionScheme);
                                            }
                                            FileInfo f = new FileInfo(loc + "temp\\" + filename);
                                            DebugOutput.PrintLn("checking DLC: " + Path.GetFileName(DLCpath) + " File: " + filename + " Size: " + f.Length + " bytes", count % 3 == 0);
                                            using (ME3Package pcc = MEPackageHandler.OpenME3Package(loc + "temp\\" + filename))
                                            {
                                                IReadOnlyList <IExportEntry> Exports = pcc.Exports;
                                                for (int i = 0; i < Exports.Count; i++)
                                                {
                                                    if (Exports[i].ClassName == "SkeletalMesh" ||
                                                        Exports[i].ClassName == "StaticMesh")
                                                    {
                                                        EntryStruct ent = new EntryStruct();
                                                        ent.DLCName    = Path.GetFileName(DLCpath);
                                                        ent.Filename   = filename;
                                                        ent.Index      = i;
                                                        ent.isDLC      = true;
                                                        ent.ObjectPath = Exports[i].GetFullPath;
                                                        ent.isSkeletal = Exports[i].ClassName == "SkeletalMesh";
                                                        Entries.Add(ent);
                                                    }
                                                }
                                            }
                                            File.Delete(loc + "temp\\" + filename);
                                        }
                                        if (count % 3 == 0)
                                        {
                                            pbar1.Value = count;
                                            Application.DoEvents();
                                        }
                                        count++;
                                    }
                                    catch (Exception ex)
                                    {
                                        DebugOutput.PrintLn("=====ERROR=====\n" + ex.ToString() + "\n=====ERROR=====");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                DebugOutput.PrintLn("=====ERROR=====\n" + ex.ToString() + "\n=====ERROR=====");
                            }
                        }
                    }
                    Directory.Delete(loc + "temp", true);
                }
                #endregion
            }
            #region Basegame Stuff
            string   dir   = ME3Directory.cookedPath;
            string[] files = Directory.GetFiles(dir, "*.pcc");
            pbar1.Maximum = files.Length - 1;
            foreach (string file in files)
            {
                DebugOutput.PrintLn("Scan file #" + count + " : " + file, count % 10 == 0);
                try
                {
                    using (ME3Package pcc = MEPackageHandler.OpenME3Package(file))
                    {
                        IReadOnlyList <IExportEntry> Exports = pcc.Exports;
                        for (int i = 0; i < Exports.Count; i++)
                        {
                            if (Exports[i].ClassName == "SkeletalMesh" ||
                                Exports[i].ClassName == "StaticMesh")
                            {
                                EntryStruct ent = new EntryStruct();
                                ent.DLCName    = "";
                                ent.Filename   = Path.GetFileName(file);
                                ent.Index      = i;
                                ent.isDLC      = false;
                                ent.ObjectPath = Exports[i].GetFullPath;
                                ent.isSkeletal = Exports[i].ClassName == "SkeletalMesh";
                                Entries.Add(ent);
                            }
                        }
                    }
                    if (count % 10 == 0)
                    {
                        Application.DoEvents();
                        pbar1.Value = count;
                    }
                    count++;
                }
                catch (Exception ex)
                {
                    DebugOutput.PrintLn("=====ERROR=====\n" + ex.ToString() + "\n=====ERROR=====");
                }
            }
            #endregion
            #region Sorting
            bool run = true;
            DebugOutput.PrintLn("=====Info=====\n\nSorting names...\n\n=====Info=====");
            count = 0;
            while (run)
            {
                run = false;
                for (int i = 0; i < Entries.Count - 1; i++)
                {
                    if (Entries[i].Filename.CompareTo(Entries[i + 1].Filename) > 0)
                    {
                        EntryStruct tmp = Entries[i];
                        Entries[i]     = Entries[i + 1];
                        Entries[i + 1] = tmp;
                        run            = true;
                        if (count++ % 100 == 0)
                        {
                            Application.DoEvents();
                        }
                    }
                }
            }
            #endregion
            TreeRefresh();
            timer1.Enabled = true;
        }
示例#30
0
        private void unpackSFARToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AutoTOC.AutoTOC toc = new AutoTOC.AutoTOC();
            if (DLC == null || DLC.Files == null)
            {
                return;
            }
            string result = "pcc; tfc; afc; cnd; tlk; bin; bik; dlc";
            string unpackFolder;

            if (!automated) //if automated, just do everything. otherwise prompt user
            {
                Microsoft.VisualBasic.Interaction.InputBox("Please enter pattern for unpacking, keep default to unpack everything.", "ME3 Explorer", "pcc; tfc; afc; cnd; tlk; bin; bik; dlc", 0, 0);

                if (result == "")
                {
                    return;
                }
                DebugOutput.PrintLn("result : " + result);
                FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
                fbd.Description  = "Choose a folder to unpack this DLC to. Unpacking may take a few minutes. To unpack the files to their proper folder choose the Mass Effect 3 directory.";
                fbd.SelectedPath = Directory.GetParent(DLC.MyFileName).FullName;
                DialogResult dresult = fbd.ShowDialog();
                if (dresult != DialogResult.OK)
                {
                    return;
                }
                unpackFolder = fbd.SelectedPath;
            }
            else
            {
                unpackFolder = autoUnpackFolder;
            }
            if (!unpackFolder.EndsWith("\\"))
            {
                unpackFolder = unpackFolder + "\\";
            }
            DebugOutput.PrintLn("Extracting DLC to : " + unpackFolder);

            result = result.Trim();
            if (result.EndsWith(";"))
            {
                result = result.Substring(0, result.Length - 1);
            }
            string[] patt = result.Split(';');
            string   file = DLC.MyFileName;                 //full path
            string   t1   = Path.GetDirectoryName(file);    //cooked
            string   t2   = Path.GetDirectoryName(t1);      //DLC_Name
            string   t3   = Path.GetDirectoryName(t2);      //DLC
            string   t4   = Path.GetDirectoryName(t3);      //BioGame

            DebugOutput.PrintLn("DLC name : " + t2);
            if (DLC.Files.Length > 1)
            {
                List <int> Indexes = new List <int>();
                for (int i = 0; i < DLC.Files.Length; i++)
                {
                    string DLCpath = DLC.Files[i].FileName;
                    for (int j = 0; j < patt.Length; j++)
                    {
                        if (DLCpath.ToLower().EndsWith(patt[j].Trim().ToLower()) && patt[j].Trim().ToLower() != "")
                        {
                            string relPath = GetRelativePath(DLCpath);
                            string outpath = unpackFolder + relPath;
                            DebugOutput.PrintLn("Extracting file #" + i.ToString("d4") + ": " + outpath);
                            if (!Directory.Exists(Path.GetDirectoryName(outpath)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(outpath));
                            }
                            using (FileStream fs = new FileStream(outpath, FileMode.Create))
                                DLC.DecompressEntry(i).WriteTo(fs);
                            Indexes.Add(i);
                            Application.DoEvents();
                            break;
                        }
                    }
                }
                DLC.DeleteEntry(Indexes);
            }

            // AutoTOC
            DebugOutput.PrintLn("Updating DLC's PCConsoleTOC.bin");
            List <string> FileNames = toc.GetFiles(t2 + "\\");
            List <string> tet       = new List <string>(t2.Split('\\'));
            string        remov     = String.Join("\\", tet.ToArray());

            for (int i = 0; i < FileNames.Count; i++)
            {
                FileNames[i] = FileNames[i].Substring(remov.Length + 1);
            }
            string[] ts = t2.Split('\\');
            tet.Clear();
            tet.AddRange(ts);
            string basepath = String.Join("\\", tet.ToArray()) + '\\';
            string tocfile  = t2 + "\\PCConsoleTOC.bin";

            toc.CreateTOC(basepath, tocfile, FileNames.ToArray());
            if (!automated)
            {
                MessageBox.Show("SFAR Unpacked.");
            }
        }
示例#31
0
 public void SetUp()
 {
     input = new DebugInput();
     output = new DebugOutput();
     i = new Interpreter(64 * 1024, input, output);
 }
示例#32
0
        private void unpackSFAR(DLCPackage DLC)
        {
            AutoTOC.AutoTOC toc = new AutoTOC.AutoTOC();
            if (DLC == null || DLC.Files == null)
            {
                return;
            }
            string result = "pcc; tfc; afc; cnd; tlk; bin; bik; dlc";

            if (result == "")
            {
                return;
            }
            result = result.Trim();
            if (result.EndsWith(";"))
            {
                result = result.Substring(0, result.Length - 1);
            }
            string[] patt     = result.Split(';');
            string   file     = DLC.MyFileName;              //full path
            string   t1       = Path.GetDirectoryName(file); //cooked
            string   t2       = Path.GetDirectoryName(t1);   //DLC_Name
            string   t3       = Path.GetDirectoryName(t2);   //DLC
            string   t4       = Path.GetDirectoryName(t3);   //BioGame
            string   gamebase = Path.GetDirectoryName(t4);   //Mass Effect3

            DebugOutput.PrintLn("Extracting DLC with gamebase : " + gamebase);
            DebugOutput.PrintLn("DLC name : " + t2);
            if (DLC.Files.Length > 1)
            {
                List <int> Indexes = new List <int>();
                for (int i = 0; i < DLC.Files.Length; i++)
                {
                    string DLCpath = DLC.Files[i].FileName;
                    for (int j = 0; j < patt.Length; j++)
                    {
                        if (DLCpath.ToLower().EndsWith(patt[j].Trim().ToLower()) && patt[j].Trim().ToLower() != "")
                        {
                            string relPath = GetRelativePath(DLCpath);
                            string outpath = gamebase + relPath;
                            DebugOutput.PrintLn("Extracting file #" + i.ToString("d4") + ": " + outpath);
                            if (!Directory.Exists(Path.GetDirectoryName(outpath)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(outpath));
                            }

                            if (!File.Exists(outpath))
                            {
                                using (FileStream fs = new FileStream(outpath, FileMode.Create))
                                    DLC.DecompressEntry(i).WriteTo(fs);
                            }
                            Indexes.Add(i);
                            Application.DoEvents();
                            break;
                        }
                    }
                }
                DLC.DeleteEntry(Indexes);
            }

            // AutoTOC
            DebugOutput.PrintLn("Updating DLC's PCConsoleTOC.bin");
            List <string> FileNames = toc.GetFiles(t2 + "\\");
            List <string> tet       = new List <string>(t2.Split('\\'));
            string        remov     = String.Join("\\", tet.ToArray());

            for (int i = 0; i < FileNames.Count; i++)
            {
                FileNames[i] = FileNames[i].Substring(remov.Length + 1);
            }
            string[] ts = t2.Split('\\');
            tet.Clear();
            tet.AddRange(ts);
            string basepath = String.Join("\\", tet.ToArray()) + '\\';
            string tocfile  = t2 + "\\PCConsoleTOC.bin";

            toc.CreateTOC(basepath, tocfile, FileNames.ToArray());
            DebugOutput.PrintLn("DLC Done.");
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DebuggerTextWriter" /> class.
 /// </summary>
 /// <param name="dbgEngDll">The DbgEngDll debugger engine.</param>
 /// <param name="outputType">Type of the output.</param>
 public DebuggerTextWriter(DbgEngDll dbgEngDll, DebugOutput outputType)
 {
     OutputType = outputType;
     outputCallbacksWide = dbgEngDll.Client.GetOutputCallbacksWide();
     outputCallbacks = dbgEngDll.Client.GetOutputCallbacks();
 }
示例#34
0
        private ME1Package(string path)
        {
            DebugOutput.PrintLn("Load file : " + path);
            FileName = Path.GetFullPath(path);
            MemoryStream tempStream = new MemoryStream();

            if (!File.Exists(FileName))
            {
                throw new FileNotFoundException("PCC file not found");
            }
            using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read))
            {
                FileInfo tempInfo = new FileInfo(FileName);
                tempStream.WriteFromStream(fs, tempInfo.Length);
                if (tempStream.Length != tempInfo.Length)
                {
                    throw new FileLoadException("File not fully read in. Try again later");
                }
            }

            tempStream.Seek(12, SeekOrigin.Begin);
            int tempNameSize = tempStream.ReadValueS32();

            tempStream.Seek(64 + tempNameSize, SeekOrigin.Begin);
            int tempGenerations = tempStream.ReadValueS32();

            tempStream.Seek(36 + tempGenerations * 12, SeekOrigin.Current);
            int tempPos = (int)tempStream.Position + 4;

            tempStream.Seek(0, SeekOrigin.Begin);
            header = tempStream.ReadBytes(tempPos);
            tempStream.Seek(0, SeekOrigin.Begin);

            if (magic != ZBlock.magic && magic.Swap() != ZBlock.magic)
            {
                DebugOutput.PrintLn("Magic number incorrect: " + magic);
                throw new FormatException("This is not an ME1 Package file. The magic number is incorrect.");
            }
            MemoryStream listsStream;

            if (IsCompressed)
            {
                DebugOutput.PrintLn("File is compressed");
                listsStream = CompressionHelper.DecompressME1orME2(tempStream);

                //Correct the header
                IsCompressed = false;
                listsStream.Seek(0, SeekOrigin.Begin);
                listsStream.WriteBytes(header);

                // Set numblocks to zero
                listsStream.WriteValueS32(0);
                //Write the magic number
                listsStream.WriteBytes(new byte[] { 0xF2, 0x56, 0x1B, 0x4E });
                // Write 4 bytes of 0
                listsStream.WriteValueS32(0);
            }
            else
            {
                DebugOutput.PrintLn("File already decompressed. Reading decompressed data.");
                //listsStream = tempStream;
                listsStream = new MemoryStream();
                tempStream.WriteTo(listsStream);
            }
            tempStream.Dispose();
            ReadNames(listsStream);
            ReadImports(listsStream);
            ReadExports(listsStream);
        }