示例#1
0
        private void SetupFbs()
        {
            var builder        = new FlatBuffers.FlatBufferBuilder(1024);
            var elementOffsets = new Offset <flatbuffers.SampleModel1Element> [1000];

            foreach (var i in Enumerable.Range(0, 1000))
            {
                elementOffsets[i] = flatbuffers.SampleModel1Element.CreateSampleModel1Element(
                    builder,
                    builder.CreateString(i.ToString()),
                    i,
                    (float)i,
                    (double)i
                    );
            }

            var elements = flatbuffers.SampleModel1Array.CreateElementsVector(builder, elementOffsets);

            flatbuffers.SampleModel1Array.StartSampleModel1Array(builder);
            {
                flatbuffers.SampleModel1Array.AddElements(
                    builder,
                    elements
                    );
            }
            var orc = flatbuffers.SampleModel1Array.EndSampleModel1Array(builder);

            builder.Finish(orc.Value);

            this.ArrayModelFbsSerialized = builder.SizedByteArray();
        }
示例#2
0
    static FlatBuffersObject.Person SerializeSingleFlatBuffers()
    {
        Console.WriteLine("FlatBuffers");

        FlatBuffersObject.Person copy = default(FlatBuffersObject.Person);
        byte[] bytes = null;

        using (new Measure("Serialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                var builder = new FlatBuffers.FlatBufferBuilder(1);

                var person = FlatBuffersObject.Person.CreatePerson(builder, 99999, builder.CreateString("Windows"), builder.CreateString("Server"), FlatBuffersObject.Sex.Male);
                builder.Finish(person.Value);

                bytes = builder.SizedByteArray();
            }
        }

        using (new Measure("Deserialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                copy = FlatBuffersObject.Person.GetRootAsPerson(new FlatBuffers.ByteBuffer(bytes));
            }
        }

        if (!dryRun)
        {
            Console.WriteLine(string.Format("{0,15}   {1}", "Binary Size", ToHumanReadableSize(bytes.Length)));
        }

        return(copy);
    }
示例#3
0
    public void ConvertMessageAnswer(string path)
    {
        List <string> lineList = this.getLineList(path);

        FlatBuffers.FlatBufferBuilder fbb = new FlatBuffers.FlatBufferBuilder(1);
        FlatBuffers.Offset <MessageAnswerTable.Data>[] data = new FlatBuffers.Offset <MessageAnswerTable.Data> [lineList.Count];
        int count = 0;

        foreach (string line in lineList)
        {
            string[] values     = line.Split(',');
            int      id         = int.Parse(values[0]);
            int      selectId   = int.Parse(values[1]);
            int[]    answerList = new int[values.Length - 1];
            for (int i = 2; i < values.Length; ++i)
            {
                string message = values[i].Replace("\\n", "\n");;
                answerList[i - 2] = int.Parse(values[i]);
            }
            data[count] = MessageAnswerTable.Data.CreateData(fbb, id, selectId, MessageAnswerTable.Data.CreateAnswerVector(fbb, answerList));
            ++count;
        }
        FlatBuffers.VectorOffset infoVec = MessageAnswerTable.DataList.CreateDatasVector(fbb, data);
        FlatBuffers.Offset <MessageAnswerTable.DataList> reslut = MessageAnswerTable.DataList.CreateDataList(fbb, infoVec);
        MessageAnswerTable.DataList.FinishDataListBuffer(fbb, reslut);
        using (System.IO.FileStream fs = new System.IO.FileStream("message-answer-table.bin", System.IO.FileMode.Create))
        {
            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
            {
                bw.Write(fbb.SizedByteArray());
            }
        }
    }
    public void FiveByteStructVector()
    {
        var builder = new FlatBuffers.FlatBufferBuilder(1024);

        Oracle.FiveByteStructTable.StartVectorVector(builder, 3);
        Oracle.FiveByteStruct.CreateFiveByteStruct(builder, 3, 3);
        Oracle.FiveByteStruct.CreateFiveByteStruct(builder, 2, 2);
        Oracle.FiveByteStruct.CreateFiveByteStruct(builder, 1, 1);
        var vectorOffset = builder.EndVector();

        Oracle.FiveByteStructTable.StartFiveByteStructTable(builder);
        Oracle.FiveByteStructTable.AddVector(builder, vectorOffset);
        var testData = Oracle.FiveByteStructTable.EndFiveByteStructTable(builder);

        builder.Finish(testData.Value);

        byte[] realBuffer = builder.SizedByteArray();
        var    parsed     = FlatBufferSerializer.Default.Parse <FiveByteStructTable>(realBuffer);

        Assert.Equal(3, parsed.Vector.Length);

        Assert.Equal(1, parsed.Vector[0].Int);
        Assert.Equal(2, parsed.Vector[1].Int);
        Assert.Equal(3, parsed.Vector[2].Int);

        Assert.Equal((byte)1, parsed.Vector[0].Byte);
        Assert.Equal((byte)2, parsed.Vector[1].Byte);
        Assert.Equal((byte)3, parsed.Vector[2].Byte);
    }
