public FFNT(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.BigEndian); Header = new FFNTHeader(er); FontInfo = new FINF(er); er.BaseStream.Position = FontInfo.TGLPOffset - 8; TextureGlyph = new TGLP(er); List<CWDH> tmp = new List<CWDH>(); er.BaseStream.Position = FontInfo.CWDHOffset - 8; CWDH Last; do { Last = new CWDH(er); tmp.Add(Last); if (Last.NextCWDHOffset != 0) er.BaseStream.Position = Last.NextCWDHOffset - 8; } while (Last.NextCWDHOffset != 0); CharWidths = tmp.ToArray(); List<CMAP> tmp2 = new List<CMAP>(); er.BaseStream.Position = FontInfo.CMAPOffset - 8; CMAP Last2; do { Last2 = new CMAP(er); tmp2.Add(Last2); if (Last2.NextCMAPOffset != 0) er.BaseStream.Position = Last2.NextCMAPOffset - 8; } while (Last2.NextCMAPOffset != 0); CharMaps = tmp2.ToArray(); er.Close(); }
public NSBTA(byte[] file) { EndianBinaryReader er = new EndianBinaryReader((Stream) new MemoryStream(file), Endianness.LittleEndian); bool OK; this.Header = new FileHeader(er, "BTA0", out OK); if (!OK) { int num1 = (int)MessageBox.Show("Error 0"); } else { this.texSRTAnmSet = new NSBTA.TexSRTAnmSet(er, out OK); if (!OK) { int num2 = (int)MessageBox.Show("Error 1"); } } er.ClearMarkers(); er.Close(); }
public TEX(byte[] file) { EndianBinaryReader er = new EndianBinaryReader((Stream) new MemoryStream(file), Endianness.LittleEndian); bool OK; this.Header = new TEX.TEXHeader(er, out OK); if (!OK) { int num = (int)MessageBox.Show("Error 1"); } else { er.BaseStream.Position = (long)this.Header.PaletteDataOffset; this.PaletteData = er.ReadBytes((int)this.Header.PaletteDataSize * (int)this.Header.NrPalettes); er.BaseStream.Position = (long)this.Header.TextureDataOffset; this.TextureData = er.ReadBytes((int)this.Header.TextureDataSize); er.BaseStream.Position = (long)this.Header.Texture4x4DataOffset; this.Texture4x4Data = er.ReadBytes((int)this.Header.Texture4x4DataSize); } er.Close(); }
public ObjFlow(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); try { Header = new ObjFlowHeader(er); Objects = new ObjFlowEntry[Header.NrObjects]; //int lastid = 0; for (int i = 0; i < Header.NrObjects; i++) { Objects[i] = new ObjFlowEntry(er); //for (int j = 0; j < Objects[i].ObjectID - lastid - 1; j++) Console.WriteLine("\"?\","); //lastid = Objects[i].ObjectID; //Console.WriteLine("\"" + Objects[i].Name + "\","); } } finally { er.Close(); } }
public SMDH(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); try { Header = new SMDHHeader(er); AppTitles = new ApplicationTitle[16]; for (int i = 0; i < 16; i++) { AppTitles[i] = new ApplicationTitle(er); } AppSettings = new ApplicationSettings(er); Reserved = er.ReadBytes(8); SmallIcon = er.ReadBytes(0x480); LargeIcon = er.ReadBytes(0x1200); } finally { er.Close(); } }
public PaletteFile(string filename) { EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, File.Open(filename, FileMode.Open)); while (true) { int blockLength = 0; PaletteBlockType blockType = (PaletteBlockType)reader.ReadInt32(); blockLength = reader.ReadInt32(); switch (blockType) { case PaletteBlockType.Attributes: //contains name of palette and some attributes //we dont care about this reader.Seek(blockLength, SeekOrigin.Current); break; case PaletteBlockType.PixelData: int entryCount = reader.ReadInt32(); int bytesPerEntry = reader.ReadInt32(); _paletteData = reader.ReadBytes(entryCount * bytesPerEntry); break; case PaletteBlockType.Null: break; default: reader.Seek(blockLength, SeekOrigin.Current); break; } if (reader.BaseStream.Position == reader.BaseStream.Length) break; } reader.Close(); }
public NDS_new(byte[] data) { EndianBinaryReader er = new EndianBinaryReader((Stream) new MemoryStream(data), Endianness.LittleEndian); this.header = new NDS_new.ROM_Header(er); er.BaseStream.Position = (long)this.header.main_rom_offset; this.main_rom = er.ReadBytes((int)this.header.main_size); er.BaseStream.Position = (long)this.header.sub_rom_offset; this.sub_rom = er.ReadBytes((int)this.header.sub_size); er.BaseStream.Position = (long)this.header.fnt_offset; this.fnt = new NDS_new.ROM_FNT(er); er.BaseStream.Position = (long)this.header.main_ovt_offset; this.main_ovt = new NDS_new.ROM_OVT[(IntPtr)(this.header.main_ovt_size / 32U)]; for (int index = 0; (long)index < (long)(this.header.main_ovt_size / 32U); ++index) { this.main_ovt[index] = new NDS_new.ROM_OVT(er); } er.BaseStream.Position = (long)this.header.sub_ovt_offset; this.sub_ovt = new NDS_new.ROM_OVT[(IntPtr)(this.header.sub_ovt_size / 32U)]; for (int index = 0; (long)index < (long)(this.header.sub_ovt_size / 32U); ++index) { this.sub_ovt[index] = new NDS_new.ROM_OVT(er); } er.BaseStream.Position = (long)this.header.fat_offset; this.fat = new FileAllocationEntry[(IntPtr)(this.header.fat_size / 8U)]; for (int index = 0; (long)index < (long)(this.header.fat_size / 8U); ++index) { this.fat[index] = new FileAllocationEntry(er); } er.BaseStream.Position = (long)this.header.banner_offset; this.banner = new NDS_new.BannerFile(er); this.FileData = new byte[(IntPtr)(this.header.fat_size / 8U)][]; for (int index = 0; (long)index < (long)(this.header.fat_size / 8U); ++index) { er.BaseStream.Position = (long)this.fat[index].fileTop; this.FileData[index] = er.ReadBytes((int)this.fat[index].fileSize); } er.Close(); }
public NSBTX(byte[] file) { EndianBinaryReader er = new EndianBinaryReader((Stream) new MemoryStream(file), Endianness.LittleEndian); bool OK; this.Header = new FileHeader(er, "BTX0", out OK); if (!OK) { int num1 = (int)MessageBox.Show("Error 0"); } else { er.SetMarkerOnCurrentOffset("TexplttSet"); this.TexPlttSet = new NSBTX.TexplttSet(er, out OK); if (!OK) { int num2 = (int)MessageBox.Show("Error 1"); } } er.ClearMarkers(); er.Close(); }
public CDMD(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); try { Header = new CDMDHeader(er); foreach (var v in Header.SectionOffsets) { er.BaseStream.Position = Header.HeaderSize + v; String sig = er.ReadString(Encoding.ASCII, 4); er.BaseStream.Position -= 4; switch (sig) { case "TPKC": CheckPoints = new CKPT(er); break; case "HPKC": CheckPaths = new CKPH(er); break; case "JBOG": GlobalObjects = new GOBJ(er); break; default: //throw new Exception("Unknown Section: " + sig); continue; //goto cont; } } cont: ; } catch (SignatureNotCorrectException e) { MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { er.Close(); } }
public NSBMD(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); try { Header = new NSBMDHeader(er); if (Header.NrBlocks > 0) { er.BaseStream.Position = Header.BlockOffsets[0]; ModelSet = new MDL0(er); } if (Header.NrBlocks > 1) { er.BaseStream.Position = Header.BlockOffsets[1]; TexPlttSet = new TEX0(er); } } finally { er.Close(); } }
public override void ToXml(XmlDocument yaml, XmlNode node, List <string> nodes, List <string> values, List <byte[]> data) { XmlAttribute attr = yaml.CreateAttribute("type"); attr.Value = "path"; node.Attributes.Append(attr); using (EndianBinaryReader rd = new EndianBinaryReader(new MemoryStream(data[Value]))) { while (rd.BaseStream.Position != rd.BaseStream.Length) { XmlElement point = yaml.CreateElement("point"); point.SetAttribute("x", rd.ReadSingle().ToString(CultureInfo.InvariantCulture) + "f"); point.SetAttribute("y", rd.ReadSingle().ToString(CultureInfo.InvariantCulture) + "f"); point.SetAttribute("z", rd.ReadSingle().ToString(CultureInfo.InvariantCulture) + "f"); point.SetAttribute("nx", rd.ReadSingle().ToString(CultureInfo.InvariantCulture) + "f"); point.SetAttribute("ny", rd.ReadSingle().ToString(CultureInfo.InvariantCulture) + "f"); point.SetAttribute("nz", rd.ReadSingle().ToString(CultureInfo.InvariantCulture) + "f"); point.SetAttribute("val", rd.ReadInt32().ToString(CultureInfo.InvariantCulture)); node.AppendChild(point); } rd.Close(); } }
public BMD(byte[] file) { EndianBinaryReader er = new EndianBinaryReader((Stream) new MemoryStream(file), Endianness.LittleEndian); this.Header = new BMD.BMDHeader(er); er.BaseStream.Position = (long)this.Header.OffsetBones; this.Bones = new BMD.BMDBone[this.Header.NrBones]; for (int Idx = 0; (long)Idx < (long)this.Header.NrBones; ++Idx) { this.Bones[Idx] = new BMD.BMDBone(er, this.Bones, Idx, (int)this.Header.PosScale); } er.BaseStream.Position = (long)this.Header.OffsetDisplayLists; this.DisplayLists = new BMD.BMDDisplayList[this.Header.NrDisplayLists]; for (int index = 0; (long)index < (long)this.Header.NrDisplayLists; ++index) { this.DisplayLists[index] = new BMD.BMDDisplayList(er, this.Header.OffsetTransformBoneMap); } er.BaseStream.Position = (long)this.Header.OffsetTextures; this.Textures = new BMD.BMDTexture[this.Header.NrTextures]; for (int index = 0; (long)index < (long)this.Header.NrTextures; ++index) { this.Textures[index] = new BMD.BMDTexture(er); } er.BaseStream.Position = (long)this.Header.OffsetPalettes; this.Palettes = new BMD.BMDPalette[this.Header.NrPalettes]; for (int index = 0; (long)index < (long)this.Header.NrPalettes; ++index) { this.Palettes[index] = new BMD.BMDPalette(er); } er.BaseStream.Position = (long)this.Header.OffsetMaterials; this.Materials = new BMD.BMDMaterial[this.Header.NrMaterials]; for (int index = 0; (long)index < (long)this.Header.NrMaterials; ++index) { this.Materials[index] = new BMD.BMDMaterial(er); } er.Close(); }
public BCA(byte[] file) { EndianBinaryReader er = new EndianBinaryReader((Stream) new MemoryStream(file), Endianness.BigEndian); bool OK; this.Header = new BCA.BCAHeader(er, "J3D1bca1", out OK); if (!OK) { // TODO: Message box //int num1 = (int) MessageBox.Show("Error 1"); } else { this.ANF1 = new BCA.ANF1Section(er, out OK); if (!OK) { // TODO: Message box //int num2 = (int) MessageBox.Show("Error 2"); } } er.Close(); }
public UtilityBin(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); Header = new UtilityBinHeader(er); er.BaseStream.Position = Header.FileNameTableOffset; FileNameTable = new UtilityBinFNT(er); er.BaseStream.Position = Header.FileAllocationTableOffset; FileAllocationTable = new FileAllocationEntry[Header.FileAllocationTableSize / 8]; for (int i = 0; i < Header.FileAllocationTableSize / 8; i++) { FileAllocationTable[i] = new FileAllocationEntry(er); } FileData = new byte[Header.FileAllocationTableSize / 8][]; for (int i = 0; i < Header.FileAllocationTableSize / 8; i++) { er.BaseStream.Position = FileAllocationTable[i].fileTop; FileData[i] = er.ReadBytes((int)FileAllocationTable[i].fileSize); } er.Close(); }
public SDAT(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); try { Header = new SDATHeader(er); if (Header.SYMBOffset != 0 && Header.SYMBLength != 0) { er.BaseStream.Position = Header.SYMBOffset; SymbolBlock = new SYMB(er); } er.BaseStream.Position = Header.INFOOffset; InfoBlock = new INFO(er); er.BaseStream.Position = Header.FATOffset; FileAllocationTable = new FAT(er); er.BaseStream.Position = Header.FILEOffset; File = new FILE(er); } finally { er.Close(); } }
public FLYT(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); try { Header = new FLYTHeader(er); //int blocknr = 0; //while (blocknr < Header.NrBlocks) //{ // String sig = er.ReadString(Encoding.ASCII, 4); // switch (sig) // { // case "lyt1": Layout = new lyt1(er); break; // case "txl1": TextureList = new txl1(er); break; // } //} } finally { er.Close(); } }
public ActFile(string filename) { Stream file = OpenDataFile(filename); if (!Exists) return; EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, file); CActor currentActor = null; Stack<CActor> actorStack = new Stack<CActor>(); List<CActor> flatActorList = new List<CActor>(); while (true) { int blockLength = 0; ActorBlockType blockType = (ActorBlockType)reader.ReadInt32(); blockLength = reader.ReadInt32(); switch (blockType) { case ActorBlockType.Name: currentActor = new CActor(); if (actorStack.Count == 0) { _actors.Add(currentActor); } else { CActor parent = actorStack.Peek(); currentActor.Parent = parent; parent.Children.Add(currentActor); } flatActorList.Add(currentActor); actorStack.Push(currentActor); currentActor.Flags = reader.ReadBytes(2); currentActor.SetName(ReadNullTerminatedString(reader)); break; case ActorBlockType.TransformMatrix: Matrix matrix = new Matrix(); matrix.M11 = reader.ReadSingle(); matrix.M12 = reader.ReadSingle(); matrix.M13 = reader.ReadSingle(); matrix.M21 = reader.ReadSingle(); matrix.M22 = reader.ReadSingle(); matrix.M23 = reader.ReadSingle(); matrix.M31 = reader.ReadSingle(); matrix.M32 = reader.ReadSingle(); matrix.M33 = reader.ReadSingle(); matrix.M41 = reader.ReadSingle(); matrix.M42 = reader.ReadSingle(); matrix.M43 = reader.ReadSingle(); matrix.M44 = 1; currentActor.Matrix = matrix; break; case ActorBlockType.HierarchyStart: //Debug.WriteLine("Hierarchy start"); break; case ActorBlockType.ActorEnd: actorStack.Pop(); //Debug.WriteLine("Hierarchy end"); break; case ActorBlockType.MaterialNames: currentActor.MaterialName = ReadNullTerminatedString(reader); break; case ActorBlockType.ModelName: string modelName = ReadNullTerminatedString(reader); currentActor.ModelName = modelName; break; case ActorBlockType.BoundingBox: currentActor.BoundingBox = new BoundingBox( new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()) * GameVars.Scale, new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()) * GameVars.Scale ); break; case ActorBlockType.Null: break; default: reader.Seek(blockLength, SeekOrigin.Current); break; } if (reader.BaseStream.Position == reader.BaseStream.Length) break; } reader.Close(); _actors.ResolveMaterials(); }
public CLYT(byte[] Data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(Data), Endianness.LittleEndian); try { Header = new CLYTHeader(er); pan1 ParentPan = new pan1("FakeDummyTopPane"); pan1 LastPan = null; grp1 ParentGrp = new grp1("FakeDummyTopGroup"); grp1 LastGrp = null; int blocknr = 0; while (blocknr < Header.NrBlocks) { String sig = er.ReadString(Encoding.ASCII, 4); UInt32 size = er.ReadUInt32(); er.BaseStream.Position -= 8; switch (sig) { case "lyt1": Layout = new lyt1(er); break; case "txl1": TextureList = new txl1(er); break; case "fnl1": FontList = new fnl1(er); break; case "mat1": Materials = new mat1(er); break; case "pan1": LastPan = new pan1(er); LastPan.Parent = ParentPan; ParentPan.Children.Add(LastPan); break; case "pic1": LastPan = new pic1(er); LastPan.Parent = ParentPan; ParentPan.Children.Add(LastPan); break; case "txt1": LastPan = new txt1(er); LastPan.Parent = ParentPan; ParentPan.Children.Add(LastPan); break; case "bnd1": LastPan = new bnd1(er); LastPan.Parent = ParentPan; ParentPan.Children.Add(LastPan); break; case "wnd1": LastPan = new wnd1(er); LastPan.Parent = ParentPan; ParentPan.Children.Add(LastPan); break; case "pas1": ParentPan = LastPan; er.BaseStream.Position += 8; break; case "pae1": ParentPan = ParentPan.Parent; er.BaseStream.Position += 8; break; case "grp1": LastGrp = new grp1(er); LastGrp.Parent = ParentGrp; ParentGrp.Children.Add(LastGrp); break; case "grs1": ParentGrp = LastGrp; er.BaseStream.Position += 8; break; case "gre1": ParentGrp = ParentGrp.Parent; er.BaseStream.Position += 8; break; case "usd1": //userdata er.BaseStream.Position += size; break; default: er.BaseStream.Position += size; break; } blocknr++; } RootPane = ParentPan.Children[0]; RootPane.Parent = null; RootGroup = ParentGrp.Children[0]; RootGroup.Parent = null; } finally { er.Close(); } }
/// <summary> /// Process data in an input file that contains a layout. /// </summary> /// <param name="filename"></param> bool ProcessData(string filename, byte[] inData) { EndianBinaryReader reader = null; // now we need to decide what they just opened if (inData == null && filename != "") { reader = new EndianBinaryReader(File.Open(filename, FileMode.Open), Encoding.GetEncoding(932)); } else { reader = new EndianBinaryReader(inData); } string magic = ""; // we have a Yaz0 compressed file if (reader.ReadStringFrom(0, 4) == "Yaz0") { // we have to close our reader so we can properly read this file as a Yaz0 stream reader.Close(); MemoryStream ms = null; if (inData == null) { ms = new Yaz0(File.Open(filename, FileMode.Open)); } else { ms = new Yaz0(new MemoryStream(inData)); } reader = new EndianBinaryReader(ms); magic = reader.ReadStringFrom(0, 4); } // we have a LZ compressed file else if (reader.ReadByteFrom(0) == 0x11) { LZ77 lzFile = new LZ77(ref reader); byte[] lzData = lzFile.getData(); // close our current reader to open a new one with our input data reader.Close(); reader = new EndianBinaryReader(lzData); magic = reader.ReadStringFrom(0, 4); } // no compression else { // it is not yaz0 compressed, so we see the magic magic = reader.ReadStringFrom(0, 4); } // now we have to check our magic to see what kind of file it is switch (magic) { case "darc": mArchive = new DARC(ref reader); break; case "NARC": mArchive = new NARC(ref reader); break; case "SARC": mArchive = new SARC(ref reader); break; case "RARC": reader.SetEndianess(Endianess.Big); mArchive = new RARC(ref reader); break; case "U?8-": reader.SetEndianess(Endianess.Big); mArchive = new U8(ref reader); break; default: MessageBox.Show("Error. Unsupported format with magic: " + magic); break; } string layoutType = ""; // some files have their string table nullified, which makes the names obfuscated // I've only seen this in SARCs from MK7, but there's probably more if (mArchive != null) { if (mArchive.isStringTableObfuscated()) { MessageBox.Show("This file has obfuscated file names. The editor attempted to find layout files, but cannot supply names."); } } reader.Close(); if (mArchive == null) { MessageBox.Show("Format not supported."); return(false); } // the only familiar format with archives in archives is SARC and RARC if (mArchive.getType() == ArchiveType.SARC || mArchive.getType() == ArchiveType.RARC) { List <string> names = mArchive.getArchiveFileNames(); if (names.Count != 0) { DialogResult res = MessageBox.Show("This archive has another archive inside of it.\nDo you wish to choose one of the found archives to select a layout?", "Internal Archive", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { LayoutChooser archiveChooser = new LayoutChooser(); archiveChooser.insertEntries(names); archiveChooser.ShowDialog(); // if this worked, we dont need to do anything bool result = ProcessData(archiveChooser.getSelectedFile(), mArchive.getDataByName(archiveChooser.getSelectedFile())); if (result) { return(true); } else { MessageBox.Show("Failed to get the internal file."); return(false); } } } } // get all of our needed files mLayoutFiles = mArchive.getLayoutFiles(); mLayoutAnimFiles = mArchive.getLayoutAnimations(); mLayoutImages = mArchive.getLayoutImages(); mLayoutControls = mArchive.getLayoutControls(); if (mLayoutFiles.Count == 0) { MessageBox.Show("This file contains no layouts."); return(false); } LayoutChooser layoutChooser = new LayoutChooser(); layoutChooser.insertEntries(new List <string>(mLayoutFiles.Keys)); layoutChooser.ShowDialog(); string selectedFile = layoutChooser.getSelectedFile(); if (selectedFile == null) { return(false); } string[] sections = selectedFile.Split('/'); mMainRoot = ""; // remove "lyt" part and the file name // this will be our main root of the entire opened file for (int i = 0; i < sections.Length - 2; i++) { mMainRoot += sections[i] + "/"; } if (layoutType == "") { layoutType = Path.GetExtension(selectedFile); } // now we have to init a layout reader EndianBinaryReader layoutReader = null; byte[] data; switch (layoutType) { case ".brlyt": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); mMainLayout = new BRLYT(ref layoutReader); layoutReader.Close(); break; case ".bclyt": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); mMainLayout = new BCLYT(ref layoutReader); break; case ".bflyt": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); mMainLayout = new BFLYT(ref layoutReader); break; case ".blo": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); if (layoutReader.ReadStringFrom(4, 4) == "blo1") { mMainLayout = new BLO1(ref layoutReader); } else { mMainLayout = new BLO2(ref layoutReader); } break; default: MessageBox.Show("This format is not supported yet."); break; } layoutReader.Close(); if (mMainLayout == null) { return(false); } // set our propertygrid with our LYT object mainPropertyGrid.SelectedObject = mMainLayout.getLayoutParams(); if (mMainLayout.getRootPanel() == null) { MessageBox.Show("Error, the root pane in this layout is not specified."); return(false); } LayoutBase pane = null; LayoutBase group = null; // now we have to grab our root panel, which is different on each console // so we have to specifically get the one we want // the same applies to our root group pane = mMainLayout.getRootPanel(); // this should be RootPane TreeNode n1 = new TreeNode { Tag = pane, Name = pane.mName, Text = pane.mName, }; panelList.Nodes.Add(n1); fillNodes(pane.getChildren()); // now for our groups group = mMainLayout.getRootGroup(); if (group != null) { TreeNode n1_1 = new TreeNode { Tag = group, Name = group.mName, Text = group.mName, }; panelList.Nodes.Add(n1_1); fillNodes(group.getChildren()); } // now for textures and fonts // but it is possible for either one to not exist if (mMainLayout.containsTextures()) { foreach (string str in mMainLayout.getTextureNames()) { texturesList.Items.Add(str); } } if (mMainLayout.containsFonts()) { foreach (string str in mMainLayout.getFontNames()) { fontsList.Items.Add(str); } } // and our materials if (mMainLayout.containsMaterials()) { foreach (string str in mMainLayout.getMaterialNames()) { materialList.Items.Add(str); } } // this draws the border of the layout mMainLayout.draw(); layoutViewer.Refresh(); return(true); }
/// <summary> /// Load materials in stream. /// </summary> /// <param name="stream">Stream to use.</param> /// <returns>Material definitions.</returns> public static IEnumerable <NSBMDAnimation> ReadJnt0(Stream stream, int blockoffset) { EndianBinaryReader reader = new EndianBinaryReader(stream, Endianness.LittleEndian); int blocksize, blockptr, blocklimit; int num, objnum, i, j, r; List <int> dataoffset = new List <int>(); int sec1offset, sec2offset; NSBMDAnimation[] animation = new NSBMDAnimation[1]; List <int> animlen = new List <int>(); //////////////////////////////////////////////// // joint blockptr = blockoffset + 4; // already read the ID, skip 4 bytes blocksize = reader.ReadInt32(); // block size blocklimit = blocksize + blockoffset; reader.ReadByte(); // skip dummy 0 num = reader.ReadByte(); //assert(num > 0); // no of joint must == 1 Console.WriteLine("No. of Joint = %02x\n", num); //dataoffset = (int*)malloc(sizeof(int)); //if (!dataoffset) return NULL; reader.BaseStream.Seek(10 + (num << 2), SeekOrigin.Current); // skip [char xyz], useless blockptr += 10; reader.BaseStream.Seek(4, SeekOrigin.Current); // go straight to joint data offset blockptr += 4; for (i = 0; i < num; i++) { dataoffset.Add(getdword(reader.ReadBytes(4)) + blockoffset); } //fseek( fnsbca, 16 * num, SEEK_CUR ); // skip names blockptr += 16 * num; for (i = 0; i < num; i++) { reader.BaseStream.Seek(dataoffset[i], SeekOrigin.Begin); //j = getdword(); if (reader.ReadBytes(4) == new byte[] { 0x4A, 0x00, 0x41, 0x43 }) { return(null); } blockptr += 4; animlen.Add(getword(reader.ReadBytes(2))); objnum = getword(reader.ReadBytes(2)); //if (objnum != g_model[0].objnum) return NULL; blockptr += 4; //animation = (ANIMATION*)calloc(sizeof(ANIMATION), objnum); //if (!animation) return NULL; animation = new NSBMDAnimation[objnum]; reader.BaseStream.Seek(4, SeekOrigin.Current); // skip 4 zeros blockptr += 4; sec1offset = getdword(reader.ReadBytes(4)) + dataoffset[i]; sec2offset = getdword(reader.ReadBytes(4)) + dataoffset[i]; blockptr += 8; for (j = 0; j < objnum; j++) { animation[j] = new NSBMDAnimation(); animation[j].dataoffset = getword(reader.ReadBytes(2)) + dataoffset[i]; } for (j = 0; j < objnum; j++) { NSBMD.NSBMDAnimation anim = animation[j]; r = getdword(reader.ReadBytes(4)); anim.flag = r; // if ((r >> 1 & 1) == 0) //{ // any transformation? if ((r >> 1 & 1) == 0) { // translation if ((r & 4) == 1) { // use Base T } else { if ((r & 8) == 1) { // consTX anim.m_trans[0] = ((float)getdword(reader.ReadBytes(4))) / 4096.0f; } else { } if ((r & 0x10) == 1) { // consTY anim.m_trans[1] = ((float)getdword(reader.ReadBytes(4))) / 4096.0f; } else { } if ((r & 0x20) == 1) { // consTZ anim.m_trans[0] = ((float)getdword(reader.ReadBytes(4))) / 4096.0f; } else { } } } if ((r >> 6 & 1) == 0) { // rotation if ((r & 0x100) == 1) { // constR anim.a = ((float)getword(reader.ReadBytes(2))) / 4096.0f; anim.b = ((float)getword(reader.ReadBytes(2))) / 4096.0f; } else { } } if ((r >> 9 & 1) == 0) { // scale if ((r & 0x400) == 1) { // use Base S } else { if ((r & 0x800) == 1) { // consSX anim.m_scale[0] = ((float)getdword(reader.ReadBytes(4))) / 4096.0f; } else { } if ((r & 0x1000) == 1) { // consSY anim.m_scale[0] = ((float)getdword(reader.ReadBytes(4))) / 4096.0f; } else { } if ((r & 0x2000) == 1) { // consSZ anim.m_scale[0] = ((float)getdword(reader.ReadBytes(4))) / 4096.0f; } else { } } // } } animation[j] = anim; } } reader.Close(); //free(dataoffset); return(animation); }
static void Dump(string FileName, EndianBinary.Endian Endian) { string OutFile = Path.GetFileNameWithoutExtension(FileName) + ".txt"; StringBuilder Output = new StringBuilder(); FileStream Input = new FileStream(FileName, FileMode.Open); EndianBinaryReader Reader = new EndianBinaryReader(Input, Endian); Section Lang = ParseSection(Reader); if (Lang.Signature != "LANG") { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid file!"); Console.ResetColor(); } Input.Seek(ParsePack(Reader, Lang)[0].Offset, SeekOrigin.Begin); Section Category = ParseSection(Reader); Input.Seek(ParsePack(Reader, Category)[0].Offset, SeekOrigin.Begin); Section String = ParseSection(Reader); List<PackEntry> StringPack = ParsePack(Reader, String); foreach (PackEntry Entry in StringPack) { Input.Seek(Entry.Offset, SeekOrigin.Begin); byte[] Buffer = new byte[Entry.Length - 2]; Reader.Read(Buffer, 0, Buffer.Length); Output.Append(UTF16.GetString(Buffer, Endian)); Output.AppendLine(null); Output.AppendLine(null); } File.WriteAllText(OutFile, Output.ToString().TrimEnd()); Reader.Close(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Dumped " + Path.GetFileName(FileName) + "!"); Console.ResetColor(); }
public MatFile(string filename) { Stream file = OpenDataFile(filename); if (!Exists) { return; } EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, file); CMaterial currentMaterial = null; while (true) { int blockLength = 0; MaterialBlockType blockType = (MaterialBlockType)reader.ReadInt32(); blockLength = reader.ReadInt32(); byte[] flags; switch (blockType) { case MaterialBlockType.Attributes: currentMaterial = new CMaterial(); _materials.Add(currentMaterial); byte[] color = reader.ReadBytes(4); byte[] otherColors = reader.ReadBytes(16); flags = reader.ReadBytes(2); byte[] transform = reader.ReadBytes(24); currentMaterial.SimpMatPixelIndex = reader.ReadByte(); currentMaterial.SimpMatGradientCount = reader.ReadByte(); currentMaterial.DoubleSided = flags[0] == 0x10; currentMaterial.Name = ReadNullTerminatedString(reader); break; case MaterialBlockType.AttributesV2: currentMaterial = new CMaterial(); _materials.Add(currentMaterial); reader.ReadBytes(4); //color reader.ReadBytes(16); //othercolors flags = reader.ReadBytes(4); // flags reader.ReadBytes(24); //transform reader.ReadBytes(4); //unk currentMaterial.DoubleSided = flags[0] == 0x10; reader.BaseStream.Position += 13; currentMaterial.Name = ReadNullTerminatedString(reader); break; case MaterialBlockType.TextureName: currentMaterial.PixName = ReadNullTerminatedString(reader); break; case MaterialBlockType.TabName: string tabName = ReadNullTerminatedString(reader); break; case MaterialBlockType.Null: break; default: reader.Seek(blockLength, SeekOrigin.Current); break; } if (reader.BaseStream.Position == reader.BaseStream.Length) { break; } } reader.Close(); }
public static bool pbmb_read(string input_name, ref int xsize, ref int ysize, ref int[] barray) //****************************************************************************80 // // Purpose: // // PBMB_READ reads the header and data from a binary portable bit map file. // // Discussion: // // Thanks to Jonas Schwertfeger for pointing out that, especially on Microsoft // Windows systems, a binary file needs to be opened as a binary file! // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 22 July 2011 // // Author: // // John Burkardt // // Parameters: // // Input, string INPUT_NAME, the name of the file containing the binary // portable bit map data. // // Output, int &XSIZE, &YSIZE, the number of rows and columns of data. // // Output, int[] *BARRAY, the array of XSIZE by YSIZE data values. // // Output, bool PBMB_READ, is true if an error occurred. // { EndianBinaryReader file_in; try { Stream file_in_s = File.OpenRead(input_name); file_in = new EndianBinaryReader(EndianBitConverter.Little, file_in_s); } catch { Console.WriteLine(""); Console.WriteLine("PBMB_READ: Fatal error!"); Console.WriteLine(" Cannot open the input file " + input_name + ""); return(true); } // // Read the header. // bool error = pbmb_read_header(ref file_in, ref xsize, ref ysize); switch (error) { case true: Console.WriteLine(""); Console.WriteLine("PBMB_READ: Fatal error!"); Console.WriteLine(" PBMB_READ_HEADER failed."); return(true); } // // Allocate storage for the data. // barray = new int [xsize * ysize]; // // Read the data. // error = pbmb_read_data(ref file_in, xsize, ysize, ref barray); file_in.Close(); switch (error) { case true: Console.WriteLine(""); Console.WriteLine("PBMB_READ: Fatal error!"); Console.WriteLine(" PBMB_READ_DATA failed."); return(true); default: return(false); } }
protected override void OnOpen(EndianBinaryReader reader) { uint files; ushort align; MemoryStream ms; EndianBinaryReader utfr; if (Encoding.ASCII.GetString(reader.ReadBytes(4)) != "CPK ") { throw new NotImplementedException("Invalid CPK header"); } ReadUTFData(reader); CPKPacket = UTFPacket; CPKEntry CPAK_entry = new CPKEntry { FileName = "CPK_HDR", FileOffsetPos = reader.BaseStream.Position + 0x10, FileSize = CPKPacket.Length, Encrypted = IsUtfEncrypted, FileType = "CPK" }; FileTable.Add(CPAK_entry); ms = new MemoryStream(UTFPacket); utfr = new EndianBinaryReader(ms, Endian.BigEndian); UTF = new UTF(); if (!UTF.ReadUTF(utfr)) { throw new NotSupportedException("Invalid UTF header in CPK file"); } utfr.Close(); ms.Close(); CPKData = new Dictionary <string, object>(); for (int i = 0; i < UTF.Columns.Count; i++) { CPKData.Add(UTF.Columns[i].name, UTF.Rows[0].rows[i].GetValue()); } TocOffset = (ulong)GetColumsData2(UTF, 0, "TocOffset", 3); long tocOffsetPos = GetColumnPostion(UTF, 0, "TocOffset"); EtocOffset = (ulong)GetColumsData2(UTF, 0, "EtocOffset", 3); long eTocOffsetPos = GetColumnPostion(UTF, 0, "EtocOffset"); ItocOffset = (ulong)GetColumsData2(UTF, 0, "ItocOffset", 3); long iTocOffsetPos = GetColumnPostion(UTF, 0, "ItocOffset"); GtocOffset = (ulong)GetColumsData2(UTF, 0, "GtocOffset", 3); long gTocOffsetPos = GetColumnPostion(UTF, 0, "GtocOffset"); ContentOffset = (ulong)GetColumsData2(UTF, 0, "ContentOffset", 3); long contentOffsetPos = GetColumnPostion(UTF, 0, "ContentOffset"); //FileTable.Add(CreateFileEntry("CONTENT_OFFSET", ContentOffset, typeof(ulong), ContentOffsetPos, "CPK", "CONTENT", false)); FileTable.Add(new CPKEntry { FileName = "CONTENT_OFFSET", FileOffset = ContentOffset, FileOffsetType = typeof(ulong), FileOffsetPos = contentOffsetPos, TOCName = "CPK", FileType = "CONTENT", Encrypted = false }); files = (uint)GetColumsData2(UTF, 0, "Files", 2); align = (ushort)GetColumsData2(UTF, 0, "Align", 1); if (TocOffset != 0xFFFFFFFFFFFFFFFF) { CPKEntry entry = new CPKEntry { FileName = "TOC_HDR", FileOffset = TocOffset, FileOffsetType = typeof(ulong), FileOffsetPos = tocOffsetPos, TOCName = "CPK", FileType = "HDR", Encrypted = false }; FileTable.Add(entry); if (!ReadTOC(reader, TocOffset, ContentOffset)) { throw new NotSupportedException("Error reading TOC from CPK file"); } } if (EtocOffset != 0xFFFFFFFFFFFFFFFF) { CPKEntry entry = new CPKEntry { FileName = "ETOC_HDR", FileOffset = EtocOffset, FileOffsetType = typeof(ulong), FileOffsetPos = eTocOffsetPos, TOCName = "CPK", FileType = "HDR", Encrypted = false }; FileTable.Add(entry); if (!ReadETOC(reader, EtocOffset)) { throw new NotSupportedException("Error reading ETOC from CPK file"); } } if (ItocOffset != 0xFFFFFFFFFFFFFFFF) { //FileEntry ITOC_entry = new FileEntry { // FileName = "ITOC_HDR", // FileOffset = ItocOffset, FileOffsetType = typeof(ulong), FileOffsetPos = ITocOffsetPos, // TOCName = "CPK", // FileType = "FILE", Encrypted = true, //}; CPKEntry entry = new CPKEntry { FileName = "ITOC_HDR", FileOffset = ItocOffset, FileOffsetType = typeof(ulong), FileOffsetPos = iTocOffsetPos, TOCName = "CPK", FileType = "HDR", Encrypted = false }; FileTable.Add(entry); if (!ReadITOC(reader, ItocOffset, ContentOffset, align)) { throw new NotSupportedException("Error reading ITOC from CPK file"); } } if (GtocOffset != 0xFFFFFFFFFFFFFFFF) { CPKEntry entry = new CPKEntry { FileName = "GTOC_HDR", FileOffset = GtocOffset, FileOffsetType = typeof(ulong), FileOffsetPos = gTocOffsetPos, TOCName = "CPK", FileType = "HDR", Encrypted = false }; FileTable.Add(entry); if (!ReadGTOC(reader, GtocOffset)) { throw new NotSupportedException("Error reading GTOC from CPK file"); } } // to get to the real files quickly AllFiles = FileTable.Where(x => x.FileType == "FILE").ToArray(); }
public bool ReadITOC(EndianBinaryReader br, ulong startoffset, ulong contentOffset, ushort align) { br.BaseStream.Seek((long)startoffset, SeekOrigin.Begin); if (Tools.ReadCString(br, 4) != "ITOC") { br.Close(); return(false); } ReadUTFData(br); ITOCPacket = UTFPacket; CPKEntry itocEntry = FileTable.Where(x => x.FileName.ToString() == "ITOC_HDR").Single(); itocEntry.Encrypted = IsUtfEncrypted; itocEntry.FileSize = ITOCPacket.Length; MemoryStream ms = new MemoryStream(UTFPacket); EndianBinaryReader utfr = new EndianBinaryReader(ms, Endian.BigEndian); Files = new UTF(); if (!Files.ReadUTF(utfr)) { br.Close(); return(false); } utfr.Close(); ms.Close(); //uint FilesL = (uint)GetColumnData(files, 0, "FilesL"); //uint FilesH = (uint)GetColumnData(files, 0, "FilesH"); byte[] dataL = (byte[])GetColumnData(Files, 0, "DataL"); long dataLPos = GetColumnPostion(Files, 0, "DataL"); byte[] dataH = (byte[])GetColumnData(Files, 0, "DataH"); long dataHPos = GetColumnPostion(Files, 0, "DataH"); UTF utfDataL, utfDataH; Dictionary <int, uint> sizeTable, cSizeTable; Dictionary <int, long> sizePosTable, cSizePosTable; Dictionary <int, Type> sizeTypeTable, cSizeTypeTable; List <int> IDs = new List <int>(); sizeTable = new Dictionary <int, uint>(); sizePosTable = new Dictionary <int, long>(); sizeTypeTable = new Dictionary <int, Type>(); cSizeTable = new Dictionary <int, uint>(); cSizePosTable = new Dictionary <int, long>(); cSizeTypeTable = new Dictionary <int, Type>(); ushort ID, size1; uint size2; long pos; Type type; if (dataL != null) { ms = new MemoryStream(dataL); utfr = new EndianBinaryReader(ms, Endian.BigEndian); utfDataL = new UTF(); utfDataL.ReadUTF(utfr); for (int i = 0; i < utfDataL.NumRows; i++) { ID = (ushort)GetColumnData(utfDataL, i, "ID"); size1 = (ushort)GetColumnData(utfDataL, i, "FileSize"); sizeTable.Add((int)ID, (uint)size1); pos = GetColumnPostion(utfDataL, i, "FileSize"); sizePosTable.Add((int)ID, pos + dataLPos); type = GetColumnType(utfDataL, i, "FileSize"); sizeTypeTable.Add((int)ID, type); if ((GetColumnData(utfDataL, i, "ExtractSize")) != null) { size1 = (ushort)GetColumnData(utfDataL, i, "ExtractSize"); cSizeTable.Add((int)ID, (uint)size1); pos = GetColumnPostion(utfDataL, i, "ExtractSize"); cSizePosTable.Add((int)ID, pos + dataLPos); type = GetColumnType(utfDataL, i, "ExtractSize"); cSizeTypeTable.Add((int)ID, type); } IDs.Add(ID); } } if (dataH != null) { ms = new MemoryStream(dataH); utfr = new EndianBinaryReader(ms, Endian.BigEndian); utfDataH = new UTF(); utfDataH.ReadUTF(utfr); for (int i = 0; i < utfDataH.NumRows; i++) { ID = (ushort)GetColumnData(utfDataH, i, "ID"); size2 = (uint)GetColumnData(utfDataH, i, "FileSize"); sizeTable.Add(ID, size2); pos = GetColumnPostion(utfDataH, i, "FileSize"); sizePosTable.Add((int)ID, pos + dataHPos); type = GetColumnType(utfDataH, i, "FileSize"); sizeTypeTable.Add((int)ID, type); if ((GetColumnData(utfDataH, i, "ExtractSize")) != null) { size2 = (uint)GetColumnData(utfDataH, i, "ExtractSize"); cSizeTable.Add(ID, size2); pos = GetColumnPostion(utfDataH, i, "ExtractSize"); cSizePosTable.Add((int)ID, pos + dataHPos); type = GetColumnType(utfDataH, i, "ExtractSize"); cSizeTypeTable.Add((int)ID, type); } IDs.Add(ID); } } CPKEntry temp; //int id = 0; uint value = 0, value2 = 0; ulong baseoffset = contentOffset; // Seems ITOC can mix up the IDs..... but they'll alwaysy be in order... IDs = IDs.OrderBy(x => x).ToList(); for (int i = 0; i < IDs.Count; i++) { int id = IDs[i]; temp = new CPKEntry(); sizeTable.TryGetValue(id, out value); cSizeTable.TryGetValue(id, out value2); temp.TOCName = "ITOC"; temp.DirName = null; temp.FileName = id.ToString("D4"); temp.FileSize = value; temp.FileSizePos = sizePosTable[id]; temp.FileSizeType = sizeTypeTable[id]; if (cSizeTable.Count > 0 && cSizeTable.ContainsKey(id)) { temp.ExtractSize = value2; temp.ExtractSizePos = cSizePosTable[id]; temp.ExtractSizeType = cSizeTypeTable[id]; } temp.FileType = "FILE"; temp.FileOffset = baseoffset; temp.ID = id; temp.UserString = null; FileTable.Add(temp); if ((value % align) > 0) { baseoffset += value + (align - (value % align)); } else { baseoffset += value; } //id++; } Files = null; utfDataL = null; utfDataH = null; ms.Close(); utfr.Close(); return(true); }
public bool ReadTOC(EndianBinaryReader br, ulong tocOffset, ulong contentOffset) { ulong addOffset = 0; if (contentOffset < 0) { addOffset = tocOffset; } else { if (tocOffset < 0) { addOffset = contentOffset; } else { if (contentOffset < tocOffset) { addOffset = contentOffset; } else { addOffset = tocOffset; } } } br.BaseStream.Seek((long)tocOffset, SeekOrigin.Begin); if (Tools.ReadCString(br, 4) != "TOC ") { br.Close(); return(false); } ReadUTFData(br); // Store unencrypted TOC TOCPacket = UTFPacket; CPKEntry tocEntry = FileTable.Where(x => x.FileName.ToString() == "TOC_HDR").Single(); tocEntry.Encrypted = IsUtfEncrypted; tocEntry.FileSize = TOCPacket.Length; MemoryStream ms = new MemoryStream(UTFPacket); EndianBinaryReader utfr = new EndianBinaryReader(ms, Endian.BigEndian); Files = new UTF(); if (!Files.ReadUTF(utfr)) { br.Close(); return(false); } utfr.Close(); ms.Close(); CPKEntry temp; for (int i = 0; i < Files.NumRows; i++) { temp = new CPKEntry(); temp.TOCName = "TOC"; temp.DirName = GetColumnData(Files, i, "DirName"); temp.FileName = GetColumnData(Files, i, "FileName"); temp.FileSize = GetColumnData(Files, i, "FileSize"); temp.FileSizePos = GetColumnPostion(Files, i, "FileSize"); temp.FileSizeType = GetColumnType(Files, i, "FileSize"); temp.ExtractSize = GetColumnData(Files, i, "ExtractSize"); temp.ExtractSizePos = GetColumnPostion(Files, i, "ExtractSize"); temp.ExtractSizeType = GetColumnType(Files, i, "ExtractSize"); temp.FileOffset = ((ulong)GetColumnData(Files, i, "FileOffset") + (ulong)addOffset); temp.FileOffsetPos = GetColumnPostion(Files, i, "FileOffset"); temp.FileOffsetType = GetColumnType(Files, i, "FileOffset"); temp.FileType = "FILE"; temp.Offset = addOffset; temp.ID = GetColumnData(Files, i, "ID"); temp.UserString = GetColumnData(Files, i, "UserString"); FileTable.Add(temp); } Files = null; return(true); }
public BOL(byte[] file) { EndianBinaryReader er = new EndianBinaryReader((Stream) new MemoryStream(file), Endianness.BigEndian); bool OK; this.Header = new BOL.BOLHeader(er, "0015", out OK); if (!OK) { int num = (int)MessageBox.Show("Error 1"); } else { er.BaseStream.Position = (long)this.Header.ItemEnemyPointsOffset; this.ItemEnemyPoints = new BOL.ItemEnemyPoint[(int)this.Header.NrItemEnemyPoints]; for (int index = 0; index < (int)this.Header.NrItemEnemyPoints; ++index) { this.ItemEnemyPoints[index] = new BOL.ItemEnemyPoint(er); } er.BaseStream.Position = (long)this.Header.CheckpointGroupsOffset; this.CheckpointGroups = new BOL.CheckpointGroup[(int)this.Header.NrCheckpointGroups]; for (int index = 0; index < (int)this.Header.NrCheckpointGroups; ++index) { this.CheckpointGroups[index] = new BOL.CheckpointGroup(er); } int length = 0; for (int index = 0; index < (int)this.Header.NrCheckpointGroups; ++index) { length += (int)this.CheckpointGroups[index].NrPoints; } this.Checkpoints = new BOL.Checkpoint[length]; for (int index = 0; index < length; ++index) { this.Checkpoints[index] = new BOL.Checkpoint(er); } er.BaseStream.Position = (long)this.Header.RoutesOffset; this.Routes = new BOL.Route[(int)this.Header.NrRoutes]; for (int index = 0; index < (int)this.Header.NrRoutes; ++index) { this.Routes[index] = new BOL.Route(er); } er.BaseStream.Position = (long)this.Header.RoutePointsOffset; this.RoutePoints = new BOL.RoutePoint[(this.Header.ObjectsOffset - this.Header.RoutePointsOffset) / 32U]; for (int index = 0; (long)index < (long)((this.Header.ObjectsOffset - this.Header.RoutePointsOffset) / 32U); ++index) { this.RoutePoints[index] = new BOL.RoutePoint(er); } er.BaseStream.Position = (long)this.Header.ObjectsOffset; this.Objects = new BOL.Object[(int)this.Header.NrObjects]; for (int index = 0; index < (int)this.Header.NrObjects; ++index) { this.Objects[index] = new BOL.Object(er); } er.BaseStream.Position = (long)this.Header.StartPositionsOffset; this.StartPositions = new BOL.StartPosition[(this.Header.AreasOffset - this.Header.StartPositionsOffset) / 40U]; for (int index = 0; (long)index < (long)((this.Header.AreasOffset - this.Header.StartPositionsOffset) / 40U); ++index) { this.StartPositions[index] = new BOL.StartPosition(er); } er.BaseStream.Position = (long)this.Header.AreasOffset; this.Areas = new BOL.Area[(int)this.Header.NrAreas]; for (int index = 0; index < (int)this.Header.NrAreas; ++index) { this.Areas[index] = new BOL.Area(er); } er.BaseStream.Position = (long)this.Header.CameraOffset; this.Cameras = new BOL.Camera[(int)this.Header.NrCameras]; for (int index = 0; index < (int)this.Header.NrCameras; ++index) { this.Cameras[index] = new BOL.Camera(er); } er.BaseStream.Position = (long)this.Header.RespawnPositionsOffset; this.Respawns = new BOL.Respawn[(this.Header.Section10Offset - this.Header.RespawnPositionsOffset) / 32U]; for (int index = 0; (long)index < (long)((this.Header.Section10Offset - this.Header.RespawnPositionsOffset) / 32U); ++index) { this.Respawns[index] = new BOL.Respawn(er); } } er.Close(); }
public PixFile(string filename) { Stream file = OpenDataFile(filename); if (!Exists) return; EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, file); PixMap currentPix=null; while (true) { int blockLength = 0; PixBlockType blockType = (PixBlockType)reader.ReadInt32(); if (blockType == PixBlockType.Null && reader.BaseStream.Position + 3 >= reader.BaseStream.Length) break; blockLength = reader.ReadInt32(); switch (blockType) { case PixBlockType.Attributes: int type = reader.ReadByte(); if (type == 7) { /* bmp palette data? - seen in some splat pack textures. Jump over it, and its pixel data */ reader.Seek(blockLength-1, SeekOrigin.Current); _skipNextPixelSection = true; break; } currentPix = new PixMap(); currentPix.Width = reader.ReadInt16(); int width2 = reader.ReadInt16(); currentPix.Height = reader.ReadInt16(); byte[] unk2 = reader.ReadBytes(4); currentPix.Name = ReadNullTerminatedString(reader); _pixMaps.Add(currentPix); break; case PixBlockType.PixelData: if (_skipNextPixelSection) { reader.Seek(blockLength, SeekOrigin.Current); _skipNextPixelSection = false; break; } int pixelCount = reader.ReadInt32(); int bytesPerPixel = reader.ReadInt32(); if (bytesPerPixel > 3) { bytesPerPixel = 1; //PixEd sometimes doesnt get this right } if (currentPix == null) { int size = (int)Math.Sqrt(pixelCount); currentPix = new PixMap(); currentPix.Name = Path.GetFileName(filename); currentPix.Width = size; currentPix.Height = size; _pixMaps.Add(currentPix); } byte[] pixels = reader.ReadBytes(pixelCount * bytesPerPixel); Texture2D texture=null; if (bytesPerPixel == 1) { texture = new Texture2D(Engine.Device, currentPix.Width, currentPix.Height, 1, TextureUsage.None, SurfaceFormat.Color); texture.SetData<byte>(Helpers.GetBytesForImage(pixels, currentPix.Width, currentPix.Height, GameVars.Palette)); } else if (bytesPerPixel == 2) { texture = new Texture2D(Engine.Device, currentPix.Width, currentPix.Height, 1, TextureUsage.None, SurfaceFormat.Bgr565); int j = 0; byte[] px = new byte[2]; for (int i = 0; i < pixels.Length; i += 2) { byte tmp = pixels[i + 1]; pixels[i + 1] = pixels[i]; pixels[i] = tmp; } texture.SetData<byte>(pixels); } else if (bytesPerPixel ==3 ) { texture = new Texture2D(Engine.Device, currentPix.Width, currentPix.Height, 1, TextureUsage.None, SurfaceFormat.Color); int j = 0; byte[] px2 = new byte[pixels.Length * 4]; for (int i = 0; i < pixels.Length; i += 3) { px2[j++] = pixels[i]; px2[j++] = pixels[i+1]; px2[j++] = pixels[i+2]; px2[j++] = 255; } texture.SetData<byte>(px2); } currentPix.Texture = texture; break; case PixBlockType.Null: break; default: reader.Seek(blockLength, SeekOrigin.Current); break; } if (reader.BaseStream.Position+3 >= reader.BaseStream.Length) break; } reader.Close(); }
static void Extract(string FileName, EndianBinary.Endian Endian) { FileStream Input = new FileStream(FileName, FileMode.Open); EndianBinaryReader Reader = new EndianBinaryReader(Input, Endian); byte b = Reader.ReadByte(); MemoryStream SignatureBuffer = new MemoryStream(); while (b != 0) { SignatureBuffer.WriteByte(b); b = Reader.ReadByte(); } string Signature = Encoding.ASCII.GetString(SignatureBuffer.ToArray()); SignatureBuffer.Dispose(); Reader.BaseStream.Seek(8, SeekOrigin.Begin); //Pula parte da assinatura if (Signature != "MSSG") { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid file!"); Console.ResetColor(); } string OutDir = Path.GetFileNameWithoutExtension(FileName); Directory.CreateDirectory(OutDir); ulong FileCount = Reader.ReadUInt64(); ulong FileLength = Reader.ReadUInt64(); Reader.ReadUInt64(); //??? 0x800 for (ulong Entry = 0; Entry < FileCount; Entry++) { Input.Seek((long)(0x20 + Entry * 0x20), SeekOrigin.Begin); ulong Offset = Reader.ReadUInt64(); ulong Length1 = Reader.ReadUInt64(); ulong Length2 = Reader.ReadUInt64(); Reader.ReadUInt64(); //Padding Input.Seek((long)Offset, SeekOrigin.Begin); byte[] Buffer = new byte[Length1]; Reader.Read(Buffer, 0, Buffer.Length); string SubFileSignature = Encoding.ASCII.GetString(Buffer, 0, 4); bool IsLangFile = SubFileSignature == "LANG"; File.WriteAllBytes(Path.Combine(OutDir, "file_" + Entry.ToString() + (IsLangFile ? ".lang" : ".bin")), Buffer); } Reader.Close(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Extracted all files from " + Path.GetFileName(FileName) + "!"); Console.ResetColor(); }
public ActFile(string filename) { Stream file = OpenDataFile(filename); if (!Exists) { return; } EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, file); CActor currentActor = null; Stack <CActor> actorStack = new Stack <CActor>(); List <CActor> flatActorList = new List <CActor>(); while (true) { int blockLength = 0; ActorBlockType blockType = (ActorBlockType)reader.ReadInt32(); blockLength = reader.ReadInt32(); switch (blockType) { case ActorBlockType.Name: currentActor = new CActor(); if (actorStack.Count == 0) { _actors.Add(currentActor); } else { CActor parent = actorStack.Peek(); currentActor.Parent = parent; parent.Children.Add(currentActor); } flatActorList.Add(currentActor); actorStack.Push(currentActor); currentActor.Flags = reader.ReadBytes(2); currentActor.SetName(ReadNullTerminatedString(reader)); break; case ActorBlockType.TransformMatrix: Matrix matrix = new Matrix(); matrix.M11 = reader.ReadSingle(); matrix.M12 = reader.ReadSingle(); matrix.M13 = reader.ReadSingle(); matrix.M21 = reader.ReadSingle(); matrix.M22 = reader.ReadSingle(); matrix.M23 = reader.ReadSingle(); matrix.M31 = reader.ReadSingle(); matrix.M32 = reader.ReadSingle(); matrix.M33 = reader.ReadSingle(); matrix.M41 = reader.ReadSingle(); matrix.M42 = reader.ReadSingle(); matrix.M43 = reader.ReadSingle(); matrix.M44 = 1; currentActor.Matrix = matrix; break; case ActorBlockType.HierarchyStart: //Debug.WriteLine("Hierarchy start"); break; case ActorBlockType.ActorEnd: actorStack.Pop(); //Debug.WriteLine("Hierarchy end"); break; case ActorBlockType.MaterialNames: currentActor.MaterialName = ReadNullTerminatedString(reader); break; case ActorBlockType.ModelName: string modelName = ReadNullTerminatedString(reader); currentActor.ModelName = modelName; break; case ActorBlockType.BoundingBox: currentActor.BoundingBox = new BoundingBox( new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()) * GameVars.Scale, new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()) * GameVars.Scale ); break; case ActorBlockType.Null: break; default: reader.Seek(blockLength, SeekOrigin.Current); break; } if (reader.BaseStream.Position == reader.BaseStream.Length) { break; } } reader.Close(); _actors.ResolveMaterials(); }
public PacketStream(Byte[] inBuff, Boolean fromServer) { FromServer = fromServer; Packets = new List <Packet>(); var stream = new MemoryStream(inBuff); var reader = new EndianBinaryReader(MiscUtil.Conversion.EndianBitConverter.Little, stream); var remLength = inBuff.Length; do { var iPacket = new Packet { Module = reader.ReadByte(), FromServer = FromServer }; var pLength = reader.ReadInt32(); var pChecksum = reader.ReadByte(); try { if (iPacket.VerifyChecksum(inBuff, pChecksum, (int)reader.BaseStream.Position - 6)) { var data = reader.ReadBytes(pLength - 6); if (data.Length >= 4) { iPacket.Stream = new MemoryStream(data); iPacket.Reader = new EndianBinaryReader(MiscUtil.Conversion.EndianBitConverter.Little, iPacket.Stream); iPacket.PacketID = iPacket.Reader.ReadUInt32(); iPacket.ContentVersion = iPacket.Reader.ReadUInt16(); iPacket.TransportVersion = iPacket.Reader.ReadUInt16(); iPacket.IsValid = true; var cData = new Byte[pLength]; Array.Copy(inBuff, 0, cData, 0, pLength); iPacket.Data = data; iPacket.CData = cData; Packets.Add(iPacket); } } else { return; } } catch { } remLength -= pLength; }while (remLength > 0); reader.Close(); stream.Close(); }
public Byaml(string byamlFile) { nodes = new List <string>(); values = new List <string>(); nodeChaches = new List <KeyValuePair <int, ShowNode> >(); searched_nodes = new List <TreeNode>(); byte[] bytes = File.ReadAllBytes(byamlFile); isYaz0 = Yaz0.IsYaz0(bytes); if (isYaz0) { bytes = Yaz0.decode(bytes); } var stream = new MemoryStream(bytes); var reader = new EndianBinaryReader(stream); reader.Endianness = Endianness.BigEndian; if (reader.ReadUInt16() != 0x4259) { throw new InvalidDataException(); } if (reader.ReadUInt16() != 0x0002) { throw new InvalidDataException(); } path = byamlFile; uint nodeOffset = reader.ReadUInt32(); if (nodeOffset > reader.BaseStream.Length) { throw new InvalidDataException(); } uint valuesOffset = reader.ReadUInt32(); if (valuesOffset > reader.BaseStream.Length) { throw new InvalidDataException(); } uint treeOffset = reader.ReadUInt32(); if (treeOffset > reader.BaseStream.Length) { throw new InvalidDataException(); } if (nodeOffset != 0) { reader.BaseStream.Seek(nodeOffset, SeekOrigin.Begin); nodes.AddRange(new ByamlNode.StringList(reader).Strings); } if (valuesOffset != 0) { reader.BaseStream.Seek(valuesOffset, SeekOrigin.Begin); values.AddRange(new ByamlNode.StringList(reader).Strings); } ByamlNodeType rootType; reader.BaseStream.Seek(treeOffset, SeekOrigin.Begin); rootType = (ByamlNodeType)reader.ReadByte(); reader.BaseStream.Seek(-1, SeekOrigin.Current); if (rootType == ByamlNodeType.UnamedNode) { tree = new ByamlNode.UnamedNode(reader); } else { tree = new ByamlNode.NamedNode(reader); } root = new ShowNode("root"); root.Type = tree.Type; reader.Close(); }
public bool Update() { var bitStream = downloader.DownloadStream; var reader = new EndianBinaryReader(EndianBitConverter.Big, bitStream); if(bitStream != null) { var stream = new StreamReader(bitStream); { reader.ReadBytes(3); //"FLV" reader.ReadBytes(6); //Other starter shit while (true) { try { var footer = reader.ReadUInt32(); var tag = new FlvTag(); tag.Load(reader); AddedTag(tag); } catch (Exception) { reader.Close(); //End of stream return false; } } } } return true; }
public void LoadImage(byte[] data, string resSFilePath = "") { using (MemoryStream ms = new MemoryStream(data)) { using (EndianBinaryReader br = new EndianBinaryReader(ms, Endian.LittleEndian)) { int name_length = br.ReadInt32(); this.name = Encoding.UTF8.GetString(br.ReadBytes(name_length)); var pos = br.BaseStream.Position; if (pos % 4 != 0) { br.BaseStream.Seek(4 - pos % 4, SeekOrigin.Current); } this.width = br.ReadInt32(); this.height = br.ReadInt32(); if ((this.width > 4096) || (this.height > 4096)) { isTexture2D = false; Console.WriteLine("Got error:{0}", "Width/Height Error\n Not a unity Texture2D data"); return; } this.textureSize = br.ReadInt32(); if ((this.width == 0) || (this.height == 0)) { isTexture2D = false; Console.WriteLine("Got error:{0}", "Width/Height Error\n Empty Texture"); return; } int tmp_pos = (int)br.BaseStream.Position; this.format = (TextureFormat)br.ReadInt32(); this.mipmapCount = br.ReadInt32(); if (this.mipmapCount > 1) { this.bMipmap = true; } int readable = br.ReadInt32(); int imageCount = br.ReadInt32(); this.dimension = (TextureDimension)br.ReadInt32(); this.filterMode = (FilterMode)br.ReadInt32(); this.anisoLevel = br.ReadInt32(); this.mipMapBias = br.ReadInt32(); this.wrapMode = (TextureWrapMode)br.ReadInt32(); int lightmapFormat = br.ReadInt32(); int colorSpace = br.ReadInt32(); this.dataSize = br.ReadInt32(); if (this.dataSize <= 0) { Console.WriteLine("Got error:{0}", "Data Length Error\n Not a unity Texture2D data"); isTexture2D = false; return; } if (this.dataSize == 0) { this.dataPos = br.ReadInt32(); this.dataSize = br.ReadInt32(); int name_len = br.ReadInt32(); if (this.dataSize <= 0) { Console.WriteLine("Got error:{0}", "Data Length is 0\n Not a unity Texture2D data"); isTexture2D = false; return; } this.resSName = Encoding.UTF8.GetString(br.ReadBytes(name_len)); if (resSFilePath == "") { resSFilePath = "./"; } string rname = string.Format("{0}\\{1}", resSFilePath, this.resSName); if (File.Exists(rname)) { this.bHasResSData = true; // 图像数据在resS中 FileStream fs = File.Open(rname, FileMode.Open, FileAccess.Read); EndianBinaryReader bs = new EndianBinaryReader(fs); bs.BaseStream.Seek(this.dataPos, SeekOrigin.Begin); textureData = bs.ReadBytes(this.dataSize); bs.Close(); fs.Close(); } else { Console.WriteLine("Got error:{0}", "resS File not found\n can't get Texture2D data"); isTexture2D = false; return; } } else { this.resSName = this.name; this.dataPos = br.BaseStream.Position; textureData = br.ReadBytes(this.dataSize); } } } }
static void CSEQ2MID(EndianBinaryReader ebr, EndianBinaryWriter ebw) { //Getting around uint filesize; int chunkCCount; int chunk8Count; int chunkPostCode; int musicTrackCount; uint seek; uint bpm; uint tpqn; int[] musicTrackOffset; int tracksStart; byte[] midiTrackData; filesize = ebr.ReadUInt32(); chunkCCount = ebr.ReadByte(); chunk8Count = ebr.ReadByte(); chunkPostCode = ebr.ReadByte(); //null track ebr.ReadByte(); //0? for (int i = 0; i < chunkCCount; i++) { ebr.ReadBytes(12); } for (int i = 0; i < chunk8Count; i++) { ebr.ReadBytes(8); } switch (chunkPostCode) { case 1: ebr.ReadBytes(5); break; case 3: ebr.ReadBytes(9); break; default: throw new Exception(chunkPostCode.ToString() + " not recognized!"); } //general music info musicTrackCount = ebr.ReadByte(); bpm = ebr.ReadUInt16(); tpqn = ebr.ReadUInt16(); //Write MThd header ebw.Write(new byte[4] { (byte)'M', (byte)'T', (byte)'h', (byte)'d' }); //MThd ebw.Write((UInt32)6); ebw.Write((UInt16)1); ebw.Write((UInt16)musicTrackCount); ebw.Write((UInt16)tpqn); //offsets musicTrackOffset = new int[musicTrackCount]; for (int i = 0; i < musicTrackCount; i++) { musicTrackOffset[i] = ebr.ReadUInt16(); } //Music tracks seek = 0; while (seek != 9 && seek != 1) { seek = ebr.ReadByte(); } tracksStart = (int)ebr.BaseStream.Position - 1; for (int i = 0; i < musicTrackCount; i++) { ebw.Write(new byte[4] { (byte)'M', (byte)'T', (byte)'r', (byte)'k' }); //MTrk uint mpqn; int channel; uint deltaTime; int opcode; int midiOpCode; int pitch; int velocity; ebr.BaseStream.Position = tracksStart + musicTrackOffset[i]; seek = 0; while (seek != 9 && seek != 1) { seek = ebr.ReadByte(); } channel = ebr.ReadByte(); channel = 0; //gather events using (MemoryStream memory = new MemoryStream()) { using (EndianBinaryWriter ebwTrack = new EndianBinaryWriter(EndianBitConverter.Big, memory)) { if (i == 0)//first track put time signature, tempo { //Tempo ebwTrack.Write((byte)0x00); //delta time ebwTrack.Write((byte)0xFF); //meta event ebwTrack.Write((byte)0x51); //event type ebwTrack.Write((byte)0x03); //length mpqn = (uint)(60000000 / bpm); ebwTrack.Write((byte)(mpqn >> 16)); ebwTrack.Write((UInt16)(mpqn & (0xFFFF))); //Time Signature ebwTrack.Write((byte)0x00); //delta time ebwTrack.Write((byte)0xFF); //meta event ebwTrack.Write((byte)0x58); //event type ebwTrack.Write((byte)0x04); //length ebwTrack.Write((byte)4); //numer ebwTrack.Write((byte)2); //denom ebwTrack.Write((byte)24); //metro ebwTrack.Write((byte)8); //32nds //MIDI reset ebwTrack.Write((byte)0x00); //delta time ebwTrack.Write((byte)0xF0); //meta event ebwTrack.Write((byte)0x05); ebwTrack.Write((byte)0x7E); ebwTrack.Write((byte)0x7F); ebwTrack.Write((byte)0x09); ebwTrack.Write((byte)0x01); ebwTrack.Write((byte)0xF7); } //Go through original events while (true) { deltaTime = r_var_len(ebr); opcode = ebr.ReadByte(); switch (opcode) { case 5: //noteOn midiOpCode = (byte)(0x90 | channel); pitch = ebr.ReadByte(); if (pitch == 0x2E) { pitch = 0x2E; } velocity = ebr.ReadByte(); ebwTrack.Write(g_var_len((uint)deltaTime)); ebwTrack.Write((byte)midiOpCode); ebwTrack.Write((byte)pitch); ebwTrack.Write((byte)velocity); break; case 1: //noteOff midiOpCode = (byte)(0x80 | channel); pitch = ebr.ReadByte(); ebwTrack.Write(g_var_len((uint)deltaTime)); ebwTrack.Write((byte)midiOpCode); ebwTrack.Write((byte)pitch); ebwTrack.Write((byte)0x00); break; case 3: //end track midiOpCode = (byte)0xFF; ebwTrack.Write(g_var_len((uint)deltaTime)); ebwTrack.Write((byte)midiOpCode); ebwTrack.Write((byte)0x2F); ebwTrack.Write((byte)0x00); goto Finish; case 6: //pitch bend?? case 7: //definitely modulation case 9: case 2: //pan? midiOpCode = (byte)(0xB0 | channel); velocity = ebr.ReadByte(); ebwTrack.Write(g_var_len((uint)deltaTime)); ebwTrack.Write((byte)midiOpCode); ebwTrack.Write((byte)0x01); //modulation ebwTrack.Write((byte)velocity); break; default: throw new Exception(opcode.ToString() + " not recognized at " + ebr.BaseStream.Position.ToString()); } //end switch } //end while Finish: ; } //end using ebrTrack midiTrackData = memory.ToArray(); } //end using memory ebw.Write((UInt32)(midiTrackData.Length)); ebw.Write(midiTrackData); }//end for ebr.Close(); ebw.Close(); }
public MatFile(string filename) { Stream file = OpenDataFile(filename); if (!Exists) return; EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, file); CMaterial currentMaterial = null; while (true) { int blockLength = 0; MaterialBlockType blockType = (MaterialBlockType)reader.ReadInt32(); blockLength = reader.ReadInt32(); byte[] flags; switch (blockType) { case MaterialBlockType.Attributes: currentMaterial = new CMaterial(); _materials.Add(currentMaterial); byte[] color = reader.ReadBytes(4); byte[] otherColors = reader.ReadBytes(16); flags = reader.ReadBytes(2); byte[] transform = reader.ReadBytes(24); currentMaterial.SimpMatPixelIndex = reader.ReadByte(); currentMaterial.SimpMatGradientCount = reader.ReadByte(); currentMaterial.DoubleSided = flags[0] == 0x10; currentMaterial.Name = ReadNullTerminatedString(reader); break; case MaterialBlockType.AttributesV2: currentMaterial = new CMaterial(); _materials.Add(currentMaterial); reader.ReadBytes(4); //color reader.ReadBytes(16); //othercolors flags = reader.ReadBytes(4); // flags reader.ReadBytes(24); //transform reader.ReadBytes(4); //unk currentMaterial.DoubleSided = flags[0] == 0x10; reader.BaseStream.Position += 13; currentMaterial.Name = ReadNullTerminatedString(reader); break; case MaterialBlockType.TextureName: currentMaterial.PixName = ReadNullTerminatedString(reader); break; case MaterialBlockType.TabName: string tabName = ReadNullTerminatedString(reader); break; case MaterialBlockType.Null: break; default: reader.Seek(blockLength, SeekOrigin.Current); break; } if (reader.BaseStream.Position == reader.BaseStream.Length) break; } reader.Close(); }
public DatFile(string filename, bool deformMainModel) { if (filename.EndsWith(".ACT", StringComparison.InvariantCultureIgnoreCase)) filename = filename.ToUpper().Replace(".ACT", ".DAT"); //fix up some 3rd party vehicle weirdness CModel currentModel = null; Stream file = OpenDataFile(filename); if (!Exists) return; EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, file); while (true) { int type = reader.ReadInt32(); int size = 0; if (type != (int)BlockType.Null) size = reader.ReadInt32(); switch (type) { case (int)BlockType.Null: break; case (int)BlockType.ModelName: reader.Seek(2, SeekOrigin.Current); string name = ReadNullTerminatedString(reader); if (deformMainModel && Path.GetFileNameWithoutExtension(name).Equals(Path.GetFileNameWithoutExtension(filename), StringComparison.InvariantCultureIgnoreCase)) currentModel = new CDeformableModel(); else currentModel = new CModel(); currentModel.Name = name; _models.Add(currentModel); break; case (int)BlockType.Vertices: ReadVertexBlock(reader, currentModel); break; case (int)BlockType.Faces: ReadPolygonBlock(reader, currentModel); break; case (int)BlockType.TextureCoords: ReadTextureMapBlock(reader, currentModel); break; case (int)BlockType.Materials: ReadMaterialsBlock(reader, currentModel); break; case (int)BlockType.FaceMaterials: ReadFaceMaterialsBlock(reader, currentModel); break; default: Debug.WriteLine("Unknown section: " + type); reader.Seek(size, SeekOrigin.Current); break; } if (reader.BaseStream.Position == reader.BaseStream.Length) break; } reader.Close(); if (filename == "FAUST.DAT") { } _models.Resolve(true); }
/* * I've been studying the NSBCA format heavily over the last few days trying to figure it out. * I've determined that the first offset in a joint animation contains Pivoting data, and the second section contains Rotation data. * Rotation keyframes are called when the second byte equals 0 and Pivot keyframes are called when it equals 128, however the data itself is definitely stored a little differently to how it is stored in NSBMD files. * Scaling keyframes hold two scaling values for whatever reason, with Translation keyframes being just straight values that can be a signed word/dword. * Each animation has a frame length, however each object in an animation seems to have a start and end position that typically don't match up with the total number of frames. * Now I haven't had much experience with model animations, but I'm guessing this might have like a decay effect on the animation if anyone has ever played around with animations in Maya? * The trickiest part is calculating the right number of keyframes stored in each object as there isn't an actual value written down anywhere. * From what I can tell it's calculated based on a bunch of things including the difference in object frame length over animation frame length, the rate in which the object (and possibly the animation) plays back as well as rounding to the upper whole number. * This looks a bit funky and overcomplicated but so far all the animations I've been working with calculate the correct number of keyframes, so I'm assuming I'm on the right track. * Am yet to get to the point of loading animations into a model, but hopefully I won't get some spastic result :S * * * * * Object Flag: --zyx-Sr-RZYX-T- * > found in the header of each object of an animation * =========================== * T - has Translation keyframes (0 Yes| 1 No) * XYZ - flags for Translation attributes * R - has Rotation/Pivot keyframes (0 Yes| 1 No) * r - flag for Rotation/Pivot attribute * S - has Scale keyframes (0 Yes| 1 No) * xyz - flags for Scale attributes * =========================== * if T-XYZ = 1 * > Fixed Translation value (signed dword) * if R-r = 1 * > Fixed Rotation/Pivot value (dword/2*word?) * if S-xyz = 1 * > Fixed Scale value (2*dword) * * Note: The below is only done when the bit flag equals 0 for that attribute (TX, TY, TZ, R/P, SX, SY, SZ) * * a|b = datasize = playback speed * > a & b are flags stored in the object header for each attribute * * Translate * ----------------------------------------------------------- * 2|0 = word = 1/1 * 2|1 = word = 1/2 * 2|2 = word = 1/3 * 0|1 = dword = 1/2 * * Rotate * ----------------------------------------------------------- * 0|0 = 2*byte = 1/1 * 0|1 = 2*byte = 1/2 * 0|2 = 2*byte = 1/3 * > byte0 = index * > byte1 = 0 Rotation | 128 Pivot * > not completely sure on rotation yet * * Scale * ----------------------------------------------------------- * 2|1 = 2*word = 1/1 * 2|1 = 2*word = 1/2 * ----------------------------------------------------------- * * Attribute [animation flag|start|end|a|b] bytes/keyframes - animation length * > bytes - the actual size of the data stored * > keyframes - bytes/datasize(see above) * * Basabasa - 0 Pivot - 33 Rotation * =========================================================== * Translate [3|0|34|2|1] 38/19 - 36 Frames * Rotate [3|0|34|0|1] 38/19 - 36 Frames * Scale [3|0|34|2|1] 76/19 - 36 Frames * =========================================================== * * Basabasa2 - 1 Pivot - 20 Rotation * =========================================================== * Rotate [3|0|78|0|1] 82/41 - 80 Frames * =========================================================== * * Bilikyu - 31 Pivot * =========================================================== * Translate [3|0|58|2|1] 62/31 - 60 Frames * Rotate [3|0|58|0|1] 62/31 - 60 Frames * =========================================================== * * Donketu - 12 Pivot / 20 Rotation * =========================================================== * Translate [3|0|10|0|1] 24/06 - 11 Frames (dword) * Translate [3|0|10|2|1] 12/06 - 11 Frames * Translate [1|0|02|2|0] 04/02 - 02 Frames * Rotate [3|0|10|0|1] 14/07 - 11 Frames * =========================================================== * * Gesso - 39 Pivot * =========================================================== * Translate [0|0|16|2|2] 14/07 - 19 Frames * Translate [0|0|16|2|2] 12/06 - 18 Frames * Translate [0|0|12|2|2] 10/05 - 14 Frames * Scale [0|0|16|2|2] 28/07 - 19 Frames * Scale [0|0|16|2|2] 24/06 - 18 Frames * Rotate [0|0|16|0|2] 16/08 - 19 Frames * Rotate [0|0|16|0|2] 16/08 - 18 Frames * Rotate [0|0|12|0|2] 14/07 - 14 Frames * =========================================================== * * TTL Bird * =========================================================== * Translate [1|0|05|2|0] 10/05 - 05 Frames * Rotate [1|0|05|0|0] 10/05 - 05 Frames * =========================================================== * * Gamaguchi - 11 Pivot - 52 Rotation * =========================================================== * Translate [3|0|08|2|0] 16/08 - 08 Frames * Translate [3|0|07|2|0] 14/07 - 07 Frames * Translate [3|0|16|2|0] 32/16 - 16 Frames * Rotate [3|0|08|0|0] 16/08 - 08 Frames * Rotate [1|0|07|0|0] 14/07 - 07 Frames * Rotate [3|0|16|0|0] 32/16 - 16 Frames * Scale [3|0|08|2|0] 32/08 - 08 Frames * Scale [1|0|07|2|0] 28/07 - 07 Frames * =========================================================== */ public static NSBCA_File Read(string Filename) { byte[] file_ = File.ReadAllBytes(Filename); if (file_[0] == 76 && file_[1] == 90 && file_[2] == 55 && file_[3] == 55) { } EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(file_), Endianness.LittleEndian); NSBCA_File ns = new NSBCA_File(); ns.Header.ID = er.ReadString(Encoding.ASCII, 4); if (ns.Header.ID == "BCA0") { ns.Header.Magic = er.ReadBytes(4); ns.Header.file_size = er.ReadInt32(); ns.Header.header_size = er.ReadInt16(); ns.Header.nSection = er.ReadInt16(); ns.Header.Section_Offset = new Int32[ns.Header.nSection]; for (int i = 0; i < ns.Header.nSection; i++) { ns.Header.Section_Offset[i] = er.ReadInt32(); } ns.JNT0.ID = er.ReadString(Encoding.ASCII, 4); if (ns.JNT0.ID == "JNT0") { ns.JNT0.Size = er.ReadInt32(); //3D Info Structure ns.JNT0.dummy = er.ReadByte(); ns.JNT0.num_objs = er.ReadByte(); ns.JNT0.section_size = er.ReadInt16(); ns.JNT0.unknownBlock.header_size = er.ReadInt16(); ns.JNT0.unknownBlock.section_size = er.ReadInt16(); ns.JNT0.unknownBlock.constant = er.ReadInt32(); ns.JNT0.unknownBlock.unknown1 = new short[ns.JNT0.num_objs]; ns.JNT0.unknownBlock.unknown2 = new short[ns.JNT0.num_objs]; for (int i = 0; i < ns.JNT0.num_objs; i++) { ns.JNT0.unknownBlock.unknown1[i] = er.ReadInt16(); ns.JNT0.unknownBlock.unknown2[i] = er.ReadInt16(); } ns.JNT0.infoBlock.header_size = er.ReadInt16(); ns.JNT0.infoBlock.data_size = er.ReadInt16(); ns.JNT0.infoBlock.Data = new NSBCA_File.jnt0.Info.info[ns.JNT0.num_objs]; for (int i = 0; i < ns.JNT0.num_objs; i++) { ns.JNT0.infoBlock.Data[i].Objectoffset = er.ReadInt32(); } ns.JNT0.names = new string[ns.JNT0.num_objs]; for (int i = 0; i < ns.JNT0.num_objs; i++) { ns.JNT0.names[i] = er.ReadString(Encoding.ASCII, 16).Replace("\0", ""); } ns.JAC = new NSBCA_File.J_AC[ns.JNT0.num_objs]; for (int i = 0; i < ns.JNT0.num_objs; i++) { er.BaseStream.Position = ns.Header.Section_Offset[0] + ns.JNT0.infoBlock.Data[i].Objectoffset; ns.JAC[i].ID = er.ReadString(Encoding.ASCII, 4); if (ns.JAC[i].ID == "J" + (char)0x00 + "AC") { ns.JAC[i].NrFrames = er.ReadInt16(); ns.JAC[i].NrObjects = er.ReadInt16(); ns.JAC[i].Unknown1 = er.ReadInt32(); ns.JAC[i].Offset1 = er.ReadInt32(); ns.JAC[i].Offset2 = er.ReadInt32(); long curposs = er.BaseStream.Position; if (ns.JAC[i].Offset2 != ns.JAC[i].Offset1) { er.BaseStream.Position = ns.Header.Section_Offset[0] + ns.JNT0.infoBlock.Data[i].Objectoffset + ns.JAC[i].Offset1; ns.JAC[i].JointData = er.ReadBytes(ns.JAC[i].Offset2 - ns.JAC[i].Offset1); er.BaseStream.Position = curposs; } long dataoffset = 0; ns.JAC[i].ObjInfoOffset = new Int32[ns.JAC[i].NrObjects]; for (int j = 0; j < ns.JAC[i].NrObjects; j++) { ns.JAC[i].ObjInfoOffset[j] = er.ReadInt16(); } ns.JAC[i].ObjInfo = new NSBCA_File.J_AC.objInfo[ns.JAC[i].NrObjects]; for (int j = 0; j < ns.JAC[i].NrObjects; j++) { er.BaseStream.Position = ns.Header.Section_Offset[0] + /* ns.JNT0.section_size*/ ns.JNT0.infoBlock.Data[i].Objectoffset + ns.JAC[i].ObjInfoOffset[j];// + 8; ns.JAC[i].ObjInfo[j].Flag = er.ReadInt16(); ns.JAC[i].ObjInfo[j].Unknown1 = er.ReadByte(); ns.JAC[i].ObjInfo[j].ID = er.ReadByte(); ns.JAC[i].ObjInfo[j].translate = new List <float> [3]; ns.JAC[i].ObjInfo[j].translate[0] = new List <float>(); ns.JAC[i].ObjInfo[j].translate[1] = new List <float>(); ns.JAC[i].ObjInfo[j].translate[2] = new List <float>(); ns.JAC[i].ObjInfo[j].translate_keyframes = new List <float> [3]; ns.JAC[i].ObjInfo[j].translate_keyframes[0] = new List <float>(); ns.JAC[i].ObjInfo[j].translate_keyframes[1] = new List <float>(); ns.JAC[i].ObjInfo[j].translate_keyframes[2] = new List <float>(); ns.JAC[i].ObjInfo[j].rotate = new List <float>(); ns.JAC[i].ObjInfo[j].rotate_keyframes = new List <float> [2]; ns.JAC[i].ObjInfo[j].rotate_keyframes[0] = new List <float>(); ns.JAC[i].ObjInfo[j].rotate_keyframes[1] = new List <float>(); ns.JAC[i].ObjInfo[j].scale = new List <float> [3][]; ns.JAC[i].ObjInfo[j].scale[0] = new List <float> [2]; ns.JAC[i].ObjInfo[j].scale[1] = new List <float> [2]; ns.JAC[i].ObjInfo[j].scale[2] = new List <float> [2]; ns.JAC[i].ObjInfo[j].scale[0][0] = new List <float>(); ns.JAC[i].ObjInfo[j].scale[0][1] = new List <float>(); ns.JAC[i].ObjInfo[j].scale[1][0] = new List <float>(); ns.JAC[i].ObjInfo[j].scale[1][1] = new List <float>(); ns.JAC[i].ObjInfo[j].scale[2][0] = new List <float>(); ns.JAC[i].ObjInfo[j].scale[2][1] = new List <float>(); ns.JAC[i].ObjInfo[j].scale_keyframes = new List <float> [3][]; ns.JAC[i].ObjInfo[j].scale_keyframes[0] = new List <float> [2]; ns.JAC[i].ObjInfo[j].scale_keyframes[1] = new List <float> [2]; ns.JAC[i].ObjInfo[j].scale_keyframes[2] = new List <float> [2]; ns.JAC[i].ObjInfo[j].scale_keyframes[0][0] = new List <float>(); ns.JAC[i].ObjInfo[j].scale_keyframes[0][1] = new List <float>(); ns.JAC[i].ObjInfo[j].scale_keyframes[1][0] = new List <float>(); ns.JAC[i].ObjInfo[j].scale_keyframes[1][1] = new List <float>(); ns.JAC[i].ObjInfo[j].scale_keyframes[2][0] = new List <float>(); ns.JAC[i].ObjInfo[j].scale_keyframes[2][1] = new List <float>(); double[] speed = { 1.0D, 0.5D, 0.33333333333333331D }; if (((ns.JAC[i].ObjInfo[j].Flag >> 1) & 1) == 0) { //struct.DModelAnimation.MTransformAni trans[] = new struct.DModelAnimation.MTransformAni[3]; //string msg = new StringBuilder().Append(msg).Append("\n -> Translate: ").ToString(); //string[] type = { "X", "Y", "Z" }; for (int k = 0; k < 3; k++) { //trans[k] = new struct.DModelAnimation.MTransformAni(this); int tflag = ns.JAC[i].ObjInfo[j].Flag >> 3 + k & 1; //msg = new StringBuilder().Append(msg).Append("\n -> T").Append(type[k]).Append(tflag).Append("[").ToString(); if (tflag == 1) { int tvar = er.ReadInt32(); //trans[k].setFrame((float)tvar / divide); ns.JAC[i].ObjInfo[j].translate[k].Add((float)tvar / 4096f); //msg = (new StringBuilder()).Append(msg).Append(tvar).ToString(); continue; } else { int param2 = er.ReadInt32(); int startFrame = param2 & 0xffff; ns.JAC[i].ObjInfo[j].tStart = startFrame; int endFrame = param2 >> 16 & 0xfff; ns.JAC[i].ObjInfo[j].tEnd = endFrame; int var2 = param2 >> 28 & 3; int speedId = param2 >> 30 & 3; int toffset = er.ReadInt32(); int width = var2 != 0 ? 2 : 4; int extra = (ns.JAC[i].Unknown1 != 3 ? 0 : ns.JAC[i].NrFrames - endFrame); int length = (int)Math.Ceiling((double)(ns.JAC[i].NrFrames + extra) * speed[speedId]); long curpos = er.BaseStream.Position; for (int t = 0; t < length; t++) { er.BaseStream.Position = ns.Header.Section_Offset[0] + /* ns.JNT0.section_size*/ ns.JNT0.infoBlock.Data[i].Objectoffset + toffset + (t * width); if (dataoffset == 0) { dataoffset = toffset; } float keyFrame = (width != 2 ? (float)er.ReadInt32() : (float)er.ReadInt16()); ns.JAC[i].ObjInfo[j].translate_keyframes[k].Add((float)LibNDSFormats.NSBMD.NSBMDGlRenderer.sign((int)keyFrame, (width != 2 ? 32 : 16)) / 4096f); //m = (new StringBuilder()).append(m).append("\n -> #").append(t).append(": ").append(keyFrame).toString(); } er.BaseStream.Position = curpos; } } } if (((ns.JAC[i].ObjInfo[j].Flag >> 6) & 1) == 0) { int rflag = ns.JAC[i].ObjInfo[j].Flag >> 8 & 1; if (rflag == 1) { //dataParser _tmp14 = pa; int rvar = er.ReadInt32(); //dataParser.getInt(data, jump, 4); ns.JAC[i].ObjInfo[j].rotate.Add((float)rvar); //msg = (new StringBuilder()).append(msg).append(rvar).toString(); //jump += 4; } else { int param2 = er.ReadInt32(); int startFrame = param2 & 0xffff; ns.JAC[i].ObjInfo[j].rStart = startFrame; int endFrame = param2 >> 16 & 0xfff; ns.JAC[i].ObjInfo[j].rEnd = endFrame; int var2 = param2 >> 28 & 3; int speedId = param2 >> 30 & 3; int roffset = er.ReadInt32(); int width = 2;//var2 != 0 ? 2 : 4; int length = (int)Math.Ceiling((double)(ns.JAC[i].NrFrames) * speed[speedId]); long curpos = er.BaseStream.Position; for (int r = 0; r < length; r++) { er.BaseStream.Position = ns.Header.Section_Offset[0] + /* ns.JNT0.section_size*/ ns.JNT0.infoBlock.Data[i].Objectoffset + roffset + (r * width); if (dataoffset == 0) { dataoffset = roffset; } int rvar6 = er.ReadInt16(); int rindex = rvar6 & 0x7fff; int mode = rvar6 >> 15 & 1; ns.JAC[i].ObjInfo[j].rotate_keyframes[0].Add(rindex); ns.JAC[i].ObjInfo[j].rotate_keyframes[1].Add(mode); } er.BaseStream.Position = curpos; } } if ((ns.JAC[i].ObjInfo[j].Flag >> 9 & 1) == 0) { //struct.DModelAnimation.MScaleAni scale[] = new struct.DModelAnimation.MScaleAni[3]; //msg = (new StringBuilder()).append(msg).append("\n -> Scale: ").toString(); for (int k = 0; k < 3; k++) { //scale[k] = new struct.DModelAnimation.MScaleAni(this); int sflag = ns.JAC[i].ObjInfo[j].Flag >> 11 + k & 1; //msg = (new StringBuilder()).append(msg).append("\n -> S").append(type[k]).append(sflag).append("[").toString(); if (sflag == 1) { //dataParser _tmp19 = pa; int svar1 = er.ReadInt32();//dataParser.getInt(data, jump, 4); ns.JAC[i].ObjInfo[j].scale[k][0].Add((float)svar1 / 4096f); //dataParser _tmp20 = pa; int svar2 = er.ReadInt32();//dataParser.getSign(data, jump + 4, 4); ns.JAC[i].ObjInfo[j].scale[k][1].Add((float)svar2 / 4096f); //int svar3 = er.ReadInt32();//dataParser.getSign(data, jump + 4, 4); //int svar4 = er.ReadInt32();//dataParser.getSign(data, jump + 4, 4); //ns.JAC[i].ObjInfo[j].scale[k][1].Add((float)svar2 / 4096f); //scale[k].setFrame(new float[] { // (float)svar1 / divide, (float)svar2 / divide //}); //msg = (new StringBuilder()).append(msg).append(svar1).append("|").append(svar2).toString(); //jump += 8; continue; } else { int param2 = er.ReadInt32(); int startFrame = param2 & 0xffff; ns.JAC[i].ObjInfo[j].sStart = startFrame; int endFrame = param2 >> 16 & 0xfff; ns.JAC[i].ObjInfo[j].sEnd = endFrame; int var2 = param2 >> 28 & 3; int speedId = param2 >> 30 & 3; int soffset = er.ReadInt32(); int width = var2 != 0 ? 2 : 4; int length = (int)Math.Ceiling((double)(ns.JAC[i].NrFrames) * speed[speedId]); long curpos = er.BaseStream.Position; for (int s = 0; s < length; s++) { er.BaseStream.Position = ns.Header.Section_Offset[0] + /* ns.JNT0.section_size*/ ns.JNT0.infoBlock.Data[i].Objectoffset + soffset + (s * width * 2); if (dataoffset == 0) { dataoffset = soffset; } ns.JAC[i].ObjInfo[j].scale_keyframes[k][0].Add((float)(width != 2 ? (float)er.ReadInt32() : (float)er.ReadInt16()) / 4096f); ns.JAC[i].ObjInfo[j].scale_keyframes[k][1].Add((float)(width != 2 ? (float)er.ReadInt32() : (float)er.ReadInt16()) / 4096f); } er.BaseStream.Position = curpos; } } } } if (dataoffset != 0) { curposs = er.BaseStream.Position; er.BaseStream.Position = ns.Header.Section_Offset[0] + ns.JNT0.infoBlock.Data[i].Objectoffset + ns.JAC[i].Offset2; ns.JAC[i].RotationData = er.ReadBytes((int)dataoffset - ns.JAC[i].Offset2); er.BaseStream.Position = curposs; } } else { //MessageBox.Show("Error"); er.Close(); return(ns); } } } else { //MessageBox.Show("Error"); er.Close(); return(ns); } } else { //MessageBox.Show("Error"); er.Close(); return(ns); } er.Close(); return(ns); }
public NDS(byte[] data) { EndianBinaryReader er = new EndianBinaryReader(new MemoryStream(data), Endianness.LittleEndian); Header = new RomHeader(er); er.BaseStream.Position = Header.MainRomOffset; MainRom = er.ReadBytes((int)Header.MainSize); if (er.ReadUInt32() == 0xDEC00621) //Nitro Footer! { er.BaseStream.Position -= 4; StaticFooter = new NitroFooter(er); } er.BaseStream.Position = Header.SubRomOffset; SubRom = er.ReadBytes((int)Header.SubSize); er.BaseStream.Position = Header.FntOffset; Fnt = new RomFNT(er); er.BaseStream.Position = Header.MainOvtOffset; MainOvt = new RomOVT[Header.MainOvtSize / 32]; for (int i = 0; i < Header.MainOvtSize / 32; i++) { MainOvt[i] = new RomOVT(er); } er.BaseStream.Position = Header.SubOvtOffset; SubOvt = new RomOVT[Header.SubOvtSize / 32]; for (int i = 0; i < Header.SubOvtSize / 32; i++) { SubOvt[i] = new RomOVT(er); } er.BaseStream.Position = Header.FatOffset; Fat = new FileAllocationEntry[Header.FatSize / 8]; for (int i = 0; i < Header.FatSize / 8; i++) { Fat[i] = new FileAllocationEntry(er); } if (Header.BannerOffset != 0) { er.BaseStream.Position = Header.BannerOffset; Banner = new RomBanner(er); } FileData = new byte[Header.FatSize / 8][]; for (int i = 0; i < Header.FatSize / 8; i++) { er.BaseStream.Position = Fat[i].fileTop; FileData[i] = er.ReadBytes((int)Fat[i].fileSize); } //RSA Signature if (Header.RomSize + 0x88 <= er.BaseStream.Length) { er.BaseStream.Position = Header.RomSize; byte[] RSASig = er.ReadBytes(0x88); for (int i = 0; i < RSASig.Length; i++) { //It could be padding, so check if there is something other than 0xFF or 0x00 if (RSASig[i] != 0xFF || RSASig[i] != 0x00) { RSASignature = RSASig; break; } } } er.Close(); }