public UIntPtr ReadUInt32Ptr(IntPtr address) { return(new UIntPtr(BitConverter.ToUInt32(ReadBytes(address, 4), 0))); }
public async Task <uint> GetCurrentScreen(CancellationToken token) { var data = await Connection.ReadBytesAsync(CurrentScreenOffset, 4, token).ConfigureAwait(false); return(BitConverter.ToUInt32(data, 0)); }
public static PingReplyExt Send(IPAddress srcAddress, IPAddress destAddress, int timeout = 5000, byte[] buffer = null, PingOptions po = null) { if (destAddress == null || destAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork || destAddress.Equals(IPAddress.Any)) { throw new ArgumentException(); } //Defining pinvoke args var source = srcAddress == null ? 0 : BitConverter.ToUInt32(srcAddress.GetAddressBytes(), 0); //Console.WriteLine($"source = {source}"); var destination = BitConverter.ToUInt32(destAddress.GetAddressBytes(), 0); var sendbuffer = buffer ?? new byte[] { }; var options = new Interop.Option { Ttl = (po == null ? (byte)255 : (byte)po.Ttl), Flags = (po == null ? (byte)0 : po.DontFragment ? (byte)0x02 : (byte)0) //0x02 }; var fullReplyBufferSize = Interop.ReplyMarshalLength + sendbuffer.Length; //Size of Reply struct and the transmitted buffer length. var allocSpace = Marshal.AllocHGlobal(fullReplyBufferSize); // unmanaged allocation of reply size. TODO Maybe should be allocated on stack try { DateTime start = DateTime.Now; var nativeCode = Interop.IcmpSendEcho2Ex( Interop.IcmpHandle, //_In_ HANDLE IcmpHandle, default(IntPtr), //_In_opt_ HANDLE Event, default(IntPtr), //_In_opt_ PIO_APC_ROUTINE ApcRoutine, default(IntPtr), //_In_opt_ PVOID ApcContext source, //_In_ IPAddr SourceAddress, destination, //_In_ IPAddr DestinationAddress, sendbuffer, //_In_ LPVOID RequestData, (short)sendbuffer.Length, //_In_ WORD RequestSize, ref options, //_In_opt_ PIP_OPTION_INFORMATION RequestOptions, allocSpace, //_Out_ LPVOID ReplyBuffer, fullReplyBufferSize, //_In_ DWORD ReplySize, timeout //_In_ DWORD Timeout ); TimeSpan duration = DateTime.Now - start; var reply = (Interop.Reply)Marshal.PtrToStructure(allocSpace, typeof(Interop.Reply)); // Parse the beginning of reply memory to reply struct byte[] replyBuffer = null; if (sendbuffer.Length != 0) { replyBuffer = new byte[sendbuffer.Length]; Marshal.Copy(allocSpace + Interop.ReplyMarshalLength, replyBuffer, 0, sendbuffer.Length); //copy the rest of the reply memory to managed byte[] } if (nativeCode == 0) //Means that native method is faulted. { return(new PingReplyExt(nativeCode, reply.Status, new IPAddress(reply.Address), duration)); } else { return(new PingReplyExt(nativeCode, reply.Status, new IPAddress(reply.Address), reply.RoundTripTime, replyBuffer)); } } finally { Marshal.FreeHGlobal(allocSpace); //free allocated space } }
private static string HashUid(string id) { return(string.Format("411.12.8453.12.83109.70.5.{0}", BitConverter.ToUInt32(BitConverter.GetBytes(id.GetHashCode()), 0))); }
public async Task <bool> CheckIfSearchingForSurprisePartner(CancellationToken token) { var data = await Connection.ReadBytesAsync(SurpriseTradeSearchOffset, 8, token).ConfigureAwait(false); return(BitConverter.ToUInt32(data, 0) == SurpriseTradeSearch_Searching); }
protected void UpdateFloat(float value, int primary, int secondary) { DoUpdate(BitConverter.ToUInt32(BitConverter.GetBytes(value), 0), primary, secondary, true); }
private void SaveStats(string id, byte[] data) { byte house; switch (id) { case "TIME": var timeSpan = TimeSpan.FromSeconds(BitConverter.ToUInt32(Reverse(data), 0)); GameDuration = string.Format("{0:D2}:{1:D2}:{2:D2}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); break; case "SCR0": case "SCR1": case "SCR2": case "SCR3": case "SCR4": case "SCR5": case "SCR6": case "SCR7": string[] score = Encoding.Default.GetString(data).Split('/'); house = Convert.ToByte(id[id.Length - 1].ToString()); FinishingPlaces[house] = Convert.ToInt32(score[0]) + 1; BuildingsOwned[house] = Convert.ToInt32(score[1]); BuildingsLost[house] = Convert.ToInt32(score[2]); BuildingsDestroyed[house] = Convert.ToInt32(score[3]); UnitsOwned[house] = Convert.ToInt32(score[4]); UnitsLost[house] = Convert.ToInt32(score[5]); UnitsKilled[house] = Convert.ToInt32(score[6]); SpiceHarvested[house] = Convert.ToInt32(score[7]); break; case "GEND": EndStatus = Encoding.Default.GetString(data); break; case "GMAP": MapName = Encoding.Default.GetString(data); break; case "GSET": string[] gameSettings = Encoding.Default.GetString(data).Split(' '); Worms = Convert.ToInt32(gameSettings[1]); Crates = gameSettings[3] == "1"; StartingCredits = Convert.ToUInt32(gameSettings[5]); TechLevel = Convert.ToInt32(gameSettings[7]); break; case "PL_0": case "PL_1": case "PL_2": case "PL_3": case "PL_4": case "PL_5": case "PL_6": case "PL_7": PlayerCount++; string[] playerSettings = Encoding.Default.GetString(data).Split('/'); house = Convert.ToByte(id[id.Length - 1].ToString()); Names[house] = playerSettings[0]; Sides[house] = playerSettings[1]; Colors[house] = NumberToColor(playerSettings[2]); Handicaps[house] = Convert.ToInt32(playerSettings[3]) + 1; break; case "SDFX": SuddenDisconnect = data[0] == 1; break; case "TRNY": TournamentGame = data[0] == 1; break; case "GMID": GameId = BitConverter.ToUInt32(Reverse(data), 0); break; case "TICK": GameTicks = BitConverter.ToUInt32(Reverse(data), 0); break; case "UNIT": UnitCount = BitConverter.ToUInt32(Reverse(data), 0); break; case "UNB0": case "UNB1": case "UNB2": case "UNB3": case "UNB4": case "UNB5": case "UNB6": case "UNB7": house = Convert.ToByte(id[id.Length - 1].ToString()); SaveUnitsOwned(house, data); break; case "BLB0": case "BLB1": case "BLB2": case "BLB3": case "BLB4": case "BLB5": case "BLB6": case "BLB7": house = Convert.ToByte(id[id.Length - 1].ToString()); SaveBuildingsOwned(house, data); break; case "CRD0": case "CRD1": case "CRD2": case "CRD3": case "CRD4": case "CRD5": case "CRD6": case "CRD7": house = Convert.ToByte(id[id.Length - 1].ToString()); Credits[house] = BitConverter.ToInt32(Reverse(data), 0); break; } }
private void ExtractData() { int position = 0; int finalSize = 0; byte[] queueToBreak = null; List <ArraySegment <byte> > segmentList = new List <ArraySegment <byte> >(); lock (queuelock) { if (m_buffers.Count > 0) { while (m_buffers.Count > 0) { byte[] localqueueChunk = m_buffers.Dequeue(); chunkList.AddRange(localqueueChunk); position += localqueueChunk.Length; } byte[] queueChunk = chunkList.ToArray(); chunkList.Clear(); queueToBreak = new byte[queueChunk.Length]; segmentList = new List <ArraySegment <byte> >(); for (int i = 0; i < queueChunk.Length;) { int size = 0; if (queueChunk.Length - 4 >= i + 4) { size = BitConverter.ToInt32(queueChunk, i); } if (size > 0 && queueChunk.Length >= i + size && BitConverter.ToUInt32(queueChunk, (i + size) - 4) == 0xCCCCCCCC) { segmentList.Add(new ArraySegment <byte>(queueChunk, i + 4, size - 8)); finalSize += (size - 8); i += size; } else { byte[] remainder = new byte[queueChunk.Length - i]; Array.Copy(queueChunk, i, remainder, 0, queueChunk.Length - i); m_buffers.Enqueue(remainder); break; } } } } lock (chunklock) { if (finalSize > 0) { var listOfSizes = new List <int>(); Array.Resize(ref queueToBreak, finalSize); foreach (var item in segmentList) { for (int i = 0; i < item.Count;) { var startOffset = i + item.Offset; int size = BitConverter.ToInt32(item.Array, startOffset); if (size > 0 && size < 4096) { listOfSizes.Add(size); var segment = new ArraySegment <byte>(item.Array, startOffset, size); m_items.Enqueue(segment); i += size; } else { break; } } } HasData(this); } } }
/// <summary> /// Tries to connect to login server, keeps trying every 10 seconds /// till there is a success. Blocking. /// </summary> public void ConnectToLogin(bool firstTime) { if (this.LoginServer != null && this.LoginServer.State == ClientState.LoggedIn) { throw new Exception("Channel already connected to login server."); } Log.WriteLine(); if (firstTime) { Log.Info("Trying to connect to login server at {0}:{1}...", ChannelServer.Instance.Conf.Channel.LoginHost, ChannelServer.Instance.Conf.Channel.LoginPort); } else { Log.Info("Trying to re-connect to login server in {0} seconds.", LoginTryTime / 1000); Thread.Sleep(LoginTryTime); } var success = false; while (!success) { try { if (this.LoginServer != null && this.LoginServer.State != ClientState.Dead) { this.LoginServer.Kill(); } this.LoginServer = new InternalClient(); this.LoginServer.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.LoginServer.Socket.Connect(ChannelServer.Instance.Conf.Channel.LoginHost, ChannelServer.Instance.Conf.Channel.LoginPort); var buffer = new byte[255]; // Recv Seed, send back empty packet to get done with the challenge. this.LoginServer.Socket.Receive(buffer); this.LoginServer.Crypto = new MabiCrypto(BitConverter.ToUInt32(buffer, 0), false); this.LoginServer.Send(Packet.Empty()); // Challenge end this.LoginServer.Socket.Receive(buffer); // Inject login server into normal data receiving. this.Server.AddReceivingClient(this.LoginServer); // Identify this.LoginServer.State = ClientState.LoggingIn; success = true; Send.Internal_ServerIdentify(); } catch (Exception ex) { Log.Error("Unable to connect to login server. ({0})", ex.Message); Log.Info("Trying again in {0} seconds.", LoginTryTime / 1000); Thread.Sleep(LoginTryTime); } } Log.Info("Connection to login server at '{0}' established.", this.LoginServer.Address); Log.WriteLine(); }
/// <summary> /// Reads a 32-bit unsigned integer. /// </summary> /// <param name="value">The value that was read.</param> /// <returns></returns> public EasyReader ReadUInt32(out uint value) { value = BitConverter.ToUInt32(ReadAndFormat(4), 0); return(this); }
public static void Forge( [Required(Description = "original signed assembly")] string originalPath, [Required(Description = "input modified assembly")] string inputPath, [Required(Description = "output forged assembly")] string outputPath) { Stream original = File.OpenRead(originalPath); bool isEncrypted = original.ReadValueBoolean(); UInt32 typeId = original.ReadValueU32(); if (isEncrypted == false || typeId != 0x2BC4F79F) { Console.WriteLine("Not an encrypted assembly that I know how to handle."); original.Close(); return; } byte[] theirSum = new byte[64]; original.Read(theirSum, 0, theirSum.Length); ushort blocks = original.ReadValueU16(); byte[] table = new byte[blocks * 8]; original.Read(table, 0, table.Length); original.Close(); // Calculate initial seed UInt32 seed = 0; for (int i = 0; i < blocks; i++) { seed += BitConverter.ToUInt32(table, i * 8); } seed = (UInt32)(table.Length - 1) & seed; Stream input = File.OpenRead(inputPath); if (input.Length != blocks * 512) { Console.WriteLine("Size mismatch, original assembly and modified assembly must have the same size! ({0} vs {1})", input.Length, blocks * 512); input.Close(); original.Close(); return; } Stream output = File.Open(outputPath, FileMode.Create, FileAccess.Write); output.WriteValueBoolean(true); output.WriteValueU32(0x2BC4F79F); output.Write(theirSum, 0, theirSum.Length); output.WriteValueU16(blocks); output.Write(table, 0, table.Length); // Encrypt data for (int i = 0; i < blocks; i++) { byte[] data = new byte[512]; input.Read(data, 0, data.Length); if ((table[(i * 8)] & 1) == 0) // non-empty block { for (int j = 0; j < 512; j++) { data[j] ^= table[seed]; seed = (UInt32)((seed + data[j]) % table.Length); } output.Write(data, 0, data.Length); } else // validate this is an empty block { for (int j = 0; j < data.Length; j++) { if (data[j] != 0) { Console.WriteLine("Block {0} should have been empty, but wasn't!", i); input.Close(); output.Close(); return; } } } } output.Close(); original.Close(); Console.WriteLine("Done."); }
/// <summary> /// Reads a 32-bit unsigned integer. /// </summary> /// <returns></returns> public uint ReadUInt32() { return(BitConverter.ToUInt32(ReadAndFormat(4), 0)); }
private void method_0(Stream TMD_Stream, SystemType SystemType) //Information located: https://3dbrew.org/wiki/Title_metadata#Signature_Type { TMD_Stream.Seek(0L, SeekOrigin.Begin); byte[] buffer1 = new byte[8]; TMD_Stream.Read(buffer1, 0, 4); this.TMD_Signature__Type_as_Int = GClass27.ToUIntNetworkBytes(BitConverter.ToUInt32(buffer1, 0)); TMD_Stream.Read(this.TMD_Signature, 0, this.TMD_Signature.Length); TMD_Stream.Read(this.TMD_Signature_Padding, 0, this.TMD_Signature_Padding.Length); TMD_Stream.Read(this.SignatureIssuer, 0, this.SignatureIssuer.Length); TMD_Stream.Read(buffer1, 0, 4); this.Version = buffer1[0]; this.ca_crl_version = buffer1[1]; this.signer_crl_version = buffer1[2]; this.Reserved = buffer1[3]; TMD_Stream.Read(buffer1, 0, 8); //Skip System Version TMD_Stream.Read(buffer1, 0, 8); //Read Title ID this.TitleId = GClass27.ToULongNetworkBytes(BitConverter.ToUInt64(buffer1, 0)); TMD_Stream.Read(buffer1, 0, 4); //Read Title Type (e.g. DSIWare, ESHOP, etc I think) this.TitleType = GClass27.ToUIntNetworkBytes(BitConverter.ToUInt32(buffer1, 0)); TMD_Stream.Read(buffer1, 0, 2); //Read Group ID this.GroupID = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 0)); TMD_Stream.Read(buffer1, 0, 2); //Read half of Save Data Size (Bytes) (Also SRL Public Save Data Size)? this.Save_Data_Size_pt1 = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 0)); TMD_Stream.Read(buffer1, 0, 2); //Read second half of Save Data Size (Bytes) (Also SRL Public Save Data Size)? this.Save_Data_Size_pt2 = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 0)); TMD_Stream.Read(this.SkippedSLRData, 0, this.SkippedSLRData.Length); //Skips SLR Private Save, Reserved, SLR Flag, and Reserved TMD_Stream.Read(buffer1, 0, 4); //Reads Access Rights this.AccessRights = GClass27.ToUIntNetworkBytes(BitConverter.ToUInt32(buffer1, 0)); TMD_Stream.Read(buffer1, 0, 8); //Read Title Version, Content Count, Boot Content, and Padding this.TitleVersion = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 0)); this.NumOfContents = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 2)); this.BootContent = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 4)); this.Padding = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 6)); if (SystemType != SystemType.SystemWii) { TMD_Stream.Position = 2820L; //Skips to Hex 0xB02 } this.list_0 = new List <GClass101>(); for (int index = 0; index < (int)this.NumOfContents; ++index) { GClass101 gclass101; if (SystemType != SystemType.SystemWiiU && SystemType != SystemType.SystemWii) { if (SystemType != SystemType.System3DS) { throw new NotImplementedException(); } A_3DS_CND_File_Hash A_3DS_CDN_File_Hash = new A_3DS_CND_File_Hash(); A_3DS_CDN_File_Hash.Hash = new byte[32]; gclass101 = (GClass101)A_3DS_CDN_File_Hash; } else { A_WiiU_CDN_File_Hash A_WiiU_CDN_File_Hash = new A_WiiU_CDN_File_Hash(); A_WiiU_CDN_File_Hash.Hash = new byte[20]; gclass101 = (GClass101)A_WiiU_CDN_File_Hash; } TMD_Stream.Read(buffer1, 0, 8); gclass101.ContentId = GClass27.ToUIntNetworkBytes(BitConverter.ToUInt32(buffer1, 0)); gclass101.Index = GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 4)); gclass101.ContentType = (GEnum6)GClass27.ToUShortNetworkBytes(BitConverter.ToUInt16(buffer1, 6)); TMD_Stream.Read(buffer1, 0, 8); gclass101.ContentSize = new DataSize(GClass27.ToULongNetworkBytes(BitConverter.ToUInt64(buffer1, 0))); TMD_Stream.Read(gclass101.Hash, 0, gclass101.Hash.Length); this.list_0.Add(gclass101); if (SystemType == SystemType.SystemWiiU) { byte[] buffer2 = new byte[12]; TMD_Stream.Read(buffer2, 0, 12); } } TMD_Stream.Read(this.Certificate1, 0, this.Certificate1.Length); TMD_Stream.Read(this.Certificate2, 0, this.Certificate2.Length); }
///<summary> /// Returns a random number between 0.0 and 1.0. ///</summary> public double NextDouble() { byte[] b = new byte[4]; r.GetBytes(b); return((double)BitConverter.ToUInt32(b, 0) / UInt32.MaxValue); }
protected override Task <ResultStatus> DoCommandOverride(ICommandContext commandContext) { var assetManager = new AssetManager(); AssetParameters.ColliderShapes = AssetParameters.ColliderShapes.Where(x => x != null && (x.GetType() != typeof(ConvexHullColliderShapeDesc) || ((ConvexHullColliderShapeDesc)x).Model != null)).ToList(); //pre process special types foreach (var convexHullDesc in (from shape in AssetParameters.ColliderShapes let type = shape.GetType() where type == typeof(ConvexHullColliderShapeDesc) select shape) .Cast <ConvexHullColliderShapeDesc>()) { //decompose and fill vertex data var loadSettings = new AssetManagerLoaderSettings { ContentFilter = AssetManagerLoaderSettings.NewContentFilterByType(typeof(Mesh)) }; var modelAsset = assetManager.Load <Model>(AttachedReferenceManager.GetUrl(convexHullDesc.Model), loadSettings); if (modelAsset == null) { continue; } convexHullDesc.ConvexHulls = new List <List <List <Vector3> > >(); convexHullDesc.ConvexHullsIndices = new List <List <List <uint> > >(); commandContext.Logger.Info("Processing convex hull generation, this might take a while!"); var nodeTransforms = new List <Matrix>(); //pre-compute all node transforms, assuming nodes are ordered... see ModelViewHierarchyUpdater var nodesLength = modelAsset.Skeleton.Nodes.Length; for (var i = 0; i < nodesLength; i++) { Matrix localMatrix; TransformComponent.CreateMatrixTRS( ref modelAsset.Skeleton.Nodes[i].Transform.Position, ref modelAsset.Skeleton.Nodes[i].Transform.Rotation, ref modelAsset.Skeleton.Nodes[i].Transform.Scale, out localMatrix); Matrix worldMatrix; if (modelAsset.Skeleton.Nodes[i].ParentIndex != -1) { var nodeTransform = nodeTransforms[modelAsset.Skeleton.Nodes[i].ParentIndex]; Matrix.Multiply(ref localMatrix, ref nodeTransform, out worldMatrix); } else { worldMatrix = localMatrix; } nodeTransforms.Add(worldMatrix); } for (var i = 0; i < nodesLength; i++) { var i1 = i; if (modelAsset.Meshes.All(x => x.NodeIndex != i1)) { continue; // no geometry in the node } var combinedVerts = new List <float>(); var combinedIndices = new List <uint>(); var hullsList = new List <List <Vector3> >(); convexHullDesc.ConvexHulls.Add(hullsList); var indicesList = new List <List <uint> >(); convexHullDesc.ConvexHullsIndices.Add(indicesList); foreach (var meshData in modelAsset.Meshes.Where(x => x.NodeIndex == i1)) { var indexOffset = (uint)combinedVerts.Count / 3; var stride = meshData.Draw.VertexBuffers[0].Declaration.VertexStride; var vertexDataAsset = assetManager.Load <Graphics.Buffer>(AttachedReferenceManager.GetUrl(meshData.Draw.VertexBuffers[0].Buffer)); var vertexData = vertexDataAsset.GetSerializationData().Content; var vertexIndex = meshData.Draw.VertexBuffers[0].Offset; for (var v = 0; v < meshData.Draw.VertexBuffers[0].Count; v++) { var posMatrix = Matrix.Translation(new Vector3(BitConverter.ToSingle(vertexData, vertexIndex + 0), BitConverter.ToSingle(vertexData, vertexIndex + 4), BitConverter.ToSingle(vertexData, vertexIndex + 8))); Matrix rotatedMatrix; var nodeTransform = nodeTransforms[i]; Matrix.Multiply(ref posMatrix, ref nodeTransform, out rotatedMatrix); combinedVerts.Add(rotatedMatrix.TranslationVector.X); combinedVerts.Add(rotatedMatrix.TranslationVector.Y); combinedVerts.Add(rotatedMatrix.TranslationVector.Z); vertexIndex += stride; } var indexDataAsset = assetManager.Load <Graphics.Buffer>(AttachedReferenceManager.GetUrl(meshData.Draw.IndexBuffer.Buffer)); var indexData = indexDataAsset.GetSerializationData().Content; var indexIndex = meshData.Draw.IndexBuffer.Offset; for (var v = 0; v < meshData.Draw.IndexBuffer.Count; v++) { if (meshData.Draw.IndexBuffer.Is32Bit) { combinedIndices.Add(BitConverter.ToUInt32(indexData, indexIndex) + indexOffset); indexIndex += 4; } else { combinedIndices.Add(BitConverter.ToUInt16(indexData, indexIndex) + indexOffset); indexIndex += 2; } } } var decompositionDesc = new ConvexHullMesh.DecompositionDesc { VertexCount = (uint)combinedVerts.Count / 3, IndicesCount = (uint)combinedIndices.Count, Vertexes = combinedVerts.ToArray(), Indices = combinedIndices.ToArray(), Depth = convexHullDesc.Depth, PosSampling = convexHullDesc.PosSampling, PosRefine = convexHullDesc.PosRefine, AngleSampling = convexHullDesc.AngleSampling, AngleRefine = convexHullDesc.AngleRefine, Alpha = convexHullDesc.Alpha, Threshold = convexHullDesc.Threshold, SimpleHull = convexHullDesc.SimpleWrap }; lock (this) { convexHullMesh = new ConvexHullMesh(); } convexHullMesh.Generate(decompositionDesc); var count = convexHullMesh.Count; commandContext.Logger.Info("Node generated " + count + " convex hulls"); var vertexCountHull = 0; for (uint h = 0; h < count; h++) { float[] points; convexHullMesh.CopyPoints(h, out points); var pointList = new List <Vector3>(); for (var v = 0; v < points.Length; v += 3) { var vert = new Vector3(points[v + 0], points[v + 1], points[v + 2]); pointList.Add(vert); vertexCountHull++; } hullsList.Add(pointList); uint[] indices; convexHullMesh.CopyIndices(h, out indices); for (var t = 0; t < indices.Length; t += 3) { Utilities.Swap(ref indices[t], ref indices[t + 2]); } var indexList = new List <uint>(indices); indicesList.Add(indexList); } lock (this) { convexHullMesh.Dispose(); convexHullMesh = null; } commandContext.Logger.Info("For a total of " + vertexCountHull + " vertexes"); } } var runtimeShape = new PhysicsColliderShape { Descriptions = AssetParameters.ColliderShapes }; assetManager.Save(Url, runtimeShape); return(Task.FromResult(ResultStatus.Successful)); }
internal Midpoint[] CacheMidpointsAndVerifyHash(int depth, bool skipIndexVerify) { var buffer = new byte[4096]; if (depth < 0 || depth > 30) { throw new ArgumentOutOfRangeException("depth"); } var count = Count; if (count == 0 || depth == 0) { return(null); } if (skipIndexVerify) { Log.Debug("Disabling Verification of PTable"); } #if MONO var workItem = GetWorkItem(); var stream = workItem.Stream; try { #else using (var stream = UnbufferedFileStream.Create(_filename, FileMode.Open, FileAccess.Read, FileShare.Read, false, 4096, 4096, false, 4096)) { #endif try { int midpointsCount; Midpoint[] midpoints; using (MD5 md5 = MD5.Create()) { try { midpointsCount = (int)Math.Max(2L, Math.Min((long)1 << depth, count)); midpoints = new Midpoint[midpointsCount]; } catch (OutOfMemoryException exc) { throw new PossibleToHandleOutOfMemoryException("Failed to allocate memory for Midpoint cache.", exc); } if (skipIndexVerify && (_version >= PTableVersions.IndexV4)) { if (_midpointsCached == midpointsCount) { //index verification is disabled and cached midpoints with the same depth requested are available //so, we can load them directly from the PTable file Log.Debug("Loading {0} cached midpoints from PTable", _midpointsCached); long startOffset = stream.Length - MD5Size - PTableFooter.GetSize(_version) - _midpointsCacheSize; stream.Seek(startOffset, SeekOrigin.Begin); for (uint k = 0; k < _midpointsCached; k++) { stream.Read(buffer, 0, _indexEntrySize); IndexEntryKey key; long index; if (_version == PTableVersions.IndexV4) { key = new IndexEntryKey(BitConverter.ToUInt64(buffer, 8), BitConverter.ToInt64(buffer, 0)); index = BitConverter.ToInt64(buffer, 8 + 8); } else { throw new InvalidOperationException("Unknown PTable version: " + _version); } midpoints[k] = new Midpoint(key, index); if (k > 0) { if (midpoints[k].Key.GreaterThan(midpoints[k - 1].Key)) { throw new CorruptIndexException(String.Format("Index entry key for midpoint {0} (stream: {1}, version: {2}) < index entry key for midpoint {3} (stream: {4}, version: {5})", k - 1, midpoints[k - 1].Key.Stream, midpoints[k - 1].Key.Version, k, midpoints[k].Key.Stream, midpoints[k].Key.Version)); } else if (midpoints[k - 1].ItemIndex > midpoints[k].ItemIndex) { throw new CorruptIndexException(String.Format("Item index for midpoint {0} ({1}) > Item index for midpoint {2} ({3})", k - 1, midpoints[k - 1].ItemIndex, k, midpoints[k].ItemIndex)); } } } return(midpoints); } else { Log.Debug("Skipping loading of cached midpoints from PTable due to count mismatch, cached midpoints: {0} / required midpoints: {1}", _midpointsCached, midpointsCount); } } if (!skipIndexVerify) { stream.Seek(0, SeekOrigin.Begin); stream.Read(buffer, 0, PTableHeader.Size); md5.TransformBlock(buffer, 0, PTableHeader.Size, null, 0); } long previousNextIndex = long.MinValue; var previousKey = new IndexEntryKey(long.MaxValue, long.MaxValue); for (long k = 0; k < midpointsCount; ++k) { var nextIndex = GetMidpointIndex(k, count, midpointsCount); if (previousNextIndex != nextIndex) { if (!skipIndexVerify) { ReadUntilWithMd5(PTableHeader.Size + _indexEntrySize * nextIndex, stream, md5); stream.Read(buffer, 0, _indexKeySize); md5.TransformBlock(buffer, 0, _indexKeySize, null, 0); } else { stream.Seek(PTableHeader.Size + _indexEntrySize * nextIndex, SeekOrigin.Begin); stream.Read(buffer, 0, _indexKeySize); } IndexEntryKey key; if (_version == PTableVersions.IndexV1) { key = new IndexEntryKey(BitConverter.ToUInt32(buffer, 4), BitConverter.ToInt32(buffer, 0)); } else if (_version == PTableVersions.IndexV2) { key = new IndexEntryKey(BitConverter.ToUInt64(buffer, 4), BitConverter.ToInt32(buffer, 0)); } else { key = new IndexEntryKey(BitConverter.ToUInt64(buffer, 8), BitConverter.ToInt64(buffer, 0)); } midpoints[k] = new Midpoint(key, nextIndex); previousNextIndex = nextIndex; previousKey = key; } else { midpoints[k] = new Midpoint(previousKey, previousNextIndex); } if (k > 0) { if (midpoints[k].Key.GreaterThan(midpoints[k - 1].Key)) { throw new CorruptIndexException(String.Format("Index entry key for midpoint {0} (stream: {1}, version: {2}) < index entry key for midpoint {3} (stream: {4}, version: {5})", k - 1, midpoints[k - 1].Key.Stream, midpoints[k - 1].Key.Version, k, midpoints[k].Key.Stream, midpoints[k].Key.Version)); } else if (midpoints[k - 1].ItemIndex > midpoints[k].ItemIndex) { throw new CorruptIndexException(String.Format("Item index for midpoint {0} ({1}) > Item index for midpoint {2} ({3})", k - 1, midpoints[k - 1].ItemIndex, k, midpoints[k].ItemIndex)); } } } if (!skipIndexVerify) { ReadUntilWithMd5(stream.Length - MD5Size, stream, md5); //verify hash (should be at stream.length - MD5Size) md5.TransformFinalBlock(Empty.ByteArray, 0, 0); var fileHash = new byte[MD5Size]; stream.Read(fileHash, 0, MD5Size); ValidateHash(md5.Hash, fileHash); } return(midpoints); } } catch { Dispose(); throw; } } #if MONO finally { ReturnWorkItem(workItem); } #endif }
public static void AddBundle(string filepath, Bundle b, SQLiteConnection con, CATFile cat) { if (b.ebx == null) { b.ebx = new List <Bundle.ebxtype>(); } if (b.res == null) { b.res = new List <Bundle.restype>(); } if (b.chunk == null) { b.chunk = new List <Bundle.chunktype>(); } SQLCommand("INSERT INTO bundles VALUES (NULL,'" + filepath + "','" + b.path + "', " + b.ebx.Count + ", " + b.res.Count + ", " + b.chunk.Count + " )", con); SQLiteCommand command = new SQLiteCommand("SELECT last_insert_rowid()", con); SQLiteDataReader reader = command.ExecuteReader(); reader.Read(); long id = (long)reader.GetValue(0); var transaction = con.BeginTransaction(); string basepath = Path.GetDirectoryName(cat.MyPath) + "\\"; if (!exceptions.Contains(b.path)) { foreach (Bundle.ebxtype ebx in b.ebx) { StringBuilder sb = new StringBuilder(); foreach (byte bb in ebx.SHA1) { sb.Append(bb.ToString("X2")); } List <uint> line = cat.FindBySHA1(ebx.SHA1); string type = ""; string guid = ""; if (line.Count == 9) { CASFile cas = new CASFile(basepath + "cas_" + line[7].ToString("d2") + ".cas"); CASFile.CASEntry entry = cas.ReadEntry(line.ToArray()); try { /* Just obtain the Guid and Type from raw EBX */ Tools.ExtractEbxGuidAndType(new MemoryStream(entry.data), out type, out guid); } catch (Exception) { } } SQLCommand("INSERT INTO ebx VALUES ('" + ebx.name.Replace("'", "") + "','" + sb.ToString() + "', " + id + ", '" + type + "', '" + guid + "')", con); } } transaction.Commit(); transaction = con.BeginTransaction(); foreach (Bundle.restype res in b.res) { StringBuilder sb = new StringBuilder(); foreach (byte bb in res.SHA1) { sb.Append(bb.ToString("X2")); } uint restype = BitConverter.ToUInt32(res.rtype, 0); SQLCommand("INSERT INTO res VALUES ('" + res.name.Replace("'", "") + "','" + sb.ToString() + "', '" + restype.ToString("X8") + "', " + id + ")", con); } transaction.Commit(); transaction = con.BeginTransaction(); foreach (Bundle.chunktype chunk in b.chunk) { StringBuilder sb = new StringBuilder(); foreach (byte bb in chunk.id) { sb.Append(bb.ToString("X2")); } StringBuilder sb2 = new StringBuilder(); foreach (byte bb2 in chunk.SHA1) { sb2.Append(bb2.ToString("X2")); } SQLCommand("INSERT INTO chunk VALUES ('" + sb.ToString() + "', '" + sb2.ToString() + "', " + id + ")", con); } transaction.Commit(); }
private object[] ProcessMessageObjects(byte[] message, string name, string format) { char[] form = format.ToCharArray(); int offset = 0; List <object> answer = new List <object>(); foreach (char ch in form) { switch (ch) { case 'b': answer.Add((sbyte)message[offset]); offset++; break; case 'B': answer.Add(message[offset]); offset++; break; case 'h': answer.Add(BitConverter.ToInt16(message, offset)); offset += 2; break; case 'H': answer.Add(BitConverter.ToUInt16(message, offset)); offset += 2; break; case 'i': answer.Add(BitConverter.ToInt32(message, offset)); offset += 4; break; case 'I': answer.Add(BitConverter.ToUInt32(message, offset)); offset += 4; break; case 'q': answer.Add(BitConverter.ToInt64(message, offset)); offset += 8; break; case 'Q': answer.Add(BitConverter.ToUInt64(message, offset)); offset += 8; break; case 'f': answer.Add(BitConverter.ToSingle(message, offset)); offset += 4; break; case 'd': answer.Add(BitConverter.ToDouble(message, offset)); offset += 8; break; case 'c': answer.Add((BitConverter.ToInt16(message, offset) / 100.0)); offset += 2; break; case 'C': answer.Add((BitConverter.ToUInt16(message, offset) / 100.0)); offset += 2; break; case 'e': answer.Add((BitConverter.ToInt32(message, offset) / 100.0)); offset += 4; break; case 'E': answer.Add((BitConverter.ToUInt32(message, offset) / 100.0)); offset += 4; break; case 'L': answer.Add(((double)BitConverter.ToInt32(message, offset) / 10000000.0)); offset += 4; break; case 'n': answer.Add(ASCIIEncoding.ASCII.GetString(message, offset, 4).Trim(new char[] { '\0' })); offset += 4; break; case 'N': answer.Add(ASCIIEncoding.ASCII.GetString(message, offset, 16).Trim(new char[] { '\0' })); offset += 16; break; case 'M': int modeno = message[offset]; answer.Add(modeno); offset++; break; case 'Z': answer.Add(ASCIIEncoding.ASCII.GetString(message, offset, 64).Trim(new char[] { '\0' })); offset += 64; break; case 'a': answer.Add(new UnionArray(message.Skip(offset).Take(64).ToArray()).Shorts.Take(32)); offset += 2 * 32; break; default: return(null); } } return(answer.ToArray()); }
public uint Hash(MD5 generator, int index) { return(BitConverter.ToUInt32(generator.ComputeHash(BitConverter.GetBytes(index)), 0)); }
/* * 105 +Format characters in the format string for binary log messages * 106 + b : int8_t * 107 + B : uint8_t * 108 + h : int16_t * 109 + H : uint16_t * 110 + i : int32_t * 111 + I : uint32_t * 112 + f : float * d : double * 113 + N : char[16] * 114 + c : int16_t * 100 * 115 + C : uint16_t * 100 * 116 + e : int32_t * 100 * 117 + E : uint32_t * 100 * 118 + L : uint32_t latitude/longitude * a : short[32] * 119 + */ /// <summary> /// Convert to ascii based on the existing format message /// </summary> /// <param name="message">raw binary message</param> /// <param name="name">Message type name</param> /// <param name="format">format string containing packet structure</param> /// <returns>formated ascii string</returns> string ProcessMessage(byte[] message, string name, string format) { char[] form = format.ToCharArray(); int offset = 0; StringBuilder line = new StringBuilder(name, 1024); foreach (char ch in form) { switch (ch) { case 'b': line.Append(", " + (sbyte)message[offset]); offset++; break; case 'B': line.Append(", " + message[offset]); offset++; break; case 'h': line.Append(", " + BitConverter.ToInt16(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 2; break; case 'H': line.Append(", " + BitConverter.ToUInt16(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 2; break; case 'i': line.Append(", " + BitConverter.ToInt32(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 4; break; case 'I': line.Append(", " + BitConverter.ToUInt32(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 4; break; case 'q': line.Append(", " + BitConverter.ToInt64(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 8; break; case 'Q': line.Append(", " + BitConverter.ToUInt64(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 8; break; case 'f': line.Append(", " + BitConverter.ToSingle(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 4; break; case 'd': line.Append(", " + BitConverter.ToDouble(message, offset) .ToString(System.Globalization.CultureInfo.InvariantCulture)); offset += 8; break; case 'c': line.Append(", " + (BitConverter.ToInt16(message, offset) / 100.0).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)); offset += 2; break; case 'C': line.Append(", " + (BitConverter.ToUInt16(message, offset) / 100.0).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)); offset += 2; break; case 'e': line.Append(", " + (BitConverter.ToInt32(message, offset) / 100.0).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)); offset += 4; break; case 'E': line.Append(", " + (BitConverter.ToUInt32(message, offset) / 100.0).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)); offset += 4; break; case 'L': line.Append(", " + ((double)BitConverter.ToInt32(message, offset) / 10000000.0).ToString( System.Globalization.CultureInfo.InvariantCulture)); offset += 4; break; case 'n': line.Append(", " + ASCIIEncoding.ASCII.GetString(message, offset, 4).Trim(new char[] { '\0' })); offset += 4; break; case 'N': line.Append(", " + ASCIIEncoding.ASCII.GetString(message, offset, 16).Trim(new char[] { '\0' })); offset += 16; break; case 'M': int modeno = message[offset]; var mode = onFlightMode?.Invoke(_firmware, modeno); string currentmode = mode == null?modeno.ToString() : mode; line.Append(", " + currentmode); offset++; break; case 'Z': line.Append(", " + ASCIIEncoding.ASCII.GetString(message, offset, 64).Trim(new char[] { '\0' })); offset += 64; break; case 'a': line.Append(", [" + String.Join(" ", new UnionArray(message.Skip(offset).Take(64).ToArray()).Shorts.Take(32).ToList()) + "]"); offset += 2 * 32; break; default: return("Bad Conversion"); } } return(line.ToString().Trim() + "\r\n"); }
/// <summary> /// Loads a .tex from memory and converts to bitmap /// </summary> /// <param name="data">raw tex data array</param> /// <param name="offset">offset into the array</param> /// <param name="count">number of bytes</param> /// <returns>bitmap of tex file.</returns> public Bitmap LoadFromTexMemory(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || (data.Length - offset) < count) { throw new ArgumentOutOfRangeException("count"); } if (data.Length < 12) { Log.LogError("TEX is not long enough to be valid."); return(null); } if (BitConverter.ToUInt32(data, offset) != 0x01584554) { Log.LogError("Unexpected TEX magic found in game files, ignoring."); return(null); } // We need to convert from TEX to DDS format as follows: // The 1st 12 bytes of a TEX file is crap. We want to throw it away // We need to change bytes 13,14,15,16 to: 0x44 0x44 0x53 0x20 // We then create it from DDS memory starting at offset 12 // I assume this is the texture offset. (Just add 12 to make it a file offset.) int textureOffset = BitConverter.ToInt32(data, offset + 4); System.Diagnostics.Debug.Assert(textureOffset == 0, "Texture Offset == 0"); if (textureOffset < 0 || textureOffset > (count - offset)) { throw new InvalidDataException("TEX texture offset is invalid."); } int textureLength = BitConverter.ToInt32(data, offset + 8); if (textureLength < 0 || textureLength > (count - offset - textureOffset)) { throw new InvalidDataException("TEX texture length is invalid."); } if (textureLength < 4) { throw new InvalidDataException("Cannot read TEX texture image magic."); } int realOffset = offset + textureOffset + 12; // realOffset + 0 = DDSmagic "DDS " or "DDSR" // Following DDSmagic we have the DDS_HEADER structure. // realOffset + 4 + 0 = DDS_HEADER Structure size. It should be 124 bytes unless its a DXT10 texture. // at offset 72 within DDS_HEADER we have the DDS_PIXELFORMAT structure. // realOffset + 8 + 0 = DDS_HEADER flags. // realOffset + 12 + 0 = DDS_HEADER Surface height (in pixels). // realOffset + 16 + 0 = DDS_HEADER Surface width (in pixels). // realOffset + 20 + 0 = DDS_HEADER Pitch Or LinearSize. // realOffset + 24 + 0 = DDS_HEADER Depth of a volume texture (in pixels). // realOffset + 28 + 0 = DDS_HEADER Number of mipmap levels // realOffset + 4 + 72 + 0 = DDS_PIXELFORMAT Structure size. Should be 32 bytes. // realOffset + 4 + 72 + 4 = DDS_PIXELFORMAT Flags / 0x1 = DDPF_ALPHAPIXELS flag // realOffset + 4 + 72 + 8 = DDS_PIXELFORMAT FOURCC - Four-character codes for specifying compressed or custom formats. // realOffset + 4 + 72 + 12 = DDS_PIXELFORMAT RGBBitCount. Make sure it's 32 bit since we have an alpha channel. // realOffset + 4 + 72 + 16 = Red Bitmask for A8R8G8B8 the red mask would be 0x00ff0000 // realOffset + 4 + 72 + 20 = Green Bitmask for A8R8G8B8 the green mask would be 0x0000ff00. // realOffset + 4 + 72 + 24 = Blue Bitmask for A8R8G8B8 the blue mask would be 0x000000ff. // realOffset + 4 + 72 + 28 = Alpha Bitmask for A8R8G8B8 the alpha mask would be 0xff000000. // realOffset + 4 + 104 = DDS_HEADER Complexity of the surfaces stored. Should always set at least 0x1000. uint textureMagic = BitConverter.ToUInt32(data, realOffset); // Check for both "DDS " and "DDSR". if ((textureMagic == 0x52534444 || textureMagic == 0x20534444) && textureLength >= 128) { // Make sure the DDS header is "valid". if (BitConverter.ToInt32(data, realOffset + 4) == 124 && BitConverter.ToInt32(data, realOffset + 76) == 32) { // Copy the texture data to a new buffer and fix the magic so it is a valid DDS texture. byte[] ddsData = new byte[textureLength]; Buffer.BlockCopy(data, realOffset, ddsData, 0, textureLength); // Change "DDSR" to "DDS " ddsData[3] = 0x20; int bitDepth = BitConverter.ToInt32(ddsData, 88); if (bitDepth >= 24) { // Set the Red pixel mask ddsData[92] = 0; ddsData[93] = 0; ddsData[94] = 0xff; ddsData[95] = 0; // Set the Green pixel mask ddsData[96] = 0; ddsData[97] = 0xff; ddsData[98] = 0; ddsData[99] = 0; // Set the Blue pixel mask ddsData[100] = 0xff; ddsData[101] = 0; ddsData[102] = 0; ddsData[103] = 0; // HACK: Fix to make 32-bit DDS files use transparency. if (bitDepth == 32) { // Add the alpha bit to the pixel format. ddsData[80] |= 1; // Set the Alpha pixel mask ddsData[104] = 0; ddsData[105] = 0; ddsData[106] = 0; ddsData[107] = 0xff; } } // Set the DDS caps flag ddsData[109] |= 0x10; // now create it from this memory buffer return(LoadFromMemory(ddsData, 0, ddsData.Length)); } else { throw new InvalidDataException("Invalid Header format."); } } else { throw new InvalidDataException("Unknown texture format."); } }
/// <summary> /// Unwrap object wrapped in <see cref="SerializedObjectWrapper"/> /// </summary> /// <param name="item"></param> /// <returns></returns> object Unwrap(SerializedObjectWrapper item) { if (item.Data.Array == null) { return(null); } if (item.Flags == RawDataFlag) { ArraySegment <byte> tmp = item.Data; if (tmp.Count == tmp.Array.Length) { return(tmp.Array); } // we should never arrive here, but it's better to be safe than sorry var retval = new byte[tmp.Count]; Array.Copy(tmp.Array, tmp.Offset, retval, 0, tmp.Count); return(retval); } var code = (TypeCode)(item.Flags & 0x00ff); byte[] data = item.Data.Array; int offset = item.Data.Offset; int count = item.Data.Count; switch (code) { // incrementing a non-existing key then getting it // returns as a string, but the flag will be 0 // so treat all 0 flagged items as string // this may help inter-client data management as well // // however we store 'null' as Empty + an empty array, // so this must special-cased for compatibilty with // earlier versions. we introduced DBNull as null marker in emc2.6 case TypeCode.Empty: return((data == null || count == 0) ? null : Encoding.UTF8.GetString(data, offset, count)); case TypeCode.DBNull: return(null); case TypeCode.String: return(Encoding.UTF8.GetString(data, offset, count)); case TypeCode.Boolean: return(BitConverter.ToBoolean(data, offset)); case TypeCode.Int16: return(BitConverter.ToInt16(data, offset)); case TypeCode.Int32: return(BitConverter.ToInt32(data, offset)); case TypeCode.Int64: return(BitConverter.ToInt64(data, offset)); case TypeCode.UInt16: return(BitConverter.ToUInt16(data, offset)); case TypeCode.UInt32: return(BitConverter.ToUInt32(data, offset)); case TypeCode.UInt64: return(BitConverter.ToUInt64(data, offset)); case TypeCode.Char: return(BitConverter.ToChar(data, offset)); case TypeCode.DateTime: return(DateTime.FromBinary(BitConverter.ToInt64(data, offset))); case TypeCode.Double: return(BitConverter.ToDouble(data, offset)); case TypeCode.Single: return(BitConverter.ToSingle(data, offset)); case TypeCode.Object: using (var ms = new MemoryStream(data, offset, count)) { return(bf.Deserialize(ms)); } default: throw new InvalidOperationException("Unknown TypeCode was returned: " + code); } }
/// <summary>A constructor to initialize a <c>new PairOfFiles</c>.</summary> /// <param name="FromStream"></param> /// <param name="SourceOrDestinationDrive"></param> /// <param name="TextEncoder"></param> public PairOfFiles(Stream FromStream, PairOfFiles ParentDirectory, bool isSource, TextConverter TextConverter) : this() { byte[] abBuffer, abTextBytes; ushort tTextLength; uint uAttributes, uFirstBlock = 0; long kCreationTimeTicks, kLastAccessTimeTicks, kLastWriteTimeTicks, kSize = -1; _ParentDirectory = ParentDirectory; _SourceDrive = _ParentDirectory.SourceDrive; _DestinationDrive = _ParentDirectory.DestinationDrive; _TextConverter = TextConverter; abBuffer = new byte[8]; FromStream.Read(abBuffer, 0, 2); tTextLength = BitConverter.ToUInt16(abBuffer, 0); abTextBytes = new byte[tTextLength]; FromStream.Read(abTextBytes, 0, tTextLength); _sRelativePath = _TextConverter.BytesToString(abTextBytes); FromStream.Read(abBuffer, 0, 4); uAttributes = BitConverter.ToUInt32(abBuffer, 0); _isDirectory = ((uAttributes & (uint)FileAttributes.Directory) > 0); FromStream.Read(abBuffer, 0, 8); kCreationTimeTicks = BitConverter.ToInt64(abBuffer, 0); FromStream.Read(abBuffer, 0, 8); kLastAccessTimeTicks = BitConverter.ToInt64(abBuffer, 0); FromStream.Read(abBuffer, 0, 8); kLastWriteTimeTicks = BitConverter.ToInt64(abBuffer, 0); if (!_isDirectory) { FromStream.Read(abBuffer, 0, 8); kSize = BitConverter.ToInt64(abBuffer, 0); if ((isSource && (_SourceDrive.eEncryptionType == Drive.nEncryptionType.DirectorySymmetric)) || (!isSource && (_DestinationDrive.eEncryptionType == Drive.nEncryptionType.DirectorySymmetric))) { FromStream.Read(abBuffer, 0, 4); uFirstBlock = BitConverter.ToUInt32(abBuffer, 0); } } if (isSource) { _uAttributesSource = uAttributes; _CreationTimeSource = new DateTime(kCreationTimeTicks); _LastAccessTimeSource = new DateTime(kLastAccessTimeTicks); LastWriteTimeSource = new DateTime(kLastWriteTimeTicks); _kSourceSize = kSize; _sSourceSize = FileSizeToString(kSize); _uFirstBlockSource = uFirstBlock; _eComparison = nComparison.UnknownDestination; } else { _uAttributesDestination = uAttributes; _CreationTimeDestination = new DateTime(kCreationTimeTicks); _LastAccessTimeDestination = new DateTime(kLastAccessTimeTicks); LastWriteTimeDestination = new DateTime(kLastWriteTimeTicks); _kDestinationSize = kSize; _sDestinationSize = FileSizeToString(kSize); _uFirstBlockDestination = uFirstBlock; _eComparison = nComparison.UnknownSource; } }
public LevelDBBlockchain(string path) { header_index.Add(GenesisBlock.Hash); Slice value; db = DB.Open(path); if (db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.CFG_Initialized), out value) && value.ToBoolean()) { ReadOptions options = new ReadOptions { FillCache = false }; value = db.Get(options, SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock)); this.current_block_hash = new UInt256(value.ToArray().Take(32).ToArray()); this.current_block_height = BitConverter.ToUInt32(value.ToArray(), 32); foreach (Block header in db.Find(options, SliceBuilder.Begin(DataEntryPrefix.DATA_HeaderList), (k, v) => { using (MemoryStream ms = new MemoryStream(v.ToArray(), false)) using (BinaryReader r = new BinaryReader(ms)) { return(new { Index = BitConverter.ToUInt32(k.ToArray(), 1), Headers = r.ReadSerializableArray <Block>() }); } }).OrderBy(p => p.Index).SelectMany(p => p.Headers).ToArray()) { if (header.Hash != GenesisBlock.Hash) { header_chain.Add(header.Hash, header, header.PrevBlock); header_index.Add(header.Hash); } stored_header_count++; } if (stored_header_count == 0) { Dictionary <UInt256, Block> table = db.Find(options, SliceBuilder.Begin(DataEntryPrefix.DATA_Block), (k, v) => Block.FromTrimmedData(v.ToArray(), 0)).ToDictionary(p => p.PrevBlock); for (UInt256 hash = GenesisBlock.Hash; hash != current_block_hash;) { Block header = table[hash]; header_chain.Add(header.Hash, header, header.PrevBlock); header_index.Add(header.Hash); hash = header.Hash; } } else if (current_block_height >= stored_header_count) { List <Block> list = new List <Block>(); for (UInt256 hash = current_block_hash; hash != header_index[(int)stored_header_count - 1];) { Block header = Block.FromTrimmedData(db.Get(options, SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(hash)).ToArray(), 0); list.Add(header); header_index.Insert((int)stored_header_count, hash); hash = header.PrevBlock; } for (int i = list.Count - 1; i >= 0; i--) { header_chain.Add(list[i].Hash, list[i], list[i].PrevBlock); } } this.current_header_hash = header_index[header_index.Count - 1]; } else { WriteBatch batch = new WriteBatch(); ReadOptions options = new ReadOptions { FillCache = false }; using (Iterator it = db.NewIterator(options)) { for (it.SeekToFirst(); it.Valid(); it.Next()) { batch.Delete(it.Key()); } } batch.Put(SliceBuilder.Begin(DataEntryPrefix.CFG_Version), 0); db.Write(WriteOptions.Default, batch); Persist(GenesisBlock); db.Put(WriteOptions.Default, SliceBuilder.Begin(DataEntryPrefix.CFG_Initialized), true); } thread_persistence = new Thread(PersistBlocks); thread_persistence.Name = "LevelDBBlockchain.PersistBlocks"; thread_persistence.Start(); AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; }
public async Task <bool> IsCorrectScreen(uint expectedScreen, CancellationToken token) { var data = await Connection.ReadBytesAsync(CurrentScreenOffset, 4, token).ConfigureAwait(false); return(BitConverter.ToUInt32(data, 0) == expectedScreen); }
public static object GetValueObject(PropertyItem property) { if (property == null) { return(null); } switch ((PropertyTagType)property.Type) { //ASCII case PropertyTagType.ASCII: ASCIIEncoding encoding = new ASCIIEncoding(); return(encoding.GetString(property.Value, 0, property.Len - 1)); //BYTE case PropertyTagType.Byte: if (property.Len == 1) { return(property.Value[0]); } else { return(property.Value); } //LONG case PropertyTagType.Long: uint[] resultLong = new uint[property.Len / 4]; for (int i = 0; i < resultLong.Length; i++) { resultLong[i] = BitConverter.ToUInt32(property.Value, i * 4); } if (resultLong.Length == 1) { return(resultLong[0]); } else { return(resultLong); } //SHORT case PropertyTagType.Short: ushort[] resultShort = new ushort[property.Len / 2]; for (int i = 0; i < resultShort.Length; i++) { resultShort[i] = BitConverter.ToUInt16(property.Value, i * 2); } if (resultShort.Length == 1) { return(resultShort[0]); } else { return(resultShort); } //SLONG case PropertyTagType.SLONG: int[] resultSLong = new int[property.Len / 4]; for (int i = 0; i < resultSLong.Length; i++) { resultSLong[i] = BitConverter.ToInt32(property.Value, i * 4); } if (resultSLong.Length == 1) { return(resultSLong[0]); } else { return(resultSLong); } //RATIONAL case PropertyTagType.Rational: Fraction[] resultRational = new Fraction[property.Len / 8]; uint uNumerator; uint uDenumerator; for (int i = 0; i < resultRational.Length; i++) { uNumerator = BitConverter.ToUInt32(property.Value, i * 8); uDenumerator = BitConverter.ToUInt32(property.Value, i * 8 + 4); resultRational[i] = new Fraction(uNumerator, uDenumerator); } if (resultRational.Length == 1) { return(resultRational[0]); } else { return(resultRational); } //SRATIONAL case PropertyTagType.SRational: Fraction[] resultSRational = new Fraction[property.Len / 8]; int sNumerator; int sDenumerator; for (int i = 0; i < resultSRational.Length; i++) { sNumerator = BitConverter.ToInt32(property.Value, i * 8); sDenumerator = BitConverter.ToInt32(property.Value, i * 8 + 4); resultSRational[i] = new Fraction(sNumerator, sDenumerator); } if (resultSRational.Length == 1) { return(resultSRational[0]); } else { return(resultSRational); } //UNDEFINE default: if (property.Len == 1) { return(property.Value[0]); } else { return(property.Value); } } }
/// <summary> /// Read int /// </summary> /// <returns></returns> public UInt32 ReadUInt32() { byte[] bytes = ReadByte(IntSize); return(BitConverter.ToUInt32(bytes, 0)); }
public override uint ReadUInt32() => BitConverter.ToUInt32(ReadRaw(sizeof(uint)), 0);
uint UnpackUint32(byte[] buf, ref int offset) { uint value = BitConverter.ToUInt32(buf, offset); offset += 4; return value; }
protected static T Read <T>(byte[] adata, ref int idx) { T res = default(T); // sizeof(T) on template does not work // SizeOf(T) (dynamic) apparently is not reliable - may return size of entire // container ther then storage size... // ...Surely, there must be more more sensible way of doing this... switch (Type.GetTypeCode(res.GetType())) { case TypeCode.UInt32: if (BitConverter.IsLittleEndian) { Array.Reverse(adata, idx, 4); } res = (T)Convert.ChangeType(BitConverter.ToUInt32(adata, idx), res.GetType()); idx += 4; break; case TypeCode.Int32: if (BitConverter.IsLittleEndian) { Array.Reverse(adata, idx, 4); } res = (T)Convert.ChangeType(BitConverter.ToInt32(adata, idx), res.GetType()); idx += 4; break; case TypeCode.UInt64: if (BitConverter.IsLittleEndian) { Array.Reverse(adata, idx, 8); } res = (T)Convert.ChangeType(BitConverter.ToUInt64(adata, idx), res.GetType()); idx += 8; break; case TypeCode.Int64: if (BitConverter.IsLittleEndian) { Array.Reverse(adata, idx, 8); } res = (T)Convert.ChangeType(BitConverter.ToInt64(adata, idx), res.GetType()); idx += 8; break; case TypeCode.UInt16: if (BitConverter.IsLittleEndian) { Array.Reverse(adata, idx, 2); } res = (T)Convert.ChangeType(BitConverter.ToUInt16(adata, idx), res.GetType()); idx += 2; break; case TypeCode.Int16: if (BitConverter.IsLittleEndian) { Array.Reverse(adata, idx, 2); } res = (T)Convert.ChangeType(BitConverter.ToInt16(adata, idx), res.GetType()); idx += 2; break; case TypeCode.Byte: res = (T)Convert.ChangeType(adata[idx++], res.GetType()); break; // fallthrough are intentional here... case TypeCode.Boolean: case TypeCode.Char: case TypeCode.DateTime: case TypeCode.DBNull: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Empty: case TypeCode.Object: case TypeCode.SByte: case TypeCode.Single: case TypeCode.String: default: Logger.Warn($"{res.GetType()} Unsupported read type."); break; } return(res); }