示例#1
0
 private void startScanToolStripMenuItem_Click(object sender, EventArgs e)
 {
     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) + " ...");
         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);
         }
     }
     RefreshLists();
     pb1.Value = 0;
 }
示例#2
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));
         PCCObject pcc = new PCCObject(file);
         for (int j = 0; j < pcc.Exports.Count(); j++)
         {
             PCCObject.ExportEntry 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");
             }
         }
     }
     database.Sort((a,b) => a.filepath.CompareTo(b.filepath));
     BitConverter.IsLittleEndian = true;
     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();
 }
示例#3
0
 public void LoadDataBase()
 {
     FileStream fs = new FileStream(DataBaseFile, FileMode.Open, FileAccess.Read);
     BitConverter.IsLittleEndian = true;
     database = new List<DBEntry>();
     byte[] buff = new byte[4];
     fs.Read(buff, 0, 4);
     int count = BitConverter.ToInt32(buff,0);
     for (int i = 0; i < count; i++) 
     {
         DBEntry e = new DBEntry();
         fs.Read(buff, 0, 4);
         e.index = BitConverter.ToInt32(buff, 0);
         fs.Read(buff, 0, 4);
         e.count = BitConverter.ToInt32(buff, 0);
         fs.Read(buff, 0, 4);
         int len = BitConverter.ToInt32(buff, 0);
         e.filepath = "";
         for (int j = 0; j < len; j++)
             e.filepath += (char)fs.ReadByte();
         database.Add(e);
     }
     fs.Close();            
 }
示例#4
0
        public void ReadIntoTable(ref DBEntry entry, BinaryReader dbReader, Dictionary <int, string> StringTable)
        {
            if (entry.Header.RecordCount == 0)
            {
                return;
            }

            TypeCode[] columnTypes = entry.Data.Columns.Cast <DataColumn>().Select(x => Type.GetTypeCode(x.DataType)).ToArray();
            int[]      padding     = entry.TableStructure.Padding.ToArray();
            Array.Resize(ref padding, entry.Data.Columns.Count);

            FieldStructureEntry[] bits = entry.GetBits();
            int recordcount            = Math.Max(entry.Header.OffsetLengths.Length, (int)entry.Header.RecordCount);

            uint recordsize = entry.Header.RecordSize + (uint)(entry.Header.HasIndexTable ? 4 : 0);

            if (entry.Header.InternalRecordSize > 0)
            {
                recordsize = entry.Header.InternalRecordSize;
            }

            entry.Data.BeginLoadData();

            for (uint i = 0; i < recordcount; i++)
            {
                //Offset map has variable record lengths
                if (entry.Header.IsTypeOf <HTFX>() || entry.Header.HasOffsetTable)
                {
                    recordsize = (uint)entry.Header.OffsetLengths[i];
                }

                //Store start position
                long offset = dbReader.BaseStream.Position;

                //Create row and add data
                var row = entry.Data.NewRow();
                for (int j = 0; j < entry.Data.Columns.Count; j++)
                {
                    if (entry.Data.Columns[j].ExtendedProperties.ContainsKey(AUTO_GENERATED))
                    {
                        row.SetField(entry.Data.Columns[j], entry.Data.Rows.Count + 1);
                        continue;
                    }

                    switch (columnTypes[j])
                    {
                    case TypeCode.Boolean:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadBoolean());
                        dbReader.BaseStream.Position += sizeof(bool) * padding[j];
                        break;

                    case TypeCode.SByte:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadSByte());
                        dbReader.BaseStream.Position += sizeof(sbyte) * padding[j];
                        break;

                    case TypeCode.Byte:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadByte());
                        dbReader.BaseStream.Position += sizeof(byte) * padding[j];
                        break;

                    case TypeCode.Int16:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadInt16());
                        dbReader.BaseStream.Position += sizeof(short) * padding[j];
                        break;

                    case TypeCode.UInt16:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadUInt16());
                        dbReader.BaseStream.Position += sizeof(ushort) * padding[j];
                        break;

                    case TypeCode.Int32:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadInt32(bits[j]));
                        dbReader.BaseStream.Position += sizeof(int) * padding[j];
                        break;

                    case TypeCode.UInt32:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadUInt32(bits[j]));
                        dbReader.BaseStream.Position += sizeof(uint) * padding[j];
                        break;

                    case TypeCode.Int64:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadInt64(bits[j]));
                        dbReader.BaseStream.Position += sizeof(long) * padding[j];
                        break;

                    case TypeCode.UInt64:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadUInt64(bits[j]));
                        dbReader.BaseStream.Position += sizeof(ulong) * padding[j];
                        break;

                    case TypeCode.Single:
                        row.SetField(entry.Data.Columns[j], dbReader.ReadSingle());
                        dbReader.BaseStream.Position += sizeof(float) * padding[j];
                        break;

                    case TypeCode.String:
                        if (entry.Header.IsTypeOf <WDB>() || entry.Header.IsTypeOf <HTFX>() || entry.Header.HasOffsetTable)
                        {
                            row.SetField(entry.Data.Columns[j], dbReader.ReadStringNull());
                        }
                        else
                        {
                            int stindex = dbReader.ReadInt32();
                            if (StringTable.ContainsKey(stindex))
                            {
                                row.SetField(entry.Data.Columns[j], StringTable[stindex]);
                            }
                            else
                            {
                                row.SetField(entry.Data.Columns[j], "String not found");
                                ErrorMessage = "Strings not found in string table";
                            }
                        }
                        break;

                    default:
                        dbReader.BaseStream.Position += 4;
                        break;
                    }
                }

                entry.Data.Rows.Add(row);

                //Scrub to the end of the record
                if (dbReader.BaseStream.Position - offset < recordsize)
                {
                    dbReader.BaseStream.Position += (recordsize - (dbReader.BaseStream.Position - offset));
                }
                else if (dbReader.BaseStream.Position - offset > recordsize)
                {
                    throw new Exception("Definition exceeds record size");
                }
            }

            entry.Data.EndLoadData();
        }
        public void Write(DBEntry entry, string savepath)
        {
            using (var fs = new FileStream(savepath, FileMode.Create))
                using (var ms = new MemoryStream())
                    using (var bw = new BinaryWriter(ms))
                    {
                        StringTable st = new StringTable(entry.Header.ExtendedStringTable);         //Preloads null byte(s)
                        entry.Header.WriteHeader(bw, entry);

                        if (!entry.Header.IsTypeOf <WDC1>())
                        {
                            if (entry.Header.IsTypeOf <WDB5>() && !entry.Header.HasOffsetTable && entry.Header.CopyTableSize > 0)
                            {
                                WriteIntoFile(entry, bw, entry.GetUniqueRows().ToArray(), ref st);                 //Insert unique rows
                            }
                            else
                            {
                                WriteIntoFile(entry, bw, entry.Data.AsEnumerable(), ref st);                 //Insert all rows
                            }


                            //Copy StringTable and StringTable size if it doesn't have inline strings
                            if (st.Size > 0 && !entry.Header.HasOffsetTable)
                            {
                                long pos = bw.BaseStream.Position;
                                bw.Scrub(entry.Header.StringTableOffset);
                                bw.Write(st.Size);
                                bw.Scrub(pos);
                                st.CopyTo(bw.BaseStream);
                            }
                            st.Dispose();

                            //Legion+ only
                            if (entry.Header.IsLegionFile)
                            {
                                //WCH7 Map
                                if (entry.Header is WCH7 wch7)
                                {
                                    bw.WriteArray(wch7.WCH7Table);
                                }

                                //OffsetMap
                                if (entry.Header.HasOffsetTable)
                                {
                                    //Update StringTableOffset with current position
                                    long pos = bw.BaseStream.Position;
                                    bw.Scrub(entry.Header.StringTableOffset);
                                    bw.Write((int)pos);
                                    bw.Scrub(pos);

                                    entry.Header.WriteOffsetMap(bw, entry, OffsetMap);

                                    OffsetMap.Clear();                     //Cleanup
                                }

                                //Index Table
                                if (entry.Header.HasIndexTable)
                                {
                                    entry.Header.WriteIndexTable(bw, entry);
                                }

                                //CopyTable - WDB5 only
                                (entry.Header as WDB5)?.WriteCopyTable(bw, entry);

                                //CommonDataTable
                                (entry.Header as WDB6)?.WriteCommonDataTable(bw, entry);
                            }
                        }

                        //Copy data to file
                        ms.Position = 0;
                        ms.CopyTo(fs);

                        //Reset write temp data
                        entry.ResetTemp();
                    }
        }
