Skip to content

Commit

Permalink
I want to break free
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkSuckerberg committed Oct 26, 2023
1 parent 2c3bb7e commit 7c9926f
Show file tree
Hide file tree
Showing 37 changed files with 605 additions and 432 deletions.
6 changes: 3 additions & 3 deletions Blocktest/BlocktestGame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public BlocktestGame(string? newIp = null) {
}

public static ContentManager? ContentManager { get; private set; }

public void SetScene(IScene newScene) {
_currentScene?.EndScene();
_currentScene = newScene;
Expand All @@ -40,8 +40,8 @@ protected override void Initialize() {
protected override void LoadContent() {
ContentManager = Content;
BlockSpritesManager.LoadBlockSprites();
if(_ip != null) {

if (_ip != null) {
SetScene(new GameScene(this, true, _ip));
return;
}
Expand Down
2 changes: 1 addition & 1 deletion Blocktest/Code/Block System/BlockSprites.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public sealed class BlockSprites {
public BlockSprites(BlockShared newBlockShared) {
_blockShared = newBlockShared;
SpriteSheet = SpriteSheet.ErrorSpriteSheet;

string path = @"Graphics\Blocks\" + _blockShared.BlockName.ToLower().Replace(" ", "");
try {
BlockSprite =
Expand Down
3 changes: 2 additions & 1 deletion Blocktest/Code/Block System/BlockSpritesManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ public sealed class BlockSpritesManager {
public static Dictionary<string, BlockSprites> AllBlocksSprites { get; private set; }

Check warning on line 7 in Blocktest/Code/Block System/BlockSpritesManager.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'AllBlocksSprites' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

public static void LoadBlockSprites() {
AllBlocksSprites = BlockManagerShared.AllBlocks.ToDictionary(uid => uid.Key, block => new BlockSprites(block.Value));
AllBlocksSprites =
BlockManagerShared.AllBlocks.ToDictionary(uid => uid.Key, block => new BlockSprites(block.Value));
}
}
25 changes: 13 additions & 12 deletions Blocktest/Code/Block System/RenderableTile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,6 @@ namespace Blocktest.Block_System;

public class RenderableTile : TileShared {
public readonly Renderable Renderable;

[Flags]
private enum DirectionalBitmask {
None = 0,
Up = 1,
Down = 2,
Right = 4,
Left = 8
}

public RenderableTile(TileShared tile, bool background) : base(tile.SourceBlock,
tile.Transform.Position / GlobalsShared.GridSize) {
Expand All @@ -32,7 +23,7 @@ public void UpdateAdjacencies(Vector2Int position, TilemapShared tilemap) {
return;
} // If the tile doesn't smooth, don't even try

var dirBitmask = DirectionalBitmask.None;
DirectionalBitmask dirBitmask = DirectionalBitmask.None;

if (HasSmoothableTile(position + Vector2Int.Up, tilemap)) {
dirBitmask |= DirectionalBitmask.Up;
Expand All @@ -48,7 +39,7 @@ public void UpdateAdjacencies(Vector2Int position, TilemapShared tilemap) {
}

Renderable.Appearance = BlockSpritesManager.AllBlocksSprites[SourceBlock.BlockUid].SpriteSheet
.OrderedSprites[(int) dirBitmask];
.OrderedSprites[(int)dirBitmask];
}

/// <summary>
Expand All @@ -61,7 +52,8 @@ private bool HasSmoothableTile(Vector2Int position, TilemapShared tilemap) {
if (tilemap.TryGetTile(position, out TileShared? tile)) {
return SourceBlock.SmoothSelf
? IsSameTileType(tile)
: tile.SourceBlock.BlockUid != "air"; // Don't smooth with air, possibly find nicer way to do this later.
: tile.SourceBlock.BlockUid !=
"air"; // Don't smooth with air, possibly find nicer way to do this later.
}
return false;
}
Expand All @@ -72,4 +64,13 @@ private bool HasSmoothableTile(Vector2Int position, TilemapShared tilemap) {
/// <param name="otherTile">The other tile to check.</param>
/// <returns>Whether or not the other block is the same type as the current tile</returns>
private bool IsSameTileType(TileShared otherTile) => otherTile.SourceBlock == SourceBlock;

[Flags]
private enum DirectionalBitmask {
None = 0,
Up = 1,
Down = 2,
Right = 4,
Left = 8
}
}
18 changes: 9 additions & 9 deletions Blocktest/Code/Block System/RenderableTilemap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
namespace Blocktest.Block_System;

public class RenderableTilemap {
private readonly TilemapShared _tilemap;

private readonly RenderableTile[,] _renderables;
private readonly Camera _camera;

/// <summary>
/// A list of <see cref="Vector2Int" />s that specify which blocks should be refreshed when a tile is placed/destroyed.
/// Defaults to the changed block and all cardinal directions.
/// </summary>
private static readonly List<Vector2Int> Adjacencies = new()
{ Vector2Int.Zero, Vector2Int.Up, Vector2Int.Down, Vector2Int.Left, Vector2Int.Right };
{ Vector2Int.Up, Vector2Int.Down, Vector2Int.Left, Vector2Int.Right };

private readonly Camera _camera;

private readonly RenderableTile[,] _renderables;
private readonly TilemapShared _tilemap;


public RenderableTilemap(TilemapShared newTilemap, Camera camera) {
Expand All @@ -28,15 +28,15 @@ public RenderableTilemap(TilemapShared newTilemap, Camera camera) {
private void OnTilemapChanged(TileShared tile, Vector2Int location) {
_camera.RenderedComponents.Remove(_renderables[location.X, location.Y].Renderable);


foreach (Vector2Int dir in Adjacencies) {
if (!_tilemap.TryGetTile(location + dir, out TileShared? adjacentTile)) {
continue;
}
_renderables[location.X + dir.X, location.Y + dir.Y].UpdateAdjacencies(location + dir, _tilemap);
}

RenderableTile newTile = new RenderableTile(tile, _tilemap.Background);
RenderableTile newTile = new(tile, _tilemap.Background);
_renderables[location.X, location.Y] = newTile;
newTile.UpdateAdjacencies(location, _tilemap);
_camera.RenderedComponents.Add(newTile.Renderable);
Expand All @@ -49,7 +49,7 @@ private void UpdateRenderables() {
if (!_tilemap.TryGetTile(new Vector2Int(x, y), out TileShared? tile)) {
continue;
}
RenderableTile newTile = new RenderableTile(tile, _tilemap.Background);
RenderableTile newTile = new(tile, _tilemap.Background);
_renderables[x, y] = newTile;
_camera.RenderedComponents.Add(newTile.Renderable);
newTile.UpdateAdjacencies(new Vector2Int(x, y), _tilemap);
Expand Down
127 changes: 97 additions & 30 deletions Blocktest/Code/Networking/Client.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,35 @@
using Blocktest.Rendering;
using LiteNetLib;
using LiteNetLib.Utils;
using Shared.Code;
using Shared.Code.Components;
using Shared.Code.Networking;
using Shared.Code.Packets;
namespace Blocktest.Networking;

public sealed class Client {
private readonly Camera _camera;
private readonly EventBasedNetListener _listener;
private readonly NetManager _manager;
public NetPeer? Server { get; private set; }
public TickBuffer ClientTickBuffer = new(0);
private readonly Dictionary<int, Renderable> _playerRenderables = new();

private readonly WorldState _worldState;
public TickBuffer ClientTickBuffer;

public Client() {
public Client(WorldState worldState, Camera camera) {
_worldState = worldState;
_camera = camera;
ClientTickBuffer = new TickBuffer(0, _worldState);
_listener = new EventBasedNetListener();
_manager = new NetManager(_listener);
_listener.NetworkReceiveEvent += NetworkReceiveEvent;
_listener.PeerConnectedEvent += PeerConnected;
_listener.PeerDisconnectedEvent += PeerDisconnected;
_manager.Start();
}

public NetPeer? Server { get; private set; }

public void Start(string ip, int port, string key) {
_manager.Connect(ip, port, key);
}
Expand All @@ -29,6 +42,20 @@ public void Update() {
_manager.PollEvents();
}

private void PeerConnected(NetPeer peer) {
Console.WriteLine("Connected to server");

Transform newTransform = new(new Vector2Int(256, 128));
Renderable newRenderable = new(newTransform, Layer.Player, Drawable.ErrorDrawable, Color.Orange);
_worldState.PlayerPositions.Add(peer.RemoteId, newTransform);
_playerRenderables.Add(peer.RemoteId, newRenderable);
_camera.RenderedComponents.Add(newRenderable);
}

private void PeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) {
Console.WriteLine("Disconnected from server");
}

/// <summary>
/// Recieve network events from LiteNetLib
/// </summary>
Expand All @@ -40,15 +67,24 @@ private void NetworkReceiveEvent(NetPeer peer, NetPacketReader packetReader, byt
DeliveryMethod deliveryMethod) {
if (Server == null) {
Server = peer;
WorldDownload worldPacket = new();
byte packetByte = packetReader.GetByte();
PacketType packetType = (PacketType)packetByte;

PacketType packetType = (PacketType)packetReader.GetByte();
if (packetType != PacketType.WorldDownload) {
Console.WriteLine("Bad packet!!!");
return;
}
worldPacket.Deserialize(packetReader);
ClientTickBuffer = new TickBuffer(worldPacket.TickNum);
ClientTickBuffer.AddPacket(worldPacket);

int sourceId = packetReader.GetInt();

WorldDownload worldPacket = HandlePacket<WorldDownload>(packetReader, sourceId);
worldPacket.Process(_worldState);
ClientTickBuffer = new TickBuffer(worldPacket.TickNum, _worldState);

SendPacket(new PeerEvent {
SourceId = Server.RemoteId,
TickNum = worldPacket.TickNum,
Type = PeerEvent.PeerEventType.PlayerList
});
} else {
HandlePackets(packetReader);
}
Expand All @@ -58,45 +94,76 @@ private void NetworkReceiveEvent(NetPeer peer, NetPacketReader packetReader, byt
/// Handles packets after the first.
/// </summary>
/// <param name="packetReader">Contains the packet sent by the server.</param>
private void HandlePackets(NetPacketReader packetReader) {
/// ACCEPTS PacketType:SourceID:TickNum:Packet
private void HandlePackets(NetDataReader packetReader) {
byte packetByte = packetReader.GetByte();
PacketType packetType = (PacketType)packetByte;

int sourceId = packetReader.GetInt();

switch (packetType) {
case PacketType.TileChange:
HandleTileChange(packetReader);
ClientTickBuffer.AddPacket(HandlePacket<TileChange>(packetReader, sourceId));
break;
case PacketType.BreakTile:
HandleBreakTile(packetReader);
ClientTickBuffer.AddPacket(HandlePacket<BreakTile>(packetReader, sourceId));
break;
case PacketType.MovePlayer:
ClientTickBuffer.AddPacket(HandlePacket<MovePlayer>(packetReader, sourceId));
break;
case PacketType.PlayerList:
ClientTickBuffer.AddPacket(HandlePacket<PlayerList>(packetReader, sourceId));
break;
case PacketType.PeerEvent:
PeerEvent eventPacket = new() { SourceId = sourceId, TickNum = packetReader.GetUShort() };
eventPacket.Deserialize(packetReader);
HandleEvent(eventPacket);
break;
case PacketType.WorldDownload:
default:
Console.WriteLine("Bad packet!!!");
break;
}
}

private void HandleTileChange(NetPacketReader packetReader) {
TileChange tileChange = new();
tileChange.Deserialize(packetReader);
ClientTickBuffer.AddPacket(tileChange);
private T HandlePacket<T>(NetDataReader packetReader, int sourceId) where T : IPacket, new() {
T packet = new() { SourceId = sourceId, TickNum = packetReader.GetUShort() };
packet.Deserialize(packetReader);
return packet;
}

private void HandleBreakTile(NetPacketReader packetReader) {
BreakTile breakTile = new();
breakTile.Deserialize(packetReader);
ClientTickBuffer.AddPacket(breakTile);
}
private void HandleEvent(PeerEvent peerEvent) {
switch (peerEvent.Type) {
case PeerEvent.PeerEventType.PeerDisconnect:
Console.WriteLine("Player disconnected");

public void SendTileChange(TileChange tileChange) {
NetDataWriter writer = new();
writer.Put((byte)PacketType.TileChange);
writer.Put(tileChange);
Server?.Send(writer, DeliveryMethod.ReliableUnordered);
_worldState.PlayerPositions.Remove(peerEvent.SourceId);
_camera.RenderedComponents.Remove(_playerRenderables[peerEvent.SourceId]);
_playerRenderables.Remove(peerEvent.SourceId);
break;
case PeerEvent.PeerEventType.PeerConnect:
Console.WriteLine("New player connected");

Transform newTransform = new(new Vector2Int(256, 128));
Renderable newRenderable = new(newTransform, Layer.Player, Drawable.ErrorDrawable, Color.Orange);
_worldState.PlayerPositions.Add(peerEvent.SourceId, newTransform);
_playerRenderables.Add(peerEvent.SourceId, newRenderable);
_camera.RenderedComponents.Add(newRenderable);
break;
case PeerEvent.PeerEventType.PlayerList:
default:
throw new ArgumentOutOfRangeException(nameof(peerEvent), peerEvent, null);
}
}

public void SendBreakTile(BreakTile breakTile) {
// SENDS PacketType:TickNum:Packet
public void SendPacket(IPacket packet, DeliveryMethod deliveryMethod = DeliveryMethod.ReliableUnordered) {
NetDataWriter writer = new();
writer.Put((byte)PacketType.BreakTile);
writer.Put(breakTile);
Server?.Send(writer, DeliveryMethod.ReliableUnordered);

writer.Put((byte)packet.GetPacketType());
writer.Put(packet.TickNum);
//ID is not needed for client to server packets
writer.Put(packet);
Server?.Send(writer, deliveryMethod);
}
}
7 changes: 3 additions & 4 deletions Blocktest/Code/Rendering/Camera.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
namespace Blocktest.Rendering;

public sealed class Camera {
private static readonly int EnumCount = Enum.GetValues(typeof(Layer)).Length;
private readonly Color _backgroundColor;
private readonly Vector2 _size;

public readonly List<Renderable> RenderedComponents = new();

public Rectangle RenderLocation;
public readonly RenderTarget2D RenderTarget;
public Vector2 Position;

public Rectangle RenderLocation;

public Camera(Vector2 position, Vector2 size, GraphicsDevice graphicsDevice, Color? backgroundColor = null) {
Position = position;
_size = size;
Expand Down Expand Up @@ -56,8 +57,6 @@ public void Draw(GraphicsDevice graphics, SpriteBatch spriteBatch) {
graphics.SetRenderTarget(null);
}

private static readonly int EnumCount = Enum.GetValues(typeof(Layer)).Length;

public Vector2 CameraToWorldPos(Vector2 mouseState) => new(
(mouseState.X - RenderLocation.X) / RenderLocation.Width * RenderTarget.Width + Position.X, Position.Y +
RenderTarget.Height -
Expand Down
2 changes: 1 addition & 1 deletion Blocktest/Code/Rendering/Drawable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ public Drawable(string fileName, Rectangle? bounds = null) {
throw new Exception($"Could not load drawable {fileName}, content manager not initialized.");
Bounds = bounds ?? Texture.Bounds;
}

public static Drawable ErrorDrawable { get; } = new(@"Graphics\Blocks\error");
}
2 changes: 1 addition & 1 deletion Blocktest/Code/Rendering/Renderable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public enum Layer {
public sealed class Renderable {
public readonly Transform Transform;
public Drawable? Appearance;
public Color RenderColor;
public Layer Layer;
public Color RenderColor;

public Renderable(Transform transform, Layer layer = Layer.Default, Drawable? appearance = null,
Color? renderColor = null) {
Expand Down
2 changes: 1 addition & 1 deletion Blocktest/Code/Rendering/SpriteSheet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ public SpriteSheet(string filename, int frameColumns, int frameRows, int padding
OrderedSprites[frameColumn + frameRow * frameColumns] = newDrawable;
}
}

public static SpriteSheet ErrorSpriteSheet { get; } = new(@"Graphics\Blocks\error", 1, 1);
}
Loading

0 comments on commit 7c9926f

Please sign in to comment.