Skip to content

Commit

Permalink
General code clean up (#378)
Browse files Browse the repository at this point in the history
* temp variables begone

* awaiting time

* code clean up :3

* add notice in license
  • Loading branch information
themonarchoftime authored Jun 19, 2023
1 parent 6900dd1 commit 775f950
Show file tree
Hide file tree
Showing 30 changed files with 76 additions and 88 deletions.
8 changes: 4 additions & 4 deletions Obsidian.API/Noise/ContinentSelector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ public override double GetValue(double x, double y, double z)
var noise = TerrainNoise.GetValue(x, y, z);
return noise switch
{
double n when n <= -0.18991 => Math.Max(-1.0, Math.Pow(2*n+1, 3)-0.6) + ContinentOceanOffset,
double n when n > -0.18991 && n <= 0.07646 => (Math.Pow(n, 3) * 50) + (0.1 * n) + ContinentOceanOffset,
double n when n > 0.07646 && n <= 0.4487 => 0.03 + ContinentOceanOffset,
double n when n > 0.4487 && n <= 0.942 => Math.Min(Math.Pow(3 * n - 1.9, 3) + 0.2 + ContinentOceanOffset, 1),
_ when noise <= -0.18991 => Math.Max(-1.0, Math.Pow(2*noise+1, 3)-0.6) + ContinentOceanOffset,
_ when noise > -0.18991 && noise <= 0.07646 => (Math.Pow(noise, 3) * 50) + (0.1 * noise) + ContinentOceanOffset,
_ when noise > 0.07646 && noise <= 0.4487 => 0.03 + ContinentOceanOffset,
_ when noise > 0.4487 && noise <= 0.942 => Math.Min(Math.Pow(3 * noise - 1.9, 3) + 0.2 + ContinentOceanOffset, 1),
_ => 1.0
};
}
Expand Down
7 changes: 3 additions & 4 deletions Obsidian.API/Noise/VoronoiTunnels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,9 @@ public override double GetValue(double x, double y, double z)
}
}

VoronoiCell primary, secondary, tertiary;
Unsafe.SkipInit(out primary);
Unsafe.SkipInit(out secondary);
Unsafe.SkipInit(out tertiary);
Unsafe.SkipInit(out VoronoiCell primary);
Unsafe.SkipInit(out VoronoiCell secondary);
Unsafe.SkipInit(out VoronoiCell tertiary);
GetMin(cells, ref primary, ref secondary, ref tertiary);

if (primary.DistanceToPoint < 0.123)
Expand Down
2 changes: 1 addition & 1 deletion Obsidian.API/_Types/Vector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ public readonly override bool Equals(object? obj)
/// <summary>
/// Enumerable array of Cardinal Directions
/// </summary>
public static readonly IEnumerable<Vector> CardinalDirs = new[] { Vector.North, Vector.South, Vector.West, Vector.East };
public static readonly IEnumerable<Vector> CardinalDirs = new[] { North, South, West, East };

internal static readonly Vector[] AllDirections = new[] { North, South, West, East, Up, Down };

Expand Down
2 changes: 1 addition & 1 deletion Obsidian.ConsoleApp/Logging/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ void PrintLinePrefix()