示例#6
0
        public void CounterStatusCheck()
        {
            //Für den ServiceProviderMock
            //Muss enthalten sein, damit der Mock nicht überschrieben wird
            IServiceProvider unused = ServiceManager.ServiceProvider;

            //Feld Infos holen
            System.Reflection.FieldInfo instance = typeof(ServiceManager).GetField("_serviceProvider", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            //Mocksaufsetzen
            //ServiceProvider
            Mock <IServiceProvider>        mockSingleton        = new Mock <IServiceProvider>();
            Mock <IActivityManager>        activityManagerMock  = new Mock <IActivityManager>();
            Mock <IServiceProvider>        activityProviderMock = new Mock <IServiceProvider>();
            Mock <AbstractStepActivity>    stepActivityMock     = new Mock <AbstractStepActivity>();
            Mock <AbstractRunningActivity> runningActivityMock  = new Mock <AbstractRunningActivity>();
            Mock <IEarablesConnection>     connectionMock       = new Mock <IEarablesConnection>();
            Mock <IPopUpService>           popUpMock            = new Mock <IPopUpService>();

            //ActivityManager
            activityManagerMock.Setup(x => x.ActitvityProvider).Returns(activityProviderMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractRunningActivity))).Returns(runningActivityMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractStepActivity))).Returns(stepActivityMock.Object);

            //IDataBaseConnection
            Mock <IDataBaseConnection> mockDataBase = new Mock <IDataBaseConnection>();
            List <DBEntry>             entries      = new List <DBEntry>();

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.GetMostRecentEntries(1)).Returns(entries);

            DateTime _dt       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            DBEntry  _entryNew = new DBEntry(_dt, 10, 0, 0);

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.SaveDBEntry(_entryNew)).Returns(1);

            //ServiceManager
            mockSingleton.Setup(x => x.GetService(typeof(IDataBaseConnection))).Returns(mockDataBase.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IActivityManager))).Returns(activityManagerMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IEarablesConnection))).Returns(connectionMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IPopUpService))).Returns(popUpMock.Object);

            //Connection
            ScanningPopUpViewModel.IsConnected = true;
            connectionMock.As <IEarablesConnection>().Setup(x => x.StartSampling());

            //ServiceProvider anlegen
            instance.SetValue(null, mockSingleton.Object);

            //Test
            StepModeViewModel viewModel = new StepModeViewModel();

            viewModel.StartActivity();
            Assert.Equal("--:--", viewModel.StepFrequency);
            viewModel.OnActivityDone(this, null);
            viewModel.OnActivityDone(this, null);
            viewModel.OnActivityDone(this, null);
            viewModel.OnRunningDone(this, new RunningEventArgs(true));
            Assert.Equal(3, viewModel.StepCounter);
            Assert.True(viewModel.IsRunning);
            Assert.NotNull(viewModel.StepFrequency);
            Assert.Equal("Du läufst!", viewModel.StatusDisplay);
            viewModel.OnRunningDone(this, new RunningEventArgs(false));
            Assert.False(viewModel.IsRunning);

            viewModel.StopActivity();
            Assert.Equal(3, viewModel.StepCounter);
            viewModel.StartActivity();
            Assert.Equal(0, viewModel.StepCounter);
            Assert.False(viewModel.IsRunning);
        }