示例#5
0
    public void ConvertMessageEvent(string path)
    {
        List <string> lineList = this.getLineList(path);

        FlatBuffers.FlatBufferBuilder fbb = new FlatBuffers.FlatBufferBuilder(1);
        FlatBuffers.Offset <MessageEventTable.Data>[] data = new FlatBuffers.Offset <MessageEventTable.Data> [lineList.Count];
        int count = 0;

        foreach (string line in lineList)
        {
            string[] values    = line.Split(',');
            int      id        = int.Parse(values[0]);
            int      checkId   = int.Parse(values[1]);
            int      messageId = int.Parse(values[2]);
            int      selectId  = int.Parse(values[3]);
            int      flag      = int.Parse(values[4]);
            int      addTime   = int.Parse(values[5]);
            data[count] = MessageEventTable.Data.CreateData(fbb, id, checkId, messageId, selectId, flag, addTime);
            ++count;
        }
        FlatBuffers.VectorOffset infoVec = MessageEventTable.DataList.CreateDatasVector(fbb, data);
        FlatBuffers.Offset <MessageEventTable.DataList> reslut = MessageEventTable.DataList.CreateDataList(fbb, infoVec);
        MessageEventTable.DataList.FinishDataListBuffer(fbb, reslut);
        using (System.IO.FileStream fs = new System.IO.FileStream("message-event-table.bin", System.IO.FileMode.Create))
        {
            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
            {
                bw.Write(fbb.SizedByteArray());
            }
        }
    }
示例#6
0
 static void StoreMultipleObjectInaFile()
 {
     using (var outputStream = new BinaryWriter(File.Create("data.dat")))
     {
         outputStream.Write(0); //indicates number of demands in the file.
         for (int i = 0; i < 10; i++)
         {
             FlatBufferBuilder fbb = new FlatBufferBuilder(1024);
             var scalarTypeOffset  = Helper.BuildScalarType(fbb);
             fbb.Finish(scalarTypeOffset.Value);
             byte[] serializedData = fbb.SizedByteArray();
             outputStream.Write(serializedData.Length);
             outputStream.Write(serializedData);
         }
         outputStream.Seek(0, SeekOrigin.Begin);
         outputStream.Write(10); //replaces the value written at the top which indicates the number of demands.
     }
     using (var ipStream = new BinaryReader(File.OpenRead("data.dat")))
     {
         var count = ipStream.ReadInt32();
         for (int i = 0; i < count; i++)
         {
             var size        = ipStream.ReadInt32();
             var bytes       = ipStream.ReadBytes(size);
             var byteBuf     = new ByteBuffer(bytes);
             var dScalarType = ScalarType.GetRootAsScalarType(byteBuf);
         }
     }
 }
