public override void Clear(StreamBuffer source) { Int32 seqNo = SeqNo; base.Clear(source); SeqNo = seqNo; }
public static Int32 GetSeqNo(StreamBuffer source) { if (source.BufferSize < HeaderSize) return -1; return source.GetInt32(Packet.HeaderSize); }
public SpriteQuad(Device device, int maxInstances) : base(device) { int slot = 0; AddVetexStreamBuffer(new VertexStreamBuffer<SpriteVertex>(InternalDevice, CreateQuadVertices(), slot, ResourceUsage.Default), CreateInputElements()); AddIndexStreamBuffer(CreateIndices()); int totalBufferSize = 16;/* FIX ME: Size needs to be multiples of 16... or is it 8? */ m_vertexBatchConstantBuffer = new ConstantStreamBuffer<VertexConstantData>(InternalDevice, totalBufferSize, 0, ConstantStreamBufferType.VertexShader, ResourceUsage.Dynamic, CpuAccessFlags.Write); m_streamBuffers.Add(m_vertexBatchConstantBuffer); totalBufferSize = Marshal.SizeOf(typeof(SpriteDrawData)) * maxInstances; slot = 1; m_instanceDataStream = new VertexStreamBuffer<SpriteDrawData>(device, totalBufferSize, slot, ResourceUsage.Dynamic, CpuAccessFlags.Write); m_streamBuffers.Add(m_instanceDataStream); }
public static new Boolean IsValidPacket(StreamBuffer buffer, out int packetSize) { if (buffer.WrittenBytes < HeaderSize) { packetSize = 0; return false; } packetSize = buffer.GetUInt16(); return (packetSize > 0 && buffer.WrittenBytes >= packetSize); }
private static short SerializeVector2(StreamBuffer outStream, object customobject) { Vector2 vo = (Vector2)customobject; lock (memVector2) { byte[] bytes = memVector2; int index = 0; Protocol.Serialize(vo.x, bytes, ref index); Protocol.Serialize(vo.y, bytes, ref index); outStream.Write(bytes, 0, 2 * 4); } return 2 * 4; }
private static object DeserializeVector3(StreamBuffer inStream, short length) { Vector3 vo = new Vector3(); lock (memVector3) { inStream.Read(memVector3, 0, 3 * 4); int index = 0; Protocol.Deserialize(out vo.x, memVector3, ref index); Protocol.Deserialize(out vo.y, memVector3, ref index); Protocol.Deserialize(out vo.z, memVector3, ref index); } return vo; }
public Boolean Dispatch(StreamBuffer buffer) { foreach (var data in _listResponseAction) { if (data.Criterion(buffer) == true) { try { _listResponseAction.Remove(data); data.Dispatcher(_session, buffer); } catch (Exception e) { Logger.Write(LogType.Err, 1, e.ToString()); } return true; } } return false; }
public NetworkSendToken(StreamBuffer buffer, Action<StreamBuffer> completion) { Buffer = buffer; _actionOnCompletion = completion; }
protected override void InternalDeserialize(StreamBuffer buffer) { base.InternalDeserialize(buffer); this.dto = new _DTO_byte(); this.dto.Deserialize(buffer); }
protected override void InternalSerialize(StreamBuffer buffer) { base.InternalSerialize(buffer); this.dto.Serialize(buffer); }
private IFileReader GetFileReader([NotNull] IExecutionContext context, StreamBuffer streamBuffer) { return(context.FileFormats.OfType <IFileReader>().FirstOrDefault(reader => reader.CanReadThisFile(new FileFormatExecutionContext(context, this), this.Uri, streamBuffer.Buffer))); }
private void Initialize() { Context = new UdfContext { PhysicalPartitions = new Dictionary <ushort, PhysicalPartition>(), PhysicalSectorSize = (int)_sectorSize, LogicalPartitions = new List <LogicalPartition>() }; IBuffer dataBuffer = new StreamBuffer(_data, Ownership.None); AnchorVolumeDescriptorPointer avdp = AnchorVolumeDescriptorPointer.FromStream(_data, 256, _sectorSize); uint sector = avdp.MainDescriptorSequence.Location; bool terminatorFound = false; while (!terminatorFound) { _data.Position = sector * (long)_sectorSize; DescriptorTag dt; if (!DescriptorTag.TryFromStream(_data, out dt)) { break; } switch (dt.TagIdentifier) { case TagIdentifier.PrimaryVolumeDescriptor: _pvd = PrimaryVolumeDescriptor.FromStream(_data, sector, _sectorSize); break; case TagIdentifier.ImplementationUseVolumeDescriptor: // Not used break; case TagIdentifier.PartitionDescriptor: PartitionDescriptor pd = PartitionDescriptor.FromStream(_data, sector, _sectorSize); if (Context.PhysicalPartitions.ContainsKey(pd.PartitionNumber)) { throw new IOException("Duplicate partition number reading UDF Partition Descriptor"); } Context.PhysicalPartitions[pd.PartitionNumber] = new PhysicalPartition(pd, dataBuffer, _sectorSize); break; case TagIdentifier.LogicalVolumeDescriptor: _lvd = LogicalVolumeDescriptor.FromStream(_data, sector, _sectorSize); break; case TagIdentifier.UnallocatedSpaceDescriptor: // Not used for reading break; case TagIdentifier.TerminatingDescriptor: terminatorFound = true; break; default: break; } sector++; } // Convert logical partition descriptors into actual partition objects for (int i = 0; i < _lvd.PartitionMaps.Length; ++i) { Context.LogicalPartitions.Add(LogicalPartition.FromDescriptor(Context, _lvd, i)); } byte[] fsdBuffer = UdfUtilities.ReadExtent(Context, _lvd.FileSetDescriptorLocation); if (DescriptorTag.IsValid(fsdBuffer, 0)) { FileSetDescriptor fsd = EndianUtilities.ToStruct <FileSetDescriptor>(fsdBuffer, 0); RootDirectory = (Directory)File.FromDescriptor(Context, fsd.RootDirectoryIcb); } }
public void TextureDepthTest() { // Reference a map buffer to test drawing with that as well. StreamBuffer buffer = null; // Create scene for this test. TestScene extScene = new TestScene { // Load the textures. ExtLoad = () => { Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png"); // Also tests mapping and initializing of map buffers in another thread. buffer = Engine.GraphicsManager.CreateQuadStreamBuffer(100); buffer.MapNextQuad(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 150, 0), new Vector2(20, 20), Color.White); buffer.MapNextQuad(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 180, 0), new Vector2(20, 20), Color.White); buffer.MapNextQuad(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 210, 0), new Vector2(20, 20), Color.White); buffer.MapNextQuad(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 240, 0), new Vector2(20, 20), Color.White); buffer.MapNextQuad(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 270, 0), new Vector2(20, 20), Color.White); buffer.MapNextQuad(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 300, 0), new Vector2(20, 20), Color.White); buffer.MapNextQuad(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 330, 0), new Vector2(20, 20), Color.White); }, // Unload the texture. ExtUnload = () => { Engine.AssetLoader.Destroy("Textures/logoAlpha.png"); // Test unloading of a map buffer. buffer.Delete(); }, // Draw textures. ExtDraw = () => { const int maxX = 5 * 49; const int maxY = 5 * 49; // Set background so we can see invalid alpha. Engine.Renderer.Render(new Vector3(0, 0, -1), Engine.Renderer.BaseTarget.Size, Color.CornflowerBlue); // Draw normally. for (int i = 0; i < 50; i++) { Engine.Renderer.Render(new Vector3(5 * i, 5 * i, i), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); } for (int i = 0; i < 50; i++) { Engine.Renderer.Render(new Vector3(5 * i, maxY - 5 * i, i), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); } // Queue draw. for (int i = 0; i < 50; i++) { Engine.Renderer.Render(new Vector3(maxX + 5 * i, maxY + 5 * i, i), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); } for (int i = 0; i < 50; i++) { Engine.Renderer.Render(new Vector3(maxX + 5 * i, maxY + maxY - 5 * i, i + 49), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); } // Draw line 0-1/1-0 with queuing. Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X, 0, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 50, 0, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 100, 0, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 150, 0, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 200, 0, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 250, 0, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 300, 0, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X, 100, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 50, 100, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 100, 100, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 150, 100, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 200, 100, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 250, 100, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 300, 100, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); // Render line 0-1/1-0 without queuing. Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X, 200, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 50, 200, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 100, 200, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 150, 200, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 200, 200, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 250, 200, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 300, 200, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X, 300, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 50, 300, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 100, 300, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 150, 300, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 200, 300, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 250, 300, 0), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X - 300, 300, 1), new Vector2(100, 100), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); // Draw a map buffer. Engine.Renderer.Render(buffer); // Render text. Atlas atlas = Engine.AssetLoader.Get <Font>("debugFont.otf").GetFontAtlas(20); Engine.Renderer.RenderString(atlas, "This is test text", new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 0, 1), Color.Red); Engine.Renderer.RenderString(atlas, "This is test text", new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 10, 2), Color.Green); Engine.Renderer.RenderString(atlas, "This is test text", new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 20, 1), Color.Blue); Engine.Renderer.Render(new Vector3(Engine.Renderer.BaseTarget.Size.X / 2 - 100, 0, 0), new Vector2(200, 100), Color.Black); } }; // Load scene. Helpers.LoadScene(extScene); // Check if what is currently on screen is what is expected. // This render is not 100% correct though, as the text has weird artifacts. Assert.Equal("YnuPlWmWruXr2t3NIVrCDj4b+fEVf6/DGH/us3q6TvQ=", Helpers.TakeScreenshot()); // Cleanup. Helpers.UnloadScene(); // Ensure the textures are unloaded. Assert.Null(Engine.AssetLoader.LoadedAssets.FirstOrDefault(x => x.Name == "Textures/logoAlpha.png")); }
protected override void InternalDeserialize(StreamBuffer buffer) { base.InternalDeserialize(buffer); this.value = buffer.ReadInt(); }
private static short SerializePhotonPlayer(StreamBuffer outStream, object customobject) { int ID = ((PhotonPlayer)customobject).ID; lock (memPlayer) { byte[] bytes = memPlayer; int off = 0; Protocol.Serialize(ID, bytes, ref off); outStream.Write(bytes, 0, 4); return 4; } }
private static object DeserializePhotonPlayer(StreamBuffer inStream, short length) { int ID; lock (memPlayer) { inStream.Read(memPlayer, 0, length); int off = 0; Protocol.Deserialize(out ID, memPlayer, ref off); } if (PhotonNetwork.networkingPeer.mActors.ContainsKey(ID)) { return PhotonNetwork.networkingPeer.mActors[ID]; } else { return null; } }
private static short SerializeQuaternion(StreamBuffer outStream, object customobject) { Quaternion o = (Quaternion)customobject; lock (memQuarternion) { byte[] bytes = memQuarternion; int index = 0; Protocol.Serialize(o.w, bytes, ref index); Protocol.Serialize(o.x, bytes, ref index); Protocol.Serialize(o.y, bytes, ref index); Protocol.Serialize(o.z, bytes, ref index); outStream.Write(bytes, 0, 4 * 4); } return 4 * 4; }
private static object DeserializeQuaternion(StreamBuffer inStream, short length) { Quaternion o = new Quaternion(); lock (memQuarternion) { inStream.Read(memQuarternion, 0, 4 * 4); int index = 0; Protocol.Deserialize(out o.w, memQuarternion, ref index); Protocol.Deserialize(out o.x, memQuarternion, ref index); Protocol.Deserialize(out o.y, memQuarternion, ref index); Protocol.Deserialize(out o.z, memQuarternion, ref index); } return o; }
/// <summary> /// 수신된 데이터가 유효한 패킷인지 여부를 확인합니다. /// 유효한 패킷으로 판단되면 packetSize에 이 패킷의 정확한 크기를 입력하고 true를 반환해야 합니다. /// </summary> /// <param name="buffer">수신된 데이터가 담긴 버퍼</param> /// <param name="packetSize">유효한 패킷의 크기</param> /// <returns>true를 반환하면 OnReceive를 통해 수신된 데이터가 전달됩니다.</returns> public static Boolean IsValidPacket(StreamBuffer buffer, out Int32 packetSize) { if (buffer.WrittenBytes < HeaderSize) { packetSize = 0; return false; } // 최초 2바이트를 수신할 패킷의 크기로 처리 packetSize = buffer.GetUInt16(0); return (packetSize > 0 && buffer.WrittenBytes >= packetSize); }
private void _writeContent(PdfStreamWriter writer, string filter, StreamBuffer buffer) { writer.WriteDictionaryBegin(); if (filter != null) { writer.WriteName("Filter"); writer.WriteName(filter); } writer.WriteName("Length"); writer.WriteInteger((int)buffer.Length); writer.WriteDictionaryEnd(); writer.WriteStream(buffer.GetBuffer(), (int)buffer.Length); _dataStream.Dispose(); _dataStream = null; // Release datastream for less memory usage }
private static short SerializeChar(StreamBuffer outStream, object customObj) { outStream.Write(new[] { (byte)((char)customObj) }, 0, 1); return(1); }
private static void Main(string[] args) { const int width = 640, height = 360; Bebop bebop = new Bebop(); Stopwatch sw = new Stopwatch(); if (bebop.Connect() == ConnectionStatus.Success) { bebop.FlatTrim(2000); Thread abortThread = new Thread(Run); abortThread.Start(); bebop.StartVideo(); VideoCapture capture = new VideoCapture(@"./bebop.sdp"); StreamBuffer buffer = new StreamBuffer(capture, width, height); buffer.AddService(new Canny(width, height)); buffer.AddService(new UltraSonicService()); buffer.Start(); bebop.TakeOff(); sw.Start(); while (abortThread.IsAlive) { Image <Bgr, byte> frame = buffer.PopLastFrame(); if (frame != null) { buffer.TransmitFrame(frame); Vector v = new Vector { Pitch = 1 }; foreach (Service service in buffer.Services) { Response r = service.GetLatestResult(); if (r != null && r.IsValid) { Vector vec = r.Vector.Copy(); vec.TimesConstant(r.Confidence / 100); v.Add(vec); } } bebop.Move(v); } } sw.Stop(); Console.WriteLine("\n" + sw.ElapsedMilliseconds + "ms"); buffer.Stop(); bebop.Land(); bebop.StopVideo(); bebop.Disconnect(); } Console.ReadLine(); }
/// <summary> /// 패킷을 전송합니다. /// </summary> /// <param name="buffer">전송할 데이터가 담긴 StreamBuffer</param> /// <param name="onSent">패킷 전송이 완료된 후 호출할 Action</param> public virtual void SendPacket(StreamBuffer buffer, Action<StreamBuffer> onSent = null) { _method.SendPacket(buffer, onSent); }
protected abstract void DoReceive(StreamBuffer receiveStreamBuffer, ref int bufferCurLen);
public void PacketHandler(Packet packet) { try { // Make this static or at least dont create a new Protocol16 for every package Protocol16 protocol16 = new Protocol16(); IpV4Datagram ip = packet.Ethernet.IpV4; UdpDatagram udp = ip.Udp; // Not technically necesasry as the bpf limits to only udp 5055 if (udp.SourcePort != 5056 && udp.DestinationPort != 5056 && udp.SourcePort != 5055 && udp.DestinationPort != 5055) { return; } var ms = udp.Payload.ToMemoryStream(); var p = new BinaryReader(ms); var peerId = IPAddress.NetworkToHostOrder(p.ReadUInt16()); var crcEnabled = p.ReadByte(); var commandCount = p.ReadByte(); var timestamp = IPAddress.NetworkToHostOrder(p.ReadInt32()); var challenge = IPAddress.NetworkToHostOrder(p.ReadInt32()); var commandHeaderLength = 12; var signifierByteLength = 1; for (int commandIdx = 0; commandIdx < commandCount; commandIdx++) { var commandType = p.ReadByte(); var channelId = p.ReadByte(); var commandFlags = p.ReadByte(); var unkBytes = p.ReadByte(); var commandLength = IPAddress.NetworkToHostOrder(p.ReadInt32()); var sequenceNumber = IPAddress.NetworkToHostOrder(p.ReadInt32()); void ParseOperation(byte messageType, StreamBuffer payload, int operationLength) { switch (messageType) { case 2: //Operation Request var requestData = protocol16.DeserializeOperationRequest(payload); _eventHandler.OnRequest(requestData.OperationCode, requestData.Parameters); break; case 3: //Operation Response var responseData = protocol16.DeserializeOperationResponse(payload); _eventHandler.OnResponse(responseData.OperationCode, responseData.ReturnCode, responseData.Parameters); break; case 4: //Event var eventData = protocol16.DeserializeEventData(payload); _eventHandler.OnEvent(eventData.Code, eventData.Parameters); break; default: p.BaseStream.Position += operationLength; break; } } switch (commandType) { case 4: //Disconnect break; case 7: //Send unreliable p.BaseStream.Position += 4; commandLength -= 4; goto case 6; case 6: //Send reliable { p.BaseStream.Position += signifierByteLength; var messageType = p.ReadByte(); var operationLength = commandLength - commandHeaderLength - 2; var payload = new StreamBuffer(p.ReadBytes(operationLength)); ParseOperation(messageType, payload, operationLength); break; } case 8: // Reliable Fragment { // Each fragment contains a starting sequence number, its sequence number, // and how many fragments total there are. var startSequenceNumber = IPAddress.NetworkToHostOrder(p.ReadInt32()); var fragmentCount = IPAddress.NetworkToHostOrder(p.ReadInt32()); var fragmentNumber = IPAddress.NetworkToHostOrder(p.ReadInt32()); var totalLength = IPAddress.NetworkToHostOrder(p.ReadInt32()); var fragmentOffset = IPAddress.NetworkToHostOrder(p.ReadInt32()); var operationLength = commandLength - 5 * 4 - commandHeaderLength; // 5 4-byte var payload = p.ReadBytes(operationLength); if (!fragmentMap.TryGetValue(startSequenceNumber, out var fragment)) { fragment = new Fragment { buffer = new byte[totalLength], totalFragments = fragmentCount, readFragments = 0 }; fragmentMap.Add(startSequenceNumber, fragment); } fragment.readFragments++; Array.Copy(payload, 0, fragment.buffer, fragmentOffset, payload.Length); if (fragment.readFragments == fragment.totalFragments) { Console.WriteLine("Fragment Complete"); var stream = new StreamBuffer(fragment.buffer); stream.Position += signifierByteLength; Console.WriteLine("Fragment Stream Read"); var messageType = stream.ReadByte(); Console.WriteLine("Fragment MessageType: " + messageType); ParseOperation(messageType, stream, operationLength); Console.WriteLine("Fragment Successfully Handled"); fragmentMap.Remove(startSequenceNumber); } break; } default: if (commandType != 1 && commandType != 5) { // Console.WriteLine("Received Unhandled Command Type: " + commandType); } p.BaseStream.Position += commandLength - commandHeaderLength; break; } } } catch (Exception e) { Console.WriteLine("PacketHandler Exception: " + e.ToString()); } }
public void StreamBufferRangesTest() { // Reference map buffers to test with. StreamBuffer buffer = null; // Create scene for this test. TestScene extScene = new TestScene { // Load the textures. ExtLoad = () => { // Init quad buffer. buffer = Engine.GraphicsManager.CreateQuadStreamBuffer(20); buffer.MapNextQuad(new Vector3(5, 10, 0), new Vector2(20, 20), Color.Red); buffer.MapNextQuad(new Vector3(5, 40, 0), new Vector2(20, 20), Color.Yellow); buffer.MapNextQuad(new Vector3(5, 70, 0), new Vector2(20, 20), Color.Green); buffer.MapNextQuad(new Vector3(5, 100, 0), new Vector2(20, 20), Color.Blue); buffer.MapNextQuad(new Vector3(5, 130, 0), new Vector2(20, 20), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); buffer.MapNextQuad(new Vector3(5, 160, 0), new Vector2(20, 20), Color.White, Engine.AssetLoader.Get <Texture>("Textures/standardPng.png")); buffer.MapNextQuad(new Vector3(5, 190, 0), new Vector2(20, 20), Color.White, Engine.AssetLoader.Get <Texture>("Textures/standardGif.gif")); }, // Unload the texture. ExtUnload = () => { // Unloads buffers. buffer.Delete(); // Unload textures. Engine.AssetLoader.Destroy("Textures/logoAlpha.png"); Engine.AssetLoader.Destroy("Textures/standardPng.png"); Engine.AssetLoader.Destroy("Textures/standardGif.gif"); }, // Draw textures. ExtDraw = () => { // Draw the buffer. Engine.Renderer.Render(buffer); } }; // Load scene. Helpers.LoadScene(extScene); Assert.Equal("/wWfA8rwIzhspD7e4LamEx3vWU85OP6jSEDMJpHXVZ8=", Helpers.TakeScreenshot()); buffer.SetRenderRange(0, 2); extScene.WaitFrames(2).Wait(); Assert.Equal("T2Z3l1pCmaMw8HKWkR3VyY6lxXJY6L44qyi+wOGp5M8=", Helpers.TakeScreenshot()); buffer.SetRenderRange(2, 4); extScene.WaitFrames(2).Wait(); Assert.Equal("o+xAalQAizKbGxcdTXktBJgcHQMgnJ1h/43V7r82uLc=", Helpers.TakeScreenshot()); buffer.SetRenderRange(4); extScene.WaitFrames(2).Wait(); Assert.Equal("0lBVAPJSqH9CXVpvqjJoo4Q+N9ZE85o2cQcQvnfXosc=", Helpers.TakeScreenshot()); // Cleanup. Helpers.UnloadScene(); // Ensure the textures are unloaded. Assert.Null(Engine.AssetLoader.LoadedAssets.FirstOrDefault(x => x.Name == "Textures/logoAlpha.png")); Assert.Null(Engine.AssetLoader.LoadedAssets.FirstOrDefault(x => x.Name == "Textures/standardPng.png")); Assert.Null(Engine.AssetLoader.LoadedAssets.FirstOrDefault(x => x.Name == "Textures/standardGif.gif")); }
/// <summary> /// StreamBuffer의 데이터를 복사하여 패킷을 생성합니다. /// </summary> /// <param name="source">복사할 데이터가 담긴 StreamBuffer 객체</param> public SecurityPacket(StreamBuffer source) { Write(source.Buffer, 0, source.WrittenBytes); }
internal void OnReceived(StreamBuffer buffer) { StreamBuffer buf = new StreamBuffer(buffer); SpinWorker.Dispatch(() => { if (NetworkEvent_Received != null) NetworkEvent_Received(this, buf); }); }
/// <summary> /// 패킷 버퍼를 초기화하고 source 데이터를 저장합니다. Packet Header의 Size는 source 버퍼의 헤더값이 사용됩니다. /// </summary> /// <param name="source">저장할 데이터</param> public void Clear(StreamBuffer source) { if (source.BufferSize < 4) throw new AegisException(ResultCode.InvalidArgument, "The source size must be at lest 4 bytes."); base.Clear(); Write(source.Buffer, 0, source.WrittenBytes); Size = GetUInt16(0); }
private StreamReader GetStreamReader([NotNull] StreamBuffer stream, IFileReader fileReader) { return(new StreamReader(stream.Stream, (fileReader as IOverrideEncoding)?.Encoding ?? this.encoding, true)); }
protected override void InternalDeserialize(StreamBuffer buffer) { base.InternalDeserialize(buffer); this.dto = new _DTO_room_info_detail(); this.dto.Deserialize(buffer); }
protected override void InternalDeserialize(StreamBuffer buffer) { base.InternalDeserialize(buffer); }
private void PacketHandle(object sender, CaptureEventArgs e) { Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); var udpPacket = packet.Extract <UdpPacket>(); if (udpPacket == null) { return; } Protocol16 protocol16 = new Protocol16(); log.Debug($"sourcePort={udpPacket.SourcePort} destPort={udpPacket.DestinationPort}"); BinaryReader binaryReader = new BinaryReader(new MemoryStream(udpPacket.PayloadData)); try { IPAddress.NetworkToHostOrder((int)binaryReader.ReadUInt16()); binaryReader.ReadByte(); byte commandCount = binaryReader.ReadByte(); IPAddress.NetworkToHostOrder(binaryReader.ReadInt32()); IPAddress.NetworkToHostOrder(binaryReader.ReadInt32()); int commandHeaderLength = 12; int signifierByteLength = 1; for (int commandIdx = 0; commandIdx < (int)commandCount; commandIdx++) { try { byte commandType = binaryReader.ReadByte(); binaryReader.ReadByte(); binaryReader.ReadByte(); binaryReader.ReadByte(); int commandLength = IPAddress.NetworkToHostOrder(binaryReader.ReadInt32()); IPAddress.NetworkToHostOrder(binaryReader.ReadInt32()); switch (commandType) { case 4: goto IL_1E7; case 5: goto IL_1CF; case 6: break; case 7: binaryReader.BaseStream.Position += 4L; commandLength -= 4; break; default: goto IL_1CF; } binaryReader.BaseStream.Position += (long)signifierByteLength; byte messageType = binaryReader.ReadByte(); int operationLength = commandLength - commandHeaderLength - 2; StreamBuffer payload = new StreamBuffer(binaryReader.ReadBytes(operationLength)); switch (messageType) { case 2: { log.Debug($"Request Packet Data: {System.Convert.ToBase64String(udpPacket.PayloadData)}"); OperationRequest requestData = protocol16.DeserializeOperationRequest(payload); Instance.OnRequest(requestData.OperationCode, requestData.Parameters); goto IL_1E7; } case 3: { OperationResponse responseData = protocol16.DeserializeOperationResponse(payload); Instance.OnResponse(responseData.OperationCode, responseData.ReturnCode, responseData.Parameters); goto IL_1E7; } case 4: { EventData eventData = protocol16.DeserializeEventData(payload); Instance.OnEvent(eventData.Code, eventData.Parameters); goto IL_1E7; } default: binaryReader.BaseStream.Position += (long)operationLength; goto IL_1E7; } IL_1CF: binaryReader.BaseStream.Position += (long)(commandLength - commandHeaderLength); IL_1E7 :; } catch (Exception ex) { log.Error(ex.StackTrace); } } } catch (Exception ex) { log.Error(ex.StackTrace); } }
public void Initialize() { _buffer = new StreamBuffer(10); _stream = new OutputStream(_buffer); }
internal BidirectionalStreamBufferStream(StreamBuffer readBuffer, StreamBuffer writeBuffer, StrongBox<int> refCount) { _readBuffer = readBuffer; _writeBuffer = writeBuffer; _refCount = refCount; }
protected override void InternalDeserialize(StreamBuffer buffer) { base.InternalDeserialize(buffer); this.dto = new _DTO_request_room_list(); this.dto.Deserialize(buffer); }
internal UnidirectionalStreamBufferStream(StreamBuffer buffer, bool reader, StrongBox<int> refCount) { _buffer = buffer; _reader = reader; _refCount = refCount; }
public override void Handle(BafClient client, BafPacket packet) { IBuffer b = new StreamBuffer(); BafPacket p = new BafPacket(PacketId.RoomChangeColorRes, b.GetAllBytes()); // client.Send(p); }
public void SendPacket(StreamBuffer buffer, Action<StreamBuffer> onSent = null) { Session?.SendPacket(buffer, onSent); }
public void PacketHandler(Packet packet) { Protocol16 protocol16 = new Protocol16(); UdpDatagram udp = packet.Ethernet.IpV4.Udp; if (udp.SourcePort != 5056 && udp.DestinationPort != 5056) { return; } BinaryReader p = new BinaryReader(udp.Payload.ToMemoryStream()); IPAddress.NetworkToHostOrder((int)p.ReadUInt16()); p.ReadByte(); byte commandCount = p.ReadByte(); IPAddress.NetworkToHostOrder(p.ReadInt32()); IPAddress.NetworkToHostOrder(p.ReadInt32()); int commandHeaderLength = 12; int signifierByteLength = 1; for (int commandIdx = 0; commandIdx < (int)commandCount; commandIdx++) { try { byte commandType = p.ReadByte(); p.ReadByte(); p.ReadByte(); p.ReadByte(); int commandLength = IPAddress.NetworkToHostOrder(p.ReadInt32()); IPAddress.NetworkToHostOrder(p.ReadInt32()); switch (commandType) { case 4: goto postPositionUpdate; case 5: goto prePositionUpdate; case 6: break; case 7: p.BaseStream.Position += 4L; commandLength -= 4; break; default: goto prePositionUpdate; } p.BaseStream.Position += (long)signifierByteLength; byte messageType = p.ReadByte(); int operationLength = commandLength - commandHeaderLength - 2; StreamBuffer payload = new StreamBuffer(p.ReadBytes(operationLength)); switch (messageType) { case 2: { OperationRequest requestData = protocol16.DeserializeOperationRequest(payload); this._eventHandler.OnRequest(requestData.OperationCode, requestData.Parameters); goto postPositionUpdate; } case 3: { OperationResponse responseData = protocol16.DeserializeOperationResponse(payload); this._eventHandler.OnResponse(responseData.OperationCode, responseData.ReturnCode, responseData.Parameters); goto postPositionUpdate; } case 4: { EventData eventData = protocol16.DeserializeEventData(payload); this._eventHandler.OnEvent(eventData.Code, eventData.Parameters); goto postPositionUpdate; } default: p.BaseStream.Position += (long)operationLength; goto postPositionUpdate; } prePositionUpdate: p.BaseStream.Position += (long)(commandLength - commandHeaderLength); postPositionUpdate :; } catch (Exception) { } } }
public PacketResponse(StreamBuffer source) : base(source) { }
public void Load(byte[] data) { int gxtSize = data.Length; int numEntries = 0; using (StreamBuffer buf = new StreamBuffer(data)) { m_masterTable.Clear(); Log.Info("Loading GXT..."); // Read TABL header string tabl = buf.ReadString(4); int tablSectionSize = buf.ReadInt32(); int tablSectionPos = buf.Position; if (tabl != "TABL") { throw InvalidGxt(); } Debug.Assert(buf.Position + tablSectionSize <= gxtSize); // Read TABL while (tablSectionPos < tablSectionSize) { var table = new Dictionary <string, string>(); // Read TABL entry string tableName = buf.ReadString(8); int tablePos = buf.ReadInt32(); tablSectionPos += 12; Debug.Assert(tablePos < gxtSize); // Jump to table and read table name buf.Seek(tablePos); string tableName2 = tableName; if (tableName != "MAIN") { tableName2 = buf.ReadString(8); } Debug.Assert(tableName == tableName2); // Read TKEY header string tkey = buf.ReadString(4); int tkeySectionSize = buf.ReadInt32(); int tkeySectionStart = buf.Position; int tkeySectionOffset = 0; if (tkey != "TKEY") { throw InvalidGxt(); } Debug.Assert(buf.Position + tkeySectionSize <= gxtSize); // Verify TDAT presence buf.Skip(tkeySectionSize); string tdat = buf.ReadString(4); int tdatSectionSize = buf.ReadInt32(); int tdatSectionStart = buf.Position; if (tdat != "TDAT") { throw InvalidGxt(); } Debug.Assert(buf.Position + tdatSectionSize <= gxtSize); // Read TKEY buf.Seek(tkeySectionStart); while (tkeySectionOffset < tkeySectionSize) { // Read TKEY entry int valueOffset = buf.ReadInt32(); string key = buf.ReadString(8); tkeySectionOffset += 12; Debug.Assert(valueOffset < tdatSectionSize); Debug.Assert(!table.ContainsKey(key)); // Read value buf.Seek(tdatSectionStart + valueOffset); table[key] = buf.ReadString(unicode: true); // zero-terminated numEntries++; buf.Seek(tkeySectionStart + tkeySectionOffset); } m_masterTable[tableName] = table; buf.Seek(tablSectionPos); } } Log.Info($"Loaded {numEntries} GXT entries from {m_masterTable.Count} tables."); }
public void Pack(string inPath, string outPath, string archiveName, string archivePath = "") { uint fileTime = 0x506fa78e; string dirPath = archivePath; if (archivePath.Length > 0) { if (!dirPath.StartsWith("\\")) { dirPath = "\\" + dirPath; archivePath = "\\" + archivePath; } if (!dirPath.EndsWith("\\")) { dirPath = dirPath + "\\"; archivePath = archivePath + "\\"; } dirPath = ".\\" + archiveName + dirPath + "%08x.dat"; } else { dirPath = ".\\" + archiveName + "\\" + "%08x.dat"; } dirPath = dirPath.Replace("\\", "/"); FpmfArchive archive = new FpmfArchive(); if (inPath.EndsWith("\\")) { inPath = inPath.Substring(0, inPath.Length - 1); } uint currentOffset = 0; string baseArchivePath = inPath + "\\" + archiveName + archivePath; string[] inFiles = Directory.GetFiles(baseArchivePath, "*", SearchOption.AllDirectories); archive.numFiles = (uint)inFiles.Length; archive.datPath = dirPath; archive.datPathLen = dirPath.Length; foreach (string inFile in inFiles) { IBuffer inReader = new StreamBuffer(inFile); FpmfArchiveFile datFile = new FpmfArchiveFile(); datFile.size = (uint)inReader.Size; datFile.datNumber = 0; datFile.offset = currentOffset; IBuffer encryptedBuff = EncryptDat(inReader, archive.key); datFile.data = encryptedBuff.GetAllBytes(); datFile.filePath = inFile.Replace(inPath + "\\" + archiveName, "."); datFile.filePathSize = (uint)datFile.filePath.Length; datFile.directoryPath = ".\\" + archiveName + "\\"; datFile.directoryPathSize = (uint)datFile.directoryPath.Length; datFile.unknown0 = fileTime; datFile.unknown1 = 0; archive.AddFile(datFile); currentOffset += datFile.size; } if (archivePath.Length > 0) { outPath = outPath + "\\" + archiveName + archivePath; } else { outPath = outPath + "\\" + archiveName + "\\"; } SavePack(archive, inPath, outPath, archiveName); }
public void StreamBufferTest() { // Shader to test shader drawing. ShaderProgram testShader = Engine.GraphicsManager.CreateShaderProgram(null, @"#version v #ifdef GL_ES precision highp float; #endif uniform sampler2D textures[16]; // Comes in from the vertex shader. in vec2 UV; in vec4 vertColor; in float Tid; out vec4 fragColor; void main() { vec4 temp; // Check if a texture is in use. if (Tid >= 0.0) { // Sample for the texture's color at the specified vertex UV and multiply it by the tint. temp = texture(textures[int(Tid)], UV) * vertColor; } else { // If no texture then just use the color. temp = vertColor; } fragColor = vec4(temp.y, temp.x, 0, temp.w); if (fragColor.a < 0.01) discard; }"); // Reference map buffers to test with. StreamBuffer quadBuffer = null; StreamBuffer overflowVerts = null; StreamBuffer overflowTextures = null; StreamBuffer colorBarfBuffer = null; // Create scene for this test. TestScene extScene = new TestScene { // Load the textures. ExtLoad = () => { // Init quad buffer. quadBuffer = Engine.GraphicsManager.CreateQuadStreamBuffer(20); quadBuffer.MapNextQuad(new Vector3(5, 10, 0), new Vector2(20, 20), Color.White); quadBuffer.MapNextQuad(new Vector3(5, 40, 0), new Vector2(20, 20), Color.White); quadBuffer.MapNextQuad(new Vector3(5, 70, 0), new Vector2(20, 20), Color.White); quadBuffer.MapNextQuad(new Vector3(5, 100, 0), new Vector2(20, 20), Color.White); quadBuffer.MapNextQuad(new Vector3(5, 130, 0), new Vector2(20, 20), Color.White); quadBuffer.MapNextQuad(new Vector3(5, 160, 0), new Vector2(20, 20), Color.White); quadBuffer.MapNextQuad(new Vector3(5, 190, 0), new Vector2(20, 20), Color.White); // Init overflow buffer. // The size is smaller than what we are mapping, the expected behavior is not to map the third one. overflowVerts = Engine.GraphicsManager.CreateQuadStreamBuffer(2); overflowVerts.MapNextQuad(new Vector3(5, 10, 0), new Vector2(20, 20), Color.White); overflowVerts.MapNextQuad(new Vector3(5, 40, 0), new Vector2(20, 20), Color.White); overflowVerts.MapNextQuad(new Vector3(5, 70, 0), new Vector2(20, 20), Color.White); // Set the texture limit really low. int oldLimit = Engine.Flags.RenderFlags.TextureArrayLimit; Engine.Flags.RenderFlags.TextureArrayLimit = 2; // Init a buffer which will overflow the texture limit. overflowTextures = Engine.GraphicsManager.CreateQuadStreamBuffer(30); overflowTextures.MapNextQuad(new Vector3(5, 10, 0), new Vector2(20, 20), Color.White, Engine.AssetLoader.Get <Texture>("Textures/logoAlpha.png")); overflowTextures.MapNextQuad(new Vector3(5, 40, 0), new Vector2(20, 20), Color.White, Engine.AssetLoader.Get <Texture>("Textures/standardPng.png")); ErrorHandler.SuppressErrors = true; overflowTextures.MapNextQuad(new Vector3(5, 70, 0), new Vector2(20, 20), Color.White, Engine.AssetLoader.Get <Texture>("Textures/standardGif.gif")); ErrorHandler.SuppressErrors = false; // Return original limit. Engine.Flags.RenderFlags.TextureArrayLimit = oldLimit; // Map color barf. colorBarfBuffer = Engine.GraphicsManager.CreateQuadStreamBuffer(100); int x = 0; int y = 0; const int size = 5; for (int i = 0; i < 100; i++) { // Map quad. colorBarfBuffer.MapNextQuad(new Vector3(x * size, y * size, 1), new Vector2(size, size), new Color(i, 255 - i, 125 + i)); // Grid logic. x++; if (x * size < 25) { continue; } x = 0; y++; } }, // Unload the texture. ExtUnload = () => { // Unloads buffers. quadBuffer.Delete(); overflowVerts.Delete(); overflowTextures.Delete(); colorBarfBuffer.Delete(); // Unload textures. Engine.AssetLoader.Destroy("Textures/logoAlpha.png"); Engine.AssetLoader.Destroy("Textures/standardPng.png"); Engine.AssetLoader.Destroy("Textures/standardGif.gif"); testShader.Delete(); }, // Draw textures. ExtDraw = () => { // Draw a map buffer. Engine.Renderer.Render(quadBuffer); // Now draw it with a shader and a matrix. Engine.Renderer.SetShader(testShader); Engine.Renderer.PushToModelMatrix(Matrix4x4.CreateTranslation(25, 0, 0)); Engine.Renderer.Render(quadBuffer); Engine.Renderer.PopModelMatrix(); Engine.Renderer.SetShader(); // Draw overflow. Engine.Renderer.PushToModelMatrix(Matrix4x4.CreateTranslation(50, 0, 0)); Engine.Renderer.Render(overflowVerts); Engine.Renderer.PopModelMatrix(); // Draw texture overflow. Engine.Renderer.PushToModelMatrix(Matrix4x4.CreateTranslation(75, 0, 0)); Engine.Renderer.Render(overflowTextures); Engine.Renderer.PopModelMatrix(); // Draw color barf. Engine.Renderer.PushToModelMatrix(Matrix4x4.CreateTranslation(100, 0, 0)); Engine.Renderer.Render(colorBarfBuffer); Engine.Renderer.PopModelMatrix(); } }; // Load scene. Helpers.LoadScene(extScene); // Check if what is currently on screen is what is expected. Assert.Equal("eJmRj5eeyngfsGEkmMJDYBVqK9pzZpOCK6GNctWpVUg=", Helpers.TakeScreenshot()); // Remap the first square and the tenth in the color barf buffer to test arbitrary remapping. colorBarfBuffer.MapQuadAt(0, new Vector3(0, 0, 1), new Vector2(5, 5), new Color(255, 255, 255)); colorBarfBuffer.MapQuadAt(10, new Vector3(250, 0, 1), new Vector2(5, 5), new Color(255, 255, 255)); // Run a cycle to draw the changed buffer. extScene.WaitFrames(2).Wait(); Assert.Equal("Znb581mqFE2GUdCaNvlS08jyd7+mUkYQrGMIT9GKPV4=", Helpers.TakeScreenshot()); // Set render range, and test rendering with that. colorBarfBuffer.SetRenderRange(0, 10); extScene.WaitFrames(2).Wait(); Assert.Equal("7iBfVG9OuqOLXFAoMx0u1O6PtBOfPl4m5RVD8kbheBQ=", Helpers.TakeScreenshot()); // Cleanup. Helpers.UnloadScene(); // Ensure the textures are unloaded. Assert.Null(Engine.AssetLoader.LoadedAssets.FirstOrDefault(x => x.Name == "Textures/logoAlpha.png")); Assert.Null(Engine.AssetLoader.LoadedAssets.FirstOrDefault(x => x.Name == "Textures/standardPng.png")); Assert.Null(Engine.AssetLoader.LoadedAssets.FirstOrDefault(x => x.Name == "Textures/standardGif.gif")); }
private void SavePack(FpmfArchive archive, string inPath, string outPath, string archiveName) { Directory.CreateDirectory(outPath); IBuffer fileBuff = new StreamBuffer(); IBuffer headerBuff = new StreamBuffer(); List <FpmfArchiveFile> archiveFiles = archive.GetFiles(); foreach (FpmfArchiveFile archiveFile in archiveFiles) { fileBuff.WriteByte((byte)archiveFile.directoryPathSize); fileBuff.WriteCString(archiveFile.directoryPath); fileBuff.Position = fileBuff.Position - 1; fileBuff.WriteByte((byte)archiveFile.filePathSize); fileBuff.WriteCString(archiveFile.filePath); fileBuff.Position = fileBuff.Position - 1; fileBuff.WriteUInt32(archiveFile.datNumber); fileBuff.WriteUInt32(archiveFile.offset); fileBuff.WriteUInt32(archiveFile.size); fileBuff.WriteUInt32(archiveFile.unknown0); fileBuff.WriteUInt32(archiveFile.unknown1); } headerBuff.WriteBytes(_MagicBytes); headerBuff.WriteInt32(0); headerBuff.WriteUInt32(archive.unknown0); headerBuff.WriteUInt32(archive.unknown1); headerBuff.WriteUInt32(archive.unknown2); headerBuff.WriteByte(archive.unknown3); headerBuff.WriteByte(archive.unknown4); headerBuff.WriteUInt32(archive.unknown5); headerBuff.WriteInt32(archive.datPath.Length + 9); headerBuff.WriteByte((byte)archive.datPath.Length); headerBuff.WriteCString(archive.datPath); headerBuff.Position = headerBuff.Position - 1; uint type = 0; switch (archiveName) { case "script": case "settings": case "item": case "interface": type = 1; break; case "help_end": type = 2; break; } headerBuff.WriteUInt32(type); headerBuff.WriteUInt32(archive.unknown8); headerBuff.WriteUInt32(archive.unknown9); headerBuff.WriteUInt32(archive.unknown10); headerBuff.WriteInt32(archive.key.Length); headerBuff.WriteBytes(archive.key); headerBuff.WriteUInt32(archive.unknown11); headerBuff.WriteInt32(fileBuff.Size + 4); headerBuff.WriteUInt32(archive.numFiles); headerBuff.WriteBytes(fileBuff.GetAllBytes()); headerBuff = EncryptHed(headerBuff); string hedPath = outPath.Substring(0, outPath.LastIndexOf("\\")) + ".hed"; BinaryWriter headerWriter = new BinaryWriter(File.Open(hedPath, FileMode.Create)); headerBuff.Position = 4; headerBuff.WriteInt32(headerBuff.Size - 12); headerWriter.Write(headerBuff.GetAllBytes(), 0, headerBuff.Size); headerWriter.Flush(); headerWriter.Close(); BinaryWriter datWriter = new BinaryWriter(File.Open(outPath + "\\" + "00000000.dat", FileMode.Create)); IBuffer outBuff = new StreamBuffer(); foreach (FpmfArchiveFile archiveFile in archiveFiles) { string inputFile = inPath + "\\" + archiveName + archiveFile.filePath.Substring(1); IBuffer datFileReader = new StreamBuffer(inputFile); datFileReader = EncryptDat(datFileReader, archive.key); outBuff.WriteBytes(datFileReader.GetAllBytes()); } datWriter.Write(outBuff.GetAllBytes(), 0, outBuff.Size); datWriter.Flush(); datWriter.Close(); }
protected override void InternalSerialize(StreamBuffer buffer) { base.InternalSerialize(buffer); buffer.Write(this.value); }
/// <summary> /// 0x403700 /// </summary> public void OpenWoItm(string itemPath) { FileInfo itemFile = new FileInfo(itemPath); if (!itemFile.Exists) { throw new FileNotFoundException($"File: {itemPath} not found."); } IBuffer buffer = new StreamBuffer(itemFile.FullName); buffer.SetPositionStart(); byte[] magicBytes = buffer.ReadBytes(5); for (int i = 0; i < 5; i++) { if (magicBytes[i] != _MagicBytesWoitm[i]) { throw new Exception("Invalid WOITM File"); } } short version = buffer.ReadInt16(); // cmp to 1 List <WoItm> woItems = new List <WoItm>(); while (buffer.Position < buffer.Size) { int itemId = buffer.ReadInt32(); int chunkSize = buffer.ReadInt32(); int chunkLen = buffer.ReadInt32(); byte[] data = buffer.ReadBytes(chunkSize - 4); WoItm woItm = new WoItm(); woItm.id = itemId; woItm.size = chunkSize; woItm.size2 = chunkLen; woItm.data = data; woItems.Add(woItm); } foreach (WoItm woItem in woItems) { IBuffer itemBuffer = new StreamBuffer(woItem.data); itemBuffer.SetPositionStart(); IBuffer outBuffer = new StreamBuffer(); uint[] xor = { 0xA522C3ED, 0x482E64B9, 0x0E52712B, 0x3ABC1D26 }; for (int i = 0; i < 4; i++) { uint a = itemBuffer.ReadUInt32(); uint b = RotateRight(a, 8); // 00403035 | C1CE 08 | ror esi,8 uint c = b & 0xFF00FF00; uint d = RotateLeft(a, 8); // 0040303E | C1C0 08 | rol eax,8 uint e = d & 0xFF00FF; uint f = c | e; outBuffer.WriteUInt32(f); } _Logger.Debug(outBuffer.ToHexString(" ")); _Logger.Info("done"); /* These 4 words are from the previous function after xor of xor[] above * uint word1 = 0x6B9306F7; * uint word2 = 0xFE7D4F35; * uint word3 = 0x406D7743; * uint word4 = 0x9C07F4C0; * * uint seed = 0; * uint seed1 = 0xFFFFFFFE; * word1 = word1 ^ seed; * uint a = ((word1 >> 16) & 0xFF) * 4; * uint b = ((word1 >> 8) & 0xFF) * 4; * uint c = (word1 >> 24) * 4; * uint e = table1[c]; * uint f = table3[a]; * uint g = e ^ f; * uint i = table3[b]; * uint j = g ^ i; * * uint k = (word2 & 0xFF) * 4; * uint l = j ^ table2[k]; * uint m = (((word2 ^ seed) >> 16) & 0xFF) * 4; * uint n = ((word2 >> 24) * 4; * uint o = table3[n]; * uint p = table4[m]; * uint q = o ^ p; * uint r = ((word2 >> 8) & 0xFF) * 4; * uint s = (q ^ table2[r]); * uint t = (word2 & 0xFF) * 4; * uint u = table1[t] ^ s; * uint v = u ^ l; * * word3 = word3 ^ v; * uint w = ((l & 0xFF) << 18) | ((l >> 8) & 0x00FFFFFF); * uint x = w ^ word4; * uint y = u ^ x; * word4 = l ^ y; * uint z = (seed1 * 4) + ???? (1628EEC8); // Missed a push earlier * uint aa = word3 ^ z; * uint ab = ((aa >> 16) & 0xFF) * 4; * uint ac = (aa >> 24) * 4; * uint ad = table1[ac]; * uint ae = (ad ^ table3[ab]); */ } _Logger.Info("done"); }
public TcpSession() { this.isConnected = false; this.streamBuffer = new StreamBuffer(); this.socket = new TcpSocket(); }
/// <summary> /// 패킷을 전송하고, 특정 패킷이 수신될 경우 dispatcher에 지정된 핸들러를 실행합니다. /// 이 기능은 AwaitableMethod보다는 빠르지만, 동시에 많이 호출될 경우 성능이 저하될 수 있습니다. /// </summary> /// <param name="buffer">전송할 데이터가 담긴 StreamBuffer</param> /// <param name="criterion">dispatcher에 지정된 핸들러를 호출할 것인지 여부를 판단하는 함수를 지정합니다.</param> /// <param name="dispatcher">실행될 함수를 지정합니다.</param> /// <param name="onSent">패킷 전송이 완료된 후 호출할 Action</param> public virtual void SendPacket(StreamBuffer buffer, PacketCriterion criterion, EventHandler_Receive dispatcher, Action<StreamBuffer> onSent = null) { _method.SendPacket(buffer, criterion, dispatcher, onSent); }
public FpmfArchive Open(string hedFilePath) { FileInfo hedFile = new FileInfo(hedFilePath); if (!hedFile.Exists) { throw new FileNotFoundException($"File: {hedFilePath} not found."); } IBuffer hedBuffer = new StreamBuffer(hedFile.FullName); if (hedBuffer.Size < 12) { throw new Exception("File to small"); } hedBuffer.SetPositionStart(); byte[] magicBytes = hedBuffer.ReadBytes(4); for (int i = 0; i < 4; i++) { if (magicBytes[i] != _MagicBytes[i]) { throw new Exception("Invalid File"); } } FpmfArchive archive = new FpmfArchive(); archive.size = hedBuffer.ReadUInt32(); uint unknown0 = hedBuffer.ReadUInt32(); hedBuffer = DecryptHed(hedBuffer); hedBuffer.SetPositionStart(); uint unknown1 = hedBuffer.ReadUInt32(); uint unknown2 = hedBuffer.ReadUInt32(); byte unknown3 = hedBuffer.ReadByte(); byte unknown4 = hedBuffer.ReadByte(); uint unknown5 = hedBuffer.ReadUInt32(); uint unknown6 = hedBuffer.ReadUInt32(); int strLen = hedBuffer.ReadByte(); archive.datPath = hedBuffer.ReadString(strLen); uint unknown7 = hedBuffer.ReadUInt32(); uint unknown8 = hedBuffer.ReadUInt32(); uint unknown9 = hedBuffer.ReadUInt32(); uint unknown10 = hedBuffer.ReadUInt32(); uint keyLen = hedBuffer.ReadUInt32(); archive.key = hedBuffer.ReadBytes((int)keyLen); uint unknown11 = hedBuffer.ReadUInt32(); uint unknown12 = hedBuffer.ReadUInt32(); uint numFiles = hedBuffer.ReadUInt32(); string relativeArchiveDir = archive.datPath .Replace("/%08x.dat", "") .Replace("./", "") .Replace('/', Path.DirectorySeparatorChar); string hedPath = hedFile.FullName.Replace(".hed", ""); string rootPath = hedPath.Replace(relativeArchiveDir, ""); DirectoryInfo rootDirectory = new DirectoryInfo(rootPath); if (!rootDirectory.Exists) { throw new FileNotFoundException( $"Could not determinate root path. (Rel:{relativeArchiveDir} Hed:{hedPath} Root:{rootPath}"); } _Logger.Info($"Using Root:{rootPath}"); Dictionary <uint, IBuffer> datBufferPool = new Dictionary <uint, IBuffer>(); for (int i = 0; i < numFiles; i++) { FpmfArchiveFile archiveFile = new FpmfArchiveFile(); strLen = hedBuffer.ReadByte(); archiveFile.directoryPath = hedBuffer.ReadString(strLen); strLen = hedBuffer.ReadByte(); archiveFile.filePath = hedBuffer.ReadString(strLen); archiveFile.datNumber = hedBuffer.ReadUInt32(); archiveFile.offset = hedBuffer.ReadUInt32(); archiveFile.size = hedBuffer.ReadUInt32(); uint unknown13 = hedBuffer.ReadUInt32(); uint unknown14 = hedBuffer.ReadUInt32(); _Logger.Info($"Processing: {archiveFile.filePath}"); IBuffer datBuffer; if (datBufferPool.ContainsKey(archiveFile.datNumber)) { datBuffer = datBufferPool[archiveFile.datNumber]; } else { string datFileName = archive.datPath .Replace("%08x", $"{archiveFile.datNumber:X8}") .Replace("./", "") .Replace('/', Path.DirectorySeparatorChar); string datFilePath = Path.Combine(rootDirectory.FullName, datFileName); FileInfo datFile = new FileInfo(datFilePath); if (!datFile.Exists) { throw new FileNotFoundException($"File: {datFilePath} not found."); } datBuffer = new StreamBuffer(datFile.FullName); datBufferPool.Add(archiveFile.datNumber, datBuffer); } IBuffer decrypted = DecryptDat(datBuffer, archiveFile.offset, archiveFile.size, archive.key); archiveFile.data = decrypted.GetAllBytes(); archive.AddFile(archiveFile); } return(archive); }
public IStreamBuffer CreateStreamBuffer(TsStreamType streamType) { ThrowIfDisposed(); var buffer = new StreamBuffer(streamType, _packetPool.FreePesPacket, this); lock (_lock) { _queues.Add(buffer); ResizeStatuses(); } return buffer; }