示例#7
0
文件: WDB6.cs 项目: w9jds/WDBXEditor
        public virtual void WriteCommonDataTable(BinaryWriter bw, DBEntry entry)
        {
            if (CommonDataTableSize == 0)
            {
                return;
            }

            long start = bw.BaseStream.Position; //Current position
            var  rows  = entry.Data.Rows.Cast <DataRow>();

            bw.WriteUInt32((uint)FieldStructure.Count); //Field count

            for (int i = 0; i < FieldStructure.Count; i++)
            {
                var field        = TableStructure.Fields[i].InternalName;
                var defaultValue = TableStructure.Fields[i].DefaultValue;
                var typeCode     = Type.GetTypeCode(entry.Data.Columns[field].DataType);
                var pk           = entry.Data.PrimaryKey[0];

                var numberDefault             = string.IsNullOrEmpty(defaultValue) ? "0" : defaultValue;
                Dictionary <int, byte[]> data = new Dictionary <int, byte[]>();
                int padding = 0;

                //Only get data if CommonDataTable
                if (FieldStructure[i].CommonDataColumn)
                {
                    switch (typeCode)
                    {
                    case TypeCode.String:
                        data = rows.Where(x => (string)x[field] != defaultValue).ToDictionary(x => (int)x[pk], y => Encoding.UTF8.GetBytes((string)y[field]));
                        break;

                    case TypeCode.UInt16:
                        data    = rows.Where(x => (ushort)x[field] != ushort.Parse(numberDefault)).ToDictionary(x => (int)x[pk], y => BitConverter.GetBytes((ushort)y[field]));
                        padding = 2;
                        break;

                    case TypeCode.Int16:
                        data    = rows.Where(x => (short)x[field] != short.Parse(numberDefault)).ToDictionary(x => (int)x[pk], y => BitConverter.GetBytes((short)y[field]));
                        padding = 2;
                        break;

                    case TypeCode.Single:
                        data = rows.Where(x => (float)x[field] != float.Parse(numberDefault)).ToDictionary(x => (int)x[pk], y => BitConverter.GetBytes((float)y[field]));
                        break;

                    case TypeCode.Int32:
                        data = rows.Where(x => (int)x[field] != int.Parse(numberDefault)).ToDictionary(x => (int)x[pk], y => BitConverter.GetBytes((int)y[field]));
                        break;

                    case TypeCode.UInt32:
                        data = rows.Where(x => (uint)x[field] != uint.Parse(numberDefault)).ToDictionary(x => (int)x[pk], y => BitConverter.GetBytes((uint)y[field]));
                        break;

                    case TypeCode.Byte:
                        data    = rows.Where(x => (byte)x[field] != byte.Parse(numberDefault)).ToDictionary(x => (int)x[pk], y => new byte[] { (byte)y[field] });
                        padding = 3;
                        break;

                    default:
                        continue;
                    }
                }

                bw.WriteInt32(data.Count);           //Count
                bw.Write(CommonDataTypes[typeCode]); //Type code
                foreach (var d in data)
                {
                    bw.WriteInt32(d.Key); //Id
                    bw.Write(d.Value);    //Value

                    if ((TableStructure == null || TableStructure?.Build >= 24492) && padding > 0)
                    {
                        bw.BaseStream.Position += padding;
                    }
                }
            }

            //Set CommonDataTableSize
            long pos = bw.BaseStream.Position;

            bw.Scrub(0x34);
            bw.WriteInt32((int)(pos - start));
            bw.Scrub(pos);
        }
        public void ActivityListCheck()
        {
            //Für den ServiceProviderMock
            //Muss enthalten sein, damit der Mock nicht überschrieben wird
            IServiceProvider unused = ServiceManager.ServiceProvider;

            //Feld Infos holen
            System.Reflection.FieldInfo instance = typeof(ServiceManager).GetField("_serviceProvider",
                                                                                   System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            //Mocksaufsetzen
            //ServiceProvider
            Mock <IServiceProvider>       mockSingleton        = new Mock <IServiceProvider>();
            Mock <IActivityManager>       activityManagerMock  = new Mock <IActivityManager>();
            Mock <IServiceProvider>       activityProviderMock = new Mock <IServiceProvider>();
            Mock <AbstractSitUpActivity>  sitUpActivityMock    = new Mock <AbstractSitUpActivity>();
            Mock <AbstractPushUpActivity> pushUpActivityMock   = new Mock <AbstractPushUpActivity>();
            Mock <IEarablesConnection>    connectionMock       = new Mock <IEarablesConnection>();
            Mock <IPopUpService>          popUpMock            = new Mock <IPopUpService>();

            //ActivityManager
            activityManagerMock.Setup(x => x.ActitvityProvider).Returns(activityProviderMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractSitUpActivity)))
            .Returns(sitUpActivityMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractPushUpActivity)))
            .Returns(pushUpActivityMock.Object);

            //IDataBaseConnection
            Mock <IDataBaseConnection> mockDataBase = new Mock <IDataBaseConnection>();

            DateTime _dt       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            DBEntry  _entryNew = new DBEntry(_dt, 10, 0, 0);

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.SaveDBEntry(_entryNew)).Returns(1);

            //PopUpService
            popUpMock.SetupSequence(x =>
                                    x.ActionSheet("Wähle eine Aktivität:", "Abbruch", null, "Liegestütze", "Sit-ups", "Pause"))
            .Returns(Task.Run(() => { return("Liegestütze"); }))
            .Returns(Task.Run(() => { return("Liegestütze"); }));
            popUpMock.SetupSequence(x => x.DisplayPrompt("Liegestütze", "Gebe die Anzahl Wiederholungen an:", "Okay",
                                                         "Abbruch", "10", 3, Keyboard.Numeric))
            .Returns(Task.Run(() => { return("12"); }))
            .Returns(Task.Run(() => { return("12"); }));

            //ServiceManager
            mockSingleton.Setup(x => x.GetService(typeof(IDataBaseConnection))).Returns(mockDataBase.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IActivityManager))).Returns(activityManagerMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IPopUpService))).Returns(popUpMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IEarablesConnection))).Returns(connectionMock.Object);

            //Connection
            ScanningPopUpViewModel.IsConnected = true;
            connectionMock.As <IEarablesConnection>().Setup(x => x.StartSampling());

            //ServiceProvider anlegen
            instance.SetValue(null, mockSingleton.Object);

            //Test
            ListenAndPerformViewModel viewModel = new ListenAndPerformViewModel();

            viewModel.AddActivityCommand.Execute(3);             //4
            Assert.Equal(4, viewModel.ActivityList.Count);
            IEnumerator <ActivityWrapper> iterator = viewModel.ActivityList.GetEnumerator();

            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            Assert.Equal("Liegestütze", iterator.Current.Name);
            Assert.Equal(12, iterator.Current.Amount);

            viewModel.SelectedActivity = iterator.Current;
            viewModel.EditActivityCommand.Execute(null);
            iterator = viewModel.ActivityList.GetEnumerator();
            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            iterator.MoveNext();
            viewModel.SelectedActivity = iterator.Current;
            viewModel.RemoveActivityCommand.Execute(null);
            Assert.Equal(3, viewModel.ActivityList.Count);
        }
示例#9
0
文件: DB.cs 项目: malinich/assist-lib
 public static string GetPath(DBEntry item)
 {
     CheckItems();
     return(_instance._items.ContainsKey(item) ? _instance._items[item] : null);
 }
示例#10
0
 public virtual void WriteOffsetMap(BinaryWriter bw, DBEntry entry, List <Tuple <int, short> > OffsetMap)
 {
 }
 public void SetParent(DBEntry newParent, string newKey)
 {
     _dbEntry = newParent;
     _key     = newKey;
 }
示例#12
0
文件: WDB5.cs 项目: lyosky/WDBXLib
 public virtual void WriteBaseHeader <T>(BinaryWriter bw, DBEntry <T> entry) where T : class
 {
     base.WriteHeader(bw, entry);
 }