示例#7
0
    public void ConvertTekiInfo(string path)
    {
        List <string> lineList = this.getLineList(path);

        FlatBuffers.FlatBufferBuilder             fbb  = new FlatBuffers.FlatBufferBuilder(1);
        FlatBuffers.Offset <TekiInfoTable.Data>[] data = new FlatBuffers.Offset <TekiInfoTable.Data> [lineList.Count];
        int count = 0;

        foreach (string line in lineList)
        {
            string[]            values         = line.Split(',');
            int                 id             = int.Parse(values[0]);
            TekiDefine.MoveType moveType       = (TekiDefine.MoveType)Enum.Parse(typeof(TekiDefine.MoveType), values[1]);
            int                 messageEventId = int.Parse(values[2]);
            data[count] = TekiInfoTable.Data.CreateData(fbb, id, moveType, messageEventId);
            ++count;
        }
        FlatBuffers.VectorOffset infoVec = TekiInfoTable.DataList.CreateDatasVector(fbb, data);
        FlatBuffers.Offset <TekiInfoTable.DataList> reslut = TekiInfoTable.DataList.CreateDataList(fbb, infoVec);
        TekiInfoTable.DataList.FinishDataListBuffer(fbb, reslut);
        using (System.IO.FileStream fs = new System.IO.FileStream("teki-info-table.bin", System.IO.FileMode.Create))
        {
            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
            {
                bw.Write(fbb.SizedByteArray());
            }
        }
    }
    public void LocationStruct()
    {
        var builder    = new FlatBuffers.FlatBufferBuilder(1024);
        var fakeString = builder.CreateString("foobar");

        Oracle.LocationHolder.StartLocationVectorVector(builder, 3);
        Oracle.Location.CreateLocation(builder, 7f, 8f, 9f);
        Oracle.Location.CreateLocation(builder, 4f, 5f, 6f);
        Oracle.Location.CreateLocation(builder, 1f, 2f, 3f);
        var vectorOffset = builder.EndVector();

        Oracle.LocationHolder.StartLocationHolder(builder);
        Oracle.LocationHolder.AddFake(builder, fakeString);
        Oracle.LocationHolder.AddSingleLocation(builder, Oracle.Location.CreateLocation(builder, 0.1f, 0.2f, 0.3f));
        Oracle.LocationHolder.AddLocationVector(builder, vectorOffset);
        var testData = Oracle.LocationHolder.EndLocationHolder(builder);

        builder.Finish(testData.Value);

        byte[] realBuffer = builder.SizedByteArray();
        var    parsed     = FlatBufferSerializer.Default.Parse <LocationHolder>(realBuffer);

        Assert.Equal("foobar", parsed.Fake);
        Assert.Equal(0.1f, parsed.Location.X);
        Assert.Equal(0.2f, parsed.Location.Y);
        Assert.Equal(0.3f, parsed.Location.Z);
        Assert.Equal(3, parsed.LocationVector.Count);

        for (int i = 0; i < 3; ++i)
        {
            Assert.Equal((float)(3 * i + 1), parsed.LocationVector[i].X);
            Assert.Equal((float)(3 * i + 2), parsed.LocationVector[i].Y);
            Assert.Equal((float)(3 * i + 3), parsed.LocationVector[i].Z);
        }
    }
    public void SortedVectors(FlatBufferDeserializationOption option)
    {
        var builder = new FlatBuffers.FlatBufferBuilder(1024 * 1024);

        var strings       = new List <string>();
        var stringOffsets = new List <FlatBuffers.Offset <Oracle.SortedVectorStringTable> >();

        List <int> ints       = new List <int>();
        var        intOffsets = new List <FlatBuffers.Offset <Oracle.SortedVectorInt32Table> >();

        List <double> doubles       = new List <double>();
        var           doubleOffsets = new List <FlatBuffers.Offset <Oracle.SortedVectorDoubleTable> >();

        const int Iterations = 1000;
        Random    random     = new Random();

        for (int i = 0; i < Iterations; ++i)
        {
            string value = Guid.NewGuid().ToString();
            strings.Add(value);
            stringOffsets.Add(Oracle.SortedVectorStringTable.CreateSortedVectorStringTable(builder, builder.CreateString(value)));
        }

        for (int i = 0; i < Iterations; ++i)
        {
            int value = random.Next();
            ints.Add(value);
            intOffsets.Add(Oracle.SortedVectorInt32Table.CreateSortedVectorInt32Table(builder, value));
        }

        for (int i = 0; i < Iterations; ++i)
        {
            double value = random.NextDouble() * random.Next();
            doubles.Add(value);
            doubleOffsets.Add(Oracle.SortedVectorDoubleTable.CreateSortedVectorDoubleTable(builder, value));
        }

        var table = Oracle.SortedVectorTest.CreateSortedVectorTest(
            builder,
            Oracle.SortedVectorInt32Table.CreateSortedVectorOfSortedVectorInt32Table(builder, intOffsets.ToArray()),
            Oracle.SortedVectorStringTable.CreateSortedVectorOfSortedVectorStringTable(builder, stringOffsets.ToArray()),
            Oracle.SortedVectorDoubleTable.CreateSortedVectorOfSortedVectorDoubleTable(builder, doubleOffsets.ToArray()));

        builder.Finish(table.Value);
        byte[] serialized = builder.SizedByteArray();

        var serializer = new FlatBufferSerializer(option);
        var parsed     = serializer.Parse <SortedVectorTest <SortedVectorItem <int> > >(serialized);

        VerifySorted(parsed.StringVector, new Utf8StringComparer(), strings, new List <string> {
            Guid.NewGuid().ToString(), "banana"
        });
        VerifySorted(parsed.IntVector, Comparer <int> .Default, ints, new List <int> {
            -1, -3, 0
        });
        VerifySorted(parsed.Double, Comparer <double> .Default, doubles, new List <double> {
            Math.PI, Math.E, Math.Sqrt(2)
        });
    }
        /// <summary>
        /// Serializes an object as FlatBuffers formatted data into a byte array
        /// </summary>
        /// <param name="obj">The object to serialize into FlatBuffers format</param>
        /// <returns>A sized buffer containing the serialized data</returns>
        public byte[] Serialize(object obj)
        {
            var builder = new FlatBufferBuilder(64);
            var context = new SerializationContext(_typeModelRegistry, obj, builder);

            context.Serialize();
            return(builder.SizedByteArray());
        }
