-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame1.cs
822 lines (743 loc) · 24.7 KB
/
Game1.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
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using CS;
using CS.Components;
using Util;
using Entities;
using MG;
using Lidgren.Network;
using Lidgren;
using MoonSharp.Interpreter;
using System.Text;
using MoonSharp.Interpreter.Loaders;
namespace TankComProject
{
delegate void funcD(params object[] objs);
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D texture;
Rectangle distRect;
SpriteFont font;
Global G;
State state;
State guiState;
DebugGraph fpsGraph;
TransformSystem transSys;
MouseFollowSystem mousesys;
DragAndDropSystem ddSys;
RenderSystem renderSys;
PhysicsSystem physics;
CameraFollowSystem cameraFollow;
SpriteSystem sprSys;
PlayerSystem playerSys;
FileStream fs;
Random r;
int eid = -1;
int Clienteid = -1;
NetClient peer;
NetServer server;
NetPeerConfiguration config;
NetPeerConfiguration clientConfig;
float acc = 0;
float serverRate = 1 / 60f;
int entitiesCount = 0;
Assembly GetAssemblyByName(string name)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach(var a in assemblies)
{
if (a.GetName().Name == name)
return a;
}
return null;
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
//TargetElapsedTime = new System.TimeSpan(0, 0, 0, 0, 33/2);
//IsFixedTimeStep = false;
}
public void Start(State s, int id)
{
G.ActivateState(state);
G.deactivateState(guiState.index);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
config = new NetPeerConfiguration("TankCom")
{ Port = 12345 };
clientConfig = new NetPeerConfiguration("TankCom");
peer = new NetClient(clientConfig);
server = new NetServer(config);
#if ANDROID
fs = new FileStream(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "data"), FileMode.OpenOrCreate, FileAccess.ReadWrite);
peer.Start();
var connection = peer.Connect("192.168.1.100", 12345);
#else
//fs = new FileStream("data", FileMode.OpenOrCreate, FileAccess.ReadWrite);
#endif
// TODO: Add your initialization logic here
//graphics.PreferredBackBufferWidth = GraphicsDevice.DisplayMode.Width;
//graphics.PreferredBackBufferHeight = GraphicsDevice.DisplayMode.Height;
//graphics.SynchronizeWithVerticalRetrace = false;
//graphics.IsFullScreen = true;
graphics.ApplyChanges();
fpsGraph = new DebugGraph(GraphicsDevice, new Rectangle(0, 50, 200, 25), 100, 60);
G = new Global();
var monogame = new MG.MonogameSystem(G);
monogame.Game = this;
var rendertargets = new RenderTargets(G);
var camerag = new Camera(G);
TransformSystem transSysG = new TransformSystem(G);
sprSys = new SpriteSystem(G);
var renderer2 = new RenderSystem(G);
var msgSys = new MessageSystem(G);
var GLuaSys = new GlobalLuaSystem(G);
var fontSys = new FontSystem(G);
var callbackRegistry = new RegistrySystem<CallBack>(G, "CallBackRegistry");
callbackRegistry.Register("KillEntity", TimerSystem.KillEntity);
callbackRegistry.Register("Start", Start);
state = new State(G);
var camera = new Camera(state);
guiState = new State(G);
var camera2 = new Camera(guiState);
#if ANDROID
state.camera.scale = new Vector2(4, 4);
guiState.camera.scale = new Vector2(4, 4);
#endif
var boxfunc = GLuaSys.luaScript.Globals.Get("createBoxCreator");
GLuaSys.luaScript.Call(boxfunc, state);
transSys = new TransformSystem(state);
physics = new PhysicsSystem(state);
renderSys = new RenderSystem(state);
cameraFollow = new CameraFollowSystem(state);
mousesys = new MouseFollowSystem(state);
ddSys = new DragAndDropSystem(state);
playerSys = new PlayerSystem(state);
//GUISystem guiSys = new GUISystem(state);
var gridfunc = GLuaSys.luaScript.Globals.Get("CreateGridSystem");
GLuaSys.luaScript.Call(gridfunc, state);
TransformSystem transSys2 = new TransformSystem(guiState);
//PhysicsSystem physics2 = new PhysicsSystem(guiState);
var renderSys2 = new RenderSystem(guiState);
//CameraFollowSystem cameraFollow2 = new CameraFollowSystem(guiState);
//SpriteSystem sprSys2 = new SpriteSystem(guiState);
MouseFollowSystem mousesys2 = new MouseFollowSystem(G);
DragAndDropSystem ddSys2 = new DragAndDropSystem(guiState);
TimerSystem timerSys = new TimerSystem(guiState);
GUISystem guiSys2 = new GUISystem(guiState);
//PlayerSystem playerSys2 = new PlayerSystem(guiState);
r = new Random();
//sprSys.CreateGridFrames("player", 30, 27);
{
sprSys.loadJSON("Content/player.json", "player");
sprSys.loadJSON("Content/button.json", "button");
}
//state.RegisterSystem(transSys);
//state.RegisterSystem(textureSys);
{
Image img = new Image(G, "cursor", Vector2.Zero, new Vector2(0, 0), 0.1f, true);
mousesys2.AddEntity(img.id);
}
{
for(int i = 0; i < 10; ++i)
{
var textObj = new Text();
textObj.Color = Color.White;
textObj.SetFont(fontSys, "font");
textObj.String = "Start";
textObj.Alignment = Align.CENTER;
var id = GUISystem.CreateButton(guiState, textObj, "button", new Rectangle(100 * i + 100, 400, 100, 50), "Start", 0.5f);
}
/*GUISystem.CreateButton(guiState, textObj, "button", new Rectangle(100, 200, 600, 200), "KillEntity", 0.5f);
GUISystem.CreateButton(guiState, textObj, "button", new Rectangle(0, 0, 600, 200), "KillEntity", 0.5f);
GUISystem.CreateButton(guiState, textObj, "button", new Rectangle(600, 200, 600, 200), "KillEntity", 0.5f);
GUISystem.CreateButton(guiState, textObj, "button", new Rectangle(400, 200, 600, 200), "KillEntity", 0.5f);*/
}
/*
var thickness = 32;
{
var e = state.CreateEntity();
Transform t = new Transform();
t.position.Y = graphics.PreferredBackBufferHeight + thickness/2;
t.position.X = graphics.PreferredBackBufferWidth / 2;
transSys.AddComponent(e, t);
var texture = new Texture2(G, "BlockUnit");
//texture.setRect(graphics.PreferredBackBufferWidth, thickness);
texture.srcRect.Width = graphics.PreferredBackBufferWidth/2;
texture.srcRect.Height = thickness/2;
texture.setScale(2, 2);
textureSys.AddComponent(e, texture);
var p = PhysicsObject.CreateBody(physics, graphics.PreferredBackBufferWidth, thickness, (int) FarseerPhysics.Dynamics.BodyType.Static);
physics.AddComponent(e, p);
}
{
var e = state.CreateEntity();
Transform t = new Transform();
t.position.Y = 0- thickness/2;
t.position.X = graphics.PreferredBackBufferWidth / 2;
transSys.AddComponent(e, t);
var texture = new Texture2(G, "BlockUnit");
texture.srcRect.Width = graphics.PreferredBackBufferWidth / 2;
texture.srcRect.Height = thickness / 2;
texture.setScale(2, 2);
textureSys.AddComponent(e, texture);
var p = PhysicsObject.CreateBody(physics, graphics.PreferredBackBufferWidth, thickness, (int)FarseerPhysics.Dynamics.BodyType.Static);
physics.AddComponent(e, p);
}
{
var e = state.CreateEntity();
Transform t = new Transform();
t.position.Y = graphics.PreferredBackBufferHeight / 2;
t.position.X = graphics.PreferredBackBufferWidth + thickness/2;
transSys.AddComponent(e, t);
var texture = new Texture2(G, "BlockUnit");
texture.srcRect.Width = thickness/2;
texture.srcRect.Height = graphics.PreferredBackBufferHeight/2;
texture.setScale(2, 2);
textureSys.AddComponent(e, texture);
var p = PhysicsObject.CreateBody(physics, thickness, graphics.PreferredBackBufferHeight, (int)FarseerPhysics.Dynamics.BodyType.Static);
physics.AddComponent(e, p);
}
{
var e = state.CreateEntity();
Transform t = new Transform();
t.position.Y = graphics.PreferredBackBufferHeight / 2;
t.position.X = 0- thickness / 2;
transSys.AddComponent(e, t);
var texture = new Texture2(G, "BlockUnit");
texture.srcRect.Width = thickness/2;
texture.srcRect.Height = graphics.PreferredBackBufferHeight/2;
texture.setScale(2, 2);
textureSys.AddComponent(e, texture);
var p = PhysicsObject.CreateBody(physics, thickness, graphics.PreferredBackBufferHeight, (int)FarseerPhysics.Dynamics.BodyType.Static);
physics.AddComponent(e, p);
}*/
//G.ActivateState(state);
G.ActivateState(guiState);
//state.Paused = true;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
texture = this.Content.Load<Texture2D>("landscape1");
int winH = texture.Height;
int winW = texture.Width;
distRect = new Rectangle(0, 0, winW, winH);
font = this.Content.Load<SpriteFont>("font");
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
//bool mhold = false;
MouseState mousestate;
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
GC.AddMemoryPressure(20000);
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
{
if (peer.ServerConnection != null)
{
var msg = peer.CreateMessage();
msg.Write(3);
msg.Write(Clienteid);
peer.SendMessage(msg, NetDeliveryMethod.ReliableOrdered);
peer.Shutdown("disconnecting");
}
Exit();
}
if (Keyboard.GetState().IsKeyDown(Keys.F1) && peer.ServerConnection == null)
{
peer.Start();
var connection = peer.Connect("192.168.1.100", 12345);
}
if (Keyboard.GetState().IsKeyDown(Keys.F2) && server.Status == NetPeerStatus.NotRunning)
{
server.Start();
}
NetIncomingMessage message;
while ((message = peer.ReadMessage()) != null)
{
switch (message.MessageType)
{
case NetIncomingMessageType.Data:
// handle custom messages
int type = message.ReadInt32();
if(type == 0)
{
//Clienteid = message.ReadInt32();
Image img2 = new Image(state, "player", new Vector2(100, 100), Vector2.Zero);
var id = img2.id;
ddSys.AddEntity(id);
var textC = (Texture2) renderSys.getComponent(img2.textureIndex);
var sprite = new Sprite(sprSys, textC);
sprite.Play("idle", 1, true);
textC.setScale(2, 2);
var player = new Player(id, physics, textC.textureRect, false);
playerSys.AddComponent(id, player);
//cameraFollow.SetEntity(id);
var msg = peer.CreateMessage();
msg.Write(1);
msg.Write(id);
peer.SendMessage(msg, NetDeliveryMethod.ReliableOrdered);
}
else if (type == 1)
{
var s = new MemoryStream();
int cap = message.ReadInt32();
byte[] bytes = message.ReadBytes(cap);
s.Write(bytes, 0, cap);
s.Position = 0;
BinaryReader reader = new BinaryReader(s);
state.Deserialize(reader);
if(Clienteid == -1)
Clienteid = message.ReadInt32();
playerSys.setControl(Clienteid);
cameraFollow.SetEntity(Clienteid);
}
else if (type == 2)
{
var id = message.ReadInt32();
if (id >= state.EntitiesCount() || id == Clienteid)
continue;
var x = message.ReadSingle();
var y = message.ReadSingle();
var ti = state.getComponentIndex(id, transSys.Index);
var pi = state.getComponentIndex(id, physics.Index);
if (ti != -1)
{
var t = new Vector2();
var t2 = transSys.getComponent(ti);
t.X = x;
t.Y = y;
if(Clienteid == id)
{
if(Vector2.Distance(t, t2.position) > 1)
{
t2.position = t;
}
} else
{
t2.position = t;
}
}
if (pi != -1)
{
var p = physics.getComponent(pi);
var vel = new Vector2(message.ReadSingle(), message.ReadSingle());
if (Clienteid == id)
{
if (Vector2.Distance(p.LinearVelocity, vel) > FarseerPhysics.ConvertUnits.ToSimUnits(1f))
{
p.LinearVelocity = vel;
}
}
else
{
p.LinearVelocity = vel;
}
}
}
else if (type == 3)
{
var id = message.ReadInt32();
if(id != -1)
state.RemoveEntity(id);
} else if (type == 4)
{
Exit();
}
else if (type == 5)
{
var bufferSize = message.ReadInt32();
var input = new MemoryStream(message.ReadBytes(bufferSize));
var binaryReader = new BinaryReader(input);
state.DeserializeEntity(binaryReader);
}
break;
case NetIncomingMessageType.StatusChanged:
// handle connection status messages
switch (message.SenderConnection.Status)
{
case NetConnectionStatus.Connected:
var msg = peer.CreateMessage();
msg.Write(0);
//msg.Write(eid);
peer.SendMessage(msg, NetDeliveryMethod.ReliableOrdered);
break;
}
break;
case NetIncomingMessageType.DebugMessage:
// handle debug messages
// (only received when compiled in DEBUG mode)
Console.WriteLine(message.ReadString());
break;
case NetIncomingMessageType.WarningMessage:
Console.WriteLine(message.ReadString());
break;
/* .. */
case NetIncomingMessageType.ConnectionApproval:
message.SenderConnection.Approve();
break;
/* .. */
default:
Console.WriteLine("unhandled message with type: "
+ message.MessageType);
break;
}
}
while ((message = server.ReadMessage()) != null)
{
switch (message.MessageType)
{
case NetIncomingMessageType.Data:
// handle custom messages
int type = message.ReadInt32();
if (type == 0)
{
Image img2 = new Image(state, "player", new Vector2(100, 100), Vector2.Zero);
var id = img2.id;
ddSys.AddEntity(id);
var textC = (Texture2) renderSys.getComponent(img2.textureIndex);
var sprite = new Sprite(sprSys, textC);
sprite.Play("idle", 1, true);
textC.setRect(100, 100);
var player = new Player(id, physics, textC.textureRect, false);
playerSys.AddComponent(id, player);
//cameraFollow.SetEntity(id);
var msg = server.CreateMessage();
msg.Write(1);
var s = new MemoryStream();
BinaryWriter writer = new BinaryWriter(s);
state.Serialize(writer);
state.addedEntities = new Queue<int>();
writer.Flush();
s.Position = 0;
byte[] bytes = s.ToArray();
msg.Write(bytes.Length);
msg.Write(bytes);
//Clienteid = message.ReadInt32();
msg.Write(id);
writer.Close();
server.SendToAll(msg, NetDeliveryMethod.ReliableOrdered);
}
else if (type == 1)
{
var s = new MemoryStream();
int cap = message.ReadInt32();
byte[] bytes = message.ReadBytes(cap);
s.Write(bytes, 0, cap);
BinaryReader reader = new BinaryReader(s);
state.Deserialize(reader);
Clienteid = message.ReadInt32();
}
else if (type == 2)
{
var id = message.ReadInt32();
var x = message.ReadSingle();
var y = message.ReadSingle();
var ti = state.getComponentIndex(id, transSys.Index);
var pi = state.getComponentIndex(id, physics.Index);
if (ti != -1)
{
var t = transSys.getComponent(ti);
t.position.X = x;
t.position.Y = y;
}
if (pi != -1)
{
var p = physics.getComponent(pi);
var vel = new Vector2(message.ReadSingle(), message.ReadSingle());
p.LinearVelocity = vel;
}
}
else if (type == 3)
{
var id = message.ReadInt32();
if (id != -1)
state.RemoveEntity(id);
}
else if (type == 4)
{
Exit();
}
else if (type == 5)
{
var bufferSize = message.ReadInt32();
var input = new MemoryStream(message.ReadBytes(bufferSize));
var binaryReader = new BinaryReader(input);
var id = state.DeserializeEntity(binaryReader);
foreach (var connection in server.Connections)
{
if (connection != message.SenderConnection)
{
var msg = server.CreateMessage();
msg.Write(5);
var s = new MemoryStream();
BinaryWriter writer = new BinaryWriter(s);
state.SerializeEntity(id, writer);
writer.Flush();
s.Position = 0;
byte[] bytes = s.ToArray();
msg.Write(bytes.Length);
msg.Write(bytes);
//Clienteid = message.ReadInt32();
msg.Write(-1);
writer.Close();
server.SendToAll(msg, NetDeliveryMethod.ReliableOrdered);
}
}
}
break;
case NetIncomingMessageType.StatusChanged:
// handle connection status messages
switch (message.SenderConnection.Status)
{
}
break;
case NetIncomingMessageType.DebugMessage:
// handle debug messages
// (only received when compiled in DEBUG mode)
Console.WriteLine(message.ReadString());
break;
case NetIncomingMessageType.WarningMessage:
Console.WriteLine(message.ReadString());
break;
/* .. */
case NetIncomingMessageType.ConnectionApproval:
message.SenderConnection.Approve();
break;
/* .. */
default:
Console.WriteLine("unhandled message with type: "
+ message.MessageType);
break;
}
}
// TODO: Add your update logic here
var dmx = mousestate.X;
var dmy = mousestate.Y;
mousestate = Mouse.GetState();
var touch = TouchPanel.GetState();
var scale = state.getSystem<Camera>().matrix.Scale;
/*if (G.mouseState.RightButton == ButtonState.Pressed || touch.Count == 2)
{
var e = state.CreateEntity();
Transform t = new Transform();
var pos = new Vector2(mousestate.X, mousestate.Y);
state.camera.toCamera(ref pos);
t.position.X = (float)pos.X/scale.X;
t.position.Y = (float)pos.Y/scale.Y;
if(touch.Count == 2)
{
var pos2 = new Vector2(touch[0].Position.X, touch[0].Position.Y);
state.camera.toCamera(ref pos2);
t.position.X = pos2.X / scale.X;
t.position.Y = pos2.Y / scale.Y;
}
Debug.Assert(!float.IsNaN(t.position.X) && !float.IsNaN(t.position.Y));
transSys.AddComponent(e, t);
Texture2 texture = new Texture2(G, "BlockUnit");
texture.setScale(2f, 2f);
//t.position.X += r.Next() % 3;
textureSys.AddComponent(e, texture);
ddSys.AddEntity(e);
var p = PhysicsObject.CreateBody(physics, texture.textureRect.Width, texture.textureRect.Height, (int)FarseerPhysics.Dynamics.BodyType.Dynamic);
//p.body.IgnoreCCD = true;
//p.body.Restitution = 0;
//p.body.FixedRotation = true;
//p.body.Friction = 1;
//p.body.IsBullet = true;
physics.AddComponent(e, p);
//mousesys.AddEntity(e);
}*/
if (Clienteid != -1)
{
var msg = peer.CreateMessage();
msg.Write(2);
msg.Write(Clienteid);
var t = transSys.getComponent(
state.getComponentIndex(Clienteid, transSys.Index));
var p = physics.getComponent(
state.getComponentIndex(Clienteid, physics.Index));
msg.Write(t.position.X);
msg.Write(t.position.Y);
msg.Write(p.LinearVelocity.X);
msg.Write(p.LinearVelocity.Y);
peer.SendMessage(msg, peer.Connections[0], NetDeliveryMethod.ReliableOrdered);
}
G.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
if(server.Status == NetPeerStatus.Running && state.addedEntities.Count > 0)
{
for (int i = 0; i < state.addedEntities.Count; ++i)
{
var msg = server.CreateMessage();
msg.Write(5);
var id = state.addedEntities.Dequeue();
var s = new MemoryStream();
BinaryWriter writer = new BinaryWriter(s);
state.SerializeEntity(id, writer);
writer.Flush();
s.Position = 0;
byte[] bytes = s.ToArray();
msg.Write(bytes.Length);
msg.Write(bytes);
//Clienteid = message.ReadInt32();
msg.Write(-1);
writer.Close();
server.SendToAll(msg, NetDeliveryMethod.ReliableOrdered);
}
/*
msg.Write(1);
var s = new MemoryStream();
BinaryWriter writer = new BinaryWriter(s);
state.Serialize(writer);
writer.Flush();
s.Position = 0;
byte[] bytes = s.ToArray();
msg.Write(bytes.Length);
msg.Write(bytes);
//Clienteid = message.ReadInt32();
msg.Write(-1);
writer.Close();
server.SendToAll(msg, NetDeliveryMethod.ReliableOrdered);
*/
}
if (peer.Status == NetPeerStatus.Running && state.addedEntities.Count > 0)
{
var msg = peer.CreateMessage();
msg.Write(5);
for (int i = 0; i < state.addedEntities.Count; ++i)
{
var id = state.addedEntities.Dequeue();
var s = new MemoryStream();
BinaryWriter writer = new BinaryWriter(s);
state.SerializeEntity(id, writer);
writer.Flush();
s.Position = 0;
byte[] bytes = s.ToArray();
msg.Write(bytes.Length);
msg.Write(bytes);
//Clienteid = message.ReadInt32();
msg.Write(-1);
writer.Close();
peer.SendMessage(msg, NetDeliveryMethod.ReliableOrdered);
}
/*
msg.Write(1);
var s = new MemoryStream();
BinaryWriter writer = new BinaryWriter(s);
state.Serialize(writer);
writer.Flush();
s.Position = 0;
byte[] bytes = s.ToArray();
msg.Write(bytes.Length);
msg.Write(bytes);
//Clienteid = message.ReadInt32();
msg.Write(-1);
writer.Close();
server.SendToAll(msg, NetDeliveryMethod.ReliableOrdered);
*/
}
entitiesCount = state.EntitiesCount();
acc += G.dt;
if (server.Status == NetPeerStatus.Running && acc >= serverRate)
{
List<int> updatedEntities = transSys.GetUpdated();
foreach (int e in updatedEntities)
{
var msg = server.CreateMessage();
msg.Write(2);
msg.Write(e);
var t = transSys.getComponent(
state.getComponentIndex(e, transSys.Index));
var p = physics.getComponent(
state.getComponentIndex(e, physics.Index));
msg.Write(t.position.X);
msg.Write(t.position.Y);
msg.Write(p.LinearVelocity.X);
msg.Write(p.LinearVelocity.Y);
server.SendToAll(msg, NetDeliveryMethod.ReliableUnordered);
}
acc -= serverRate;
}
//var fpsTime = ((double)1000 / gameTime.ElapsedGameTime.Milliseconds);
//fpsGraph.Update(fpsTime);
if (G.getSystem<MG.MonogameSystem>().keyboardState.IsKeyDown(Keys.F11))
{
fs = new FileStream("data", FileMode.OpenOrCreate, FileAccess.ReadWrite);
G.Serialize(fs);
fs.Close();
}
if (G.getSystem<MG.MonogameSystem>().keyboardState.IsKeyDown(Keys.F12))
{
fs = new FileStream("data", FileMode.OpenOrCreate, FileAccess.ReadWrite);
G.Deserialize(fs);
fs.Close();
}
base.Update(gameTime);
}
Vector2 position = new Vector2(0, 0);
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
var fpsTime = ((double)1000 / gameTime.ElapsedGameTime.Milliseconds);
#if DEBUG
fpsGraph.Update(fpsTime);
#endif
spriteBatch.Begin(sortMode: SpriteSortMode.FrontToBack, samplerState: SamplerState.PointClamp);
{
Vector2 textMiddlePoint = font.MeasureString("HELLO") / 2;
// Places text in center of the screen
G.Render();
#if DEBUG
spriteBatch.DrawString(font, "FPS: " + fpsTime.ToString(), position, Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 0.9f);
spriteBatch.DrawString(font, "Memory:" + GC.GetTotalMemory(false) / 1024, new Vector2(0, 10), Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 0.9f);
fpsGraph.Draw(spriteBatch);
#endif
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}