示例#13
0
        private static void WriteValue <T>(BinaryWriter bw, DBEntry <T> entry, object value, uint padding, StringTable st, FieldStructureEntry bits, bool duplicates) where T : class
        {
            switch (Type.GetTypeCode(value.GetType()))
            {
            case TypeCode.SByte:
                bw.Write((sbyte)value);
                bw.BaseStream.Position += sizeof(sbyte) * padding;
                break;

            case TypeCode.Byte:
                bw.Write((byte)value);
                bw.BaseStream.Position += sizeof(byte) * padding;
                break;

            case TypeCode.Int16:
                bw.Write((short)value);
                bw.BaseStream.Position += sizeof(short) * padding;
                break;

            case TypeCode.UInt16:
                bw.Write((ushort)value);
                bw.BaseStream.Position += sizeof(ushort) * padding;
                break;

            case TypeCode.Int32:
                bw.WriteInt32((int)value, bits);
                bw.BaseStream.Position += sizeof(int) * padding;
                break;

            case TypeCode.UInt32:
                bw.WriteUInt32((uint)value, bits);
                bw.BaseStream.Position += sizeof(uint) * padding;
                break;

            case TypeCode.Int64:
                bw.WriteInt64((long)value, bits);
                bw.BaseStream.Position += sizeof(long) * padding;
                break;

            case TypeCode.UInt64:
                bw.WriteUInt64((ulong)value, bits);
                bw.BaseStream.Position += sizeof(ulong) * padding;
                break;

            case TypeCode.Single:
                bw.Write((float)value);
                bw.BaseStream.Position += sizeof(float) * padding;
                break;

            case TypeCode.String:
                if (entry.Header.HasOffsetTable)
                {
                    bw.Write(Encoding.UTF8.GetBytes(value.ToString()));
                    bw.Write((byte)0);
                }
                else
                {
                    bw.Write(st.Write(value.ToString(), duplicates));
                }
                break;

            default:
                throw new Exception($"Unknown TypeCode {value.GetType().Name}");
            }
        }
示例#14
0
 public static string GetLocalizationText(this DBEntry dBEntry, string key)
 {
     return($"{dBEntry.name}@{key}".GetLocalizationText());
 }
示例#15
0
        private static void WriteIntoFile <T>(DBEntry <T> entry, BinaryWriter bw, IEnumerable <T> rows, ref StringTable st) where T : class
        {
            TypeCode[]            columnTypes = entry.TableStructure.Select(x => Type.GetTypeCode(x.PropertyType)).ToArray();
            uint[]                padding     = entry.Padding.ToArray();
            FieldStructureEntry[] bits        = entry.GetBits();

            bool duplicates = false;

            duplicates |= (entry.Header.IsTypeOf <WDB2>() && entry.Header.MaxId != 0);       //WDB2 with MaxId > 0 allows duplicates
            duplicates |= (entry.Header.IsTypeOf <WCH7>() && entry.Header.UnknownWCH7 != 0); //WCH7 with Unknown > 0 allows duplicates

            T lastrow = rows.Last();

            foreach (T row in rows)
            {
                long offset = bw.BaseStream.Position;

                for (int j = 0; j < entry.TableStructure.Length; j++)
                {
                    PropertyInfo field = entry.TableStructure[j];

                    if (field.GetAttribute <DBKeyAttribute>()?.AutoGenerated == true) //Autogenerated so skip
                    {
                        continue;
                    }

                    if (entry.Header.HasIndexTable && j == 0) //Inline Id so skip
                    {
                        continue;
                    }

                    if (entry.Header.IsTypeOf <WCH5>() && entry.Header.HasOffsetTable && j == 0) //Inline Id so skip
                    {
                        continue;
                    }

                    if (entry.Header.IsTypeOf <WDB6>() && (bits?[j].CommonDataColumn ?? false))
                    {
                        continue;
                    }

                    if (columnTypes[j] == TypeCode.Object)
                    {
                        if (field.PropertyType.IsArray)
                        {
                            Array array = (Array)field.GetValue(row);
                            for (int x = 0; x < array.Length; x++)
                            {
                                WriteValue(bw, entry, array.GetValue(x), padding[j], st, bits?[j], duplicates);
                            }
                        }
                        else if (field.PropertyType == typeof(LocalizedString))
                        {
                            ((LocalizedString)field.GetValue(row)).Write(bw, st, duplicates);
                        }
                        else
                        {
                            throw new Exception($"Unknown Type {field.PropertyType.Name}.");
                        }
                    }
                    else
                    {
                        WriteValue(bw, entry, field.GetValue(row), padding[j], st, bits?[j], duplicates);
                    }
                }

                //Calculate and write the row's padding
                entry.Header.WriteRecordPadding(bw, entry, offset);

                //Store the offset map
                if (entry.Header.HasOffsetTable)
                {
                    OffsetMap.Add(new Tuple <int, short>((int)offset, (short)(bw.BaseStream.Position - offset)));
                }

                //WDB5 + OffsetMap without SecondIndex for the last row pads to next mod 4
                if (entry.Header.IsTypeOf <WDB5>() && entry.Header.HasOffsetTable && !entry.Header.HasSecondIndex && row == lastrow)
                {
                    long rem = bw.BaseStream.Position % 4;
                    bw.BaseStream.Position += (rem == 0 ? 0 : (4 - rem));
                }
            }
        }
示例#16
0
        public static void Write <T>(DBEntry <T> entry, string savepath) where T : class
        {
            if (entry.Rows.HasDuplicateKeys)
            {
                throw new Exception("Collection contains duplicate keys");
            }


            using (var fs = new FileStream(savepath, FileMode.Create))
                using (var ms = new MemoryStream())
                    using (var bw = new BinaryWriter(ms))
                    {
                        StringTable stringtable = new StringTable(entry.Header.ExtendedStringTable); //Preloads null byte(s)
                        entry.Header.WriteHeader(bw, entry);

                        if (entry.Header.IsTypeOf <WDB5>() && !entry.Header.HasOffsetTable && entry.Header.CopyTableSize > 0)
                        {
                            WriteIntoFile(entry, bw, entry.GetUniqueRows().ToArray(), ref stringtable); //Insert unique rows
                        }
                        else
                        {
                            WriteIntoFile(entry, bw, entry.Rows.AsEnumerable(), ref stringtable); //Insert all rows
                        }

                        //Copy StringTable and StringTable size if it doesn't have inline strings
                        if (stringtable.Size > 0 && !entry.Header.HasOffsetTable)
                        {
                            long pos = bw.BaseStream.Position;
                            bw.Scrub(entry.Header.StringTableOffset);
                            bw.Write(stringtable.Size);
                            bw.Scrub(pos);
                            stringtable.CopyTo(bw.BaseStream);
                        }
                        stringtable.Dispose();

                        //Legion+ only
                        if (entry.Header.IsLegionFile)
                        {
                            //WCH7 Map
                            if (entry.Header.IsTypeOf <WCH7>())
                            {
                                bw.WriteArray(((WCH7)entry.Header).WCH7Table);
                            }

                            //OffsetMap
                            if (entry.Header.HasOffsetTable)
                            {
                                //Update StringTableOffset with current position
                                long pos = bw.BaseStream.Position;
                                bw.Scrub(entry.Header.StringTableOffset);
                                bw.Write((int)pos);
                                bw.Scrub(pos);

                                entry.Header.WriteOffsetMap(bw, entry, OffsetMap);

                                OffsetMap.Clear(); //Cleanup
                            }

                            //Index Table
                            if (entry.Header.HasIndexTable)
                            {
                                entry.Header.WriteIndexTable(bw, entry);
                            }

                            //CopyTable - WDB5 only
                            if (entry.Header.IsTypeOf <WDB5>())
                            {
                                ((WDB5)entry.Header).WriteCopyTable(bw, entry);
                            }

                            //CommonDataTable
                            if (entry.Header.IsTypeOf <WDB6>())
                            {
                                ((WDB6)entry.Header).WriteCommonDataTable(bw, entry);
                            }
                        }

                        //Copy data to file
                        ms.Position = 0;
                        ms.CopyTo(fs);
                    }
        }
