mas-bandwidth/yojimbo

Message Types vs Data Blocks

kingoftheconnors opened this issue · 1 comments

Hey! Just started working with this package, and hoping to get some usage advice! I'm confused about the use of Message Types.

Most uses of Message Types in the examples have special classes for each one, with unique serialization functions. Are Message types supposed to be entirely different serializations, or descriptors of different use cases for a message?

In my old netcode solution, I would pass a number for the event type. So "20" for activating a certain power, and "21" for building a wall. In Yojimbo, would these events be different message types? Or should I keep with the "number for type" system?

To answer my own question, it's an emphatic YES. My main confusion was about message serializations:

class TestMessage : public yojimbo::Message {
public:
    int m_data;

    TestMessage() :
        m_data(0) {}

    template <typename Stream>
    bool Serialize(Stream& stream) {
        serialize_int(stream, m_data, 0, 512);
        return true;
    }

    YOJIMBO_VIRTUAL_SERIALIZE_FUNCTIONS();
};

Here I read serialize_int and thought it was WRITING to m_data. But it's actually the opposite: Messages are sent as streams, and m_data is not a stream---yet!

serialize_int takes in a number and WRITES it to the stream, now ready to send it along. When received by the client, it'll automatically unpack the stream into its original m_data variables.

Here's my example of a message with multiple pieces of data:

struct PlayerStateMessage : public Message
{
    short x;
    short y;
    uint8_t state;

    PlayerStateMessage() : x(0), y(0), state(0) {}

    template <typename Stream> bool Serialize( Stream & stream )
    {        
        serialize_int(stream, x, -32767, 32767);
        serialize_int(stream, y, -32767, 32767);
        serialize_int(stream, state, 0, 256);
        return true;
    }

    YOJIMBO_VIRTUAL_SERIALIZE_FUNCTIONS();
};

If you have multiple event types (player dead or whatever), every id will use different variables right? Turning a player invisible won't require an X and Y input! So you make a different class to serialize a different set of inputs!

I hope this helps anyone else looking to use this package!