示例#11
0
    static FlatBuffersObject.PersonVector SerializeArrayFlatBuffers()
    {
        Console.WriteLine("FlatBuffers");

        FlatBuffersObject.PersonVector copy = default(FlatBuffersObject.PersonVector);
        byte[] bytes = null;

        Func <FlatBuffers.FlatBufferBuilder, FlatBuffers.Offset <FlatBuffersObject.Person>[]> makeVector = b =>
        {
            var array = new FlatBuffers.Offset <FlatBuffersObject.Person> [1000];
            var count = 0;
            for (int j = 1000; j < 2000; j++)
            {
                var person = FlatBuffersObject.Person.CreatePerson(b, j, b.CreateString("Windows"), b.CreateString("Server"), FlatBuffersObject.Sex.Female);
                array[count++] = person;
            }
            return(array);
        };

        using (new Measure("Serialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                var builder = new FlatBuffers.FlatBufferBuilder(1);

                var personVector = FlatBuffersObject.PersonVector.CreatePersonVector(builder, FlatBuffersObject.PersonVector.CreateListVector(builder, makeVector(builder)));
                builder.Finish(personVector.Value);

                bytes = builder.SizedByteArray();
            }
        }

        using (new Measure("Deserialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                copy = FlatBuffersObject.PersonVector.GetRootAsPersonVector(new FlatBuffers.ByteBuffer(bytes));
            }
        }

        using (new Measure("ReSerialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                var bb       = copy.ByteBuffer;
                var newbytes = new byte[bb.Length];
                Buffer.BlockCopy(bb.Data, 0, newbytes, 0, bb.Length);
            }
        }

        if (!dryRun)
        {
            Console.WriteLine(string.Format("{0,15}   {1}", "Binary Size", ToHumanReadableSize(bytes.Length)));
        }

        return(copy);
    }
示例#12
0
    void relay_start_callback(object req, ApiClient api_client)
    {
        if (null != req)
        {
            RelayStart relay_start = (RelayStart)req;

            relay_info = relay_start.response;

            string[] address = relay_info.server_address.Split(':');

            if (client != null)
            {
                if (true == client.IsConnected())
                {
                    log("already connected server. server[" + address[0] + ":" + address[1] + "]");
                    return;
                }
            }
            else
            {
                client = new wise.net.Client();
            }

            if (false == client.Connect(address[0], int.Parse(address[1])))
            {
                log("cannot connect server. server[" + address[0] + ":" + address[1] + "]");
                return;
            }

            log("connect server. server[" + address[0] + ":" + address[1] + "]");

            foreach (var member in relay_info.members)
            {
                if (member.id == user_index.ToString())
                {
                    FlatBuffers.FlatBufferBuilder builder = new FlatBuffers.FlatBufferBuilder(1);
                    var offset = PACKET.ENTER.CreateENTER(builder, builder.CreateString(login_info.UserID), builder.CreateString(member.hash), user_index);
                    builder.Finish(offset.Value);

                    if (false == client.Send((int)PACKET_C2S.ENTER, builder.SizedByteArray(), uint.Parse(relay_info.roomnum.ToString())))
                    {
                        log("can't enter.");
                    }
                    return;
                }
            }

            log("not find my information from relay/start.");
        }
        else
        {
            log("failed relay_start.");
        }
    }
示例#13
0
        static void AssertMonsterType()
        {
            FlatBufferBuilder fbb = new FlatBufferBuilder(1024);
            var monsterTypeOffset = Helper.BuildMonster(fbb);

            fbb.Finish(monsterTypeOffset.Value);
            byte[] serializedBuffer = fbb.SizedByteArray(); //Gets serialized instance as byte array

            var buffer   = new ByteBuffer(serializedBuffer);
            var dMonster = Monster.GetRootAsMonster(buffer); // Gets deserialized object

            Assert.AreEqual(Color.Red, dMonster.Color);
        }
    private void SendDisconnectMessage()
    {
        var builder = new FlatBuffers.FlatBufferBuilder(1024);

        NetworkedPhysics.Message.StartMessage(builder);
        NetworkedPhysics.Message.AddDataType(builder, NetworkedPhysics.MessageType.ClientDisconnectMessage);
        var message = NetworkedPhysics.Message.EndMessage(builder);

        builder.Finish(message.Value);

        byte[] bytes = builder.SizedByteArray();
        _udpClient.Send(bytes, bytes.Length);
        Debug.Log("Sent Disconnect message " + bytes.Length);
    }
示例#15
0
        static void AssertScalarType()
        {
            //initial buffer size
            FlatBufferBuilder fbb = new FlatBufferBuilder(1024);
            var scalarTypeOffset  = Helper.BuildScalarType(fbb);

            fbb.Finish(scalarTypeOffset.Value);

            byte[] serializedData = fbb.SizedByteArray();
            var    buffer         = new ByteBuffer(serializedData);
            var    dScalarType    = ScalarType.GetRootAsScalarType(buffer);

            Assert.IsTrue(dScalarType.BoolType);
        }