示例#17
0
        private static object ReadValue <T>(BinaryReader dbReader, DBEntry <T> entry, TypeCode type, uint padding, Dictionary <int, string> StringTable, FieldStructureEntry bits) where T : class
        {
            object value;

            switch (type)
            {
            case TypeCode.Boolean:
                value = dbReader.ReadBoolean();
                dbReader.BaseStream.Position += sizeof(bool) * padding;
                break;

            case TypeCode.SByte:
                value = dbReader.ReadSByte();
                dbReader.BaseStream.Position += sizeof(sbyte) * padding;
                break;

            case TypeCode.Byte:
                value = dbReader.ReadByte();
                dbReader.BaseStream.Position += sizeof(byte) * padding;
                break;

            case TypeCode.Int16:
                value = dbReader.ReadInt16();
                dbReader.BaseStream.Position += sizeof(short) * padding;
                break;

            case TypeCode.UInt16:
                value = dbReader.ReadUInt16();
                dbReader.BaseStream.Position += sizeof(ushort) * padding;
                break;

            case TypeCode.Int32:
                value = dbReader.ReadInt32(bits);
                dbReader.BaseStream.Position += sizeof(int) * padding;
                break;

            case TypeCode.UInt32:
                value = dbReader.ReadUInt32(bits);
                dbReader.BaseStream.Position += sizeof(uint) * padding;
                break;

            case TypeCode.Int64:
                value = dbReader.ReadInt64(bits);
                dbReader.BaseStream.Position += sizeof(long) * padding;
                break;

            case TypeCode.UInt64:
                value = dbReader.ReadUInt64(bits);
                dbReader.BaseStream.Position += sizeof(ulong) * padding;
                break;

            case TypeCode.Single:
                value = dbReader.ReadSingle();
                dbReader.BaseStream.Position += sizeof(float) * padding;
                break;

            case TypeCode.String:
                if (entry.Header.IsTypeOf <WDB>() || entry.Header.IsTypeOf <HTFX>() || entry.Header.HasOffsetTable)
                {
                    value = dbReader.ReadStringNull();
                }
                else
                {
                    int stindex = dbReader.ReadInt32();
                    if (!StringTable.ContainsKey(stindex))
                    {
                        throw new Exception("Strings not found in string table");
                    }

                    value = StringTable[stindex];
                }
                break;

            default:
                throw new Exception($"Unknown TypeCode");
            }

            return(value);
        }
示例#18
0
        private static void ReadIntoTable <T>(ref DBEntry <T> entry, BinaryReader dbReader, Dictionary <int, string> stringtable) where T : class
        {
            if (entry.Header.RecordCount == 0)
            {
                return;
            }

            TypeCode[] columnTypes = entry.TableStructure.Select(x => Type.GetTypeCode(x.PropertyType)).ToArray();
            uint[]     padding     = entry.Padding.ToArray();

            FieldStructureEntry[] bits = entry.GetBits();
            int  recordcount           = Math.Max(entry.Header.OffsetLengths.Length, (int)entry.Header.RecordCount);
            uint recordsize            = entry.Header.RecordSize + (uint)(entry.Header.HasIndexTable ? 4 : 0);

            if (entry.Header.CommonDataTableSize > 0)
            {
                recordsize = ((WDB6)entry.Header).RawRecordSize;
            }

            for (uint i = 0; i < recordcount; i++)
            {
                //Offset map has variable record lengths
                if (entry.Header.HasOffsetTable || entry.Header.IsTypeOf <HTFX>())
                {
                    recordsize = (uint)entry.Header.OffsetLengths[i];
                }

                //Store start position
                long offset = dbReader.BaseStream.Position;

                //Create row and add data
                T row = (T)Activator.CreateInstance(typeof(T));

                for (int j = 0; j < entry.TableStructure.Length; j++)
                {
                    PropertyInfo field = entry.TableStructure[j];

                    if (entry.TableStructure[j].GetAttribute <DBKeyAttribute>()?.AutoGenerated == true)
                    {
                        field.SetValue(row, entry.Rows.Count + 1);
                        continue;
                    }

                    if (columnTypes[j] == TypeCode.Object)
                    {
                        if (field.PropertyType.IsArray)
                        {
                            uint     arraySize = field.GetAttribute <DBFieldAttribute>().ArraySize;
                            TypeCode type      = Type.GetTypeCode(field.PropertyType.GetElementType());

                            Array array = Array.CreateInstance(field.PropertyType.GetElementType(), arraySize);
                            for (int x = 0; x < arraySize; x++)
                            {
                                array.SetValue(ReadValue(dbReader, entry, type, padding[j], stringtable, bits[j]), x);
                            }

                            field.SetValue(row, array);
                        }
                        else if (field.PropertyType == typeof(LocalizedString))
                        {
                            LocalizedString locale = new LocalizedString(entry.Build);
                            locale.Load(dbReader, stringtable);
                            field.SetValue(row, locale);
                        }
                        else
                        {
                            throw new Exception($"Unknown Type {field.PropertyType.Name}");
                        }
                    }
                    else
                    {
                        field.SetValue(row, ReadValue(dbReader, entry, columnTypes[j], padding[j], stringtable, bits[j]));
                    }
                }

                entry.Rows.Add(row);

                //Scrub to the end of the record
                if (dbReader.BaseStream.Position - offset < recordsize)
                {
                    dbReader.BaseStream.Position += (recordsize - (dbReader.BaseStream.Position - offset));
                }
                else if (dbReader.BaseStream.Position - offset > recordsize)
                {
                    throw new Exception("Definition exceeds record size");
                }
            }
        }
