-
Notifications
You must be signed in to change notification settings - Fork 0
/
Player.cs
1135 lines (1008 loc) · 40.2 KB
/
Player.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* uBuilder - A lightweight custom Minecraft Classic server written in C#
* Copyright 2010 Calvin "calzoneman" Montgomery
*
* Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License
* (see http://creativecommons.org/licenses/by-sa/3.0/, or LICENSE.txt for a full license
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace uBuilder
{
public class Player
{
public short x, y, z;
public byte rotx, roty;
public string username;
public string prefix = "";
public string ip;
public bool loggedIn = false;
public int loginTmr = 0;
public byte id;
public ushort rank = 0x01; //Guest
public bool disconnected = false;
//public Dictionary<string, object> buildMeta = new Dictionary<string, object>();
public Bindings binding = Bindings.None;
public bool painting = false, cuboiding = false;
public byte holding = 1;
public CuboidParameters cParams;
public TeleportBlockParams tParams;
public ShapeArgs sArgs;
public short[] lastTeleport = new short[] { 0, 0, 0 };
public bool flying = false;
public int[] lastFlyPos = new int[] { 0, 0, 0 };
public List<Block> flyBlocks = null;
public string messageBlockText = "";
public Block[] copyClipboard = null;
public PermissionSet currentPermissions = PermissionSet.Guest;
public World world;
object queueLock = new object();
public static Dictionary<string, char> specialChars;
public TcpClient plyClient;
public BinaryReader inputReader;
public BinaryWriter outputWriter;
public Queue<Packet> outQueue;
public Queue<Packet> blockQueue;
public Thread IOThread;
//Events
//Login
public delegate void LoginHandler(Player p);
public event LoginHandler OnLogin = null;
public void ResetLoginHandler() { OnLogin = null; }
//Blockchange
public delegate void BlockHandler(Player p, int x, int y, int z, byte type);
public event BlockHandler OnBlockchange = null;
public void ResetBlockHandler() { OnBlockchange = null; }
//Movement
public delegate void PositionChangeHandler(Player p, short[] oldPos, byte[] oldRot, short[] newPos, byte[] newRot);
public event PositionChangeHandler OnMovement = null;
public void ResetPositionChangeHandler() { OnMovement = null; }
//Chat
public delegate void ChatHandler(Player p, string msg);
public event ChatHandler OnChat = null;
public void ResetChatHandler() { OnChat = null; }
public Player(TcpClient client, string ip, byte id)
{
try
{
this.username = "player";
this.plyClient = client;
this.x = 0;
this.y = 0;
this.z = 0;
this.rotx = 0;
this.roty = 0;
this.prefix = "";
this.id = id;
this.ip = ip;
this.world = null;
this.outQueue = new Queue<Packet>();
this.blockQueue = new Queue<Packet>();
this.IOThread = new Thread(PlayerIO);
this.outputWriter = new BinaryWriter(client.GetStream());
this.inputReader = new BinaryReader(client.GetStream());
this.IOThread.IsBackground = true;
this.IOThread.Start();
}
catch
{
}
}
public void PlayerIO()
{
try
{
Login();
}
catch (IOException) { Disconnect(true); }
catch (SocketException) { Disconnect(true); }
catch (ObjectDisposedException) { Disconnect(true); }
catch (Exception e) { Program.server.logger.log(e); Disconnect(true); }
DateTime pingTime = DateTime.Now;
while (!disconnected)
{
try
{
//Send whatever remains in the queue
lock (queueLock)
{
//Process generic packets
while (outQueue.Count > 0)
{
Packet p = outQueue.Dequeue();
if (this.world == null && !"01234".Contains(p.raw[0].ToString())) //Process all login/map packets first
{
outQueue.Enqueue(p);
}
else
{
this.outputWriter.Write(p.raw);
}
}
//Process blockchanges (separation should reduce lag)
if (this.world != null)
{
while (blockQueue.Count > 0)
{
Packet p = blockQueue.Dequeue();
this.outputWriter.Write(p.raw);
}
}
}
if (((TimeSpan)(DateTime.Now - pingTime)).TotalSeconds > 2)
{
this.outputWriter.Write((byte)ServerPacket.Ping); //Ping
pingTime = DateTime.Now;
}
//Accept input
while (plyClient.GetStream().DataAvailable)
{
byte opcode = this.inputReader.ReadByte();
switch ((ClientPacket)opcode)
{
case ClientPacket.Login:
if (loggedIn)
{
Program.server.logger.log("Player " + username + " has already logged in!", Logger.LogType.Warning);
Kick("Already logged in", false);
}
break;
case ClientPacket.Blockchange:
PlayerBlockchange();
break;
case ClientPacket.MoveRotate:
PositionChange();
break;
case ClientPacket.Message:
PlayerMessage();
break;
default:
Program.server.logger.log("Unhandled packet type \"" + opcode + "\"", Logger.LogType.Warning);
Kick("Unknown packet type", false);
break;
}
}
//Clean up
GC.Collect();
GC.WaitForPendingFinalizers();
Thread.Sleep(10);
}
catch (IOException) { Disconnect(false); }
catch (SocketException) { Disconnect(false); }
catch (ObjectDisposedException) { Disconnect(false); }
catch (Exception e) { Program.server.logger.log(e); Disconnect(false); }
}
}
public string GetFormattedName()
{
return Rank.GetColor(this.rank) + this.prefix + this.username;
}
#region Received Data
public void Login()
{
byte opLogin = this.inputReader.ReadByte();
if (opLogin != (byte)ClientPacket.Login)
{
Program.server.logger.log("Wrong login opcode received from " + ip, Logger.LogType.Warning);
Kick("Wrong Login Opcode", true);
return;
}
byte plyProtocol = this.inputReader.ReadByte();
if (plyProtocol != Protocol.version) //Shouldn't happen
{
Program.server.logger.log("Wrong protocol version received from " + ip, Logger.LogType.Warning);
Kick("Wrong Protocol Version", true);
return;
}
//Read username
this.username = Encoding.ASCII.GetString(this.inputReader.ReadBytes(64)).Trim();
//Verify the name
if (Program.server.verify_names)
{
string mppass = Encoding.ASCII.GetString(this.inputReader.ReadBytes(64)).Trim();
while (mppass.Length < 32) { mppass = "0" + mppass; }
MD5 hasher = new MD5CryptoServiceProvider();
byte[] cmpHash = hasher.ComputeHash(Encoding.ASCII.GetBytes(Program.server.salt + username));
for (int i = 0; i < 16; i += 2)
{
if (mppass[i] + "" + mppass[i + 1] != cmpHash[i / 2].ToString("x2"))
{
Kick("Name verification failed!", true);
}
}
}
//Unused byte
this.inputReader.ReadByte();
if (Program.server.ipbanned.Contains(ip))
{
Kick("You're IP Banned!", true);
return;
}
//Check Rank
if (Program.server.playerRanksDict.ContainsKey(username.ToLower()))
{
this.rank = Program.server.playerRanksDict[username.ToLower()];
}
else
{
this.rank = Rank.RankLevel("guest");
Program.server.saveRanks();
}
if (rank == Rank.RankLevel("none"))
{
Kick("You're banned!", true);
return;
}
currentPermissions = Rank.Permissions(rank);
//Send a response
this.outputWriter.Write((byte)ServerPacket.Login);
this.outputWriter.Write((byte)Protocol.version); // Protocol version
this.outputWriter.Write(Encoding.ASCII.GetBytes(Program.server.serverName.PadRight(64).Substring(0, 64))); // name
this.outputWriter.Write(Encoding.ASCII.GetBytes(Program.server.motd.PadRight(64).Substring(0, 64))); //motd
if (rank >= Rank.RankLevel("operator")) { this.outputWriter.Write((byte)0x64); } //Can break adminium
else { this.outputWriter.Write((byte)0x00); } //Cannot break adminium
Program.server.logger.log(ip + " logged in as " + username);
//Find an empty slot for them
bool emptySlot = false;
for (int i = 0; i < Program.server.playerlist.Length - 1; i++)
{
if (Program.server.playerlist[i] == null)
{
emptySlot = true;
break;
}
}
if (!emptySlot) //Server is full :(
{
Kick("Server is full!", true);
return;
}
//We are logged in now
loggedIn = true;
Program.server.plyCount++;
if (Program.server.accounts.ContainsKey(username.ToLower()))
{
Program.server.accounts[username.ToLower()].Visit();
Program.server.accounts[username.ToLower()].SetIP(ip);
}
else
{
Program.server.accounts.Add(username.ToLower(), new Account(this));
Program.server.SavePlayerStats();
}
//Init any player-specific plugins
//ExamplePlugins.Init(this);
MessageBlockCheck.Init(this);
TeleportBlockCheck.Init(this);
//OnMovement += new PositionChangeHandler(FlyCommand.FlyMove);
//If they are ranked operator or admin, give them a snazzy prefix
if (rank >= Rank.RankLevel("operator")) { prefix = "+"; }
if (rank >= Rank.RankLevel("owner")) { prefix = "@"; }
//Send the map
this.SendPacket(new Packet(new byte[1] { (byte)ServerPacket.MapBegin }));
SendMap(Program.server.world);
//Announce the player's arrival
string loginMessage = Rank.GetColor(rank).ToString();
if(!prefix.Equals(""))
{
loginMessage += prefix;
}
loginMessage += username + "&e joined the game";
GlobalMessage(loginMessage);
if (this.OnLogin != null) //Call the OnLogin Event
{
OnLogin(this);
}
}
public void PrintPlayerlist()
{
for(int i = 0; i < Program.server.playerlist.Length; i++)
{
string name = "";
if(Program.server.playerlist[i] == null)
{
name = "null";
}
else
{
name = Program.server.playerlist[i].username;
}
Console.WriteLine(i + "|" + name);
}
}
public void PositionChange()
{
short[] oldPos = new short[3] { x, y, z };
byte[] oldRot = new byte[2] { rotx, roty };
this.inputReader.ReadByte();
this.x = IPAddress.NetworkToHostOrder(this.inputReader.ReadInt16());
this.y = IPAddress.NetworkToHostOrder(this.inputReader.ReadInt16());
this.z = IPAddress.NetworkToHostOrder(this.inputReader.ReadInt16());
this.rotx = this.inputReader.ReadByte();
this.roty = this.inputReader.ReadByte();
foreach (Player pl in Program.server.playerlist)
{
if (pl != null && pl.loggedIn && pl != this)
{
pl.SendPlayerPositionChange(this);
}
}
if (this.OnMovement != null)
{
OnMovement(this, oldPos, oldRot, new short[] { x, y, z }, new byte[] { rotx, roty });
}
}
public void PlayerMessage()
{
this.inputReader.ReadByte();
string rawmsg = Encoding.ASCII.GetString(this.inputReader.ReadBytes(64)).Trim();
rawmsg = ParseSpecialChar(rawmsg);
if (OnChat != null)
{
OnChat(this, rawmsg);
return;
}
//Test for commands
if (!rawmsg.Trim().Equals("") && rawmsg.Trim()[0] == '/')
{
string cmd = "", args = "";
if (rawmsg.Contains(" "))
{
cmd = rawmsg.Trim().Substring(1, rawmsg.IndexOf(' ') - 1);
args = rawmsg.Trim().Substring(rawmsg.IndexOf(' ')).Trim();
}
else { cmd = rawmsg.Substring(1); }
Command.HandleCommand(this, cmd, args);
return;
}
//Test for PMs
if (!rawmsg.Trim().Equals("") && rawmsg.Trim()[0] == '@' && rawmsg.Trim()[1] != '@' && rawmsg.Trim().Contains(" "))
{
string tname = rawmsg.Trim().Substring(1, rawmsg.IndexOf(" ") - 1);
Player target = FindPlayer(this, tname, false);
if (target != null)
{
target.SendMessage(0x00, Rank.GetColor(this.rank) + "(" + this.prefix + this.username + ")&e " + (char)26 + "&f " + rawmsg.Substring(rawmsg.IndexOf(" ") + 1));
this.SendMessage(0x00, Rank.GetColor(target.rank) + "(" + target.prefix + target.username + ")&e " + (char)27 + "&f " + rawmsg.Substring(rawmsg.IndexOf(" ") + 1));
Program.server.accounts[username.ToLower()].messagesSent++;
}
return;
}
string message = "";
message = Rank.GetColor(rank) + "<" + prefix + username + "> &f" + rawmsg;
if (rank >= Rank.RankLevel("player") && !message.Contains("@@")) { message = ParseColors(message); }
Program.server.logger.log(message, Logger.LogType.Chat);
Program.server.accounts[username.ToLower()].messagesSent++;
foreach (Player p in Program.server.playerlist)
{
if (p != null && p.loggedIn)
{
p.SendMessage(id, message);
}
}
}
public void PlayerBlockchange()
{
short x = IPAddress.HostToNetworkOrder(this.inputReader.ReadInt16());
short y = IPAddress.HostToNetworkOrder(this.inputReader.ReadInt16());
short z = IPAddress.HostToNetworkOrder(this.inputReader.ReadInt16());
byte action = this.inputReader.ReadByte();
byte type = this.inputReader.ReadByte();
if (this.rank == 0) { return; }
byte mapBlock = world.GetTile(x, y, z);
if (mapBlock == Blocks.door || mapBlock == Blocks.irondoor || mapBlock == Blocks.darkgreydoor)
{
if (action == 0)
{
if (OnBlockchange == null)
{
Program.server.advPhysics.Queue(x, y, z, mapBlock, PhysType.Door, new object[] { Blocks.DoorOpenType(mapBlock) });
return;
}
}
else return;
}
if (action == 0)
{
if (!painting && !cuboiding)
{
type = 0;
}
}
AuthenticateAndSetBlock(x, y, z, type);
}
public void AuthenticateAndSetBlock(int x, int y, int z, byte type)
{
byte mapBlock = world.GetTile(x, y, z);
if (rank == 0 || !loggedIn) return;
if (type == 1 && this.binding != Bindings.None)
{
type = (byte)this.binding;
}
if (type == 0 && flyBlocks != null)
{
Block fly = flyBlocks.Find(b => b.x == (short)x && b.y == (short)y && b.z == (short)z);
if (fly != null)
{
SendBlock(fly.x, fly.y, fly.z, Blocks.air);
SendBlock(fly.x, (short)(fly.y - 1), fly.z, Blocks.glass);
return;
}
}
if (mapBlock == 7 && rank < Rank.RankLevel("operator"))
{
Kick("Attempted to break adminium", false);
return;
}
if (type == 7 && rank < Rank.RankLevel("operator"))
{
Kick("Illegal tile type", false);
return;
}
if ((type >= 8 && type <= 11) && rank < Rank.RankLevel("operator") && type != (byte)this.binding)
{
Kick("Illegal tile type", false);
return;
}
if (type > 49 && type != (byte)this.binding && !Blocks.blockNames.ContainsValue(type))
{
Kick("Illegal tile type", false);
return;
}
if (mapBlock == Blocks.teleportBlock)
{
if (this.OnBlockchange != (BlockHandler)TeleportBlockCommand.BlockDeleted)
{
SendMessage(0xFF, "That block is a teleport block. Use /tpdel to remove it.");
SendBlock((short)x, (short)y, (short)z, Blocks.tnt);
return;
}
}
if ((mapBlock == Blocks.doorOpen || mapBlock == Blocks.irondoorOpen || mapBlock == Blocks.darkgreydoorOpen) && !(OnBlockchange != null || DrawThreadManager.Active_Thread(this) || (Bindings)binding == Bindings.Air))
{
SendMessage(0xFF, "That block cannot be changed.");
SendBlock((short)x, (short)y, (short)z, Blocks.air);
return;
}
if (mapBlock == Blocks.door || mapBlock == Blocks.irondoor || mapBlock == Blocks.darkgreydoor)
{
if (type == 0)
{
if (OnBlockchange == null && !DrawThreadManager.Active_Thread(this))
{
Program.server.advPhysics.Queue(x, y, z, mapBlock, PhysType.Door, new object[] { Blocks.DoorOpenType(mapBlock) });
return;
}
}
else if(!(OnBlockchange != null || DrawThreadManager.Active_Thread(this))) return;
}
if (type != 0 && type != mapBlock)
{
Program.server.accounts[username.ToLower()].PlaceBlock();
}
else if(type != mapBlock)
{
Program.server.accounts[username.ToLower()].DeleteBlock();
}
if (this.OnBlockchange != null)
{
OnBlockchange(this, x, y, z, type);
return;
}
if (type != mapBlock)
{
if (!world.SetTile(x, y, z, type)) SendBlock((short)x, (short)y, (short)z, mapBlock);
}
}
#endregion
#region Sending
//Marked virtual so ConsolePlayer can override it
public virtual void SendMessage(byte pid, string message)
{
try
{
foreach (string line in SplitLines(message))
{
if (!loggedIn) { return; }
Packet msgPacket = new Packet(66);
msgPacket.Append((byte)ServerPacket.Message);
msgPacket.Append(pid);
msgPacket.Append(Sanitize(line));
this.SendPacket(msgPacket);
}
}
catch (IOException) { }
catch (SocketException) { }
catch (Exception e) { Program.server.logger.log(e); }
}
public void SendBlock(short x, short y, short z, byte type)
{
Packet block = new Packet(8);
block.Append((byte)ServerPacket.Blockchange);
block.Append(x);
block.Append(y);
block.Append(z);
block.Append(Blocks.ConvertType(type));
this.SendPacket(block);
}
public void Kick(string reason, bool silent) //Disconnect someone
{
try
{
if (!loggedIn) { silent = true; }
if (!this.plyClient.Connected) //Oops
{
Program.server.logger.log("Player " + username + " has already disconnected.", Logger.LogType.Warning);
return;
}
//Send kick (0x0e + kick message)
this.outputWriter.Write((byte)ServerPacket.Kick);
this.outputWriter.Write(reason);
this.plyClient.Close();
Program.server.logger.log("Player " + username + " kicked (" + reason + ")");
if (!silent)
{
GlobalMessage("Player " + GetFormattedName() + "&e kicked (" + reason + ")");
}
Disconnect(silent);
}
catch
{
Disconnect(true);
}
}
/*public void SendMap(ref byte[] leveldata, short width, short height, short depth)
{
try
{
byte[] buffer = new byte[leveldata.Length + 4];
BitConverter.GetBytes(IPAddress.HostToNetworkOrder(leveldata.Length)).CopyTo(buffer, 0);
for (int i = 0; i < leveldata.Length; ++i)
{
buffer[4 + i] = leveldata[i];
}
buffer = GZip(buffer);
int number = (int)Math.Ceiling(((double)buffer.Length) / 1024);
for (int i = 1; buffer.Length > 0; ++i)
{
Packet chunk = new Packet(1028);
short length = (short)Math.Min(buffer.Length, 1024);
chunk.Append((byte)ServerPacket.MapChunk);
chunk.Append(length);
chunk.Append(byteArraySlice(ref buffer, 0, length));
for (short j = length; j < 1024; j++)
{
chunk.Append((byte)0);
}
byte[] tempbuffer = new byte[buffer.Length - length];
Buffer.BlockCopy(buffer, length, tempbuffer, 0, buffer.Length - length);
buffer = tempbuffer;
chunk.Append((byte)((i * 100.0) / number));
this.SendPacket(chunk);
System.Threading.Thread.Sleep(1);
}
Packet mapFinal = new Packet(7);
mapFinal.Append((byte)ServerPacket.MapFinal);
mapFinal.Append((short)width);
mapFinal.Append((short)depth);
mapFinal.Append((short)height);
this.SendPacket(mapFinal);
//Spawn player
this.SpawnPlayer(this, true);
this.SendSpawn(new short[3] { 8 * 32 + 16, 64, 8 * 32 + 16 }, new byte[2] { 0, 0 });
//Spawn other players
foreach (Player p in Program.server.playerlist)
{
if (p != null && p.loggedIn && p != this)
{
this.SpawnPlayer(p, false);
}
}
//Spawn self
GlobalSpawnPlayer(this);
}
catch (IOException) { }
catch (SocketException) { }
catch (Exception e) { Program.server.logger.log(e); }
} */
public void SendMap(World w)
{
try
{
byte[] buffer = new byte[w.blocks.Length + 4];
BitConverter.GetBytes(IPAddress.HostToNetworkOrder(w.blocks.Length)).CopyTo(buffer, 0);
for (int i = 0; i < w.blocks.Length; ++i)
{
buffer[4 + i] = Blocks.ConvertType(w.blocks[i]);
}
buffer = GZip(buffer);
int number = (int)Math.Ceiling(((double)buffer.Length) / 1024);
for (int i = 1; buffer.Length > 0; ++i)
{
Packet chunk = new Packet(1028);
short length = (short)Math.Min(buffer.Length, 1024);
chunk.Append((byte)ServerPacket.MapChunk);
chunk.Append(length);
chunk.Append(byteArraySlice(ref buffer, 0, length));
for (short j = length; j < 1024; j++)
{
chunk.Append((byte)0);
}
byte[] tempbuffer = new byte[buffer.Length - length];
Buffer.BlockCopy(buffer, length, tempbuffer, 0, buffer.Length - length);
buffer = tempbuffer;
chunk.Append((byte)((i * 100.0) / number));
this.SendPacket(chunk);
System.Threading.Thread.Sleep(1);
}
Packet mapFinal = new Packet(7);
mapFinal.Append((byte)ServerPacket.MapFinal);
mapFinal.Append(w.width);
mapFinal.Append(w.height);
mapFinal.Append(w.depth);
this.SendPacket(mapFinal);
//Spawn player (convert map coordinates to player coordinates and set player pos)
this.x = (short)(w.spawnx << 5);
this.y = (short)(w.spawny << 5);
this.z = (short)(w.spawnz << 5);
this.rotx = w.srotx;
this.roty = w.sroty;
this.SpawnPlayer(this, true);
//Spawn other players
foreach (Player p in Program.server.playerlist)
{
if (p != null && p.loggedIn && p != this)
{
this.SpawnPlayer(p, false);
}
}
//Spawn self
GlobalSpawnPlayer(this);
this.world = w;
}
catch (IOException) { }
catch (SocketException) { }
catch (Exception e) { Program.server.logger.log(e); }
}
public void SpawnPlayer(Player p, bool self)
{
try
{
Packet spawn = new Packet(74);
spawn.Append((byte)ServerPacket.SpawnEntity);
if (self) { spawn.Append((byte)255); }
else { spawn.Append(p.id); }
spawn.Append(Rank.GetColor(p.rank) + p.username); //username
spawn.Append((short)p.x); //x position
spawn.Append((short)p.y); //y position
spawn.Append((short)p.z); //z position
spawn.Append(p.rotx); //x rotation
spawn.Append(p.roty); //y rotation
this.SendPacket(spawn);
}
catch (IOException) { }
catch (SocketException) { }
catch (Exception e) { Program.server.logger.log(e); }
}
public void SendSpawn(short[] pos, byte[] rot)
{
try
{
Packet spawn = new Packet(10);
//Now move+rotate (teleport)
spawn.Append((byte)ServerPacket.MoveRotate); //Move+Rotate
spawn.Append((byte)255); // Self
spawn.Append(pos[0]); //x position
spawn.Append(pos[1]); //y position
spawn.Append(pos[2]); //z position
spawn.Append(rot[0]); //x rotation
spawn.Append(rot[1]); //y rotation
this.SendPacket(spawn);
}
catch (IOException) { }
catch (SocketException) { }
catch (Exception e) { Program.server.logger.log(e); }
}
public void SendPlayerPositionChange(Player p)
{
try
{
Packet posChange = new Packet(10);
posChange.Append((byte)ServerPacket.MoveRotate);
posChange.Append(p.id);
posChange.Append(p.x);
posChange.Append(p.y);
posChange.Append(p.z);
posChange.Append(p.rotx);
posChange.Append(p.roty);
this.SendPacket(posChange);
}
catch (IOException) { }
catch (SocketException) { }
catch (Exception e) { Program.server.logger.log(e); }
}
public void SendPacket(Packet p)
{
lock (queueLock)
{
if (p.raw[0] == (byte)ServerPacket.Blockchange)
{
this.blockQueue.Enqueue(p);
}
else
{
this.outQueue.Enqueue(p);
}
}
}
#endregion
#region Global Stuff
public static void GlobalBlockchange(short x, short y, short z, byte type)
{
Packet blockPacket = new Packet(8);
blockPacket.Append((byte)ServerPacket.Blockchange);
blockPacket.Append(x);
blockPacket.Append(y);
blockPacket.Append(z);
blockPacket.Append(type);
foreach (Player p in Program.server.playerlist)
{
try
{
if (p != null && p.loggedIn && !p.disconnected)
{
p.SendPacket(blockPacket);
}
}
catch
{
p.Disconnect(false);
}
}
}
public static void GlobalMessage(string message)
{
message = "[ " + message + " ]";
foreach (string line in SplitLines(message))
{
foreach (Player p in Program.server.playerlist)
{
try
{
if (p != null && p.loggedIn && !p.disconnected)
{
p.SendMessage(0xFF, line);
}
}
catch
{
Program.server.logger.log("Failed to send Global Message to " + p.username, Logger.LogType.Warning);
p.Disconnect(false);
}
}
}
Program.server.logger.log("(Global) " + message, Logger.LogType.Chat);
}
public static void GlobalSpawnPlayer(Player p)
{
foreach (Player pl in Program.server.playerlist)
{
try
{
if (pl != null && pl.loggedIn && pl != p)
{
pl.SpawnPlayer(p, false);
}
}
catch { }
}
}
#endregion
#region Disconnecting
public void Disconnect(bool silent)
{
try
{
if (this.disconnected) { return; }
this.loggedIn = false;
if (!silent)
{
GlobalMessage(GetFormattedName() + "&e disconnected.");
foreach (Player pl in Program.server.playerlist)
{
if (pl != null && pl.loggedIn)
{
pl.outputWriter.Write((byte)ServerPacket.PlayerDie);
pl.outputWriter.Write(this.id);
}
}
}
Program.server.logger.log(username + "(" + ip + ") disconnected.");
Program.server.playerlist[id] = null;
Program.server.plyCount--;
if (this.plyClient.Connected && !this.disconnected) { this.plyClient.Close(); }
this.disconnected = true;
}
catch
{
}
}
#endregion
#region Data Handlers
public static string Sanitize(string input)
{
input = input.Trim((char)0x20);
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if ((int)input[i] >= 128)
{
output.Append(' ');
}
else
{
output.Append(input[i]);
}
}
if ((int)(input[input.Length - 1]) < 0x20)
{
output.Append((char)39);
}
return output.ToString();
}
public static string ParseSpecialChar(string input)
{
if (input.Contains("@@")) { return input; }
foreach (KeyValuePair<string, char> rule in specialChars)
{
input = input.Replace(rule.Key, String.Empty + rule.Value);
}
/*while (input.Contains(@"\#"))
{
int index = input.IndexOf(@"\#") + 2;
if (index < input.Length)
{
try
{
int num = Int32.Parse(input.Substring(index, input.IndexOf(' ', index) - index));
if (num >= 128) { break; }
input = input.Remove(index - 2, 2 + num.ToString().Length);
input = input.Insert(index - 2, "" + (char)num);
}
catch
{