示例#16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="path"></param>
        public static void SaveAsScriptable(FlatBufferBuilder builder,
                                            string path)
        {
            if (path.Contains(Application.dataPath))
            {
                var destinationPath = path.Replace(Application.dataPath, "Assets");
                var bin             = AssetDatabase.LoadAssetAtPath(destinationPath, typeof(BinaryStorage)) as BinaryStorage;
                if (bin == null)
                {
                    bin      = ScriptableObject.CreateInstance <BinaryStorage>();
                    bin.data = builder.SizedByteArray();
                    Directory.CreateDirectory(destinationPath);
                    AssetDatabase.CreateAsset(bin, destinationPath);
                }
                else
                {
                    bin.data = builder.SizedByteArray();
                }

                EditorUtility.SetDirty(bin);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
        }
示例#17
0
        static void AssertComplexType()
        {
            //initial buffer size
            FlatBufferBuilder fbb = new FlatBufferBuilder(1024);
            var complexTypeOffset = Helper.BuildComplexType(fbb);

            fbb.Finish(complexTypeOffset.Value);

            byte[] serializedBuffer = fbb.SizedByteArray();
            var    buffer           = new ByteBuffer(serializedBuffer);
            var    dComplexType     = ComplexType.GetRootAsComplexType(buffer);

            var intVector = dComplexType.GetIntVectorTypeArray(); // To get array

            Assert.AreEqual(intVector.Length, 5);
        }
    public void VectorOfUnion()
    {
        Oracle.VectorOfUnionTableT table = new Oracle.VectorOfUnionTableT
        {
            Value = new List <Oracle.UnionUnion>
            {
                new Oracle.UnionUnion {
                    Value = new Oracle.BasicTypesT {
                        Int = 7
                    }, Type = Oracle.Union.BasicTypes
                },
                new Oracle.UnionUnion {
                    Value = new Oracle.LocationT {
                        X = 1, Y = 2, Z = 3
                    }, Type = Oracle.Union.Location
                },
                new Oracle.UnionUnion {
                    Value = "foobar", Type = Oracle.Union.stringValue
                },
            }
        };

        var builder = new FlatBuffers.FlatBufferBuilder(1024);
        var offset  = Oracle.VectorOfUnionTable.Pack(builder, table);

        builder.Finish(offset.Value);
        byte[] data = builder.SizedByteArray();

        var parsed = FlatBufferSerializer.Default.Parse <ArrayVectorOfUnionTable>(data);

        Assert.Equal(3, parsed.Union.Length);

        Assert.Equal(1, parsed.Union[0].Discriminator);
        Assert.Equal(2, parsed.Union[1].Discriminator);
        Assert.Equal(3, parsed.Union[2].Discriminator);

        Assert.True(parsed.Union[0].TryGet(out BasicTypes basicTypes));
        Assert.Equal(7, basicTypes.Int);

        Assert.True(parsed.Union[1].TryGet(out Location location));
        Assert.Equal(1, location.X);
        Assert.Equal(2, location.Y);
        Assert.Equal(3, location.Z);

        Assert.True(parsed.Union[2].TryGet(out string str));
        Assert.Equal("foobar", str);
    }
示例#19
0
    void send_broadcast()
    {
        if (time != 0.0f)
        {
            log("elapsed time : " + time + " count : " + count);
        }

        FlatBuffers.FlatBufferBuilder builder = new FlatBuffers.FlatBufferBuilder(1);

        var offset = PACKET.BROADCAST.CreateBROADCAST(builder, builder.CreateString(login_info.UserID), user_index, builder.CreateString(count.ToString()));

        builder.Finish(offset.Value);

        client.Send((int)PACKET_C2S.BROADCAST, builder.SizedByteArray(), uint.Parse(relay_info.roomnum.ToString()));

        count++;
        time = Time.deltaTime;
    }
    private void SendInputMessage(InputType type)
    {
        var builder = new FlatBuffers.FlatBufferBuilder(1024);

        ClientInputMessage.StartClientInputMessage(builder);
        ClientInputMessage.AddType(builder, type);
        var input = ClientInputMessage.EndClientInputMessage(builder);

        Message.StartMessage(builder);
        Message.AddDataType(builder, MessageType.ClientInputMessage);
        Message.AddData(builder, input.Value);
        var message = Message.EndMessage(builder);

        builder.Finish(message.Value);

        byte[] bytes = builder.SizedByteArray();
        _udpClient.Send(bytes, bytes.Length);
        //Debug.Log("Sent Input message " + bytes.Length);
    }
    private void SendMessageAck(int messageId)
    {
        var builder = new FlatBuffers.FlatBufferBuilder(1024);

        MessageAck.StartMessageAck(builder);
        MessageAck.AddMessageId(builder, messageId);
        var ack = MessageAck.EndMessageAck(builder);

        Message.StartMessage(builder);
        Message.AddDataType(builder, MessageType.MessageAck);
        Message.AddData(builder, ack.Value);
        var message = NetworkedPhysics.Message.EndMessage(builder);

        builder.Finish(message.Value);

        byte[] bytes = builder.SizedByteArray();
        _udpClient.Send(bytes, bytes.Length);
        //Debug.Log("Sent MessageAck message " + messageId + " " + bytes.Length);
    }
示例#22
0
    public void ConvertEvent(string dst, string path)
    {
        List <string> lineList = this.getLineList(path);

        FlatBuffers.FlatBufferBuilder          fbb  = new FlatBuffers.FlatBufferBuilder(1);
        FlatBuffers.Offset <EventTable.Data>[] data = new FlatBuffers.Offset <EventTable.Data> [lineList.Count];
        int count = 0;

        foreach (string line in lineList)
        {
            string[] values  = line.Split(',');
            int      id      = int.Parse(values[0]);
            int      bitNum  = values.Length - 1;
            int      byteNum = ((bitNum - 1) / 8) + 1;
            byte[]   flag    = new byte[byteNum];
            int      byteNo  = -1;
            for (int i = 0; i < byteNum; ++i)
            {
                flag[i] = 0;
            }
            for (int i = 0; i < bitNum; ++i)
            {
                if ((i % 8) == 0)
                {
                    ++byteNo;
                }
                flag[byteNo] |= (byte)(int.Parse(values[1 + i]) << (i % 8));
            }
            data[count] = EventTable.Data.CreateData(fbb, id, EventTable.Data.CreateFlagVector(fbb, flag));
            ++count;
        }
        FlatBuffers.VectorOffset infoVec = EventTable.DataList.CreateDatasVector(fbb, data);
        FlatBuffers.Offset <EventTable.DataList> reslut = EventTable.DataList.CreateDataList(fbb, infoVec);
        EventTable.DataList.FinishDataListBuffer(fbb, reslut);
        using (System.IO.FileStream fs = new System.IO.FileStream(dst, System.IO.FileMode.Create))
        {
            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
            {
                bw.Write(fbb.SizedByteArray());
            }
        }
    }
    public void ScalarVectors()
    {
        var builder  = new FlatBuffers.FlatBufferBuilder(1024);
        var testData = Oracle.Vectors.CreateVectors(
            builder,
            Oracle.Vectors.CreateIntVectorVector(builder, new[] { 1, 2, 3, 4, 5, 6, }),
            Oracle.Vectors.CreateLongVectorVector(builder, new[] { 7L, 8, 9, 10, 11, 12, }),
            Oracle.Vectors.CreateByteVector1Vector(builder, new byte[] { 1, 2, 3, 4, 5 }),
            Oracle.Vectors.CreateByteVector2Vector(builder, new byte[] { 1, 2, 3, 4, 5 }));

        builder.Finish(testData.Value);

        byte[] realBuffer = builder.SizedByteArray();

        var parsed = FlatBufferSerializer.Default.Parse <ScalarVectorsTable>(realBuffer);

        IList <int> intItems = parsed.IntVector;

        Assert.Equal(6, intItems.Count);
        for (int i = 0; i < 6; ++i)
        {
            Assert.Equal(1 + i, intItems[i]);
        }

        IList <long> longItems = parsed.LongVector;

        Assert.Equal(6, longItems.Count);
        for (int i = 0; i < 6; ++i)
        {
            Assert.Equal(7 + i, longItems[i]);
        }

        Memory <byte> mem = parsed.ByteVector2.Value;

        Assert.Equal(5, mem.Length);
        for (int i = 1; i <= 5; ++i)
        {
            Assert.Equal(i, mem.Span[i - 1]);
        }

        Assert.True(parsed.ByteVector3.IsEmpty);
    }
示例#24
0
    public void ConvertMessage(string path)
    {
        List <string> lineList = this.getLineList(path);

        FlatBuffers.FlatBufferBuilder            fbb  = new FlatBuffers.FlatBufferBuilder(1);
        FlatBuffers.Offset <MessageTable.Data>[] data = new FlatBuffers.Offset <MessageTable.Data> [lineList.Count];
        int count = 0;

        foreach (string line in lineList)
        {
            string[]      works  = line.Split(',');
            List <string> values = new List <string>();
            int           id     = int.Parse(works[0]);
            for (int i = 1; i < works.Length; ++i)
            {
                if (string.IsNullOrEmpty(works[i]))
                {
                    break;
                }
                values.Add(works[i]);
            }
            FlatBuffers.StringOffset[] messageList = new FlatBuffers.StringOffset[values.Count];
            for (int i = 0; i < values.Count; ++i)
            {
                string message = values[i].Replace("\\n", "\n");;
                messageList[i] = fbb.CreateString(message);
            }
            data[count] = MessageTable.Data.CreateData(fbb, id, MessageTable.Data.CreateMessageVector(fbb, messageList));
            ++count;
        }
        FlatBuffers.VectorOffset infoVec = MessageTable.DataList.CreateDatasVector(fbb, data);
        FlatBuffers.Offset <MessageTable.DataList> reslut = MessageTable.DataList.CreateDataList(fbb, infoVec);
        MessageTable.DataList.FinishDataListBuffer(fbb, reslut);
        using (System.IO.FileStream fs = new System.IO.FileStream("message-table.bin", System.IO.FileMode.Create))
        {
            using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
            {
                bw.Write(fbb.SizedByteArray());
            }
        }
    }
示例#25
0
        static void AssertObject()
        {
            var fbuilder = new FlatBufferBuilder(50);

            fbuilder.StartTable(2); //Creates a table with 2 fields. These fields only has index and no Name
            fbuilder.AddInt(0, 10, int.MinValue);
            fbuilder.AddLong(1, 20, long.MinValue);
            var offset = fbuilder.EndTable();

            fbuilder.Finish(offset);
            var keyBytes = fbuilder.SizedByteArray();

            var byteBuffer = new ByteBuffer(keyBytes);
            var bb_pos     = byteBuffer.GetInt(byteBuffer.Position) + byteBuffer.Position; //+ byteBuffer.Position is needed when a file has multiple objects to read
            var table      = new Table(bb_pos, byteBuffer);
            var offs       = 4;
            var t0         = table.bb.GetInt(table.__offset(offs) + table.bb_pos);

            offs += 2;
            var t1 = table.bb.GetLong(table.__offset(offs) + table.bb_pos);
        }
    public void LinkedList()
    {
        var builder  = new FlatBuffers.FlatBufferBuilder(1024);
        var testData = Oracle.LinkedListNode.CreateLinkedListNode(
            builder,
            builder.CreateString("node 1"),
            Oracle.LinkedListNode.CreateLinkedListNode(
                builder,
                builder.CreateString("node 2")));

        builder.Finish(testData.Value);

        byte[] realBuffer = builder.SizedByteArray();

        var linkedList = FlatBufferSerializer.Default.Parse <TestLinkedListNode>(realBuffer);

        Assert.NotNull(linkedList);
        Assert.NotNull(linkedList.Next);
        Assert.Null(linkedList.Next.Next);

        Assert.Equal("node 1", linkedList.Value);
        Assert.Equal("node 2", linkedList.Next.Value);
    }
示例#27
0
    void Start()
    {
        oNetworkManager MainPlayer = NetworkObject.mainPlayer.GetComponent <oNetworkManager>();

        NetDataReader.GetInstace().Reder[Class.Player] = (data) => {
            var m_player = Player.GetRootAsPlayer(data.ByteBuffer);

            if (m_player.ID != MainPlayer.id)
            {
                if (!OPlayers.ContainsKey(m_player.ID))
                {
                    var obj = Instantiate(PlayerPrifab, Vector3.zero, Quaternion.identity);
                    obj.AddComponent <OtherPlayer>();
                    obj.AddComponent <oNetworkIdentity>().id   = m_player.ID;
                    obj.GetComponent <oNetworkIdentity>().type = oNetworkIdentity.ObjType.player;
                    OPlayers[m_player.ID] = obj.GetComponent <OtherPlayer>();
                    SendToMe_PlayerStat.Send(m_player.ID);
                }

                OPlayers[m_player.ID].UpdateOtherObj(m_player);
            }
            else if (m_player.ID == MainPlayer.id)
            {
                var pos = m_player.Pos.Value;
                MainPlayer.transform.position.Set(pos.X, pos.Y, pos.Z);
            }
        };



        NetDataReader.GetInstace().Reder[Class.FirstCharacterData] = (data) =>
        {
            var FirstPlayerData = FirstCharacterData.GetRootAsFirstCharacterData(data.ByteBuffer);


            var fbb = new FlatBuffers.FlatBufferBuilder(1);

            fbb.Finish(PlayerStat.CreatePlayerStat(
                           fbb,
                           Class.PlayerStat,
                           FirstPlayerData.HP,
                           FirstPlayerData.HPLim,
                           FirstPlayerData.MP,
                           FirstPlayerData.MPLim,
                           FirstPlayerData.EXP,
                           FirstPlayerData.Attack,
                           FirstPlayerData.LV,
                           FirstPlayerData.ID
                           ).Value);

            var buf = new FlatBuffers.ByteBuffer(fbb.SizedByteArray());

            var _PlayerStat = PlayerStat.GetRootAsPlayerStat(buf);

            var pos = FirstPlayerData.Pos.Value;
            MainPlayer.GetComponent <oCreature>().Data_Update(_PlayerStat);
            MainPlayer.GetComponent <oCreature>().Data_Update(pos);
            MainPlayer.GetComponent <NetworkObject>().m_CurrentHP.NoEventSet(_PlayerStat.HP);
            MainPlayer.GetComponent <NetworkObject>().m_CurrentMP.NoEventSet(_PlayerStat.MP);
            MainPlayer.GetComponent <NetworkObject>().m_CurrentHPLim.NoEventSet(_PlayerStat.HPLim);
            MainPlayer.GetComponent <NetworkObject>().m_CurrentMPLim.NoEventSet(_PlayerStat.MPLim);
            MainPlayer.GetComponent <NetworkObject>().m_CurrentLV.NoEventSet(_PlayerStat.LV);
            MainPlayer.GetComponent <NetworkObject>().m_CurrentEXP.NoEventSet(_PlayerStat.EXP);
            MainPlayer.GetComponent <NetworkObject>().m_CurrentATK.NoEventSet(_PlayerStat.Attack);

            MainPlayer.GetComponent <NetworkObject>().CharacterName.NoEventSet(FirstPlayerData.Name);
            Vector3 v3 = new Vector3();
            v3.Set(pos.X, pos.Y, pos.Z);
        };



        NetDataReader.GetInstace().Reder[Class.fEquipSome] = (data) =>
        {
            var equipSome = fEquipSome.GetRootAsfEquipSome(data.ByteBuffer);
            Debug.Log(MainPlayer.GetComponent <oNetworkIdentity>().id + ":" + equipSome.PID + ":" + equipSome.SlotNum + ":" + equipSome.ObjNum);
            if (MainPlayer.GetComponent <oNetworkIdentity>().id == equipSome.PID)
            {
                MainPlayer.GetComponent <EquipManager>().Equip(equipSome.ObjNum, equipSome.SlotNum);
            }
            else
            {
                OPlayers[equipSome.PID].GetComponent <EquipManager>().Equip(equipSome.ObjNum, -1);
            }
        };


        NetDataReader.GetInstace().Reder[Class.PlayerStat] = (data) => {
            var _PlayerStat = PlayerStat.GetRootAsPlayerStat(data.ByteBuffer);
            var player      = MainPlayer.GetComponent <NetworkObject>();

            if (_PlayerStat.ID == MainPlayer.id)
            {
                MainPlayer.GetComponent <oCreature>().Data_Update(_PlayerStat);
                player.m_CurrentHP.NoEventSet(_PlayerStat.HP);
                player.m_CurrentMP.NoEventSet(_PlayerStat.MP);
                player.m_CurrentHPLim.NoEventSet(_PlayerStat.HPLim);
                player.m_CurrentMPLim.NoEventSet(_PlayerStat.MPLim);
                player.m_CurrentEXP.NoEventSet(_PlayerStat.EXP);
                player.m_CurrentATK.NoEventSet(_PlayerStat.Attack);
                if (_PlayerStat.LV > player.m_CurrentLV.Value)
                {
                    IG_EffectManager.Show(player.gameObject.transform.position, "LVUP");
                }
                player.m_CurrentLV.NoEventSet(_PlayerStat.LV);
            }
            else if (OPlayers.ContainsKey(_PlayerStat.ID))
            {
                if (OPlayers[_PlayerStat.ID].GetComponent <oCreature>() == null)
                {
                    OPlayers[_PlayerStat.ID].gameObject.AddComponent <oCreature>();
                    OPlayers[_PlayerStat.ID].gameObject.AddComponent <SendStateManager>();
                    OPlayers[_PlayerStat.ID].gameObject.GetComponent <OtherPlayer>().SetStatEvent();
                    OPlayers[_PlayerStat.ID].gameObject.name = _PlayerStat.NikName;
                }

                OPlayers[_PlayerStat.ID].gameObject.GetComponent <oCreature>().Data_Update(_PlayerStat);
            }
        };
    }
示例#28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="path"></param>
 public static void Save(FlatBufferBuilder builder,
                         string path)
 {
     File.WriteAllBytes(path, builder.SizedByteArray());
 }
示例#29
0
        /// <summary>
        /// Sends a chat message.
        /// </summary>
        /// <param name="message">Message.</param>
        public static void sendChatMessage(string message)
        {
            FlatBufferBuilder fbb = new FlatBufferBuilder (1);

            var mon = NetMessage.CreateNetMessage (fbb,
                NetID.Chat,
                Chat.CreateChat (fbb,
                    fbb.CreateString (userName),
                    fbb.CreateString (message)).Value);

            NetMessage.FinishNetMessageBuffer (fbb, mon);

            peer.Send (0, fbb.SizedByteArray (), PacketFlags.Reliable);
        }