示例#19
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
                {
                    using (ME3Package pcc = MEPackageHandler.OpenME3Package(file))
                    {
                        DBEntry ent = new DBEntry();
                        ent.filename = Path.GetFileName(file);
                        ent.Objects  = new List <ObjInf>();
                        IReadOnlyList <IExportEntry> Exports = pcc.Exports;
                        for (int i = 0; i < Exports.Count; i++)
                        {
                            IExportEntry ex = 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;
        }
示例#20
0
 public static string GetLocalizationText(this DBEntry dBEntry, string key)
 {
     return(Localization.Translate(string.Format("{0}@{1}", dBEntry.name, key)));
 }
示例#21
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
                {
                    PCCObject pcc = new PCCObject(file);
                    for (int j = 0; j < pcc.Exports.Count(); j++)
                    {
                        PCCObject.ExportEntry 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));
            BitConverter.IsLittleEndian = true;
            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();
        }
示例#22
0
文件: WCH5.cs 项目: lyosky/WDBXLib
 public override void WriteRecordPadding <T>(BinaryWriter bw, DBEntry <T> entry, long offset)
 {
 }
示例#23
0
        public static void PopulateToolStripMenuWithDBEntries(ToolStripItemCollection itemCollection, Type dbEntryType, ToolStripItemClickedEventHandler onClickEventHandler = null, bool addRandomOption = false, string tagPrefix = "")
        {
            if (addRandomOption)
            {
                itemCollection.Add("(Random)").Tag = "";
            }

            foreach (string id in Database.Instance.GetAllEntriesIDs(dbEntryType))
            {
                ToolStripItemCollection parentCollection = itemCollection;

                DBEntry dbEntry = Database.Instance.GetEntry(dbEntryType, id);
                if (dbEntry == null)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(dbEntry.UICategory)) // Database entry belong to a collection
                {
                    string categoryName = dbEntry.UICategory;
                    string categoryID   = "*" + dbEntry.UICategory;

                    if (!parentCollection.ContainsKey(categoryID))
                    {
                        ToolStripItem categoryItem = parentCollection.Add(categoryName);

                        categoryItem.Name      = categoryID;
                        categoryItem.BackColor = BLUEPRINT_BACKCOLOR_MENU;
                        categoryItem.Font      = BLUEPRINT_FONT;
                        categoryItem.ForeColor = BLUEPRINT_FORECOLOR;
                    }

                    parentCollection = ((ToolStripMenuItem)parentCollection[categoryID]).DropDownItems;
                }

                ToolStripMenuItem item = new ToolStripMenuItem
                {
                    Text        = dbEntry.UIDisplayName,
                    ToolTipText = dbEntry.UIDescription,
                    Tag         = tagPrefix + id,
                    BackColor   = BLUEPRINT_BACKCOLOR_MENU,
                    Font        = BLUEPRINT_FONT,
                    ForeColor   = BLUEPRINT_FORECOLOR,
                };

                parentCollection.Add(item);
            }

            foreach (ToolStripMenuItem item in itemCollection)
            {
                if (item.DropDownItems.Count > 0)
                {
                    if (onClickEventHandler != null)
                    {
                        item.DropDownItemClicked += onClickEventHandler;
                    }
                    SortContextMenuStrip(item.DropDownItems);
                }
            }

            SortContextMenuStrip(itemCollection);
        }
示例#24
0
 public virtual void WriteIndexTable(BinaryWriter bw, DBEntry entry)
 {
 }
示例#25
0
 private void loadDBToolStripMenuItem_Click(object sender, EventArgs e)
 {
     OpenFileDialog d = new OpenFileDialog();
     d.Filter = "*.db|*.db";
     if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         FileStream fs = new FileStream(d.FileName, FileMode.Open, FileAccess.Read);
         
         int magic = ReadInt32(fs);
         if (magic != 0x12345678)
         {
             MessageBox.Show("Not a database!");
             fs.Close();
             return;
         }
         int count = ReadInt32(fs);
         database = new List<DBEntry>();
         for (int i = 0; i < count; i++)
         {
             DBEntry en = new DBEntry();
             en.filename = ReadString(fs);
             en.Objects = new List<ObjInf>();
             int count2 = ReadInt32(fs);
             for (int j = 0; j < count2; j++)
             {
                 ObjInf o = new ObjInf();
                 o.Index = ReadInt32(fs);
                 o.Type = ReadInt32(fs);
                 o.name = ReadString(fs);
                 en.Objects.Add(o);
             }
             database.Add(en);
         }
         fs.Close();
         RefreshLists();
         MessageBox.Show("Done");
     }
 }
        public void ConstructorCheck()
        {
            //Für den ServiceProviderMock
            //Muss enthalten sein, damit der Mock nicht überschrieben wird
            IServiceProvider unused = ServiceManager.ServiceProvider;

            //Feld Infos holen
            System.Reflection.FieldInfo instance = typeof(ServiceManager).GetField("_serviceProvider",
                                                                                   System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            //Mocksaufsetzen
            //ServiceProvider
            Mock <IServiceProvider>       mockSingleton        = new Mock <IServiceProvider>();
            Mock <IActivityManager>       activityManagerMock  = new Mock <IActivityManager>();
            Mock <IServiceProvider>       activityProviderMock = new Mock <IServiceProvider>();
            Mock <AbstractSitUpActivity>  sitUpActivityMock    = new Mock <AbstractSitUpActivity>();
            Mock <AbstractPushUpActivity> pushUpActivityMock   = new Mock <AbstractPushUpActivity>();
            Mock <IEarablesConnection>    connectionMock       = new Mock <IEarablesConnection>();
            Mock <IPopUpService>          popUpMock            = new Mock <IPopUpService>();

            //ActivityManager
            activityManagerMock.Setup(x => x.ActitvityProvider).Returns(activityProviderMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractSitUpActivity)))
            .Returns(sitUpActivityMock.Object);
            activityProviderMock.Setup(x => x.GetService(typeof(AbstractPushUpActivity)))
            .Returns(pushUpActivityMock.Object);

            //IDataBaseConnection
            Mock <IDataBaseConnection> mockDataBase = new Mock <IDataBaseConnection>();

            DateTime _dt       = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            DBEntry  _entryNew = new DBEntry(_dt, 10, 0, 0);

            mockDataBase.As <IDataBaseConnection>().Setup(x => x.SaveDBEntry(_entryNew)).Returns(1);

            //ServiceManager
            mockSingleton.Setup(x => x.GetService(typeof(IDataBaseConnection))).Returns(mockDataBase.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IActivityManager))).Returns(activityManagerMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IPopUpService))).Returns(popUpMock.Object);
            mockSingleton.Setup(x => x.GetService(typeof(IEarablesConnection))).Returns(connectionMock.Object);

            //Connection
            ScanningPopUpViewModel.IsConnected = true;
            connectionMock.As <IEarablesConnection>().Setup(x => x.StartSampling());

            //ServiceProvider anlegen
            instance.SetValue(null, mockSingleton.Object);

            //Test
            ListenAndPerformViewModel     viewModel = new ListenAndPerformViewModel();
            IEnumerator <ActivityWrapper> iterator  = viewModel.ActivityList.GetEnumerator();

            Assert.Equal(3, viewModel.ActivityList.Count);
            iterator.MoveNext();
            Assert.Equal("Liegestütze", iterator.Current.Name);
            iterator.MoveNext();
            Assert.Equal("Pause", iterator.Current.Name);
            iterator.MoveNext();
            Assert.Equal("Sit-ups", iterator.Current.Name);
            viewModel.Milliseconds = "0";
            viewModel.Seconds      = "0";
            viewModel.Minutes      = "0";
            Assert.Equal("0", viewModel.Milliseconds);
            Assert.Equal("0", viewModel.Seconds);
            Assert.Equal("0", viewModel.Minutes);
        }
