private void ReadTEX(string filename, Stream tex) { var bin = new BinaryReader(tex); BlizzHeader chunk; long position = 0; while (position < tex.Length) { tex.Position = position; chunk = new BlizzHeader(bin.ReadChars(4), bin.ReadUInt32()); chunk.Flip(); position = tex.Position + chunk.Size; switch (chunk.ToString()) { case "TXVR": ReadTXVRChunk(bin); continue; case "TXFN": ReadTXFNChunk(bin, chunk); continue; case "TXBT": case "TXMD": continue; default: throw new Exception(String.Format("{2} Found unknown header at offset {1} \"{0}\" while we should've already read them all!", chunk.ToString(), position.ToString(), filename)); } } }
protected byte[] GetImageBytes() { Stream fs = FileUpload.PostedFile.InputStream; BinaryReader br = new BinaryReader(fs); Byte[] bytes = br.ReadBytes((Int32)fs.Length); return bytes; }
private void ReadTXFNChunk(BinaryReader bin, BlizzHeader chunk) { //List of BLP filenames var blpFilesChunk = bin.ReadBytes((int)chunk.Size); var str = new StringBuilder(); for (var i = 0; i < blpFilesChunk.Length; i++) { if (blpFilesChunk[i] == '\0') { if (str.Length > 1) { str.Replace("..", "."); str.Append(".blp"); //Filenames in TEX dont have have BLP extensions if (!CASC.FileExists(str.ToString())) { new WoWFormatLib.Utils.MissingFile(str.ToString()); } } str = new StringBuilder(); } else { str.Append((char)blpFilesChunk[i]); } } }
private static string DeCrypting() { var res = string.Empty; var file = new FileStream(Controller.GetPath(), FileMode.Open, FileAccess.Read, FileShare.None, 32, FileOptions.SequentialScan); var reader = new BinaryReader(file); var writer = new BinaryWriter(new FileStream(Processor.GetNewName(Controller.GetPath()), FileMode.Create, FileAccess.Write, FileShare.None, 32, FileOptions.WriteThrough)); try { var pos = 0; while (pos < file.Length) { var c = reader.ReadUInt16(); //var pow = Processor.fast_exp(c, Controller.GetKc(), Controller.GetR()); var pow = Processor.Pows(c, Controller.GetKc(), Controller.GetR()); if (pos < 256) res += pow + " "; writer.Write((byte)(pow)); pos += 2; } } finally { writer.Close(); reader.Close(); } return "Decoding Complete!\n" + res; }
public ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter) { _client = client; _stream = stream; _binaryReader = binaryReader; _binaryWriter = binaryWriter; }
internal BFCodeLabel(BinaryReader reader) { _name = reader.ReadCString(24); _offset = reader.ReadUInt32(); int unused = reader.ReadInt32(); _opcodeIndex = (int)_offset; }
public IDictionary<byte[], IList<long>> Read(BinaryReader reader, int keyWidth) { var indexWidth = reader.ReadInt64(); var buckets = new Dictionary<byte[], IList<long>>(new ByteArrayComparer()); while (reader.BaseStream.Position < reader.BaseStream.Length) { var bucket = new List<long>(); var index = reader.ReadBytes(keyWidth); for (int i = 0; i < indexWidth - keyWidth; i += sizeof (long)) { var value = reader.ReadInt64(); if (value != long.MaxValue) { bucket.Add(value); } else { reader.BaseStream.Seek(indexWidth - keyWidth - i - sizeof (long), SeekOrigin.Current); break; } } buckets[index] = bucket; } return buckets; }
public void TestIncompleteRewind() { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(1); bw.Write(2); bw.Write(3); bw.Write(4); bw.Write(5); bw.Write(6); bw.Write(7); bw.Flush(); ms.Position = 0; RewindableStream stream = new RewindableStream(ms); stream.StartRecording(); BinaryReader br = new BinaryReader(stream); Assert.AreEqual(br.ReadInt32(), 1); Assert.AreEqual(br.ReadInt32(), 2); Assert.AreEqual(br.ReadInt32(), 3); Assert.AreEqual(br.ReadInt32(), 4); stream.Rewind(true); Assert.AreEqual(br.ReadInt32(), 1); Assert.AreEqual(br.ReadInt32(), 2); stream.StartRecording(); Assert.AreEqual(br.ReadInt32(), 3); Assert.AreEqual(br.ReadInt32(), 4); Assert.AreEqual(br.ReadInt32(), 5); stream.Rewind(true); Assert.AreEqual(br.ReadInt32(), 3); Assert.AreEqual(br.ReadInt32(), 4); Assert.AreEqual(br.ReadInt32(), 5); Assert.AreEqual(br.ReadInt32(), 6); Assert.AreEqual(br.ReadInt32(), 7); }
public KinectReader(Stream fileStream, int width, int height) { this.Width = width; this.Height = height; this.reader = new BinaryReader(fileStream); this.createIndexes(); }
// // Un-marshal an object instance from the data input stream // public override void TightUnmarshal(OpenWireFormat wireFormat, Object o, BinaryReader dataIn, BooleanStream bs) { base.TightUnmarshal(wireFormat, o, dataIn, bs); ConsumerInfo info = (ConsumerInfo)o; info.ConsumerId = (ConsumerId) TightUnmarshalCachedObject(wireFormat, dataIn, bs); info.Browser = bs.ReadBoolean(); info.Destination = (ActiveMQDestination) TightUnmarshalCachedObject(wireFormat, dataIn, bs); info.PrefetchSize = dataIn.ReadInt32(); info.MaximumPendingMessageLimit = dataIn.ReadInt32(); info.DispatchAsync = bs.ReadBoolean(); info.Selector = TightUnmarshalString(dataIn, bs); info.SubscriptionName = TightUnmarshalString(dataIn, bs); info.NoLocal = bs.ReadBoolean(); info.Exclusive = bs.ReadBoolean(); info.Retroactive = bs.ReadBoolean(); info.Priority = dataIn.ReadByte(); if (bs.ReadBoolean()) { short size = dataIn.ReadInt16(); BrokerId[] value = new BrokerId[size]; for( int i=0; i < size; i++ ) { value[i] = (BrokerId) TightUnmarshalNestedObject(wireFormat,dataIn, bs); } info.BrokerPath = value; } else { info.BrokerPath = null; } info.AdditionalPredicate = (BooleanExpression) TightUnmarshalNestedObject(wireFormat, dataIn, bs); info.NetworkSubscription = bs.ReadBoolean(); info.OptimizedAcknowledge = bs.ReadBoolean(); info.NoRangeAcks = bs.ReadBoolean(); }
public RespawnInfo(BinaryReader reader, int Version, int Customversion) { MonsterIndex = reader.ReadInt32(); Location = new Point(reader.ReadInt32(), reader.ReadInt32()); Count = reader.ReadUInt16(); Spread = reader.ReadUInt16(); Delay = reader.ReadUInt16(); Direction = reader.ReadByte(); if (Envir.LoadVersion >= 36) { RoutePath = reader.ReadString(); } if (Version > 67) { RandomDelay = reader.ReadUInt16(); RespawnIndex = reader.ReadInt32(); SaveRespawnTime = reader.ReadBoolean(); RespawnTicks = reader.ReadUInt16(); } else { RespawnIndex = ++SMain.Envir.RespawnIndex; } }
public static PEType GetPEType(string path) { if (string.IsNullOrEmpty(path)) return PEType.Unknown; var br = new BinaryReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite )); br.BaseStream.Seek(0x3C, SeekOrigin.Begin); br.BaseStream.Seek(br.ReadInt32() + 4, SeekOrigin.Begin); ushort machine = br.ReadUInt16(); br.Close(); if (machine == 0x014C) return PEType.X32; if (machine == 0x8664) return PEType.X64; return PEType.Unknown; }
public void Load(BinaryReader br, FileStream fs) { Offset = br.ReadInt32(); Offset += 16; FrameCount = br.ReadInt32(); MipWidth = br.ReadInt32(); MipHeight = br.ReadInt32(); StartX = br.ReadInt32(); StartY = br.ReadInt32(); TileCount = br.ReadUInt16(); TotalCount = br.ReadUInt16(); CellWidth = br.ReadUInt16(); CellHeight = br.ReadUInt16(); Frames = new EanFrame[TotalCount]; long curPos = fs.Position; fs.Seek((long)Offset, SeekOrigin.Begin); for (int i = 0; i < TotalCount; i++) { Frames[i].X = br.ReadUInt16(); Frames[i].Y = br.ReadUInt16(); Frames[i].Width = br.ReadUInt16(); Frames[i].Height = br.ReadUInt16(); } fs.Seek((long)curPos, SeekOrigin.Begin); }
static Map LoadHeaderInternal( Stream stream ) { BinaryReader bs = new BinaryReader( stream ); byte version = bs.ReadByte(); if( version != 1 && version != 2 ) throw new MapFormatException(); Position spawn = new Position(); // Read in the spawn location spawn.X = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32); spawn.H = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32); spawn.Y = (short)(IPAddress.NetworkToHostOrder( bs.ReadInt16() ) * 32); // Read in the spawn orientation spawn.R = bs.ReadByte(); spawn.L = bs.ReadByte(); // Read in the map dimesions int widthX = IPAddress.NetworkToHostOrder( bs.ReadInt16() ); int widthY = IPAddress.NetworkToHostOrder( bs.ReadInt16() ); int height = IPAddress.NetworkToHostOrder( bs.ReadInt16() ); Map map = new Map( null, widthX, widthY, height, false ); map.SetSpawn( spawn ); return map; }
internal override void Read(BinaryReader reader) { Version = reader.ReadUInt16(); VersionNeededToExtract = reader.ReadUInt16(); Flags = (HeaderFlags) reader.ReadUInt16(); CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16(); LastModifiedTime = reader.ReadUInt16(); LastModifiedDate = reader.ReadUInt16(); Crc = reader.ReadUInt32(); CompressedSize = reader.ReadUInt32(); UncompressedSize = reader.ReadUInt32(); ushort nameLength = reader.ReadUInt16(); ushort extraLength = reader.ReadUInt16(); ushort commentLength = reader.ReadUInt16(); DiskNumberStart = reader.ReadUInt16(); InternalFileAttributes = reader.ReadUInt16(); ExternalFileAttributes = reader.ReadUInt32(); RelativeOffsetOfEntryHeader = reader.ReadUInt32(); byte[] name = reader.ReadBytes(nameLength); Name = DecodeString(name); byte[] extra = reader.ReadBytes(extraLength); byte[] comment = reader.ReadBytes(commentLength); Comment = DecodeString(comment); LoadExtra(extra); }
/// <summary> /// Creates texture atlas from stream. /// </summary> /// <param name="device"></param> public TextureAtlas ( RenderSystem rs, Stream stream, bool useSRgb = false ) { var device = rs.Game.GraphicsDevice; using ( var br = new BinaryReader(stream) ) { br.ExpectFourCC("ATLS", "texture atlas"); int count = br.ReadInt32(); for ( int i=0; i<count; i++ ) { var element = new Element(); element.Index = i; element.Name = br.ReadString(); element.X = br.ReadInt32(); element.Y = br.ReadInt32(); element.Width = br.ReadInt32(); element.Height = br.ReadInt32(); elements.Add( element ); } int ddsFileLength = br.ReadInt32(); var ddsImageBytes = br.ReadBytes( ddsFileLength ); texture = new UserTexture( rs, ddsImageBytes, useSRgb ); } dictionary = elements.ToDictionary( e => e.Name ); }
public MDBlob(BinaryReader reader) { //read length indicator _length = MModule.DecodeInt32(reader); _data = reader.ReadBytes(_length); }
public void testWrite() { MemoryStream stream = new MemoryStream(); CollectionMetadataWriter writer = new CollectionMetadataWriter(stream); DocumentInfo doc1 = new DocumentInfo("http://www.google.com/index.html", "Google", 150, "#Section1", null); DocumentInfo doc2 = new DocumentInfo("http://www.google.com/index.html", "Google", 250, "#Section2", null); writer.AddDocumentInfo(0, doc1); writer.AddDocumentInfo(1, doc2); writer.WriteOut(); BinaryReader reader = new BinaryReader(stream); long collectionTokenCount = reader.ReadInt64(); Assert.AreEqual(400, collectionTokenCount); FileIndex<long, DocumentInfo> documentIndex = new FileIndex<long, DocumentInfo>( new LongEncoder(), new DocumentInfoEncoder(), stream); Assert.AreEqual(2, documentIndex.EntryCount); DocumentInfo docInfo; Assert.IsTrue(documentIndex.TryGet(0, out docInfo)); Assert.AreEqual(doc1, docInfo); Assert.IsTrue(documentIndex.TryGet(1, out docInfo)); Assert.AreEqual(doc2, docInfo); }
static RadarColorData() { using (FileStream index = new FileStream(FileManager.GetFilePath("Radarcol.mul"), FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader bin = new BinaryReader(index); // Prior to 7.0.7.1, all clients have 0x10000 colors. Newer clients have fewer colors. int colorCount = (int)index.Length / 2; for (int i = 0; i < colorCount; i++) { uint c = bin.ReadUInt16(); Colors[i] = 0xFF000000 | ( ((((c >> 10) & 0x1F) * multiplier)) | ((((c >> 5) & 0x1F) * multiplier) << 8) | (((c & 0x1F) * multiplier) << 16) ); } // fill the remainder of the color table with non-transparent magenta. for (int i = colorCount; i < Colors.Length; i++) { Colors[i] = 0xFFFF00FF; } Metrics.ReportDataRead((int)bin.BaseStream.Position); } }
public static MessageBase Deserialize(byte[] data) { using (MemoryStream stream = new MemoryStream(data)) using (BinaryReader reader = new BinaryReader(stream)) { // Ignore initial key reader.ReadByte(); byte payloadLength = reader.ReadByte(); byte packageSequence = reader.ReadByte(); byte systemId = reader.ReadByte(); byte componentId = reader.ReadByte(); byte messageId = reader.ReadByte(); // Create instance based on message id MessageBase message = null; Type messageType; if (_messageTypes.TryGetValue(messageId, out messageType)) { message = (MessageBase)Activator.CreateInstance(messageType); message._fields = new object[message._fieldTypes.Length]; for (int i = 0; i < message._fieldTypes.Length; ++i) { message.ReadField(reader, i); } // TODO: Verify CRC byte LSBCRC = reader.ReadByte(); byte MSBCRC = reader.ReadByte(); } return message; } }
public short[,] Read(string filePath) { short[,] imagePixels = null; FileStream fs = File.Open(filePath, FileMode.Open); using (BinaryReader reader = new BinaryReader(fs)) { if (ReadHeader(reader)) { int width, height; byte depth; if (ReadIHDR(reader, out width, out height, out depth)) { string chunkType = ""; while (chunkType != "IEND") { byte[] chunkData = ReadChunk(reader, out chunkType); // we only support image with one IDAT if (chunkType == "IDAT") { imagePixels = DecompressImageData(chunkData, width, height); } } } } } return imagePixels; }
public byte[] FilenameToBytes(string filename) { byte[] data = null; // get the file information form the selected file FileInfo fInfo = new FileInfo(filename); // get the length of the file to see if it is possible // to upload it (with the standard 4 MB limit) long numBytes = fInfo.Length; double dLen = Convert.ToDouble(fInfo.Length / 1000000); // set up a file stream and binary reader for the // selected file FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fStream); // convert the file to a byte array data = br.ReadBytes((int)numBytes); br.Close(); fStream.Close(); fStream.Dispose(); return data; }
private Frame[] GetAnimation() { if (_patch.length < 1) return null; MemoryStream ms = new MemoryStream(_patch.data); BinaryReader bin = new BinaryReader(ms); if (_patch.length < 1) return null; ushort[] palette = new ushort[0x100]; for( int i = 0; i < 0x100; ++i ) palette[i] = (ushort)( bin.ReadUInt16() ^ 0x8000 ); int start = (int)bin.BaseStream.Position; int frameCount = bin.ReadInt32(); int[] lookups = new int[frameCount]; for( int i = 0; i < frameCount; ++i ) lookups[i] = start + bin.ReadInt32(); Frame[] frames = new Frame[frameCount]; for( int i = 0; i < frameCount; ++i ) { bin.BaseStream.Seek(lookups[i], SeekOrigin.Begin); frames[i] = new Frame(palette, bin, false); } return frames; }
/// <summary> /// Reads a *.anim file into this Anim instance. /// </summary> /// <param name="FileData">The filedata for the *.anim file.</param> public Anim(byte[] FileData) { MemoryStream MemStream = new MemoryStream(FileData); BinaryReader Reader = new BinaryReader(MemStream); m_Version = Endian.SwapUInt32(Reader.ReadUInt32()); m_Name = Encoding.ASCII.GetString(Reader.ReadBytes(Endian.SwapInt16(Reader.ReadInt16()))); m_Duration = Reader.ReadSingle() / 1000; //Why does this have to be divided by 1000? o_O m_Distance = Reader.ReadSingle(); m_IsMoving = Reader.ReadByte(); m_NumTranslations = Endian.SwapUInt32(Reader.ReadUInt32()); m_TranslationsTableOffset = Reader.BaseStream.Position; Reader.BaseStream.Seek(m_TranslationsTableOffset + 12 * m_NumTranslations, SeekOrigin.Begin); m_NumRotations = Endian.SwapUInt32(Reader.ReadUInt32()); m_RotationsTableOffset = Reader.BaseStream.Position; Reader.BaseStream.Seek(m_RotationsTableOffset + 16 * m_NumRotations, SeekOrigin.Begin); m_MotionCount = Endian.SwapUInt32(Reader.ReadUInt32()); for (int i = 0; i < m_MotionCount; i++) m_Motions.Add(ReadMotion(Reader)); }
//add near end of Terraria.IO.WorldFile.loadWorld before setting failure and success internal static void ReadModFile(string path, bool isCloudSave) { path = Path.ChangeExtension(path, ".twld"); if (!FileUtilities.Exists(path, isCloudSave)) { return; } byte[] buffer = FileUtilities.ReadAllBytes(path, isCloudSave); using (MemoryStream stream = new MemoryStream(buffer)) { using (BinaryReader reader = new BinaryReader(stream)) { byte limit = reader.ReadByte(); if (limit == 0) { return; } byte[] flags = reader.ReadBytes(limit); if (flags.Length < numByteFlags) { Array.Resize(ref flags, numByteFlags); } ReadModWorld(flags, reader); } } }
public override void LoadData(BinaryReader reader, StructInstance instance) { int size = GetExpressionAttribute("size").EvaluateInt(instance); long baseOffset = reader.BaseStream.Position; uint baseValue; switch(size) { case 1: baseValue = reader.ReadByte(); break; case 2: baseValue = reader.ReadUInt16(); break; case 4: baseValue = reader.ReadUInt32(); break; default: throw new LoadDataException("Invalid bitfield size " + size); } BitfieldReader bitFieldReader = new BitfieldReader(baseValue, size, baseOffset); foreach(StructField field in ChildFields) { if (field is IntBasedField) { IntBasedField intBasedField = (IntBasedField) field; int? bit = intBasedField.GetIntAttribute("bit"); if (bit.HasValue) bitFieldReader.SetBits(bit.Value, bit.Value); else { int? fromBit = intBasedField.GetIntAttribute("frombit"); int? toBit = intBasedField.GetIntAttribute("tobit"); bitFieldReader.SetBits(fromBit.Value, toBit.Value); } } field.LoadData(bitFieldReader, instance); } }
static Map LoadHeaderInternal( [NotNull] Stream stream ) { if( stream == null ) throw new ArgumentNullException( "stream" ); BinaryReader reader = new BinaryReader( stream ); // Read in the magic number if( reader.ReadUInt32() != Identifier ) { throw new MapFormatException(); } // Read in the map dimesions int width = reader.ReadInt16(); int length = reader.ReadInt16(); int height = reader.ReadInt16(); // ReSharper disable UseObjectOrCollectionInitializer Map map = new Map( null, width, length, height, false ); // ReSharper restore UseObjectOrCollectionInitializer // Read in the spawn location map.Spawn = new Position { X = reader.ReadInt16(), Y = reader.ReadInt16(), Z = reader.ReadInt16(), R = reader.ReadByte(), L = reader.ReadByte() }; return map; }
public static Shape Load(string fn) { if (!System.IO.File.Exists(fn)) throw new System.Exception("File not found: " + fn); System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream(fn, System.IO.FileMode.Open)); Shape s = new Shape(); s.Width = br.ReadInt32(); s.Height = br.ReadInt32(); s.matrix = new bool[s.Width, s.Height]; try { for (int x = 0; x < s.Width; x++) for (int y = 0; y < s.Height; y++) s.notEmptyCellsCount += (s.matrix[x, y] = br.ReadBoolean()) ? 1 : 0; } catch (System.IO.EndOfStreamException) { throw new System.Exception("Invalid data for shape " + fn); } br.Close(); s.CreateTexture(); return s; }
public static bool RequestImageComparisonStatus(string testName = null) { if (!Connect()) throw new InvalidOperationException("Could not connect to image comparer server"); try { if (testName == null && NUnit.Framework.TestContext.CurrentContext == null) { testName = NUnit.Framework.TestContext.CurrentContext.Test.FullName; } var networkStream = ImageComparisonServer.GetStream(); var binaryWriter = new BinaryWriter(networkStream); var binaryReader = new BinaryReader(networkStream); // Header binaryWriter.Write((int)ImageServerMessageType.RequestImageComparisonStatus); binaryWriter.Write(testName); return binaryReader.ReadBoolean(); } catch (Exception) { throw; } }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { // Initialize ApplicationSprite sprite.AttachSpriteTo(page.Content); sprite.Invoke( base64 => { var bytes = Convert.FromBase64String(base64); new IHTMLPre { innerText = bytes.ToHexString() }.AttachToDocument(); var r = new BinaryReader(new MemoryStream(bytes)); var space = r.ReadByte(); new IHTMLPre { innerText = new { space }.ToString() }.AttachToDocument(); try { // implemented in Redux build configuration // script: error JSC1000: No implementation found for this native method, please implement [System.IO.BinaryReader.ReadSingle()] var f = r.ReadSingle(); new IHTMLPre { innerText = new { f }.ToString() }.AttachToDocument(); } catch (Exception ex) { new IHTMLPre { innerText = "error: " + new { ex.Message }.ToString() }.AttachToDocument(); } } ); }
public override void Read(System.IO.BinaryReader br) { this.propertyValue = br.ReadInt16(); }
public static Code LoadBasement(string saveName) { Code ret = Code.SUCCESS; if (System.IO.File.Exists(saveName + fileExt)) { // open save file and prepare a binary reader System.IO.FileStream saveFile = System.IO.File.OpenRead(saveName + fileExt); System.IO.BinaryReader br = new System.IO.BinaryReader(saveFile); // read fileData fields individually (very stupid, and a maintainance hurdle) BasementSerialFileData fileData; fileData.bID = (BasementSerialID)br.ReadUInt32(); fileData.versionMajor = br.ReadUInt32(); fileData.versionMinor = br.ReadUInt32(); br.Close(); saveFile.Close(); // check version if (fileData.versionMajor == buildVersionMajor && fileData.versionMinor == buildVersionMinor) { switch (fileData.bID) { case BasementSerialID.BASEMENT_Beginning: { SceneManager.LoadScene("Basement0"); } break; case BasementSerialID.BASEMENT_Memories: { SceneManager.LoadScene("Basement1"); } break; case BasementSerialID.BASEMENT_PostDance: { SceneManager.LoadScene("Basement2"); } break; case BasementSerialID.BASEMENT_AllGood: { SceneManager.LoadScene("Basement3"); } break; case BasementSerialID.BASEMENT_NotGood: { SceneManager.LoadScene("Basement4"); } break; case BasementSerialID.BASEMENT_BackToNormal: { SceneManager.LoadScene("Basement5"); } break; default: { ret = Code.INVALID_FILE_DATA; } break; } } else { ret = Code.VERSION_MISMATCH; } } else { ret = Code.SAVE_FILE_NOT_FOUND; } return(ret); }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); this.fieldpad = binaryReader.ReadBytes(4); pointerQueue.Enqueue(binaryReader.ReadBlamPointer(2)); pointerQueue.Enqueue(binaryReader.ReadBlamPointer(1)); this.fieldpad0 = binaryReader.ReadBytes(8); return(pointerQueue); }
public void ReadBinaryData(System.IO.BinaryReader r) { x = r.ReadSingle(); y = r.ReadSingle(); z = r.ReadSingle(); }
public void Read(System.IO.BinaryReader r) { count = r.ReadInt32(); }
public void Read(System.IO.BinaryReader r) { _val = r.ReadString(); }
private static HttpResponseValue SendRequestSyncImpl( object[] requestNativeData, string method, string url, List <string> headers, int contentMode, // 0 - null, 1 - text, 2 - binary object content, bool outputIsBinary) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = method; string contentType = null; for (int i = 0; i < headers.Count; i += 2) { string headerName = headers[i]; string headerValue = headers[i + 1]; switch (headerName.ToLower()) { case "user-agent": request.UserAgent = headerValue; break; case "content-type": contentType = headerValue; break; default: request.Headers.Add(headerName, headerValue); break; } } if (contentMode != 0) { byte[] contentBytes; if (contentMode == 2) { contentBytes = (byte[])content; } else { string body = (string)content; contentBytes = System.Text.UTF8Encoding.UTF8.GetBytes(body); } request.ContentLength = Convert.ToInt64(contentBytes.Length); if (contentType != null) { request.ContentType = contentType; } System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(request.GetRequestStream()); streamWriter.Write(contentBytes); streamWriter.Flush(); streamWriter.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); int statusCode = (int)response.StatusCode; string statusMessage = response.StatusDescription; byte[] responseBytes = null; string responseString = null; if (outputIsBinary) { System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(response.GetResponseStream()); byte[] buffer = new byte[1024]; List <byte> contentList = new List <byte>(); int bytesRead = 1; while (bytesRead > 0) { bytesRead = binaryReader.Read(buffer, 0, buffer.Length); if (bytesRead == 1024) { contentList.AddRange(buffer); } else { for (int i = 0; i < bytesRead; ++i) { contentList.Add(buffer[i]); } } } binaryReader.Close(); responseBytes = contentList.ToArray(); } else { System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream()); responseString = streamReader.ReadToEnd(); streamReader.Close(); } List <string> responseHeaders = new List <string>(); foreach (string headerName in response.Headers.AllKeys) { foreach (string headerValue in response.Headers.GetValues(headerName)) { responseHeaders.Add(headerName); responseHeaders.Add(headerValue); } } return(new HttpResponseValue() { StatusCode = statusCode, StatusMessage = statusMessage, IsContentBinary = outputIsBinary, ContentString = responseString, ContentBytes = responseBytes, Headers = responseHeaders.ToArray(), }); }
void ISerializable.Deserialize(System.IO.BinaryReader br) { Deserialize(br); }
public void Reset( Vector2 worldSize, byte[] terrainV2Data, bool loadingDataFromBeforeDigging, byte[] legacyData, ulong[] customStyleWorkshopIds = null, string simpleData = null) { Debug.Assert(worldSize.magnitude > 0f); Util.Log($"Resetting terrain!"); float groundSizeX = worldSize.x; float groundSizeZ = worldSize.y; var newDims = new Int3( Mathf.CeilToInt(groundSizeX / BLOCK_SIZE.x), BlocksYCount, Mathf.CeilToInt(groundSizeZ / BLOCK_SIZE.z)); Debug.Assert(newDims >= new Int3(10, 10, 10)); Int3 newBotCenter = new Int3(newDims.x / 2, 0, newDims.z / 2); // If old data exists, make sure we restore it. This is the resize use case. byte[] restoreData = null; Int3 restoreDims = Int3.zero(); if (terrainV2 != null) { var oldDims = terrainV2.GetWorldDimensions(); restoreDims = Int3.Min(oldDims, newDims); Int3 start = oldDims / 2 - restoreDims / 2; Int3 end = start + restoreDims; Debug.Assert(start >= Int3.zero()); Debug.Assert(end <= oldDims); restoreData = terrainV2.Serialize(start, end); Destroy(terrainV2.gameObject); terrainV2 = null; } using (Util.Profile("terrainV2 instantiate")) terrainV2 = Instantiate(terrainV2Prefab, Vector3.zero, Quaternion.identity, this.transform); using (Util.Profile("terrainV2 SetWorldDimensions")) terrainV2.SetWorldDimensions(newDims); terrainV2.SetRootOffset(new Vector3( -newDims.x / 2 * 2.5f, BlocksYStart * BlockHeight + BlockHeight / 2f, -newDims.z / 2 * 2.5f)); using (Util.Profile("Create color terrain textures")) { int texSize = terrainV2.GetStyleTextureResolution(); // Color32 way faster in general than Color. for (int i = 0; i < NumSolidColorStyles; i++) { Color32[] pixels = new Color32[texSize * texSize]; Color32 color32 = rendering.blockColors[i]; for (int j = 0; j < pixels.Length; j++) { pixels[j] = color32; } terrainV2.SetStyleTextures(i, pixels); // color // 10 is orange if (i == (int)BlockStyle.SolidColor10) { fallbackTexture = pixels; } } } Debug.Assert(fallbackTexture != null, "Could not find fallbackTexture?"); // TODO why do we do these specifically? Are they not read in via the loop below? terrainV2.SetStyleTextures((int)BlockStyle.Stone, terrainV2Textures[4].GetPixels32()); // stone terrainV2.SetStyleTextures((int)BlockStyle.Space, terrainV2Textures[1].GetPixels32()); // metal terrainV2.SetStyleTextures((int)BlockStyle.Grass, terrainV2Textures[8].GetPixels32(), terrainV2Textures[7].GetPixels32(), terrainV2Textures[6].GetPixels32()); // grass terrainV2.SetStyleTextures((int)BlockStyle.SnowRock, terrainV2Textures[11].GetPixels32(), terrainV2Textures[10].GetPixels32(), terrainV2Textures[9].GetPixels32()); // snow foreach (object obj in Enum.GetValues(typeof(BlockStyle))) { BlockStyle style = (BlockStyle)obj; if ((int)style <= (int)BlockStyle.SnowRock) { // We hard code this above for now. continue; } Color32[] topOrAtlas = null; Color32[] side = null; Color32[] overflow = null; foreach (var tex in terrainV2Textures) { if (tex == null) { continue; } if (!tex.name.StartsWith(style.ToString().ToLowerInvariant())) { continue; } if (tex.name.EndsWith("-top") || tex.name == style.ToString().ToLowerInvariant()) { topOrAtlas = tex.GetPixels32(); } else if (tex.name.EndsWith("-side-ceiling")) { side = tex.GetPixels32(); } else if (tex.name.EndsWith("-overflow")) { overflow = tex.GetPixels32(); } } if (topOrAtlas == null) { Util.LogWarning($"Had to use fallback texture for terrain style {style}. side={side}, overflow={overflow}"); topOrAtlas = fallbackTexture; } if (side != null) { #if UNITY_EDITOR Debug.Assert(overflow != null, $"{style.ToString()} style has a side texture but not an overflow?"); #endif } else { if (overflow != null) { Util.LogWarning($"Style {style} had an overflow texture but not a side? IGNORING overflow."); overflow = null; } } terrainV2.SetStyleTextures((int)style, topOrAtlas, side, overflow); } // Custom styles this.customStyleWorkshopIds.Clear(); if (customStyleWorkshopIds != null) { this.customStyleWorkshopIds.AddRange(customStyleWorkshopIds); } UpdateCustomStyleWorkshopIds(); if (restoreData != null) { terrainV2.Deserialize(restoreData, (newDims / 2 - restoreDims / 2)); } if (legacyData != null) { LoadLegacyTerrainData(legacyData); // But move all the blocks to our new system. using (Util.Profile("legacySync")) { foreach (var args in database.EnumerateBlocks()) { terrainV2.SetCell(args.cell.ToInt3() + GetV2Offset(), (int)args.value.style, (int)args.value.blockType - 1, (int)args.value.direction); } } } if (terrainV2Data != null) { Util.Log($"loading v2 data of {terrainV2Data.Length} bytes"); using (Util.Profile("terrainV2 Deserialize")) terrainV2.Deserialize(terrainV2Data); // Legacy upgrade if (loadingDataFromBeforeDigging) { // The serialized data was before digging. We need to move it up, effectively. Debug.Assert(BlocksYStart < 0); // Copy... byte[] temp = terrainV2.Serialize( Int3.zero(), newDims.WithY(newDims.y + BlocksYStart)); // Move up.. terrainV2.Deserialize( temp, Int3.zero().WithY(-BlocksYStart)); // At this point, we actually have 2 copies of the terrain, offset by // some Y! heh. But the SetSlices call below will deal with that. } } if (loadingDataFromBeforeDigging) { // Fill in the ground. BlockStyle style = BlockStyle.Grass; switch (stage.GetGroundType()) { case GameBuilderStage.GroundType.Snow: style = BlockStyle.SnowRock; break; case GameBuilderStage.GroundType.SolidColor: case GameBuilderStage.GroundType.Space: case GameBuilderStage.GroundType.Grass: default: style = BlockStyle.Grass; break; } terrainV2.SetSlices(0, (0 - BlocksYStart), (int)style, 0, 0); } if (!simpleData.IsNullOrEmpty()) { byte[] zippedBytes = System.Convert.FromBase64String(simpleData); using (var zippedStream = new System.IO.MemoryStream(zippedBytes, 0, zippedBytes.Length)) using (var unzipped = new System.IO.Compression.GZipStream(zippedStream, System.IO.Compression.CompressionMode.Decompress)) using (System.IO.BinaryReader reader = new System.IO.BinaryReader(unzipped)) { int version = reader.ReadUInt16(); // Unused. Debug.Assert(version == 0, $"Unknown simpleData version: {version}"); uint numBlocks = reader.ReadUInt32(); Util.Log($"reading in {numBlocks} from simpleData"); for (int i = 0; i < numBlocks; i++) { short x = reader.ReadInt16(); short y = reader.ReadInt16(); short z = reader.ReadInt16(); byte shape = reader.ReadByte(); byte direction = reader.ReadByte(); ushort style = reader.ReadUInt16(); this.SetCellValue( new Cell(x, y, z), new CellValue { blockType = (BlockShape)shape, direction = (BlockDirection)direction, style = (BlockStyle)style }); } } } // Now mark chunks with actors in them as important foreach (var actor in engine.EnumerateActors()) { // Non-dynamic-physics actors don't need terrain to exist...well, less so. if (!actor.GetEnablePhysics()) { continue; } var pos = actor.GetSpawnPosition(); Int3 cell = GetContainingCell(pos).ToInt3(); terrainV2.ReportRigidbodyAt((cell + GetV2Offset())); } }
// Helper to deserialize Transform directly from a BinaryReader void DeserializeTransformFromReader(Transform tr, System.IO.BinaryReader reader) { tr.localPosition = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); tr.localEulerAngles = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); tr.localScale = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); }
public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue) { base.ReadInstances(binaryReader, pointerQueue); this.TeamColors = base.ReadBlockArrayData <MultiplayerColorBlock>(binaryReader, pointerQueue.Dequeue()); }
public void ReadFromStream(int fileVersion, System.IO.BinaryReader readStream) { throw new System.NotImplementedException(); }
public override void Read(System.IO.BinaryReader br) { this.propertyValue = null; }
public override void Read(System.IO.BinaryReader br) { Int64 tmp = br.ReadInt64(); propertyValue = DateTime.FromFileTime(tmp); }
// Read a big endian Int, and advances the BinaryReader's position static int GetBigEndianIntFromBinaryReader(System.IO.BinaryReader br) { byte[] tempBytes = new byte[4]; tempBytes = br.ReadBytes(4); return((tempBytes[0] << 24) | (tempBytes[1] << 16) | (tempBytes[2] << 8) | tempBytes[3]); }
public void Read(System.IO.BinaryReader r) { _val = r.ReadDecimal(); }
public override void Read(System.IO.BinaryReader br) { Double temp = br.ReadDouble(); this.propertyValue = DateTime.FromOADate(temp); }
public override void Read(System.IO.BinaryReader br) { Int64 temp = br.ReadInt64(); this.propertyValue = (double)(temp /= 10000); }
public static bool SetBoolValue(string ValueName, bool ValueToSet, string ConfigFileName) { try { string SettingsPath = Application.dataPath.Remove(Application.dataPath.LastIndexOf("/")) + "/ProjectSettings/" + ConfigFileName + ".asset"; System.IO.FileStream fs; System.IO.BinaryReader br; fs = System.IO.File.Open(SettingsPath, System.IO.FileMode.Open); br = new System.IO.BinaryReader(fs); // Read the unsigned int at offset 0x0C in the file. // This contains the offset at which the setting's numerical values are stored. br.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Begin); // For some reason, the offset is Big Endian in the file. int SettingsOffset = GetBigEndianIntFromBinaryReader(br); // In the file, we start with 0x14 bytes, then a string containing the unity version, // then 0x0C bytes, then a string containing the base class name, followed by a string containing "base". string tempStr; br.BaseStream.Seek(0x14, System.IO.SeekOrigin.Begin); tempStr = GetStringFromBinaryReader(br); // Unity Version br.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Current); tempStr = GetStringFromBinaryReader(br); // Config file Name if (tempStr != ConfigFileName) { // File format has changed, return error return(false); } tempStr = GetStringFromBinaryReader(br); // "Base" if (tempStr != "Base") { // File format has changed, return error return(false); } // This string is then followed by 24 bytes br.BaseStream.Seek(24, System.IO.SeekOrigin.Current); // We then have a series of String (type), String (variable name), and 24 bytes // We can use the type of the settings before the field we are looking for to // find its offset after SettingsOffset. while (br.BaseStream.Position < br.BaseStream.Length) { string SettingType = GetStringFromBinaryReader(br); string SettingName = GetStringFromBinaryReader(br); if (SettingName == ValueName) { break; } br.BaseStream.Seek(24, System.IO.SeekOrigin.Current); if (GetSizeofTypeByString(SettingType) == -1) { // File format has changed, return error return(false); } SettingsOffset += GetSizeofTypeByString(SettingType); } // Set the setting in the file System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs); bw.Seek(SettingsOffset, System.IO.SeekOrigin.Begin); bw.Write(ValueToSet ? (byte)1 : (byte)0); bw.Close(); fs.Close(); } catch (Exception) { // Error happened return(false); } // Success! return(true); }
void ISerializable.Deserialize(System.IO.BinaryReader br) { mId = br.ReadInt32(); mPos = PETools.Serialize.ReadVector3(br); mPrefabPath = PETools.Serialize.ReadNullableString(br); }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); return(pointerQueue); }
public bool Load(byte[] file) { var br = new System.IO.BinaryReader(new System.IO.MemoryStream(file)); var buf = new byte[1024]; if (br.Read(buf, 0, 16) != 16) { br.Close(); return(false); } if (buf[0] != 'E' || buf[1] != 'F' || buf[2] != 'K' || buf[3] != 'M') { return(false); } int version = BitConverter.ToInt32(buf, 4); if (version > (int)LatestSupportVersion) { return(false); } GUID = BitConverter.ToUInt64(buf, 8); while (true) { if (br.Read(buf, 0, 8) != 8) { br.Close(); break; } if (buf[0] == 'D' && buf[1] == 'E' && buf[2] == 'S' && buf[3] == 'C') { var temp = new byte[BitConverter.ToInt32(buf, 4)]; if (br.Read(temp, 0, temp.Length) != temp.Length) { return(false); } var reader = new BinaryReader(temp); int count = 0; reader.Get(ref count); for (int i = 0; i < count; i++) { int lang = 0; string name = null; string desc = null; reader.Get(ref lang); reader.Get(ref name, Encoding.UTF8); reader.Get(ref desc, Encoding.UTF8); Names.Add((Language)lang, name); Descriptions.Add((Language)lang, desc); } } if (buf[0] == 'P' && buf[1] == 'R' && buf[2] == 'M' && buf[3] == '_') { var temp = new byte[BitConverter.ToInt32(buf, 4)]; if (br.Read(temp, 0, temp.Length) != temp.Length) { return(false); } var reader = new BinaryReader(temp); reader.Get(ref ShadingModel); reader.Get(ref HasNormal); reader.Get(ref HasRefraction); reader.Get(ref CustomData1Count); reader.Get(ref CustomData2Count); int textureCount = 0; reader.Get(ref textureCount); List <TextureInformation> textures = new List <TextureInformation>(); for (int i = 0; i < textureCount; i++) { TextureInformation info = new TextureInformation(); reader.Get(ref info.Name, Encoding.UTF8); // name is for human, uniformName is a variable name after 3 if (version >= 3) { reader.Get(ref info.UniformName, Encoding.UTF8); } else { info.UniformName = info.Name; } reader.Get(ref info.DefaultPath, Encoding.UTF8); reader.Get(ref info.Index); reader.Get(ref info.Priority); reader.Get(ref info.IsParam); int textureType = 0; reader.Get(ref textureType); info.Type = (TextureType)textureType; reader.Get(ref info.Sampler); // convert a path into absolute if (string.IsNullOrEmpty(info.DefaultPath)) { info.DefaultPath = string.Empty; } textures.Add(info); } Textures = textures.ToArray(); int uniformCount = 0; reader.Get(ref uniformCount); List <UniformInformation> uniforms = new List <UniformInformation>(); for (int i = 0; i < uniformCount; i++) { UniformInformation info = new UniformInformation(); reader.Get(ref info.Name, Encoding.UTF8); // name is for human, uniformName is a variable name after 3 if (version >= 3) { reader.Get(ref info.UniformName, Encoding.UTF8); } else { info.UniformName = info.Name; } reader.Get(ref info.Offset); reader.Get(ref info.Priority); reader.Get(ref info.Type); reader.Get(ref info.DefaultValues[0]); reader.Get(ref info.DefaultValues[1]); reader.Get(ref info.DefaultValues[2]); reader.Get(ref info.DefaultValues[3]); uniforms.Add(info); } Uniforms = uniforms.ToArray(); } if (buf[0] == 'P' && buf[1] == 'R' && buf[2] == 'M' && buf[3] == '2') { var temp = new byte[BitConverter.ToInt32(buf, 4)]; if (br.Read(temp, 0, temp.Length) != temp.Length) { return(false); } var reader = new BinaryReader(temp); if (version >= 2) { int customDataCount = 0; reader.Get(ref customDataCount); AllocateCustomData(customDataCount); for (int j = 0; j < customDataCount; j++) { int count = 0; reader.Get(ref count); for (int i = 0; i < count; i++) { int lang = 0; string name = null; string desc = null; reader.Get(ref lang); reader.Get(ref name, Encoding.UTF8); reader.Get(ref desc, Encoding.UTF8); CustomData[j].Summaries.Add((Language)lang, name); CustomData[j].Descriptions.Add((Language)lang, desc); } } } int textureCount = 0; reader.Get(ref textureCount); for (int j = 0; j < textureCount; j++) { int count = 0; reader.Get(ref count); for (int i = 0; i < count; i++) { int lang = 0; string name = null; string desc = null; reader.Get(ref lang); reader.Get(ref name, Encoding.UTF8); reader.Get(ref desc, Encoding.UTF8); Textures[j].Summaries.Add((Language)lang, name); Textures[j].Descriptions.Add((Language)lang, desc); } } int uniformCount = 0; reader.Get(ref uniformCount); for (int j = 0; j < uniformCount; j++) { int count = 0; reader.Get(ref count); for (int i = 0; i < count; i++) { int lang = 0; string name = null; string desc = null; reader.Get(ref lang); reader.Get(ref name, Encoding.UTF8); reader.Get(ref desc, Encoding.UTF8); Uniforms[j].Summaries.Add((Language)lang, name); Uniforms[j].Descriptions.Add((Language)lang, desc); } } } if (buf[0] == 'E' && buf[1] == '_' && buf[2] == 'C' && buf[3] == 'D') { var temp = new byte[BitConverter.ToInt32(buf, 4)]; if (br.Read(temp, 0, temp.Length) != temp.Length) { return(false); } var reader = new BinaryReader(temp); int customDataCount = 0; reader.Get(ref customDataCount); AllocateCustomData(customDataCount); for (int j = 0; j < customDataCount; j++) { reader.Get(ref CustomData[j].DefaultValues[0]); reader.Get(ref CustomData[j].DefaultValues[1]); reader.Get(ref CustomData[j].DefaultValues[2]); reader.Get(ref CustomData[j].DefaultValues[3]); } } if (buf[0] == 'G' && buf[1] == 'E' && buf[2] == 'N' && buf[3] == 'E') { var temp = new byte[BitConverter.ToInt32(buf, 4)]; if (br.Read(temp, 0, temp.Length) != temp.Length) { return(false); } var reader = new BinaryReader(temp); reader.Get(ref Code, Encoding.UTF8); } if (buf[0] == 'D' && buf[1] == 'A' && buf[2] == 'T' && buf[3] == 'A') { var temp = new byte[BitConverter.ToInt32(buf, 4)]; if (br.Read(temp, 0, temp.Length) != temp.Length) { return(false); } string jsonText = Encoding.UTF8.GetString(temp); EditorData = JsonConvert.DeserializeObject <JObject>(jsonText); } } return(true); }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); this.RenderModelSectionGroupDetailLevels = ((DetailLevels)(binaryReader.ReadInt16())); this.fieldpad = binaryReader.ReadBytes(2); pointerQueue.Enqueue(binaryReader.ReadBlamPointer(16)); return(pointerQueue); }
public static JSONNode Deserialize(System.IO.BinaryReader aReader) { JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte(); switch (type) { case JSONBinaryTag.Array: { int count = aReader.ReadInt32(); JSONArray tmp = new JSONArray(); for (int i = 0; i < count; i++) { tmp.Add(Deserialize(aReader)); } return(tmp); } case JSONBinaryTag.Class: { int count = aReader.ReadInt32(); JSONClass tmp = new JSONClass(); for (int i = 0; i < count; i++) { string key = aReader.ReadString(); var val = Deserialize(aReader); tmp.Add(key, val); } return(tmp); } case JSONBinaryTag.Value: { return(new JSONData(aReader.ReadString())); } case JSONBinaryTag.IntValue: { return(new JSONData(aReader.ReadInt32())); } case JSONBinaryTag.DoubleValue: { return(new JSONData(aReader.ReadDouble())); } case JSONBinaryTag.BoolValue: { return(new JSONData(aReader.ReadBoolean())); } case JSONBinaryTag.FloatValue: { return(new JSONData(aReader.ReadSingle())); } default: { throw new Exception("Error deserializing JSON. Unknown tag: " + type); } } }
public CompiledMaterialInformationErrorCode Load(string path) { if (string.IsNullOrEmpty(path)) { return(CompiledMaterialInformationErrorCode.NotFound); } System.IO.FileStream fs = null; if (!System.IO.File.Exists(path)) { return(CompiledMaterialInformationErrorCode.NotFound); } try { fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } catch { return(CompiledMaterialInformationErrorCode.FailedToOpen); } var br = new System.IO.BinaryReader(fs); var buf = new byte[1024]; if (br.Read(buf, 0, 20) != 20) { fs.Dispose(); br.Close(); return(CompiledMaterialInformationErrorCode.InvalidFormat); } if (buf[0] != 'e' || buf[1] != 'M' || buf[2] != 'C' || buf[3] != 'B') { fs.Dispose(); br.Close(); return(CompiledMaterialInformationErrorCode.InvalidFormat); } Version = BitConverter.ToInt32(buf, 4); // bacause of camera position node, structure of uniform is changed if (Version < (int)OldestSupportVersion) { fs.Dispose(); br.Close(); return(CompiledMaterialInformationErrorCode.TooOldFormat); } if (Version > (int)LatestSupportVersion) { fs.Dispose(); br.Close(); return(CompiledMaterialInformationErrorCode.TooNewFormat); } int fversion = BitConverter.ToInt32(buf, 4); GUID = BitConverter.ToUInt64(buf, 8); var platformCount = BitConverter.ToInt32(buf, 16); for (int i = 0; i < platformCount; i++) { if (br.Read(buf, 0, 4) != 4) { fs.Dispose(); br.Close(); return(CompiledMaterialInformationErrorCode.InvalidFormat); } var type = (CompiledMaterialPlatformType)BitConverter.ToInt32(buf, 0); Platforms.Add(type); } fs.Dispose(); br.Close(); return(CompiledMaterialInformationErrorCode.OK); }
public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue) { base.ReadInstances(binaryReader, pointerQueue); }
public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue) { base.ReadInstances(binaryReader, pointerQueue); this.CompiledShader = base.ReadDataShortArray(binaryReader, pointerQueue.Dequeue()); this.Code = base.ReadDataByteArray(binaryReader, pointerQueue.Dequeue()); }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); this.StartTransitionIndex = binaryReader.ReadInt32(); this.Alpha = binaryReader.ReadSingle(); this.Position = binaryReader.ReadVector3(); return(pointerQueue); }
public override System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader) { System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue <Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader)); this.RandomPlayerNames = binaryReader.ReadTagReference(); this.TeamNames = binaryReader.ReadTagReference(); pointerQueue.Enqueue(binaryReader.ReadBlamPointer(12)); this.MultiplayerText = binaryReader.ReadTagReference(); return(pointerQueue); }
// Helper to deserialize Rigidbody directly from a BinaryReader void DeserializeRigidbodyFromReader(Rigidbody body, System.IO.BinaryReader reader) { body.velocity = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); body.angularVelocity = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); }