-
Notifications
You must be signed in to change notification settings - Fork 35
/
Level.cs
3540 lines (3173 loc) · 192 KB
/
Level.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
/*
Copyright 2010 MCSharp team (Modified for use with MCZall/MCLawl/MCForge)
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.osedu.org/licenses/ECL-2.0
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Data;
using System.Threading;
//using MySql.Data.MySqlClient;
//using MySql.Data.Types;
///WARNING! DO NOT CHANGE THE WAY THE LEVEL IS SAVED/LOADED!
///You MUST make it able to save and load as a new version other wise you will make old levels incompatible!
namespace MCLawl
{
public enum LevelPermission
{
Banned = -20,
Guest = 0,
Builder = 30,
AdvBuilder = 50,
Operator = 80,
Admin = 100,
Nobody = 120,
Null = 150
}
public class Level
{
public int id;
public string name;
public ushort width; // x
public ushort depth; // y THIS IS STUPID, SHOULD HAVE BEEN Z
public ushort height; // z THIS IS STUPID, SHOULD HAVE BEEN Y
public int currentUndo = 0;
public List<UndoPos> UndoBuffer = new List<UndoPos>();
public struct UndoPos { public int location; public byte oldType, newType; public DateTime timePerformed; }
//Block change recording
public struct BlockPos { public ushort x, y, z; public byte type; public DateTime TimePerformed; public bool deleted; public string name; }
public List<BlockPos> blockCache = new List<BlockPos>();
public ushort spawnx;
public ushort spawny;
public ushort spawnz;
public byte rotx;
public byte roty;
public ushort jailx, jaily, jailz;
public byte jailrotx, jailroty;
public bool edgeWater = false;
public List<Player> players { get { return getPlayers(); } }
public Thread physThread;
public bool physPause = false;
public DateTime physResume;
public System.Timers.Timer physTimer = new System.Timers.Timer(1000);
public int physics = 0;
public bool realistic = true;
public bool finite = false;
public bool ai = true;
public bool Death = false;
public int fall = 9;
public int drown = 70;
public bool unload = true;
public bool rp = true;
public bool Instant = false;
public bool Killer = true;
public bool GrassDestroy = true;
public bool GrassGrow = true;
public bool worldChat = true;
public bool fishstill = false;
public int speedPhysics = 250;
public int overload = 1500;
public string theme = "Normal";
public string motd = "ignore";
public LevelPermission permissionvisit = LevelPermission.Guest;
public LevelPermission permissionbuild = LevelPermission.Builder;// What ranks can go to this map (excludes banned)
public byte[] blocks;
public struct Zone { public ushort smallX, smallY, smallZ, bigX, bigY, bigZ; public string Owner; }
public List<Zone> ZoneList;
List<Check> ListCheck = new List<Check>(); //A list of blocks that need to be updated
List<Update> ListUpdate = new List<Update>(); //A list of block to change after calculation
//CTF STUFF
public CTFGame ctfgame = new CTFGame();
public bool ctfmode = false;
public int lastCheck = 0;
public int lastUpdate = 0;
public bool changed = false;
public bool backedup = false;
public Level(string n, ushort x, ushort y, ushort z, string type)
{
width = x; depth = y; height = z;
if (width < 16) { width = 16; }
if (depth < 16) { depth = 16; }
if (height < 16) { height = 16; }
name = n;
blocks = new byte[width * depth * height];
ZoneList = new List<Zone>();
switch (type)
{
case "flat":
case "pixel":
ushort half = (ushort)(depth / 2);
for (x = 0; x < width; ++x)
{
for (z = 0; z < height; ++z)
{
for (y = 0; y < depth; ++y)
{
//Block b = new Block();
switch (type)
{
case "flat":
if (y != half)
{
SetTile(x, y, z, (byte)((y >= half) ? Block.air : Block.dirt));
}
else
{
SetTile(x, y, z, Block.grass);
}
break;
case "pixel":
if (y == 0)
SetTile(x, y, z, Block.blackrock);
else
if (x == 0 || x == width - 1 || z == 0 || z == height - 1)
SetTile(x, y, z, Block.white);
break;
}
//blocks[x + width * z + width * height * y] = b;
}
}
}
break;
case "island":
case "mountains":
case "ocean":
case "forest":
case "desert":
Server.MapGen.GenerateMap(this, type);
break;
default:
break;
}
spawnx = (ushort)(width / 2);
spawny = (ushort)(depth * 0.75f);
spawnz = (ushort)(height / 2);
rotx = 0; roty = 0;
}
public void CopyBlocks(byte[] source, int offset)
{
blocks = new byte[width * depth * height];
Array.Copy(source, offset, blocks, 0, blocks.Length);
for (int i = 0; i < blocks.Length; i++)
{
if (blocks[i] >= 50) blocks[i] = 0;
if (blocks[i] == Block.waterstill) blocks[i] = Block.water;
else if (blocks[i] == Block.water) blocks[i] = Block.waterstill;
else if (blocks[i] == Block.lava) blocks[i] = Block.lavastill;
else if (blocks[i] == Block.lavastill) blocks[i] = Block.lava;
}
}
public bool Unload()
{
if (Server.mainLevel == this) return false;
if (this.name.Contains("&cMuseum ")) return false;
Player.players.ForEach(delegate(Player pl)
{
if (pl.level == this) Command.all.Find("goto").Use(pl, Server.mainLevel.name);
});
if (changed)
{
Save();
saveChanges();
}
physThread.Abort();
physThread.Join();
Server.levels.Remove(this);
GC.Collect();
GC.WaitForPendingFinalizers();
Player.GlobalMessageOps("&3" + name + Server.DefaultColor + " was unloaded.");
Server.s.Log(name + " was unloaded.");
return true;
}
public void saveChanges()
{
if (blockCache.Count == 0) return;
List<BlockPos> tempCache = blockCache;
blockCache = new List<BlockPos>();
string queryString;
queryString = "INSERT INTO `Block" + name + "` (Username, TimePerformed, X, Y, Z, type, deleted) VALUES ";
foreach (BlockPos bP in tempCache)
{
queryString += "('" + bP.name + "', '" + bP.TimePerformed.ToString("yyyy-MM-dd HH:mm:ss") + "', " + (int)bP.x + ", " + (int)bP.y + ", " + (int)bP.z + ", " + bP.type + ", " + bP.deleted + "), ";
}
queryString = queryString.Remove(queryString.Length - 2);
MySQL.executeQuery(queryString);
tempCache.Clear();
}
public byte GetTile(ushort x, ushort y, ushort z)
{
//if (PosToInt(x, y, z) >= blocks.Length) { return null; }
//Avoid internal overflow
if (x < 0) { return Block.Zero; }
if (x >= width) { return Block.Zero; }
if (y < 0) { return Block.Zero; }
if (y >= depth) { return Block.Zero; }
if (z < 0) { return Block.Zero; }
if (z >= height) { return Block.Zero; }
return blocks[PosToInt(x, y, z)];
}
public byte GetTile(int b)
{
ushort x = 0, y = 0, z = 0;
IntToPos(b, out x, out y, out z);
return GetTile(x, y, z);
}
public void SetTile(ushort x, ushort y, ushort z, byte type)
{
blocks[x + width * z + width * height * y] = type;
//blockchanges[x + width * z + width * height * y] = pName;
}
public static Level Find(string levelName)
{
Level tempLevel = null; bool returnNull = false;
foreach (Level level in Server.levels)
{
if (level.name.ToLower() == levelName) return level;
if (level.name.ToLower().IndexOf(levelName.ToLower()) != -1)
{
if (tempLevel == null) tempLevel = level;
else returnNull = true;
}
}
if (returnNull == true) return null;
if (tempLevel != null) return tempLevel;
return null;
}
public static Level FindExact(string levelName)
{
return Server.levels.Find(lvl => levelName.ToLower() == lvl.name.ToLower());
}
public void Blockchange(Player p, ushort x, ushort y, ushort z, byte type) { Blockchange(p, x, y, z, type, true); }
public void Blockchange(Player p, ushort x, ushort y, ushort z, byte type, bool addaction)
{
string errorLocation = "start";
retry: try
{
if (x < 0 || y < 0 || z < 0) return;
if (x >= width || y >= depth || z >= height) return;
byte b = GetTile(x, y, z);
errorLocation = "Block rank checking";
if (!Block.AllowBreak(b))
{
if (!Block.canPlace(p, b) && !Block.BuildIn(b))
{
p.SendBlockchange(x, y, z, b);
return;
}
}
errorLocation = "Zone checking";
#region zones
bool AllowBuild = true, foundDel = false, inZone = false; string Owners = ""; List<Zone> toDel = new List<Zone>();
if ((p.group.Permission < LevelPermission.Admin || p.ZoneCheck || p.zoneDel) && !Block.AllowBreak(b))
{
if (ZoneList.Count == 0) AllowBuild = true;
else
{
foreach (Zone Zn in ZoneList)
{
if (Zn.smallX <= x && x <= Zn.bigX && Zn.smallY <= y && y <= Zn.bigY && Zn.smallZ <= z && z <= Zn.bigZ)
{
inZone = true;
if (p.zoneDel)
{
//DB
MySQL.executeQuery("DELETE FROM `Zone" + p.level.name + "` WHERE Owner='" + Zn.Owner + "' AND SmallX='" + Zn.smallX + "' AND SMALLY='" + Zn.smallY + "' AND SMALLZ='" + Zn.smallZ + "' AND BIGX='" + Zn.bigX + "' AND BIGY='" + Zn.bigY + "' AND BIGZ='" + Zn.bigZ + "'");
toDel.Add(Zn);
p.SendBlockchange(x, y, z, b);
Player.SendMessage(p, "Zone deleted for &b" + Zn.Owner);
foundDel = true;
}
else
{
if (Zn.Owner.Substring(0, 3) == "grp")
{
if (Group.Find(Zn.Owner.Substring(3)).Permission <= p.group.Permission && !p.ZoneCheck)
{
AllowBuild = true;
break;
}
else
{
AllowBuild = false;
Owners += ", " + Zn.Owner.Substring(3);
}
}
else
{
if (Zn.Owner.ToLower() == p.name.ToLower() && !p.ZoneCheck)
{
AllowBuild = true;
break;
}
else
{
AllowBuild = false;
Owners += ", " + Zn.Owner;
}
}
}
}
}
}
if (p.zoneDel)
{
if (!foundDel) Player.SendMessage(p, "No zones found to delete.");
else
{
foreach (Zone Zn in toDel)
{
ZoneList.Remove(Zn);
}
}
p.zoneDel = false;
return;
}
if (!AllowBuild || p.ZoneCheck)
{
if (Owners != "") Player.SendMessage(p, "This zone belongs to &b" + Owners.Remove(0, 2) + ".");
else Player.SendMessage(p, "This zone belongs to no one.");
p.ZoneSpam = DateTime.Now;
p.SendBlockchange(x, y, z, b);
if (p.ZoneCheck) if (!p.staticCommands) p.ZoneCheck = false;
return;
}
}
#endregion
errorLocation = "Map rank checking";
if (Owners == "")
{
if (p.group.Permission < this.permissionbuild && (!inZone || !AllowBuild))
{
p.SendBlockchange(x, y, z, b);
Player.SendMessage(p, "Must be at least " + PermissionToName(permissionbuild) + " to build here");
return;
}
}
errorLocation = "Block sending";
if (Block.Convert(b) != Block.Convert(type) && !Instant)
Player.GlobalBlockchange(this, x, y, z, type);
if (b == Block.sponge && physics > 0 && type != Block.sponge) PhysSpongeRemoved(PosToInt(x, y, z));
errorLocation = "Undo buffer filling";
Player.UndoPos Pos;
Pos.x = x; Pos.y = y; Pos.z = z; Pos.mapName = name;
Pos.type = b; Pos.newtype = type; Pos.timePlaced = DateTime.Now;
p.UndoBuffer.Add(Pos);
errorLocation = "Setting tile";
p.loginBlocks++;
p.overallBlocks++;
SetTile(x, y, z, type); //Updates server level blocks
errorLocation = "Growing grass";
if (GetTile(x, (ushort)(y - 1), z) == Block.grass && GrassDestroy && !Block.LightPass(type)) { Blockchange(p, x, (ushort)(y - 1), z, Block.dirt); }
errorLocation = "Adding physics";
if (physics > 0) if (Block.Physics(type)) AddCheck(PosToInt(x, y, z));
changed = true;
backedup = false;
}
catch (OutOfMemoryException)
{
Player.SendMessage(p, "Undo buffer too big! Cleared!");
p.UndoBuffer.Clear();
goto retry;
}
catch (Exception e)
{
Server.ErrorLog(e);
Player.GlobalMessageOps(p.name + " triggered a non-fatal error on " + name);
Player.GlobalMessageOps("Error location: " + errorLocation);
Server.s.Log(p.name + " triggered a non-fatal error on " + name);
Server.s.Log("Error location: " + errorLocation);
}
//if (addaction)
//{
// if (edits.Count == edits.Capacity) { edits.Capacity += 1024; }
// if (p.actions.Count == p.actions.Capacity) { p.actions.Capacity += 128; }
// if (b.lastaction.Count == 5) { b.lastaction.RemoveAt(0); }
// Edit foo = new Edit(this); foo.block = b; foo.from = p.name;
// foo.before = b.type; foo.after = type;
// b.lastaction.Add(foo); edits.Add(foo); p.actions.Add(foo);
//} b.type = type;
}
public void Blockchange(ushort x, ushort y, ushort z, byte type, bool overRide = false, string extraInfo = "") //Block change made by physics
{
if (x < 0 || y < 0 || z < 0) return;
if (x >= width || y >= depth || z >= height) return;
byte b = GetTile(x, y, z);
try
{
if (!overRide)
if (Block.OPBlocks(b) || Block.OPBlocks(type)) return;
if (Block.Convert(b) != Block.Convert(type)) //Should save bandwidth sending identical looking blocks, like air/op_air changes.
Player.GlobalBlockchange(this, x, y, z, type);
if (b == Block.sponge && physics > 0 && type != Block.sponge)
PhysSpongeRemoved(PosToInt(x, y, z));
try
{
UndoPos uP;
uP.location = PosToInt(x, y, z);
uP.newType = type;
uP.oldType = b;
uP.timePerformed = DateTime.Now;
if (currentUndo > Server.physUndo)
{
currentUndo = 0;
UndoBuffer[currentUndo] = uP;
}
else if (UndoBuffer.Count < Server.physUndo)
{
currentUndo++;
UndoBuffer.Add(uP);
}
else
{
currentUndo++;
UndoBuffer[currentUndo] = uP;
}
}
catch { }
SetTile(x, y, z, type); //Updates server level blocks
if (physics > 0)
if (Block.Physics(type) || extraInfo != "") AddCheck(PosToInt(x, y, z), extraInfo);
}
catch
{
SetTile(x, y, z, type);
}
}
public void skipChange(ushort x, ushort y, ushort z, byte type)
{
if (x < 0 || y < 0 || z < 0) return;
if (x >= width || y >= depth || z >= height) return;
SetTile(x, y, z, type);
}
public void Save(Boolean Override = false)
{
string path = "levels/" + name + ".lvl";
try
{
if (!Directory.Exists("levels")) Directory.CreateDirectory("levels");
if (!Directory.Exists("levels/level properties")) Directory.CreateDirectory("levels/level properties");
if (changed == true || !File.Exists(path) || Override)
{
FileStream fs = File.Create(path + ".back");
GZipStream gs = new GZipStream(fs, CompressionMode.Compress);
byte[] header = new byte[16];
BitConverter.GetBytes(1874).CopyTo(header, 0);
gs.Write(header, 0, 2);
BitConverter.GetBytes(width).CopyTo(header, 0);
BitConverter.GetBytes(height).CopyTo(header, 2);
BitConverter.GetBytes(depth).CopyTo(header, 4);
BitConverter.GetBytes(spawnx).CopyTo(header, 6);
BitConverter.GetBytes(spawnz).CopyTo(header, 8);
BitConverter.GetBytes(spawny).CopyTo(header, 10);
header[12] = rotx; header[13] = roty;
header[14] = (byte)permissionvisit;
header[15] = (byte)permissionbuild;
gs.Write(header, 0, header.Length);
byte[] level = new byte[blocks.Length];
for (int i = 0; i < blocks.Length; ++i)
{
if (blocks[i] < 80)
{
level[i] = blocks[i];
}
else
{
level[i] = Block.SaveConvert(blocks[i]);
}
} gs.Write(level, 0, level.Length); gs.Close();
fs.Close();
File.Delete(path + ".backup");
File.Copy(path + ".back", path + ".backup");
File.Delete(path);
File.Move(path + ".back", path);
StreamWriter SW = new StreamWriter(File.Create("levels/level properties/" + name + ".properties"));
SW.WriteLine("#Level properties for " + name);
SW.WriteLine("Theme = " + theme);
SW.WriteLine("Physics = " + physics.ToString());
SW.WriteLine("Physics speed = " + speedPhysics.ToString());
SW.WriteLine("Physics overload = " + overload.ToString());
SW.WriteLine("Finite mode = " + finite.ToString());
SW.WriteLine("Animal AI = " + ai.ToString());
SW.WriteLine("Edge water = " + edgeWater.ToString());
SW.WriteLine("Survival death = " + Death.ToString());
SW.WriteLine("Fall = " + fall.ToString());
SW.WriteLine("Drown = " + drown.ToString());
SW.WriteLine("MOTD = " + motd);
SW.WriteLine("JailX = " + jailx.ToString());
SW.WriteLine("JailY = " + jaily.ToString());
SW.WriteLine("JailZ = " + jailz.ToString());
SW.WriteLine("Unload = " + unload);
SW.WriteLine("PerBuild = " + PermissionToName(permissionbuild));
SW.WriteLine("PerVisit = " + PermissionToName(permissionvisit));
SW.Flush();
SW.Close();
Server.s.Log("SAVED: Level \"" + name + "\". (" + players.Count + "/" + Player.players.Count + "/" + Server.players + ")");
changed = false;
fs.Dispose();
gs.Dispose();
SW.Dispose();
}
else
{
Server.s.Log("Skipping level save for " + name + ".");
}
}
catch (Exception e)
{
Server.s.Log("FAILED TO SAVE :" + name);
Player.GlobalMessage("FAILED TO SAVE :" + name);
Server.ErrorLog(e);
return;
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
public int Backup(bool Forced = false, string backupName = "")
{
if (!backedup || Forced)
{
int backupNumber = 1; string backupPath = @Server.backupLocation;
if (Directory.Exists(backupPath + "/" + name))
{
backupNumber = Directory.GetDirectories(backupPath + "/" + name).Length + 1;
}
else
{
Directory.CreateDirectory(backupPath + "/" + name);
}
string path = backupPath + "/" + name + "/" + backupNumber;
if (backupName != "")
{
path = backupPath + "/" + name + "/" + backupName;
}
Directory.CreateDirectory(path);
string BackPath = path + "/" + name + ".lvl";
string current = "levels/" + name + ".lvl";
try
{
File.Copy(current, BackPath, true);
backedup = true;
return backupNumber;
}
catch (Exception e)
{
Server.ErrorLog(e);
Server.s.Log("FAILED TO INCREMENTAL BACKUP :" + name);
return -1;
}
}
else
{
Server.s.Log("Level unchanged, skipping backup");
return -1;
}
}
public static Level Load(string givenName) { return Load(givenName, 0); }
public static Level Load(string givenName, byte phys)
{
MySQL.executeQuery("CREATE TABLE if not exists `Block" + givenName + "` (Username CHAR(20), TimePerformed DATETIME, X SMALLINT UNSIGNED, Y SMALLINT UNSIGNED, Z SMALLINT UNSIGNED, Type TINYINT UNSIGNED, Deleted BOOL)");
MySQL.executeQuery("CREATE TABLE if not exists `Portals" + givenName + "` (EntryX SMALLINT UNSIGNED, EntryY SMALLINT UNSIGNED, EntryZ SMALLINT UNSIGNED, ExitMap CHAR(20), ExitX SMALLINT UNSIGNED, ExitY SMALLINT UNSIGNED, ExitZ SMALLINT UNSIGNED)");
MySQL.executeQuery("CREATE TABLE if not exists `Messages" + givenName + "` (X SMALLINT UNSIGNED, Y SMALLINT UNSIGNED, Z SMALLINT UNSIGNED, Message CHAR(255));");
MySQL.executeQuery("CREATE TABLE if not exists `Zone" + givenName + "` (SmallX SMALLINT UNSIGNED, SmallY SMALLINT UNSIGNED, SmallZ SMALLINT UNSIGNED, BigX SMALLINT UNSIGNED, BigY SMALLINT UNSIGNED, BigZ SMALLINT UNSIGNED, Owner VARCHAR(20));");
string path = "levels/" + givenName + ".lvl";
if (File.Exists(path))
{
FileStream fs = File.OpenRead(path);
try
{
GZipStream gs = new GZipStream(fs, CompressionMode.Decompress);
byte[] ver = new byte[2];
gs.Read(ver, 0, ver.Length);
ushort version = BitConverter.ToUInt16(ver, 0);
Level level;
if (version == 1874)
{
byte[] header = new byte[16]; gs.Read(header, 0, header.Length);
ushort width = BitConverter.ToUInt16(header, 0);
ushort height = BitConverter.ToUInt16(header, 2);
ushort depth = BitConverter.ToUInt16(header, 4);
level = new Level("temp", width, depth, height, "empty");
level.spawnx = BitConverter.ToUInt16(header, 6);
level.spawnz = BitConverter.ToUInt16(header, 8);
level.spawny = BitConverter.ToUInt16(header, 10);
level.rotx = header[12]; level.roty = header[13];
//level.permissionvisit = (LevelPermission)header[14];
//level.permissionbuild = (LevelPermission)header[15];
}
else
{
byte[] header = new byte[12]; gs.Read(header, 0, header.Length);
ushort width = version;
ushort height = BitConverter.ToUInt16(header, 0);
ushort depth = BitConverter.ToUInt16(header, 2);
level = new Level("temp", width, depth, height, "grass");
level.spawnx = BitConverter.ToUInt16(header, 4);
level.spawnz = BitConverter.ToUInt16(header, 6);
level.spawny = BitConverter.ToUInt16(header, 8);
level.rotx = header[10]; level.roty = header[11];
}
level.permissionbuild = (LevelPermission)11;
level.name = givenName;
level.setPhysics(phys);
byte[] blocks = new byte[level.width * level.height * level.depth];
gs.Read(blocks, 0, blocks.Length);
level.blocks = blocks;
gs.Close();
level.backedup = true;
DataTable ZoneDB = MySQL.fillData("SELECT * FROM `Zone" + givenName + "`");
Zone Zn;
for (int i = 0; i < ZoneDB.Rows.Count; ++i)
{
Zn.smallX = (ushort)ZoneDB.Rows[i]["SmallX"];
Zn.smallY = (ushort)ZoneDB.Rows[i]["SmallY"];
Zn.smallZ = (ushort)ZoneDB.Rows[i]["SmallZ"];
Zn.bigX = (ushort)ZoneDB.Rows[i]["BigX"];
Zn.bigY = (ushort)ZoneDB.Rows[i]["BigY"];
Zn.bigZ = (ushort)ZoneDB.Rows[i]["BigZ"];
Zn.Owner = ZoneDB.Rows[i]["Owner"].ToString();
level.ZoneList.Add(Zn);
}
ZoneDB.Dispose();
level.jailx = (ushort)(level.spawnx * 32); level.jaily = (ushort)(level.spawny * 32); level.jailz = (ushort)(level.spawnz * 32);
level.jailrotx = level.rotx; level.jailroty = level.roty;
level.physThread = new Thread(new ThreadStart(level.Physics));
try
{
DataTable foundDB = MySQL.fillData("SELECT * FROM `Portals" + givenName + "`");
for (int i = 0; i < foundDB.Rows.Count; ++i)
{
if (!Block.portal(level.GetTile((ushort)foundDB.Rows[i]["EntryX"], (ushort)foundDB.Rows[i]["EntryY"], (ushort)foundDB.Rows[i]["EntryZ"])))
{
MySQL.executeQuery("DELETE FROM `Portals" + givenName + "` WHERE EntryX=" + foundDB.Rows[i]["EntryX"] + " AND EntryY=" + foundDB.Rows[i]["EntryY"] + " AND EntryZ=" + foundDB.Rows[i]["EntryZ"]);
}
}
foundDB = MySQL.fillData("SELECT * FROM `Messages" + givenName + "`");
for (int i = 0; i < foundDB.Rows.Count; ++i)
{
if (!Block.mb(level.GetTile((ushort)foundDB.Rows[i]["X"], (ushort)foundDB.Rows[i]["Y"], (ushort)foundDB.Rows[i]["Z"])))
{
MySQL.executeQuery("DELETE FROM `Messages" + givenName + "` WHERE X=" + foundDB.Rows[i]["X"] + " AND Y=" + foundDB.Rows[i]["Y"] + " AND Z=" + foundDB.Rows[i]["Z"]);
}
}
foundDB.Dispose();
}
catch (Exception e) { Server.ErrorLog(e); }
try
{
string foundLocation;
foundLocation = "levels/level properties/" + level.name + ".properties";
if (!File.Exists(foundLocation))
{
foundLocation = "levels/level properties/" + level.name;
}
foreach (string line in File.ReadAllLines(foundLocation))
{
try
{
if (line[0] != '#')
{
string value = line.Substring(line.IndexOf(" = ") + 3);
switch (line.Substring(0, line.IndexOf(" = ")).ToLower())
{
case "theme": level.theme = value; break;
case "physics": level.setPhysics(int.Parse(value)); break;
case "physics speed": level.speedPhysics = int.Parse(value); break;
case "physics overload": level.overload = int.Parse(value); break;
case "finite mode": level.finite = bool.Parse(value); break;
case "animal ai": level.ai = bool.Parse(value); break;
case "edge water": level.edgeWater = bool.Parse(value); break;
case "survival death": level.Death = bool.Parse(value); break;
case "fall": level.fall = int.Parse(value); break;
case "drown": level.drown = int.Parse(value); break;
case "motd": level.motd = value; break;
case "jailx": level.jailx = ushort.Parse(value); break;
case "jaily": level.jaily = ushort.Parse(value); break;
case "jailz": level.jailz = ushort.Parse(value); break;
case "unload": level.unload = bool.Parse(value); break;
case "perbuild":
if (PermissionFromName(value) != LevelPermission.Null) level.permissionbuild = PermissionFromName(value);
break;
case "pervisit":
if (PermissionFromName(value) != LevelPermission.Null) level.permissionvisit = PermissionFromName(value);
break;
}
}
}
catch (Exception e) { Server.ErrorLog(e); }
}
} catch { }
Server.s.Log("Level \"" + level.name + "\" loaded.");
level.ctfgame.mapOn = level;
return level;
}
catch (Exception ex) { Server.ErrorLog(ex); return null; }
finally { fs.Close(); }
}
else { Server.s.Log("ERROR loading level."); return null; }
}
public void ChatLevel(string message)
{
foreach (Player pl in Player.players)
{
if (pl.level == this) pl.SendMessage(message);
}
}
public void setPhysics(int newValue)
{
if (physics == 0 && newValue != 0)
{
for (int i = 0; i < blocks.Length; i++)
if (Block.NeedRestart(blocks[i]))
AddCheck(i);
}
physics = newValue;
}
public void Physics()
{
int wait = speedPhysics;
while (true)
{
try
{
retry: if (wait > 0) Thread.Sleep(wait);
if (physics == 0 || ListCheck.Count == 0) goto retry;
DateTime Start = DateTime.Now;
if (physics > 0) CalcPhysics();
TimeSpan Took = DateTime.Now - Start;
wait = (int)speedPhysics - (int)Took.TotalMilliseconds;
if (wait < (int)(-overload * 0.75f))
{
Level Cause = this;
if (wait < -overload)
{
if (!Server.physicsRestart) Cause.setPhysics(0);
Cause.ClearPhysics();
Player.GlobalMessage("Physics shutdown on &b" + Cause.name);
Server.s.Log("Physics shutdown on " + name);
wait = speedPhysics;
}
else
{
foreach (Player p in Player.players)
{
if (p.level == this) Player.SendMessage(p, "Physics warning!");
}
Server.s.Log("Physics warning on " + name);
}
}
}
catch
{
wait = speedPhysics;
}
}
}
public int PosToInt(ushort x, ushort y, ushort z)
{
if (x < 0) { return -1; }
if (x >= width) { return -1; }
if (y < 0) { return -1; }
if (y >= depth) { return -1; }
if (z < 0) { return -1; }
if (z >= height) { return -1; }
return x + (z * width) + (y * width * height);
//alternate method: (h * widthY + y) * widthX + x;
}
public void IntToPos(int pos, out ushort x, out ushort y, out ushort z)
{
y = (ushort)(pos / width / height); pos -= y * width * height;
z = (ushort)(pos / width); pos -= z * width; x = (ushort)pos;
}
public int IntOffset(int pos, int x, int y, int z)
{
return pos + x + z * width + y * width * height;
}
#region ==Physics==
public struct Pos { public ushort x, z; }
public string foundInfo(ushort x, ushort y, ushort z)
{
Check foundCheck = null;
try
{
foundCheck = ListCheck.Find(Check => Check.b == PosToInt(x, y, z));
} catch { }
if (foundCheck != null)
return foundCheck.extraInfo;
return "";
}
public void CalcPhysics()
{
try
{
if (physics > 0)
{
ushort x, y, z; int mx, my, mz;
Random rand = new Random();
lastCheck = ListCheck.Count;
ListCheck.ForEach(delegate(Check C)
{
try
{
IntToPos(C.b, out x, out y, out z);
bool InnerChange = false; bool skip = false;
int storedRand = 0;
Player foundPlayer = null; int foundNum = 75, currentNum, newNum, oldNum;
string foundInfo = C.extraInfo;
newPhysic: if (foundInfo != "")
{
int currentLoop = 0;
if (!foundInfo.Contains("wait")) if (blocks[C.b] == Block.air) C.extraInfo = "";
bool drop = false; int dropnum = 0;
bool wait = false; int waitnum = 0;
bool dissipate = false; int dissipatenum = 0;
bool revert = false; byte reverttype = 0;
bool explode = false; int explodenum = 0;
bool finiteWater = false;
bool rainbow = false; int rainbownum = 0;
bool door = false;
foreach (string s in C.extraInfo.Split(' '))
{
if (currentLoop % 2 == 0)
{ //Type of code
switch (s)
{
case "wait":
wait = true;
waitnum = int.Parse(C.extraInfo.Split(' ')[currentLoop + 1]);
break;
case "drop":
drop = true;
dropnum = int.Parse(C.extraInfo.Split(' ')[currentLoop + 1]);
break;
case "dissipate":
dissipate = true;
dissipatenum = int.Parse(C.extraInfo.Split(' ')[currentLoop + 1]);
break;
case "revert":
revert = true;
reverttype = Byte.Parse(C.extraInfo.Split(' ')[currentLoop + 1]);
break;
case "explode":
explode = true;
explodenum = int.Parse(C.extraInfo.Split(' ')[currentLoop + 1]);
break;
case "finite":
finiteWater = true;
break;
case "rainbow":
rainbow = true;
rainbownum = int.Parse(C.extraInfo.Split(' ')[currentLoop + 1]);
break;
case "door":
door = true;
break;