示例#27
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
         {
             using (ME3Package pcc = MEPackageHandler.OpenME3Package(file))
             {
                 DBEntry ent = new DBEntry();
                 ent.filename = Path.GetFileName(file);
                 ent.Objects = new List<ObjInf>();
                 IReadOnlyList<IExportEntry> Exports = pcc.Exports;
                 for (int i = 0; i < Exports.Count; i++)
                 {
                     IExportEntry ex = 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;
 }
        public DBEntry Read(MemoryStream stream, string dbFile)
        {
            FileName        = dbFile;
            stream.Position = 0;

            using (var dbReader = new BinaryReader(stream, Encoding.UTF8))
            {
                DBHeader header = ExtractHeader(dbReader);
                long     pos    = dbReader.BaseStream.Position;

                //No header - must be invalid
                if (header == null)
                {
                    throw new Exception("Unknown file type.");
                }

                if (header.CheckRecordSize && header.RecordSize == 0)
                {
                    throw new Exception("File contains no records.");
                }
                if (header.CheckRecordCount && header.RecordCount == 0)
                {
                    throw new Exception("File contains no records.");
                }

                DBEntry entry = new DBEntry(header, dbFile);
                if (header.CheckTableStructure && entry.TableStructure == null)
                {
                    throw new Exception("Definition missing.");
                }

                if (header is WDC1 wdc1)
                {
                    Dictionary <int, string> StringTable = wdc1.ReadStringTable(dbReader);
                    wdc1.LoadDefinitionSizes(entry);

                    //Read the data
                    using (MemoryStream ms = new MemoryStream(header.ReadData(dbReader, pos)))
                        using (BinaryReader dataReader = new BinaryReader(ms, Encoding.UTF8))
                        {
                            wdc1.AddRelationshipColumn(entry);
                            //wdc1.SetColumnMinMaxValues(entry);
                            ReadIntoTable(ref entry, dataReader, StringTable);
                        }

                    stream.Dispose();
                    return(entry);
                }
                else if (header.IsTypeOf <WDBC>() || header.IsTypeOf <WDB2>())
                {
                    long stringTableStart = dbReader.BaseStream.Position += header.RecordCount * header.RecordSize;
                    Dictionary <int, string> StringTable = new StringTable().Read(dbReader, stringTableStart);                    //Get stringtable
                    dbReader.Scrub(pos);

                    ReadIntoTable(ref entry, dbReader, StringTable);                     //Read data

                    stream.Dispose();
                    return(entry);
                }
                else if (header.IsTypeOf <WDB5>() || header.IsTypeOf <WCH5>() || header.IsTypeOf <WDB6>())
                {
                    int  CopyTableSize       = header.CopyTableSize;              //Only WDB5 has a copy table
                    uint CommonDataTableSize = header.CommonDataTableSize;        //Only WDB6 has a CommonDataTable

                    //StringTable - only if applicable
                    long copyTablePos     = dbReader.BaseStream.Length - CommonDataTableSize - CopyTableSize;
                    long indexTablePos    = copyTablePos - (header.HasIndexTable ? header.RecordCount * 4 : 0);
                    long wch7TablePos     = indexTablePos - (header.UnknownWCH7 * 4);
                    long stringTableStart = wch7TablePos - header.StringBlockSize;
                    Dictionary <int, string> StringTable = new Dictionary <int, string>();
                    if (!header.HasOffsetTable)                     //Stringtable is only present if there isn't an offset map
                    {
                        dbReader.Scrub(stringTableStart);
                        StringTable = new StringTable().Read(dbReader, stringTableStart, stringTableStart + header.StringBlockSize);
                        dbReader.Scrub(pos);
                    }

                    //Read the data
                    using (MemoryStream ms = new MemoryStream(header.ReadData(dbReader, pos)))
                        using (BinaryReader dataReader = new BinaryReader(ms, Encoding.UTF8))
                        {
                            entry.UpdateColumnTypes();
                            ReadIntoTable(ref entry, dataReader, StringTable);
                        }

                    //Cleanup
                    header.OffsetLengths = null;

                    stream.Dispose();
                    return(entry);
                }
                else if (header.IsTypeOf <WDB>())
                {
                    WDB wdb = (WDB)header;
                    using (MemoryStream ms = new MemoryStream(wdb.ReadData(dbReader)))
                        using (BinaryReader dataReader = new BinaryReader(ms, Encoding.UTF8))
                        {
                            ReadIntoTable(ref entry, dataReader, new Dictionary <int, string>());
                        }

                    stream.Dispose();
                    return(entry);
                }
                else if (header.IsTypeOf <HTFX>())
                {
                    //Load data when needed later
                    stream.Dispose();
                    return(entry);
                }
                else
                {
                    stream.Dispose();
                    throw new Exception($"Invalid filetype.");
                }
            }
        }
 /**
  * <summary>Loads Sprite icon associated with DBEntry and with name X@Icon where X is DBEntry name</summary>
  * <param name="item">DBEntry</param>
  */
 public static Sprite LoadIcon(this DBEntry item)
 {
     return(item.LoadSprite("Icon"));
 }
        private void WriteIntoFile(DBEntry entry, BinaryWriter bw, IEnumerable <DataRow> rows, ref StringTable st)
        {
            TypeCode[] columnTypes = entry.Data.Columns.Cast <DataColumn>().Select(x => Type.GetTypeCode(x.DataType)).ToArray();
            //int[] padding = entry.GetPadding();
            var bits = entry.GetBits();

            bool duplicates = false;

            if (entry.Header.IsTypeOf <WDB2>() && entry.Header.MaxId != 0)            //WDB2 with MaxId > 0 allows duplicates
            {
                duplicates = true;
            }
            else if (entry.Header.IsTypeOf <WCH7>() && entry.Header.UnknownWCH7 != 0)            //WCH7 with Unknown > 0 allows duplicates
            {
                duplicates = true;
            }

            var lastrow = rows.Last();

            foreach (DataRow row in rows)
            {
                long offset = bw.BaseStream.Position;

                for (int j = 0; j < entry.Data.Columns.Count; j++)
                {
                    if (entry.Data.Columns[j].ExtendedProperties.ContainsKey(AUTO_GENERATED))                     //Autogenerated so skip
                    {
                        continue;
                    }

                    if (entry.Header.HasIndexTable && j == 0)                     //Inline Id so skip
                    {
                        continue;
                    }

                    if (entry.Header.IsTypeOf <WCH5>() && entry.Header.HasOffsetTable && j == 0)                    //Inline Id so skip
                    {
                        continue;
                    }

                    if (entry.Header.IsTypeOf <WDB6>() && (bits?[j].CommonDataColumn ?? false))
                    {
                        continue;
                    }

                    switch (columnTypes[j])
                    {
                    case TypeCode.SByte:
                        bw.Write(row.Field <sbyte>(j));
                        break;

                    case TypeCode.Byte:
                        bw.Write(row.Field <byte>(j));
                        break;

                    case TypeCode.Int16:
                        bw.Write(row.Field <short>(j));
                        break;

                    case TypeCode.UInt16:
                        bw.Write(row.Field <ushort>(j));
                        break;

                    case TypeCode.Int32:
                        bw.WriteInt32(row.Field <int>(j), bits?[j]);
                        break;

                    case TypeCode.UInt32:
                        bw.WriteUInt32(row.Field <uint>(j), bits?[j]);
                        break;

                    case TypeCode.Int64:
                        bw.WriteInt64(row.Field <long>(j), bits?[j]);
                        break;

                    case TypeCode.UInt64:
                        bw.WriteUInt64(row.Field <ulong>(j), bits?[j]);
                        break;

                    case TypeCode.Single:
                        bw.Write(row.Field <float>(j));
                        break;

                    case TypeCode.String:
                        if (entry.Header.HasOffsetTable)
                        {
                            bw.Write(Encoding.UTF8.GetBytes(row.Field <string>(j)));
                            bw.Write((byte)0);
                        }
                        else
                        {
                            bw.Write(st.Write(row.Field <string>(j), duplicates));
                        }
                        break;

                    default:
                        throw new Exception($"Unknown TypeCode {columnTypes[j].ToString()}");
                    }

                    //bw.BaseStream.Position += padding[j];
                }

                //Calculate and write the row's padding
                entry.Header.WriteRecordPadding(bw, entry, offset);

                //Store the offset map
                if (entry.Header.HasOffsetTable)
                {
                    OffsetMap.Add(new Tuple <int, short>((int)offset, (short)(bw.BaseStream.Position - offset)));
                }

                //WDB5 + OffsetMap without SecondIndex for the last row pads to next mod 4
                if (entry.Header.IsTypeOf <WDB5>() && entry.Header.HasOffsetTable && !entry.Header.HasRelationshipData && row == lastrow)
                {
                    long rem = bw.BaseStream.Position % 4;
                    bw.BaseStream.Position += (rem == 0 ? 0 : (4 - rem));
                }
            }
        }
示例#31
0
 public static string GetTitle(this DBEntry dBEntry)
 {
     return(GetLocalizationText(dBEntry, KEY_TITLE));
 }
示例#32
0
 public virtual void WriteBaseHeader(BinaryWriter bw, DBEntry entry)
 {
     base.WriteHeader(bw, entry);
 }
示例#33
0
 public static string GetDescription(this DBEntry dBEntry)
 {
     return(GetLocalizationText(dBEntry, KEY_DESCRIPTION));
 }
示例#34
0
 public static string GetLocalizationText(this DBEntry dBEntry, string key, params object[] localizationParams)
 {
     return(string.Format(GetLocalizationText(dBEntry, key), localizationParams));
 }
示例#35
0
        private static DBEntry <T> Read <T>(FileStream stream, string dbFile, DBHeader counterpart = null) where T : class
        {
            FileName        = dbFile;
            stream.Position = 0;

            using (var dbReader = new BinaryReader(stream, Encoding.UTF8))
            {
                DBHeader header = ReadHeader(dbReader, counterpart);
                long     pos    = dbReader.BaseStream.Position;

                ValidationChecks <T>(header, out uint build);

                DBEntry <T> entry = new DBEntry <T>(header, dbFile, build);
                if (entry.TableStructure == null)
                {
                    throw new Exception("Definition missing.");
                }

                if (header.IsTypeOf <WDBC>() || header.IsTypeOf <WDB2>())
                {
                    long stringTableStart = dbReader.BaseStream.Position += header.RecordCount * header.RecordSize;
                    Dictionary <int, string> StringTable = new StringTable().Read(dbReader, stringTableStart); //Get stringtable
                    dbReader.Scrub(pos);

                    ReadIntoTable(ref entry, dbReader, StringTable); //Read data

                    stream.Dispose();
                    return(entry);
                }
                else if (header.IsTypeOf <WDB5>() || header.IsTypeOf <WCH5>() || header.IsTypeOf <WDB6>())
                {
                    int  CopyTableSize       = header.CopyTableSize;       //Only WDB5 has a copy table
                    uint CommonDataTableSize = header.CommonDataTableSize; //Only WDB6 has a CommonDataTable

                    //StringTable - only if applicable
                    long copyTablePos     = dbReader.BaseStream.Length - CommonDataTableSize - CopyTableSize;
                    long indexTablePos    = copyTablePos - (header.HasIndexTable ? header.RecordCount * 4 : 0);
                    long wch7TablePos     = indexTablePos - (header.UnknownWCH7 * 4);
                    long stringTableStart = wch7TablePos - header.StringBlockSize;

                    Dictionary <int, string> StringTable = new Dictionary <int, string>();
                    if (!header.HasOffsetTable) //Stringtable is only present if there isn't an offset map
                    {
                        dbReader.Scrub(stringTableStart);
                        StringTable = new StringTable().Read(dbReader, stringTableStart, stringTableStart + header.StringBlockSize);
                        dbReader.Scrub(pos);
                    }

                    //Read the data
                    using (MemoryStream ms = new MemoryStream(header.ReadData(dbReader, pos, entry.Build)))
                        using (BinaryReader dataReader = new BinaryReader(ms, Encoding.UTF8))
                        {
                            ReadIntoTable(ref entry, dataReader, StringTable);
                        }

                    //Cleanup
                    header.OffsetLengths = null;

                    stream.Dispose();
                    return(entry);
                }
                else if (header.IsTypeOf <WDB>())
                {
                    WDB wdb = (WDB)header;
                    using (MemoryStream ms = new MemoryStream(wdb.ReadData(dbReader)))
                        using (BinaryReader dataReader = new BinaryReader(ms, Encoding.UTF8))
                        {
                            ReadIntoTable(ref entry, dataReader, new Dictionary <int, string>());
                        }

                    stream.Dispose();
                    return(entry);
                }
                else if (header.IsTypeOf <HTFX>())
                {
                    HTFX htfx = (HTFX)header;
                    using (MemoryStream ms = new MemoryStream(htfx.ReadData(counterpart as WDB6)))
                        using (BinaryReader dataReader = new BinaryReader(ms, Encoding.UTF8))
                        {
                            ReadIntoTable(ref entry, dataReader, new Dictionary <int, string>());
                        }

                    stream.Dispose();
                    return(entry);
                }
                else
                {
                    stream.Dispose();
                    throw new Exception($"Invalid filetype.");
                }
            }
        }