/
GameWindow.cs
3934 lines (3861 loc) · 151 KB
/
GameWindow.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
using System;
using System.Collections.Generic;
using System.Text;
using OpenTK;
using ManicDigger.Collisions;
using System.Runtime.InteropServices;
using System.Drawing;
using OpenTK.Graphics;
using System.Windows.Forms;
using OpenTK.Graphics.OpenGL;
using System.Drawing.Imaging;
using System.Threading;
using System.IO;
using System.Net;
using System.Drawing.Drawing2D;
using ManicDigger.Network;
using ManicDigger.Renderers;
namespace ManicDigger
{
[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 12)]
public struct VertexPositionTexture
{
public Vector3 Position;
public float u;
public float v;
public byte r;
public byte g;
public byte b;
public byte a;
public VertexPositionTexture(float x, float y, float z, float u, float v)
{
Position = new Vector3(x, y, z);
this.u = u;
this.v = v;
r = byte.MaxValue;
g = byte.MaxValue;
b = byte.MaxValue;
a = byte.MaxValue;
}
public VertexPositionTexture(float x, float y, float z, float u, float v, FastColor c)
{
Position = new Vector3(x, y, z);
this.u = u;
this.v = v;
r = c.R;
g = c.G;
b = c.B;
a = c.A;
}
static uint ToRgba(Color color)
{
return (uint)color.A << 24 | (uint)color.B << 16 | (uint)color.G << 8 | (uint)color.R;
}
}
public class VerticesIndicesToLoad
{
public VertexPositionTexture[] vertices;
public ushort[] indices;
public Vector3 position;
public bool transparent;
public int texture;
public float radius;
public Vector3 center;
public bool wasrendered = false;
public int indicesCount;
public int verticesCount;
}
public class Config3d
{
public bool ENABLE_BACKFACECULLING = false;
public bool ENABLE_TRANSPARENCY = true;
public bool ENABLE_MIPMAPS = true;
public bool ENABLE_VSYNC = false;
public float viewdistance = 512;
}
public interface IThe3d
{
int LoadTexture(string filename);
int LoadTexture(Bitmap bmp);
Matrix4 ModelViewMatrix { get; }
Matrix4 ProjectionMatrix { get; }
}
public class The3dDummy : IThe3d
{
public int TextureId;
#region IThe3d Members
public int LoadTexture(string filename)
{
return TextureId;
}
public int LoadTerrainTexture(string filename)
{
return TextureId;
}
#endregion
#region IThe3d Members
public int LoadTexture(Bitmap bmp)
{
return TextureId;
}
#endregion
#region IThe3d Members
public Matrix4 ModelViewMatrix
{
get { return new Matrix4(); }
}
public Matrix4 ProjectionMatrix
{
get { return new Matrix4(); }
}
#endregion
}
public class CameraMove
{
public bool TurnLeft;
public bool TurnRight;
public bool DistanceUp;
public bool DistanceDown;
public bool AngleUp;
public bool AngleDown;
public int MoveX;
public int MoveY;
public float Distance;
}
public interface IKamera
{
void Move(CameraMove move, float p);
Vector3 Position { get; }
}
public class KameraDummy : IKamera
{
#region IKamera Members
public void Move(CameraMove move, float p)
{
}
public Vector3 Position { get; set; }
#endregion
}
public class Kamera : IKamera
{
public Vector3 Position
{
get
{
float cx = (float)(Math.Cos(tt * .5) * FlatDistance + Center.X);
float cy = (float)(Math.Sin(tt * .5) * FlatDistance + Center.Z);
return new Vector3(cx, Center.Y + CameraHeightFromCenter, cy);
}
}
float distance = 5;
public float Distance
{
get { return distance; }
set
{
distance = value;
if (distance < MinimumDistance)
{
distance = MinimumDistance;
}
}
}
public float Angle = 45;
public float MinimumDistance = 2f;
float CameraHeightFromCenter
{
//get { return (float)Math.Tan(Angle * Math.PI/180) * Distance; }
get { return (float)Math.Sin(Angle * Math.PI / 180) * Distance; }
}
float FlatDistance
{
get { return (float)Math.Cos(Angle * Math.PI / 180) * Distance; }
}
public Vector3 Center { get; set; }
public float tt = 0;
public void TurnLeft(float p)
{
tt += p;
}
public void TurnRight(float p)
{
tt -= p;
}
public void Move(CameraMove camera_move, float p)
{
p *= 2;
p *= 2;
if (camera_move.TurnLeft)
{
TurnLeft(p);
}
if (camera_move.TurnRight)
{
TurnRight(p);
}
if (camera_move.DistanceUp)
{
Distance += p;
}
if (camera_move.DistanceDown)
{
Distance -= p;
}
if (camera_move.AngleUp)
{
Angle += p * 10;
}
if (camera_move.AngleDown)
{
Angle -= p * 10;
}
Distance = camera_move.Distance;
if (MaximumAngle < MinimumAngle) { throw new Exception(); }
if (Angle > MaximumAngle) { Angle = MaximumAngle; }
if (Angle < MinimumAngle) { Angle = MinimumAngle; }
}
public int MaximumAngle = 89;
public int MinimumAngle = 0;
}
public interface IInterpolation
{
object Interpolate(object a, object b, float progress);
}
public interface INetworkInterpolation
{
void AddNetworkPacket(object c, double time);
object InterpolatedState(double time);
}
class NetworkInterpolation : INetworkInterpolation
{
struct Packet
{
public double timestamp;
public object content;
}
public IInterpolation req { get; set; }
public bool EXTRAPOLATE = false;
public float DELAY = 0.2f;
public float EXTRAPOLATION_TIME = 0.2f;
List<Packet> received = new List<Packet>();
public void AddNetworkPacket(object c, double time)
{
Packet p = new Packet();
p.content = c;
p.timestamp = time;
received.Add(p);
if (received.Count > 100)
{
received.RemoveRange(0, received.Count - 100);
}
}
public object InterpolatedState(double time)
{
double curtime = time;
double interpolationtime = curtime - DELAY;
int p1;
int p2;
if (received.Count == 0)
{
return null;
}
object result;
if (received.Count > 0 && interpolationtime < received[0].timestamp)
{
p1 = 0;
p2 = 0;
}
//extrapolate
else if (EXTRAPOLATE && (received.Count >= 2)
&& interpolationtime > received[received.Count - 1].timestamp)
{
p1 = received.Count - 2;
p2 = received.Count - 1;
interpolationtime = Math.Min(interpolationtime, received[received.Count - 1].timestamp + EXTRAPOLATION_TIME);
}
else
{
p1 = 0;
for (int i = 0; i < received.Count; i++)
{
if (received[i].timestamp <= interpolationtime)
{
p1 = i;
}
}
p2 = p1;
if (received.Count - 1 > p1)
{
p2++;
}
}
if (p1 == p2)
{
result = received[p1].content;
}
else
{
result = req.Interpolate(received[p1].content, received[p2].content,
(float)((interpolationtime - received[p1].timestamp)
/ (received[p2].timestamp - received[p1].timestamp)));
}
return result;
}
}
public enum Direction4
{
Left,
Right,
Up,
Down,
}
public class The3d : IThe3d
{
[Inject]
public Config3d config3d { get; set; }
public bool ALLOW_NON_POWER_OF_TWO = false;
public int LoadTexture(string filename)
{
Bitmap bmp = new Bitmap(filename);
return LoadTexture(bmp);
}
bool IsPowerOfTwo(uint x)
{
return (
x == 1 || x == 2 || x == 4 || x == 8 || x == 16 || x == 32 ||
x == 64 || x == 128 || x == 256 || x == 512 || x == 1024 ||
x == 2048 || x == 4096 || x == 8192 || x == 16384 ||
x == 32768 || x == 65536 || x == 131072 || x == 262144 ||
x == 524288 || x == 1048576 || x == 2097152 ||
x == 4194304 || x == 8388608 || x == 16777216 ||
x == 33554432 || x == 67108864 || x == 134217728 ||
x == 268435456 || x == 536870912 || x == 1073741824 ||
x == 2147483648);
}
//http://www.opentk.com/doc/graphics/textures/loading
public int LoadTexture(Bitmap bmp)
{
GL.Enable(EnableCap.Texture2D);
int id = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, id);
if (!config3d.ENABLE_MIPMAPS)
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
}
else
{
try
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, 1); //DOES NOT WORK ON ???
}
catch
{
try
{
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); //DOES NOT WORK ON ATI GRAPHIC CARDS
}
catch
{
config3d.ENABLE_MIPMAPS = false;
}
}
int[] MipMapCount = new int[1];
GL.GetTexParameter(TextureTarget.Texture2D, GetTextureParameter.TextureMaxLevel, out MipMapCount[0]);
if (MipMapCount[0] == 0)
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
}
else
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.NearestMipmapLinear);
}
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLevel, 4);
}
BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
bmp.UnlockBits(bmp_data);
GL.Enable(EnableCap.DepthTest);
if (config3d.ENABLE_TRANSPARENCY)
{
GL.Enable(EnableCap.AlphaTest);
GL.AlphaFunc(AlphaFunction.Greater, 0.5f);
}
if (config3d.ENABLE_TRANSPARENCY)
{
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
}
return id;
}
#region IThe3d Members
public Matrix4 ModelViewMatrix { get; set; }
public Matrix4 ProjectionMatrix { get; set; }
#endregion
}
public interface IKeyboard
{
OpenTK.Input.KeyboardDevice keyboardstate { get; }
OpenTK.Input.KeyboardKeyEventArgs keypressed { get; }
OpenTK.Input.KeyboardKeyEventArgs keydepressed { get; }
}
public interface IViewport3d : ILocalPlayerPosition, IKeyboard
{
int[] MaterialSlots { get; set; }
int activematerial { get; set; }
Dictionary<int, int> FiniteInventory { get; set; }
bool ENABLE_FREEMOVE { get; set; }
bool ENABLE_MOVE { get; set; }
void Log(string s);
Dictionary<string, string> PerformanceInfo { get; }
AnimationHint LocalPlayerAnimationHint { get; set; }
Vector3 PickCubePos { get; }
string LocalPlayerName { get; }
void GuiStateCraft(List<CraftingRecipe> recipes, List<int> blocks, Action<int?> craftingRecipeSelected);
int SelectedModelId { get; }
bool ENABLE_FINITEINVENTORY { get; set; }
bool SkySphereNight { get; set; }
}
public class AnimationHint
{
#region IViewport3d Members
public bool SkySphereNight { get; set; }
#endregion
public bool InVehicle;
public Vector3 DrawFix;
public bool leanleft;
public bool leanright;
}
public class ViewportDummy : IViewport3d
{
#region IViewport3d Members
public int[] MaterialSlots { get; set; }
public int activematerial { get; set; }
public bool ENABLE_FREEMOVE { get; set; }
public bool ENABLE_MOVE { get; set; }
public void Log(string s)
{
}
#endregion
#region ILocalPlayerPosition Members
public Vector3 LocalPlayerPosition { get; set; }
public Vector3 LocalPlayerOrientation { get; set; }
public bool Swimming { get { return false; } }
public float CharacterHeight { get; set; }
#endregion
#region IKeyboard Members
public OpenTK.Input.KeyboardDevice keyboardstate
{
get { throw new NotImplementedException(); }
}
public OpenTK.Input.KeyboardKeyEventArgs keypressed
{
get { throw new NotImplementedException(); }
}
#endregion
#region IViewport3d Members
public Dictionary<string, string> PerformanceInfo { get; set; }
#endregion
#region IViewport3d Members
public AnimationHint LocalPlayerAnimationHint { get; set; }
#endregion
#region IViewport3d Members
public Vector3 PickCubePos { get; set; }
#endregion
#region IViewport3d Members
public Dictionary<int, int> FiniteInventory { get; set; }
#endregion
#region IViewport3d Members
public string LocalPlayerName { get; set; }
#endregion
#region IViewport3d Members
public void GuiStateCraft(List<CraftingRecipe> recipes, List<int> blocks, Action<int?> craftingRecipeSelected)
{
}
#endregion
#region IKeyboard Members
public OpenTK.Input.KeyboardKeyEventArgs keydepressed
{
get { throw new NotImplementedException(); }
}
#endregion
#region IViewport3d Members
public int SelectedModelId
{
get { throw new NotImplementedException(); }
}
#endregion
#region IViewport3d Members
public bool ENABLE_FINITEINVENTORY { get; set; }
#endregion
#region IViewport3d Members
public bool SkySphereNight { get; set; }
#endregion
}
public interface IModelToDraw
{
void Draw(float dt);
IEnumerable<Triangle3D> TrianglesForPicking { get; }
int Id { get; }
}
public interface IGameMode
{
void OnPick(Vector3 blockposnew, Vector3 blockposold, Vector3 pos3d, bool right);
void SendSetBlock(Vector3 vector3, BlockSetMode blockSetMode, int type);
void OnNewFrame(double dt);
IEnumerable<ICharacterToDraw> Characters { get; }
IEnumerable<IModelToDraw> Models { get; }
Vector3 PlayerPositionSpawn { get; set; }
Vector3 PlayerOrientationSpawn { get; }
void OnNewMap();
byte[] SaveState();
void LoadState(byte[] savegame);
int FiniteInventoryAmount(int blocktype);
int FiniteInventoryMax { get; }
double SIMULATIONLAG_SECONDS { get; set; }
void ModelClick(int selectedmodelid);
}
public interface ICharacterToDraw : IModelToDraw
{
/*
Vector3 Pos3d { get; }
Vector3 Dir3d { get; }
bool Moves { get; }
*/
}
public class AnimationState
{
public float interp;
public int frame;
public object data;
public float slowdownTimer;
}
public class AngleInterpolation
{
public static int InterpolateAngle256(int a, int b, float progress)
{
if (progress != 0 && b != a)
{
int diff = NormalizeAngle256(b - a);
if (diff >= CircleHalf256)
{
diff -= CircleFull256;
}
a += (int)(progress * diff);
}
return NormalizeAngle256(a);
}
static int CircleHalf256 = 256 / 2;
static int CircleFull256 = 256;
static private int NormalizeAngle256(int v)
{
return (v + int.MaxValue / 2) % 256;
}
public static double InterpolateAngle360(double a, double b, double progress)
{
if (progress != 0 && b != a)
{
double diff = NormalizeAngle360(b - a);
if (diff >= CircleHalf360)
{
diff -= CircleFull360;
}
a += (progress * diff);
}
return NormalizeAngle360(a);
}
static int CircleHalf360 = 360 / 2;
static int CircleFull360 = 360;
static private double NormalizeAngle360(double v)
{
return (v + ((int.MaxValue / 2) / 360) * 360) % 360;
}
}
public interface ICurrentShadows
{
bool ShadowsFull { get; set; }
}
/// <summary>
/// </summary>
/// <remarks>
/// Requires OpenTK.
/// </remarks>
public class ManicDiggerGameWindow : GameWindow, IGameExit, ILocalPlayerPosition, IMap, IThe3d, IGui, IViewport3d
{
[Inject]
public ITerrainRenderer terrain { get; set; }
[Inject]
public IGameMode game { get; set; }
[Inject]
public IMapStorage map { get; set; }
[Inject]
public IClients clients { get; set; }
[Inject]
public CharacterPhysics physics { get; set; }
[Inject]
public INetworkClient network { get; set; }
[Inject]
public IInternetGameFactory internetgamefactory { get; set; }
[Inject]
public IAudio audio { get; set; }
[Inject]
public IGetFilePath getfile { get; set; }
[Inject]
public IGameData data { get; set; }
[Inject]
public ILoginClient login { get; set; }
[Inject]
public Config3d config3d { get; set; }
[Inject]
public WeaponRenderer weapon { get; set; }
[Inject]
public ICharacterRenderer characterdrawer { get; set; }
[Inject]
public ICurrentShadows currentshadows;
[Inject]
public IShadows shadows;
const float rotation_speed = 180.0f * 0.05f;
//float angle;
bool IsMono = Type.GetType("Mono.Runtime") != null;
public void DrawMap()
{
terrain.UpdateAllTiles();
}
#region IThe3d Members
public Matrix4 ModelViewMatrix
{
get { return m_theModelView; }
}
public Matrix4 ProjectionMatrix
{
get { return m_projectionMatrix; }
}
#endregion
public void SetTileAndUpdate(Vector3 pos, int type)
{
// frametickmainthreadtodo.Add(() =>
// {
int x = (int)pos.X;
int y = (int)pos.Y;
int z = (int)pos.Z;
map.SetBlock(x, y, z, type);
terrain.UpdateTile(x, y, z);
// terrain.UpdateAllTiles();
// });
}
const bool ENABLE_FULLSCREEN = false;
public ManicDiggerGameWindow()
: base(1000, 550, GraphicsMode.Default, "",
ENABLE_FULLSCREEN ? GameWindowFlags.Fullscreen : GameWindowFlags.Default) { VSync = VSyncMode.Adaptive; }
//glControl1.
The3d the3d = new The3d();
public int LoadTexture(string filename)
{
the3d.config3d = config3d;
return the3d.LoadTexture(filename);
}
public int LoadTexture(Bitmap bmp)
{
the3d.config3d = config3d;
return the3d.LoadTexture(bmp);
}
protected override void OnFocusedChanged(EventArgs e)
{
if (guistate == GuiState.Normal)
{ GuiStateEscapeMenu(); }
else if (guistate == GuiState.MainMenu || guistate == GuiState.EscapeMenu)
{ }
else if (guistate == GuiState.Inventory)
{ }
else if (guistate == GuiState.MapLoading)
{
DrawMapLoading();
}
else if (guistate == GuiState.CraftingRecipes)
{ }
else { throw new Exception(); }
base.OnFocusedChanged(e);
}
[Inject]
public MapManipulator mapManipulator { get; set; }
public bool SkySphereNight { get; set; }
public static System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string version = GL.GetString(StringName.Version);
int major = (int)version[0];
int minor = (int)version[2];
if (major <= 1 && minor < 5)
{
//System.Windows.Forms.MessageBox.Show("You need at least OpenGL 1.5 to run this example. Aborting.", "VBOs not supported",
//System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
this.Exit();
}
if (!config3d.ENABLE_VSYNC)
{
TargetRenderFrequency = 0;
}
GL.ClearColor(Color.Black);
//GL.Frustum(double.MinValue, double.MaxValue, double.MinValue, double.MaxValue, 1, 1000);
//clientgame.GeneratePlainMap();
//clientgame.LoadMapMinecraft();
if (GameUrl == null)
{
if (ENABLE_MAINMENU)
{
guistate = GuiState.MainMenu;
FreeMouse = true;
mapManipulator.LoadMap(map, getfile.GetFile("menu" + MapManipulator.XmlSaveExtension));
ENABLE_FREEMOVE = true;
player.playerposition = new Vector3(4.691565f, 45.2253f, 2.52523f);
player.playerorientation = new Vector3(3.897586f, 2.385999f, 0f);
}
else
{
GuiActionGenerateNewMap();
GuiStateBackToGame();
}
DrawMap();
terrain.Start();
}
else
{
ClientCommand(".server " + GameUrl);
}
Mouse.Move += new EventHandler<OpenTK.Input.MouseMoveEventArgs>(Mouse_Move);
Mouse.WheelChanged += new EventHandler<OpenTK.Input.MouseWheelEventArgs>(Mouse_WheelChanged);
if (config3d.ENABLE_BACKFACECULLING)
{
GL.DepthMask(true);
GL.Enable(EnableCap.DepthTest);
GL.CullFace(CullFaceMode.Back);
GL.Enable(EnableCap.CullFace);
}
Keyboard.KeyRepeat = true;
Keyboard.KeyDown += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
Keyboard.KeyUp += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);
materialSlots = data.DefaultMaterialSlots;
GL.Enable(EnableCap.Lighting);
SetAmbientLight(terraincolor);
GL.Enable(EnableCap.ColorMaterial);
GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.AmbientAndDiffuse);
KeyPress += new EventHandler<OpenTK.KeyPressEventArgs>(ManicDiggerGameWindow_KeyPress);
GL.ShadeModel(ShadingModel.Smooth);
System.Windows.Forms.Cursor.Hide();
}
void ManicDiggerGameWindow_KeyPress(object sender, OpenTK.KeyPressEventArgs e)
{
if (e.KeyChar == '&') return;
if ((e.KeyChar == 't' || e.KeyChar == 'T') && GuiTyping == TypingState.None)
{
GuiTyping = TypingState.Typing;
GuiTypingBuffer = "";
FreeMouse = true;
return;
}
if (e.KeyChar == '/' && GuiTyping == TypingState.None)
{
GuiTyping = TypingState.Typing;
GuiTypingBuffer = "/";
return;
}
if (GuiTyping == TypingState.Typing)
{
char c = e.KeyChar; if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || char.IsPunctuation(c) || char.IsSeparator(c) || char.IsSymbol(c))
{
if (GuiTypingBuffer.Length > 64) return;
GuiTypingBuffer += e.KeyChar;
}
}
}
float overheadcameradistance = 10;
float tppcameradistance = 3;
void Mouse_WheelChanged(object sender, OpenTK.Input.MouseWheelEventArgs e)
{
if (keyboardstate[OpenTK.Input.Key.LControl])
{
if (cameratype == CameraType.Overhead)
{
overheadcameradistance -= e.DeltaPrecise;
if (overheadcameradistance < 1) { overheadcameradistance = 1; }
}
if (cameratype == CameraType.Tpp)
{
tppcameradistance -= e.DeltaPrecise;
if (tppcameradistance < 1) { tppcameradistance = 1; }
}
}
}
public bool ENABLE_MAINMENU = false;
private static void SetAmbientLight(Color c)
{
float mult = 1f;
float[] global_ambient = new float[] { (float)c.R / 255f * mult, (float)c.G / 255f * mult, (float)c.B / 255f * mult, 1f };
GL.LightModel(LightModelParameter.LightModelAmbient, global_ambient);
}
protected override void OnClosed(EventArgs e)
{
exit = true;
base.OnClosed(e);
}
string soundbuild = "build.wav";
string sounddestruct = "destruct.wav";
string soundclone = "clone.wav";
//ISoundPlayer soundplayer = new SoundPlayerDummy();
void ClientCommand(string s)
{
if (s == "")
{
return;
}
string[] ss = s.Split(new char[] { ' ' });
if (s.StartsWith("."))
{
try
{
string cmd = ss[0].Substring(1);
string arguments;
if (s.IndexOf(" ") == -1)
{ arguments = ""; }
else
{ arguments = s.Substring(s.IndexOf(" ")); }
arguments = arguments.Trim();
if (cmd == "server" || cmd == "connect")
{
string server = arguments;
if (server.Length == 32)
{
server = "http://minecraft.net/play.jsp?server=" + server;
}
LoadPassword();
ConnectToInternetGame(username, pass, server);
return;
}
else if (cmd == "nick" || cmd == "user" || cmd == "username")
{
username = arguments;
}
else if (cmd == "pass" || cmd == "password")
{
pass = arguments;
}
else if (cmd == "load")
{
if (arguments == "")
{
AddChatline("error: missing arg1 - savename");
}
string filename = arguments;
//if no extension given, then add default
if (filename.IndexOf(".") == -1)
{
filename += MapManipulator.XmlSaveExtension;
}
//mapManipulator.LoadMap(map, filename);
game.LoadState(File.ReadAllBytes(filename));
terrain.UpdateAllTiles();
}
else if (cmd == "save")
{
if (arguments == "")
{
AddChatline("error: missing arg1 - savename");
return;
}
File.WriteAllBytes(arguments + MapManipulator.XmlSaveExtension, game.SaveState());
//mapManipulator.SaveMap(map, arguments + MapManipulator.XmlSaveExtension);
}
else if (cmd == "fps")
{
ENABLE_DRAWFPS = BoolCommandArgument(arguments) || arguments.Trim() == "2";
ENABLE_DRAWFPSHISTORY = arguments.Trim() == "2";
}
else if (cmd == ".test")
{
try
{
for (int x = 1; x < 100; x++)
{
for (int y = 1; y < 100; y++)
{
for (int z = 1; z < 50; z++)
{
SetTileAndUpdate(new Vector3(x, y, z), 5);
}
}
}
}
catch (Exception e) { Console.WriteLine("Cannot update tile! : " + e.Message); }
}
else if (cmd == "savefeature")
{
string[] ss1 = arguments.Split(new[] { ' ' });
int size = int.Parse(ss1[0]);
string filename = ss1[1];
MapStorage m = new MapStorage();
m.Map = new byte[size, size, size];
m.MapSizeX = size;
m.MapSizeY = size;
m.MapSizeZ = size;
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
for (int z = 0; z < size; z++)
{
int xx = (int)player.playerposition.X + 1 + x;
int yy = (int)player.playerposition.Z + 1 + y;
int zz = (int)player.playerposition.Y + z;
if (MapUtil.IsValidPos(map, xx, yy, zz)
&& MapUtil.IsValidPos(m, x, y, z))
{
m.Map[x, y, z] = (byte)map.GetBlock(xx, yy, zz);
}
}
}
}
if (!filename.Contains("."))
{
filename += MapManipulator.XmlSaveExtension;
}
mapManipulator.SaveMap(m, filename);
}
else if (cmd == "fog")
{
int foglevel;
foglevel = int.Parse(arguments);
//if (foglevel <= 16)
//{
// terrain.DrawDistance = (int)Math.Pow(2, foglevel);
//}
//else
{
int foglevel2 = foglevel;
if (foglevel2 > 1024)
{
foglevel2 = 1024;
}
if (foglevel2 % 2 == 0)
{
foglevel2--;
}
the3d.config3d.viewdistance = foglevel2;
//terrain.UpdateAllTiles();
}
}
else if (cmd == "noclip")
{
ENABLE_NOCLIP = BoolCommandArgument(arguments);
}
else if (cmd == "freemove")
{
ENABLE_FREEMOVE = BoolCommandArgument(arguments);
}
else if (cmd == "fov")
{
int arg = int.Parse(arguments);
int minfov = 1;
int maxfov = 179;
if (arg < minfov || arg > maxfov)
{
throw new Exception(string.Format("Valid field of view: {0}-{1}", minfov, maxfov));
}
float fov = (float)(2 * Math.PI * ((float)arg / 360));
this.fov = fov;
OnResize(new EventArgs());
}
else if (cmd == "tp" || cmd == "teleport")
{
string arg = arguments;
bool tp = false;
foreach (var k in clients.Players)
{
if (k.Value.Name.Equals(arg, StringComparison.InvariantCultureIgnoreCase))
{
player.playerposition = k.Value.Position;
tp = true;
}
}
if (!tp)
{