if (message.IsNullOrEmpty())
{
this.LogTrace($"Empty log message sent. Dumping stacktrace:\n{new System.Diagnostics.StackTrace().ToString().Replace("\n", " ")}");
this.LogTrace($"Empty log message sent. Dumping stacktrace:\n{new StackTrace().ToString().Replace("\n", " ")}");
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,12 @@ private static void SetStateFromIdMethod(string fullName, CodeBuilder stateBuild
{
var name = property.Name.Replace("Is", string.Empty);

var method = "";

if (property.Type == "bool")
method = $"bool.Parse(values[{count}]);";
else if (property.Type == "int")
method = $"int.Parse(values[{count}]);";
else
method = $"Enum.Parse<{property.Type}>(values[{count}]);";
var method = property.Type switch
{
"bool" => $"bool.Parse(values[{count}]);",
"int" => $"int.Parse(values[{count}]);",
_ => $"Enum.Parse<{property.Type}>(values[{count}]);"
};

stateBuilder.Line($"this.{name} = {method}");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ private static void GenerateDamageTypes(Codec[] damageTypes, CodeBuilder builder

if (value.ValueKind == JsonValueKind.String && name != "MessageId")
{
if (name == "Scaling")
name = "DamageScaling";
else if (name == "Effects")
name = "DamageEffects";
name = name switch
{
"Scaling" => "DamageScaling",
"Effects" => "DamageEffects",
_ => name
};

builder.Append($"{name}.{value.GetString()!.ToPascalCase()}, ");
}
Expand Down
8 changes: 4 additions & 4 deletions Obsidian/BlockUpdate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ internal IBlock? Block
set
{
_block = value;
if (value is IBlock b)
if (value is IBlock)
{
if (TagsRegistry.Blocks.GravityAffected.Entries.Contains(b.RegistryId))
if (TagsRegistry.Blocks.GravityAffected.Entries.Contains(value.RegistryId))
{
Delay = 1;
}
else if (b.Material == Material.Lava)
else if (value.Material == Material.Lava)
{
Delay = 40;
}
else if (b.Material == Material.Water)
else if (value.Material == Material.Water)
{
Delay = 5;
}
Expand Down
8 changes: 4 additions & 4 deletions Obsidian/ChunkData/BiomeContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,17 @@ public Biome Get(int x, int y, int z)
return this.Palette.GetValueFromIndex(storageId);
}

public override async Task WriteToAsync(MinecraftStream stream)
public async override Task WriteToAsync(MinecraftStream stream)
{
stream.WriteUnsignedByte(this.BitsPerEntry);
await stream.WriteUnsignedByteAsync(this.BitsPerEntry);

await this.Palette.WriteToAsync(stream);

stream.WriteVarInt(this.DataArray.storage.Length);
await stream.WriteVarIntAsync(this.DataArray.storage.Length);

long[] storage = this.DataArray.storage;
for (int i = 0; i < storage.Length; i++)
stream.WriteLong(storage[i]);
await stream.WriteLongAsync(storage[i]);
}

public override void WriteTo(MinecraftStream stream)
Expand Down
7 changes: 3 additions & 4 deletions Obsidian/ChunkData/BlockStateContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,12 @@ public void Fill(IBlock block)
private short GetNonAirBlocks()
{
int validBlocksCount = 0;
int indexOne, indexTwo, indexThree;

if (!Palette.TryGetId(BlocksRegistry.Air, out indexOne))
if (!Palette.TryGetId(BlocksRegistry.Air, out var indexOne))
goto NO_AIR;
if (!Palette.TryGetId(BlocksRegistry.CaveAir, out indexTwo))
if (!Palette.TryGetId(BlocksRegistry.CaveAir, out var indexTwo))
goto NO_CAVE;
if (!Palette.TryGetId(BlocksRegistry.VoidAir, out indexThree))
if (!Palette.TryGetId(BlocksRegistry.VoidAir, out var indexThree))
goto TWO_INDEXES;

// 1 1 1
Expand Down
4 changes: 2 additions & 2 deletions Obsidian/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ public Client(Socket socket, ServerConfiguration config, int playerId, Server or
var packetId = 0;
var packetData = Array.Empty<byte>();

using (var packetStream = new MinecraftStream(receivedData))
await using (var packetStream = new MinecraftStream(receivedData))
{
try
{
Expand Down Expand Up @@ -746,7 +746,7 @@ internal async Task SendChunkAsync(Chunk chunk)

private async Task SendServerBrand()
{
using var stream = new MinecraftStream();
await using var stream = new MinecraftStream();
await stream.WriteStringAsync(Server.Brand);
await QueuePacketAsync(new PluginMessagePacket("minecraft:brand", stream.ToArray()));
Logger.LogDebug("Sent server brand.");
Expand Down
3 changes: 1 addition & 2 deletions Obsidian/Commands/Parsers/LocationTypeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ public override bool TryParseArgument(string input, CommandContext context, out
var splitted = input.Split(' ');
var location = new VectorF();

var ctx = context;
for (int i = 0; i < splitted.Length; i++)
{
var text = splitted[i];
Expand All @@ -34,7 +33,7 @@ public override bool TryParseArgument(string input, CommandContext context, out
}
else if (text.StartsWith("~"))
{
if (ctx.Player is not Player player)
if (context.Player is not Player player)
{
result = default;
return false;
Expand Down
3 changes: 1 addition & 2 deletions Obsidian/Commands/Parsers/PlayerTypeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ public PlayerTypeParser() : base(48, "obsidian:player")

public override bool TryParseArgument(string input, CommandContext context, out IPlayer result)
{
var ctx = context;
var server = (Server)ctx.Server;
var server = (Server)context.Server;

Player player = null;

Expand Down
2 changes: 1 addition & 1 deletion Obsidian/Entities/FallingBlock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public async override Task TickAsync()
checkedBlocks.Add(upcomingBlockPos);

var upcomingBlock = await world.GetBlockAsync(upcomingBlockPos);
if (upcomingBlock is IBlock block && !TagsRegistry.Blocks.ReplaceableByLiquid.Entries.Contains(block.RegistryId) && !block.IsLiquid)
if (upcomingBlock is IBlock && !TagsRegistry.Blocks.ReplaceableByLiquid.Entries.Contains(upcomingBlock.RegistryId) && !upcomingBlock.IsLiquid)
{
await ConvertToBlock(upcomingBlockPos + Vector.Up);
}
Expand Down
1 change: 0 additions & 1 deletion Obsidian/Entities/Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -947,7 +947,6 @@ internal async Task<bool> UpdateChunksAsync(bool unloadAll = false, int distance
List<(int X, int Z)> clientUnneededChunks = new(client.LoadedChunks);

(int playerChunkX, int playerChunkZ) = Position.ToChunkCoord();
(int lastPlayerChunkX, int lastPlayerChunkZ) = LastPosition.ToChunkCoord();

int dist = distance < 1 ? ClientInformation.ViewDistance : distance;
for (int x = playerChunkX + dist; x > playerChunkX - dist; x--)
Expand Down
6 changes: 3 additions & 3 deletions Obsidian/Hosting/DefaultServerEnvironment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ private static async Task<ServerConfiguration> LoadServerConfigurationAsync()

if (configFile.Exists)
{
using var configFileStream = configFile.OpenRead();
await using var configFileStream = configFile.OpenRead();
return await configFileStream.FromJsonAsync<ServerConfiguration>()
?? throw new Exception("Server config file exists, but is invalid. Is it corrupt?");
}
Expand Down Expand Up @@ -117,7 +117,7 @@ private static async Task<List<ServerWorld>> LoadServerWorldsAsync()

if (worldsFile.Exists)
{
using var worldsFileStream = worldsFile.OpenRead();
await using var worldsFileStream = worldsFile.OpenRead();
return await worldsFileStream.FromJsonAsync<List<ServerWorld>>()
?? throw new Exception("A worlds file does exist, but is invalid. Is it corrupt?");
}
Expand All @@ -134,7 +134,7 @@ private static async Task<List<ServerWorld>> LoadServerWorldsAsync()
}
};

using var fileStream = worldsFile.Create();
await using var fileStream = worldsFile.Create();
await worlds.ToJsonAsync(fileStream);

return worlds;
Expand Down
2 changes: 1 addition & 1 deletion Obsidian/Net/MinecraftStream.Writing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1004,7 +1004,7 @@ public async Task WriteSlotAsync(ItemStack slot)
writer.WriteByte("Count", (byte)slot.Count);

writer.EndCompound();
writer.TryFinish();
await writer.TryFinishAsync();
}
}

Expand Down
6 changes: 3 additions & 3 deletions Obsidian/Net/Packets/Play/Serverbound/PlayerActionPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public partial class PlayerActionPacket : IServerboundPacket
public async ValueTask HandleAsync(Server server, Player player)
{
IBlock? b = await player.world.GetBlockAsync(Position);
if (b is not IBlock block)
if (b is not IBlock)
return;

if (Status == PlayerActionStatus.FinishedDigging || (Status == PlayerActionStatus.StartedDigging && player.Gamemode == Gamemode.Creative))
Expand All @@ -36,7 +36,7 @@ public async ValueTask HandleAsync(Server server, Player player)
SequenceID = Sequence
});

var blockBreakEvent = await server.Events.BlockBreak.InvokeAsync(new BlockBreakEventArgs(server, player, block, Position));
var blockBreakEvent = await server.Events.BlockBreak.InvokeAsync(new BlockBreakEventArgs(server, player, b, Position));
if (blockBreakEvent.Handled)
return;
}
Expand All @@ -45,7 +45,7 @@ public async ValueTask HandleAsync(Server server, Player player)
{
Player = player.Uuid,
Packet = this
}, block);
}, b);
}
}

Expand Down
6 changes: 3 additions & 3 deletions Obsidian/Net/Packets/Play/Serverbound/UseItemOnPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ public async ValueTask HandleAsync(Server server, Player player)

var b = await player.world.GetBlockAsync(position);

if (b is not IBlock interactedBlock)
if (b is not IBlock)
return;

if (TagsRegistry.Blocks.PlayersCanInteract.Entries.Contains(interactedBlock.RegistryId) && !player.Sneaking)
if (TagsRegistry.Blocks.PlayersCanInteract.Entries.Contains(b.RegistryId) && !player.Sneaking)
{
await server.Events.PlayerInteract.InvokeAsync(new PlayerInteractEventArgs(player)
{
Item = currentItem,
Block = interactedBlock,
Block = b,
BlockLocation = this.Position,
});

Expand Down
6 changes: 3 additions & 3 deletions Obsidian/Plugins/PluginProviders/RemotePluginProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,23 +178,23 @@ private PluginContainer CompilePluginFiles((string owner, string name) repositor

private async Task<JsonDocument> ScanDirectoryAsync(string owner, string name, string tree)
{
using var stream = await GetFileStreamAsync($"https://api.github.com/repos/{owner}/{name}/git/trees/{tree}?recursive=1");
await using var stream = await GetFileStreamAsync($"https://api.github.com/repos/{owner}/{name}/git/trees/{tree}?recursive=1");
if (stream == null)
return null;
return await JsonDocument.ParseAsync(stream);
}

private async Task<JsonDocument> GetJsonFileAsync(string owner, string name, string tree, string path)
{
using var stream = await GetFileStreamAsync($"https://www.github.com/{owner}/{name}/raw/{tree}/{path}");
await using var stream = await GetFileStreamAsync($"https://www.github.com/{owner}/{name}/raw/{tree}/{path}");
if (stream == null)
return null;
return await JsonDocument.ParseAsync(stream);
}

private async Task<XmlDocument> GetXmlFileAsync(string owner, string name, string tree, string path)
{
using var stream = await GetFileStreamAsync($"https://www.github.com/{owner}/{name}/raw/{tree}/{path}");
await using var stream = await GetFileStreamAsync($"https://www.github.com/{owner}/{name}/raw/{tree}/{path}");
if (stream == null)
return null;

Expand Down
8 changes: 4 additions & 4 deletions Obsidian/Server.Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ await player.SendSoundAsync(SoundEffectBuilder.Create(SoundId.BlockEnderChestOpe
.WithSoundPosition(blockPosition.SoundPosition)
.Build());
}
else if (type == Material.Furnace || type == Material.BlastFurnace || type == Material.Smoker)
else if (type is Material.Furnace or Material.BlastFurnace or Material.Smoker)
{
InventoryType actualType = type switch
{
Expand Down Expand Up @@ -268,11 +268,11 @@ await player.SendSoundAsync(SoundEffectBuilder.Create(SoundId.BlockBarrelOpen, S
new NbtTag<string>("CustomName", container.Title.ToJson())
};

player.world.SetBlockEntity(blockPosition, tileEntity);
await player.world.SetBlockEntity(blockPosition, tileEntity);
}
else if (tileEntity is NbtCompound dataCompound)
else if (tileEntity is NbtCompound)
{
if (dataCompound.TryGetTag("Items", out var tag))
if (tileEntity.TryGetTag("Items", out var tag))
{
var items = tag as NbtList;

Expand Down
2 changes: 1 addition & 1 deletion Obsidian/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ private async Task AcceptClientsAsync()
if (Config.IpWhitelistEnabled && !Config.WhitelistedIPs.Contains(ip))
{
_logger.LogInformation("{ip} is not whitelisted. Closing connection", ip);
socket.Disconnect(false);
await socket.DisconnectAsync(false);
return;
}

Expand Down
4 changes: 2 additions & 2 deletions Obsidian/Utilities/Collections/DataArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ internal sealed class DataArray
// Multiplier and shifter should be selected with index [bitsPerEntry]
// This trick may yield incorrect results when "dividing" numbers out of range 0..4096,
// but DataArray shouldn't be used for that many elements
private static ReadOnlySpan<int> Multipliers => new int[] { 0, 1, 1, 3121, 1, 2731, 3277, 3641, 1, 2341, 2731, 3277, 3277, 1, 1, 1, 1, 2731, 2731, 2731, 2731, 2731, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
private static ReadOnlySpan<int> Shifts => new int[] { 0, 6, 5, 16, 4, 15, 15, 15, 3, 14, 14, 14, 14, 2, 2, 2, 2, 13, 13, 13, 13, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private static ReadOnlySpan<int> Multipliers => new[] { 0, 1, 1, 3121, 1, 2731, 3277, 3641, 1, 2341, 2731, 3277, 3277, 1, 1, 1, 1, 2731, 2731, 2731, 2731, 2731, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
private static ReadOnlySpan<int> Shifts => new[] { 0, 6, 5, 16, 4, 15, 15, 15, 3, 14, 14, 14, 14, 2, 2, 2, 2, 13, 13, 13, 13, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

public int BitsPerEntry => bitsPerEntry;
public int Length => entriesCount;
Expand Down
Loading

0 comments on commit 775f950

Please sign in to comment.