sabvente
sabvente

Reputation: 308

How to implement delta compression of an object in C#?

I'm working on a server-based multiplayer game written in C#. The server and the client shares code and each object has the same int ID. I want to make the networking to be light as possible, by sending only the changed data.

The game has classes, which have numerous fields/properties, and they often change. I'm seeking a way to detect when these values change and send these values to the client side.

Basically, this algorithm:

  1. Flag object when it's changed
  2. With the changed objects at network Tick:
    1. Compare each property with their previous state
    2. Send only the changed values
    3. Store old values
  3. Receive them on the client side
  4. Instantiate the same type of object, or find it by ID
  5. Set the new values

Of course, .NET Reflection may be eable to solve this problem, but iterating throuh 1000 object and their properties in each Tick, would be a bottleneck in performance.

I can send the basic types (int, float, vector), and maintain connection. My questions are these:

What's the best approach to send an object's Class and instantiate it?

How should I detect property change and how to serialise properties so I can find their "pair" on the client when receiving.

Upvotes: 3

Views: 1224

Answers (1)

Kikaimaru
Kikaimaru

Reputation: 1851

You can create something like this:

class Mob {
private int _health;
public int Health
{
   get { return _health; }
   set { _health = value; DirtyFlags |= MobDirtyFlags.Health
}
}

this means a lot of code for each property

Or you can have some custom dictionary and every change in that dictionary would be tracked, so

mob.Properties["Health"] = 10; would track that you changed something.

This is how Mooege (Diablo 3 emulator) does this.

First approach can be rewritten with aspects (probably some custom code that will generate all that code that is written above at runtime via Reflection.Emit or something similar). Or if you know what will all your entities look like, you can generate classes for them from some templates (using something like T4)

as for serialization, this is good enough: (key: int, value: object) where key would be some enum like ActorProperties { Health, Strength, ...}

Upvotes: 3

Related Questions