Skip to content

Commit 1399b5a

Browse files
committed
fix checksum issue. improve demo with moving entities. closes #25
1 parent 2f6aee4 commit 1399b5a

File tree

11 files changed

+112
-40
lines changed

11 files changed

+112
-40
lines changed

Assets/ColyseusClient.cs

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using UnityEngine;
22
using System.Collections;
3+
using System.Collections.Generic;
34
using System;
45
using Colyseus;
56

@@ -14,6 +15,9 @@ public class ColyseusClient : MonoBehaviour {
1415
public string port = "3553";
1516
public string roomName = "chat";
1617

18+
// map of players
19+
Dictionary<string, GameObject> players = new Dictionary<string, GameObject>();
20+
1721
// Use this for initialization
1822
IEnumerator Start () {
1923

@@ -29,8 +33,8 @@ IEnumerator Start () {
2933
room.OnJoin += OnRoomJoined;
3034
room.OnUpdate += OnUpdateHandler;
3135

32-
room.Listen ("players/:id/:axis", this.OnPlayerMove);
3336
room.Listen ("players/:id", this.OnPlayerChange);
37+
room.Listen ("players/:id/:axis", this.OnPlayerMove);
3438
room.Listen ("messages/:number", this.OnMessageAdded);
3539
room.Listen (this.OnChangeFallback);
3640

@@ -78,19 +82,63 @@ void OnRoomJoined (object sender, EventArgs e)
7882
Debug.Log("Joined room successfully.");
7983
}
8084

85+
void OnUpdateHandler (object sender, RoomUpdateEventArgs e)
86+
{
87+
// Setup room first state
88+
if (e.isFirstState) {
89+
IndexedDictionary<string, object> players = (IndexedDictionary<string, object>) e.state ["players"];
90+
91+
// trigger to add existing players
92+
foreach(KeyValuePair<string, object> player in players)
93+
{
94+
this.OnPlayerChange (new DataChange {
95+
path = new Dictionary<string, string> {
96+
{"id", player.Key}
97+
},
98+
operation = "add",
99+
value = player.Value
100+
});
101+
}
102+
}
103+
}
104+
81105
void OnPlayerChange (DataChange change)
82106
{
83107
Debug.Log ("OnPlayerChange");
84108
Debug.Log (change.operation);
85109
Debug.Log (change.path["id"]);
86110
Debug.Log (change.value);
111+
112+
if (change.operation == "add") {
113+
IndexedDictionary<string, object> value = (IndexedDictionary<string, object>) change.value;
114+
115+
GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
116+
117+
cube.transform.position = new Vector3 (Convert.ToSingle(value ["x"]), Convert.ToSingle(value ["y"]), 0);
118+
119+
// add "player" to map of players by id.
120+
players.Add (change.path ["id"], cube);
121+
122+
} else if (change.operation == "remove") {
123+
// remove player from scene
124+
GameObject cube;
125+
players.TryGetValue (change.path ["id"], out cube);
126+
Destroy (cube);
127+
128+
players.Remove (change.path ["id"]);
129+
}
87130
}
88131

89132
void OnPlayerMove (DataChange change)
90133
{
91134
Debug.Log ("OnPlayerMove");
92135
Debug.Log ("playerId: " + change.path["id"] + ", Axis: " + change.path["axis"]);
93136
Debug.Log (change.value);
137+
138+
GameObject cube;
139+
players.TryGetValue (change.path ["id"], out cube);
140+
141+
cube.transform.Translate (new Vector3 (Convert.ToSingle(change.value), 0, 0));
94142
}
95143

96144
void OnPlayerRemoved (DataChange change)
@@ -115,11 +163,6 @@ void OnChangeFallback (PatchObject change)
115163
// Debug.Log (change.value);
116164
}
117165

118-
void OnUpdateHandler (object sender, RoomUpdateEventArgs e)
119-
{
120-
// Debug.Log(e.state);
121-
}
122-
123166
void OnApplicationQuit()
124167
{
125168
// Ensure the connection with server is closed immediatelly

Assets/Player.prefab

6.72 KB
Binary file not shown.

Assets/Plugins/FossilDelta/Delta.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,12 @@ public static byte[] Apply(byte[] origin, byte[] delta) {
200200

201201
case ';':
202202
byte[] output = zOut.ToArray ();
203-
if (cnt != Checksum (output))
204-
throw new Exception("bad checksum");
203+
//
204+
// Checksum is optional (2017-10-05)
205+
// http://fossil-scm.org/xfer/info/d3a46b2a45b92bbc
206+
//
207+
//if (cnt != Checksum (output))
208+
// throw new Exception("bad checksum");
205209
if (total != limit)
206210
throw new Exception("generated size does not match predicted size");
207211
return output;

Assets/Plugins/GameDevWare.Serialization/Metadata/ReflectionUtils.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,12 @@ internal static class GettersAndSetters
3434

3535
static GettersAndSetters()
3636
{
37+
#if ((UNITY_WEBGL || UNITY_IOS || ENABLE_IL2CPP) && !UNITY_EDITOR)
38+
AotRuntime = true;
39+
#else
3740
try { Expression.Lambda<Func<bool>>(Expression.Constant(true)).Compile(); }
3841
catch (Exception) { AotRuntime = true; }
39-
42+
#endif
4043
ReadFunctions = new Dictionary<MemberInfo, Func<object, object>>();
4144
WriteFunctions = new Dictionary<MemberInfo, Action<object, object>>();
4245
ConstructorFunctions = new Dictionary<MemberInfo, Func<object>>();
@@ -108,7 +111,6 @@ public static bool TryGetAssessors(FieldInfo fieldInfo, out Func<object, object>
108111
if (AotRuntime || fieldInfo.IsStatic)
109112
return false;
110113

111-
112114
lock (ReadFunctions)
113115
{
114116
if (ReadFunctions.TryGetValue(fieldInfo, out getFn) == false)

Assets/Plugins/GameDevWare.Serialization/SerializationContext.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/*
1+
/*
22
Copyright (c) 2016 Denis Zykov, GameDevWare.com
33
44
This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918
@@ -18,6 +18,7 @@ to use it in your project you should accept Terms of Service and EULA
1818
using System.Collections.Generic;
1919
using System.Linq;
2020
using System.Reflection;
21+
using System.Runtime.Serialization;
2122
using System.Text;
2223
using GameDevWare.Serialization.Serializers;
2324

Assets/Plugins/GameDevWare.Serialization/Serializers/ObjectSerializer.cs

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/*
1+
/*
22
Copyright (c) 2016 Denis Zykov, GameDevWare.com
33
44
This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918
@@ -27,6 +27,7 @@ public class ObjectSerializer : TypeSerializer
2727
public const string TYPE_MEMBER_NAME = "_type";
2828

2929
private static readonly Regex VersionRegEx = new Regex(@", Version=[^\]]+", RegexOptions.None);
30+
private static readonly string BclTypePart = typeof(byte).AssemblyQualifiedName.Substring(typeof(byte).FullName.Length);
3031

3132
private readonly Type objectType;
3233
private readonly string objectTypeNameWithoutVersion;
@@ -57,7 +58,7 @@ public ObjectSerializer(SerializationContext context, Type type)
5758
this.baseTypeSerializer = (ObjectSerializer)baseSerializer;
5859
}
5960

60-
this.objectTypeDescription = TypeDescription.Get(type);
61+
this.objectTypeDescription = TypeDescription.Get(type);
6162
}
6263

6364
public override object Deserialize(IJsonReader reader)
@@ -145,7 +146,17 @@ private object DeserializeMembers(IJsonReader reader, IndexedDictionary<string,
145146
{
146147
reader.NextToken();
147148
var typeName = reader.ReadString(false);
148-
var type = reader.Context.GetType(typeName, true, true);
149+
var type = default(Type);
150+
try
151+
{
152+
type = reader.Context.GetType(typeName, true, true);
153+
}
154+
catch (Exception getTypeError)
155+
{
156+
throw new SerializationException(string.Format("Failed to resolve type '{0}' of value for '{1}' of '{2}' type.\r\n" +
157+
"More detailed information in inner exception.", typeName, memberName, this.objectType.Name), getTypeError);
158+
}
159+
149160
if (type == typeof(object))
150161
{
151162
this.DeserializeMembers(reader, container, ref serializerOverride);
@@ -283,12 +294,15 @@ public static string GetVersionInvariantObjectTypeName(Type type)
283294
{
284295
if (type == null) throw new ArgumentNullException("type");
285296

286-
return VersionRegEx.Replace(type.AssemblyQualifiedName ?? type.FullName, string.Empty);
297+
var fullName = (type.AssemblyQualifiedName ?? type.FullName ?? type.Name);
298+
fullName = VersionRegEx.Replace(fullName, string.Empty);
299+
fullName = fullName.Replace(BclTypePart, ""); // remove BCL path of type information for better interop compatibility
300+
return fullName;
287301
}
288302

289303
public override string ToString()
290304
{
291-
return string.Format("object, {0}", objectType);
305+
return string.Format("object, {0}", this.objectType);
292306
}
293307
}
294308
}

ProjectSettings/ProjectSettings.asset

493 Bytes
Binary file not shown.

ProjectSettings/ProjectVersion.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
m_EditorVersion: 5.6.2f1
1+
m_EditorVersion: 2017.1.1f1

Server/chat_room.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,24 +24,24 @@ class ChatRoom extends Room {
2424
}
2525

2626
onJoin (client) {
27-
console.log("client joined!", client.id);
28-
this.state.players[client.id] = { x: 0, y: 0 };
27+
console.log("client joined!", client.sessionId);
28+
this.state.players[client.sessionId] = { x: 0, y: 0 };
2929
}
3030

3131
onLeave (client) {
32-
console.log("client left!", client.id);
33-
delete this.state.players[client.id];
32+
console.log("client left!", client.sessionId);
33+
delete this.state.players[client.sessionId];
3434
}
3535

3636
onMessage (client, data) {
37-
console.log(data, "received from", client.id);
38-
this.state.messages.push(client.id + " sent " + data);
37+
console.log(data, "received from", client.sessionId);
38+
this.state.messages.push(client.sessionId + " sent " + data);
3939
}
4040

4141
update () {
4242
console.log("num clients:", Object.keys(this.clients).length);
43-
for (var id in this.state.players) {
44-
this.state.players[id].x++;
43+
for (var sessionId in this.state.players) {
44+
this.state.players[sessionId].x += 0.0001;
4545
}
4646
}
4747

Server/index.js

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,29 @@
1-
"use strict";
1+
const cluster = require("cluster");
2+
const express = require("express");
23

3-
var colyseus = require('colyseus')
4-
, http = require('http')
4+
const ClusterServer = require("colyseus").ClusterServer;
5+
const ChatRoom = require('./chat_room');
56

6-
, express = require('express')
7-
// , cors = require('cors')
7+
const PORT = process.env.PORT || 3553;
8+
const gameServer = new ClusterServer();
89

9-
, port = process.env.PORT || 3553
10-
, app = express()
11-
, server = http.createServer(app)
12-
, gameServer = new colyseus.Server({ server: server })
10+
// Register ChatRoom as "chat"
11+
gameServer.register("chat", ChatRoom);
1312

14-
, ChatRoom = require('./chat_room');
13+
if (cluster.isMaster) {
14+
gameServer.listen(PORT);
15+
gameServer.fork();
1516

16-
gameServer.register('chat', ChatRoom)
17+
} else {
18+
let app = new express();
1719

18-
app.use(express.static( __dirname ))
19-
gameServer.listen(port, '127.0.0.1');
20+
app.get("/something", function (req, res) {
21+
console.log("something!", process.pid);
22+
res.send("Hey!");
23+
});
2024

21-
console.log(`Listening on http://localhost:${ port }`)
25+
// Create HTTP Server
26+
gameServer.attach({ server: app });
27+
}
28+
29+
console.log("Listening on " + PORT);

0 commit comments

Comments
 (0)