From ed2bdce38e95715b863af5df609269657773b3a5 Mon Sep 17 00:00:00 2001 From: jvbsl Date: Sun, 12 Dec 2021 17:39:34 +0100 Subject: [PATCH] Small refactoring * Introduced nullability * Fixed some nullability problems * Refactored old C# style to more recent ones * Removed unused usings * Removed some unused code * Fixed some spelling mistakes * Updated engenious to newer version(for better nullability compatibility) --- .../OctoAwesome.Basics/Biomes/BiomeBase.cs | 47 +- .../Biomes/FlatlandBiome.cs | 13 +- .../Biomes/HighMountainBiome.cs | 12 +- .../OctoAwesome.Basics/Biomes/HillsBiome.cs | 10 +- .../OctoAwesome.Basics/Biomes/IBiome.cs | 14 +- .../Biomes/LandBiomeGenerator.cs | 27 +- .../Biomes/LargeBiomeBase.cs | 36 +- .../Biomes/OceanBiomeGenerator.cs | 20 +- .../Biomes/SurfaceBiomeGenerator.cs | 24 +- .../Climate/ComplexClimateMap.cs | 15 +- .../OctoAwesome.Basics/ComplexPlanet.cs | 31 +- .../ComplexPlanetGenerator.cs | 8 +- .../OctoAwesome.Basics/DebugMapGenerator.cs | 14 +- .../Blocks/BirchWoodBlockDefinition.cs | 20 +- .../Blocks/BlueCottonBlockDefinition.cs | 21 +- .../Blocks/BrickBlockDefinition.cs | 20 +- .../Blocks/CactusBlockDefinition.cs | 29 +- .../Definitions/Blocks/DirtBlockDefinition.cs | 25 +- .../Blocks/GrassBlockDefinition.cs | 45 +- .../Blocks/GravelBlockDefinition.cs | 23 +- .../Blocks/GreenCottonBlockDefinition.cs | 23 +- .../Blocks/GreystoneBlockDefinition.cs | 23 +- .../Definitions/Blocks/IceBlockDefinition.cs | 23 +- .../Blocks/LeavesBlockDefinition.cs | 24 +- .../Blocks/OrangeLeavesBlockDefinition.cs | 23 +- .../Blocks/PlankBlockDefinition.cs | 31 +- .../Blocks/RedCottonBlockDefinition.cs | 23 +- .../Blocks/RedPlankBlockDefinition.cs | 31 +- .../Definitions/Blocks/SandBlockDefinition.cs | 22 +- .../Definitions/Blocks/SnowBlockDefinition.cs | 48 +- .../Blocks/StoneBlockDefinition.cs | 24 +- .../Blocks/StoneBrickBlockDefinition.cs | 23 +- .../Blocks/TanCottonBlockDefinition.cs | 23 +- .../Blocks/WaterBlockDefinition.cs | 19 +- .../Definitions/Blocks/WoodBlockDefinition.cs | 24 +- .../Definitions/Items/Axe.cs | 8 +- .../Definitions/Items/AxeDefinition.cs | 29 +- .../Definitions/Items/Bucket.cs | 14 +- .../Definitions/Items/BucketDefinition.cs | 28 +- .../Definitions/Items/ChestItem.cs | 14 +- .../Definitions/Items/ChestItemDefinition.cs | 19 +- .../Definitions/Items/Hammer.cs | 7 +- .../Definitions/Items/HammerDefinition.cs | 20 +- .../Definitions/Items/Hoe.cs | 7 +- .../Definitions/Items/HoeDefinition.cs | 20 +- .../Definitions/Items/PickAxeDefinition.cs | 55 +- .../Definitions/Items/Pickaxe.cs | 8 +- .../Definitions/Items/Shovel.cs | 9 +- .../Definitions/Items/ShovelDefinition.cs | 28 +- .../Definitions/Items/Sword.cs | 7 +- .../Definitions/Items/SwordDefinition.cs | 20 +- .../Materials/BrickMaterialDefinition.cs | 12 +- .../Materials/CactusMaterialDefinition.cs | 12 +- .../Materials/ClayMaterialDefinition.cs | 12 +- .../Materials/CottonMaterialDefinition.cs | 12 +- .../Materials/DirtMaterialDefinition.cs | 12 +- .../Materials/GlassMaterialDefinition.cs | 12 +- .../Materials/GravelMaterialDefinition.cs | 12 +- .../Materials/IceMaterialDefinition.cs | 12 +- .../Materials/LeaveMaterialDefinition.cs | 12 +- .../Materials/SandMaterialDefinition.cs | 12 +- .../Materials/SnowMaterialDefinition.cs | 12 +- .../Materials/StoneMaterialDefinition.cs | 12 +- .../Materials/WaterMaterialDefinition.cs | 14 +- .../Materials/WoodMaterialDefinition.cs | 12 +- .../Definitions/Trees/BirchTreeDefinition.cs | 37 +- .../Definitions/Trees/CactusTreeDefinition.cs | 28 +- .../Definitions/Trees/OakTreeDefinition.cs | 37 +- .../Definitions/Trees/SpruceTreeDefinition.cs | 37 +- .../Entities/WauziEntity.cs | 16 +- .../EntityComponents/BodyPowerComponent.cs | 12 +- .../EntityCollisionComponent.cs | 6 +- .../EntityComponents/ForceComponent.cs | 10 +- .../EntityComponents/GravityComponent.cs | 9 +- .../EntityComponents/MassComponent.cs | 8 +- .../EntityComponents/MoveableComponent.cs | 11 +- .../EntityComponents/PowerComponent.cs | 11 +- .../UIComponents/TransferUIComponent.cs | 10 +- .../UIComponents/UIComponent.cs | 9 +- OctoAwesome/OctoAwesome.Basics/Extension.cs | 24 +- .../FunctionBlocks/Chest.cs | 14 +- .../OctoAwesome.Basics/ITreeDefinition.cs | 4 - .../OctoAwesome.Basics/Noise/INoise.cs | 18 +- .../Noise/PerlinNoiseGenerator.cs | 535 ------------------ .../Noise/SimplexNoiseGenerator.cs | 251 +++----- .../OctoAwesome.Basics.csproj | 6 +- .../AccelerationComponent.cs | 8 +- .../BlockInteractionComponent.cs | 33 +- .../CollisionComponent.cs | 2 + .../FunctionalBlockInteractionComponent.cs | 10 +- .../SimulationComponents/MoveComponent.cs | 6 +- .../OctoAwesome.Basics/TreePopulator.cs | 12 +- .../UI/Screens/TransferScreen.cs | 6 +- .../OctoAwesome.Basics/WauziPopulator.cs | 20 +- .../Components/AssetComponent.cs | 11 +- .../Controls/CompassControl.cs | 10 +- .../Controls/CrosshairControl.cs | 22 +- .../Controls/GroupBox.cs | 47 +- .../Controls/HealthBarControl.cs | 6 +- .../Controls/InventoryControl.cs | 15 +- .../OctoAwesome.Client.UI/Controls/Line.cs | 3 +- .../OctoAwesome.Client.UI.csproj | 3 +- .../OctoAwesome.Client.UI/ResourcePack.cs | 14 +- OctoAwesome/OctoAwesome.Client.UI/Tools.cs | 3 +- .../Cache/ChunkRendererDbContext.cs | 32 +- .../Cache/VerticesForChunk.cs | 13 +- .../Components/CameraComponent.cs | 5 +- .../Components/ChunkRenderer.cs | 112 ++-- .../Components/EntityGameComponent.cs | 14 +- .../Components/KeyMapper.cs | 33 +- .../Components/PlayerComponent.cs | 101 +++- .../Components/SimulationComponent.cs | 17 +- .../VertexPositionNormalTextureLight.cs | 4 +- .../VertexPositionNormalTexturePacked.cs | 3 - .../ContainerResourceManager.cs | 102 ++-- .../Control/BindingsOptionControl.cs | 5 +- .../Control/DebugControl.cs | 28 +- .../Control/ExtensionsOptionControl.cs | 26 +- .../Control/OptionsOptionControl.cs | 28 +- .../Control/ResourcePacksOptionControl.cs | 38 +- .../Control/SceneControl.cs | 84 ++- .../Control/ToolbarControl.cs | 28 +- .../OctoAwesome.Client/Crew/CrewMember.cs | 53 +- .../OctoAwesome.Client.csproj | 9 +- OctoAwesome/OctoAwesome.Client/OctoGame.cs | 63 +-- OctoAwesome/OctoAwesome.Client/Program.cs | 16 +- .../OctoAwesome.Client/Screens/BaseScreen.cs | 31 +- .../Screens/ConnectionScreen.cs | 2 +- .../Screens/CreateUniverseScreen.cs | 16 +- .../Screens/CreditsScreen.cs | 10 +- .../Screens/CrewMemberScreen.cs | 12 +- .../OctoAwesome.Client/Screens/GameScreen.cs | 2 - .../Screens/InventoryScreen.cs | 38 +- .../OctoAwesome.Client/Screens/LoadScreen.cs | 38 +- .../Screens/LoadingScreen.cs | 10 +- .../OctoAwesome.Client/Screens/MainScreen.cs | 2 - .../Screens/MessageScreen.cs | 4 +- .../Screens/OptionsScreen.cs | 5 - .../Screens/QuoteProvider.cs | 6 +- OctoAwesome/OctoAwesome.Client/Settings.cs | 113 +--- .../OctoAwesome.Database/Checks/ICheckable.cs | 5 +- ...lidException.cs => InvalidKeyException.cs} | 8 +- .../Checks/ValueFileCheck.cs | 49 +- OctoAwesome/OctoAwesome.Database/Database.cs | 30 +- .../OctoAwesome.Database/DatabaseContext.cs | 19 +- .../OctoAwesome.Database/Defragmentation.cs | 6 - .../Expressions/InstanceCreator.cs | 4 +- OctoAwesome/OctoAwesome.Database/GuidTag.cs | 25 +- .../OctoAwesome.Database/IDatabaseContext.cs | 4 +- OctoAwesome/OctoAwesome.Database/ITag.cs | 6 +- OctoAwesome/OctoAwesome.Database/IdManager.cs | 11 +- OctoAwesome/OctoAwesome.Database/IdTag.cs | 25 +- OctoAwesome/OctoAwesome.Database/Key.cs | 48 +- OctoAwesome/OctoAwesome.Database/KeyStore.cs | 6 +- .../OctoAwesome.Database.csproj | 3 +- OctoAwesome/OctoAwesome.Database/Operation.cs | 2 - OctoAwesome/OctoAwesome.Database/Reader.cs | 9 +- .../Threading/DatabaseLock.cs | 20 +- .../Threading/DatabaseLockMonitor.cs | 8 +- .../Threading/DatabaseOperation.cs | 3 +- OctoAwesome/OctoAwesome.Database/Value.cs | 7 +- .../OctoAwesome.Database/ValueStore.cs | 7 +- OctoAwesome/OctoAwesome.Database/Writer.cs | 40 +- .../CommandParameter.cs | 12 +- .../Commands/ChunkCommands.cs | 8 +- .../Commands/GeneralCommands.cs | 9 +- .../Commands/NotificationCommands.cs | 7 +- .../Commands/PlayerCommands.cs | 14 +- .../OctoAwesome.GameServer.csproj | 1 + OctoAwesome/OctoAwesome.GameServer/Program.cs | 17 +- .../OctoAwesome.GameServer/ServerHandler.cs | 19 +- .../SimulationManagerTests.cs | 2 - OctoAwesome/OctoAwesome.Network/BaseClient.cs | 20 +- OctoAwesome/OctoAwesome.Network/Client.cs | 9 +- .../OctoAwesome.Network/ConnectedClient.cs | 24 +- .../NetworkPersistenceManager.cs | 62 +- .../NetworkUpdateManager.cs | 8 +- .../OctoAwesome.Network.csproj | 6 +- .../OctoAwesome.Network/OctoNetworkStream.cs | 16 +- .../OctoAwesome.Network/OfficialCommand.cs | 10 +- OctoAwesome/OctoAwesome.Network/Package.cs | 26 +- .../Pooling/PackagePool.cs | 16 +- OctoAwesome/OctoAwesome.Network/Server.cs | 9 +- .../ServerDataNotification.cs | 15 +- OctoAwesome/OctoAwesome.Network/Settings.cs | 28 +- .../OctoAwesome.Network/SimulationManager.cs | 67 +-- OctoAwesome/OctoAwesome.Network/Startup.cs | 9 +- OctoAwesome/OctoAwesome.PoC/Cache.cs | 1 - OctoAwesome/OctoAwesome.PoC/CacheService.cs | 4 +- OctoAwesome/OctoAwesome.PoC/ComponentCache.cs | 11 +- .../OctoAwesome.PoC/DependencyAgent.cs | 6 - OctoAwesome/OctoAwesome.PoC/DependencyItem.cs | 3 - OctoAwesome/OctoAwesome.PoC/DependencyLeaf.cs | 8 - OctoAwesome/OctoAwesome.PoC/DependencyTree.cs | 2 - OctoAwesome/OctoAwesome.PoC/Progam.cs | 6 +- OctoAwesome/OctoAwesome.PoC/Rx/Relay.cs | 9 +- OctoAwesome/OctoAwesome.PoC/Rx/UpdateHub.cs | 1 - .../OctoAwesome.Runtime/DatabaseProvider.cs | 16 +- .../OctoAwesome.Runtime/DefinitionManager.cs | 26 +- .../DiskPersistenceManager.cs | 68 +-- .../OctoAwesome.Runtime/ExtensionLoader.cs | 25 +- .../OctoAwesome.Runtime/GameService.cs | 9 +- .../OctoAwesome.Runtime/IPlayerController.cs | 18 - .../OctoAwesome.Runtime.csproj | 5 +- .../OctoAwesome.Runtime/ResourceManager.cs | 133 ++--- .../OctoAwesome.Tests/CollisionTests.cs | 6 - .../OctoAwesome.Tests/GlobalChunkCacheTest.cs | 4 - OctoAwesome/OctoAwesome.Tests/Index2Tests.cs | 5 - OctoAwesome/OctoAwesome.Tests/Index3Tests.cs | 6 - .../OctoAwesome.Tests/LocalChunkCacheTest.cs | 2 - .../OctoAwesome.Tests/SettingsManagerTests.cs | 12 - .../StandaloneTypeContainerTests.cs | 12 +- OctoAwesome/OctoAwesome/Awaiter.cs | 46 +- OctoAwesome/OctoAwesome/Block.cs | 23 +- OctoAwesome/OctoAwesome/BlockInfo.cs | 26 +- OctoAwesome/OctoAwesome/Caching/Cache.cs | 55 +- .../OctoAwesome/Caching/CacheService.cs | 15 +- .../OctoAwesome/Caching/ChunkColumnCache.cs | 16 +- .../Caching/ComponentContainerCache.cs | 2 +- .../OctoAwesome/Caching/GenericCaster.cs | 4 +- .../OctoAwesome/Caching/LoadingMode.cs | 3 + .../Caching/PositionComponentCache.cs | 47 +- OctoAwesome/OctoAwesome/Chunk.cs | 151 +---- OctoAwesome/OctoAwesome/ChunkColumn.cs | 52 +- OctoAwesome/OctoAwesome/ClientType.cs | 11 +- OctoAwesome/OctoAwesome/CollisionPlane.cs | 55 +- OctoAwesome/OctoAwesome/ComponentContainer.cs | 38 +- .../OctoAwesome/Components/Comparer.cs | 69 --- .../OctoAwesome/Components/Component.cs | 12 +- .../OctoAwesome/Components/ComponentList.cs | 31 +- .../OctoAwesome/Components/IComponent.cs | 7 +- .../Components/IComponentContainer.cs | 9 + .../Components/IContainsComponents.cs | 15 - .../Components/IEntityComponent.cs | 10 +- .../IEntityNotificationComponent.cs | 6 +- .../Components/IFunctionalBlockComponent.cs | 9 +- .../OctoAwesome/Components/IHoldComponent.cs | 11 +- .../Components/SimulationComponent.cs | 132 ++--- OctoAwesome/OctoAwesome/Coordinate.cs | 30 +- .../Definitions/BlockDefinition.cs | 10 +- .../Definitions/IBlockDefinition.cs | 3 +- .../Definitions/IDefinitionManager.cs | 5 +- .../Definitions/IFluidMaterialDefinition.cs | 9 +- .../Definitions/IGasMaterialDefinition.cs | 9 +- OctoAwesome/OctoAwesome/Definitions/IItem.cs | 4 +- .../Definitions/IItemDefinition.cs | 3 +- .../Definitions/ISolidMaterialDefinition.cs | 8 +- .../OctoAwesome/Definitions/Items/Hand.cs | 10 +- .../Definitions/Items/HandDefinition.cs | 28 +- .../OctoAwesome/Definitions/Items/Item.cs | 14 +- OctoAwesome/OctoAwesome/Entity.cs | 8 +- .../EntityComponents/AnimationComponent.cs | 10 +- .../EntityComponents/BodyComponent.cs | 10 +- .../EntityComponents/BoxCollisionComponent.cs | 8 +- .../EntityComponents/CollisionComponent.cs | 7 +- .../EntityComponents/ControllableComponent.cs | 14 +- .../EntityComponents/HeadComponent.cs | 12 +- .../EntityComponents/InstanceComponent.cs | 15 +- .../EntityComponents/InventoryComponent.cs | 23 +- .../LocalChunkCacheComponent.cs | 12 +- .../EntityComponents/PositionComponent.cs | 33 +- .../EntityComponents/RenderComponent.cs | 13 +- .../EntityComponents/ToolBarComponent.cs | 16 +- OctoAwesome/OctoAwesome/EntityList.cs | 20 +- .../OctoAwesome/Expressions/ArrayOfList.cs | 23 - OctoAwesome/OctoAwesome/Extension.cs | 9 +- .../OctoAwesome/FailEntityChunkArgs.cs | 4 +- OctoAwesome/OctoAwesome/FunctionalBlock.cs | 13 +- OctoAwesome/OctoAwesome/GlobalChunkCache.cs | 29 +- OctoAwesome/OctoAwesome/IChunk.cs | 10 +- OctoAwesome/OctoAwesome/IChunkColumn.cs | 7 +- OctoAwesome/OctoAwesome/IEntityList.cs | 8 +- OctoAwesome/OctoAwesome/IExtension.cs | 9 +- OctoAwesome/OctoAwesome/IExtensionLoader.cs | 4 +- OctoAwesome/OctoAwesome/IExtensionResolver.cs | 4 +- OctoAwesome/OctoAwesome/IFluidInventory.cs | 8 +- OctoAwesome/OctoAwesome/IGlobalChunkCache.cs | 6 +- OctoAwesome/OctoAwesome/IInventoryable.cs | 9 +- OctoAwesome/OctoAwesome/ILocalChunkCache.cs | 6 +- OctoAwesome/OctoAwesome/IMapGenerator.cs | 1 - .../OctoAwesome/IPersistenceManager.cs | 22 +- OctoAwesome/OctoAwesome/IPlanet.cs | 5 +- OctoAwesome/OctoAwesome/IResourceManager.cs | 46 +- OctoAwesome/OctoAwesome/ISettings.cs | 2 +- OctoAwesome/OctoAwesome/ITypeContainer.cs | 30 +- OctoAwesome/OctoAwesome/IUniverse.cs | 1 - OctoAwesome/OctoAwesome/Index2.cs | 31 +- OctoAwesome/OctoAwesome/Index3.cs | 41 +- .../Information/BlockHitInformation.cs | 13 +- ...stanceBehaviour.cs => InstanceBehavior.cs} | 2 +- OctoAwesome/OctoAwesome/InventorySlot.cs | 15 +- OctoAwesome/OctoAwesome/LocalBuilder.cs | 22 +- OctoAwesome/OctoAwesome/LocalChunkCache.cs | 63 +-- OctoAwesome/OctoAwesome/Logging/ILogger.cs | 12 +- OctoAwesome/OctoAwesome/Logging/Logger.cs | 18 +- OctoAwesome/OctoAwesome/Logging/NullLogger.cs | 23 +- .../Notifications/BlockChangedNotification.cs | 5 +- .../Notifications/BlockNotificationType.cs | 10 +- .../BlocksChangedNotification.cs | 13 +- .../Notifications/DefaultChannels.cs | 2 + .../Notifications/EntityNotification.cs | 24 +- .../FunctionalBlockNotification.cs | 19 +- .../Notifications/IChunkNotification.cs | 10 +- .../Notifications/INotificationSubject.cs | 10 +- .../OctoAwesome/Notifications/IUpdateHub.cs | 6 +- .../OctoAwesome/Notifications/Notification.cs | 11 +- .../PropertyChangedNotification.cs | 13 +- .../Notifications/SerializableNotification.cs | 7 +- .../OctoAwesome/Notifications/UpdateHub.cs | 8 +- OctoAwesome/OctoAwesome/OctoAwesome.csproj | 7 +- .../OctoAwesome/OctoMath/Polynomial.cs | 17 +- OctoAwesome/OctoAwesome/Planet.cs | 15 +- OctoAwesome/OctoAwesome/PlanetIndex3.cs | 29 +- OctoAwesome/OctoAwesome/Player.cs | 28 +- OctoAwesome/OctoAwesome/Pooling/ChunkPool.cs | 20 +- OctoAwesome/OctoAwesome/Pooling/IPool.cs | 16 +- .../OctoAwesome/Pooling/IPoolElement.cs | 1 + OctoAwesome/OctoAwesome/Pooling/Pool.cs | 15 +- OctoAwesome/OctoAwesome/RemoteEntity.cs | 11 +- OctoAwesome/OctoAwesome/Rx/ConcurrentRelay.cs | 10 +- .../OctoAwesome/Rx/IObservableExtension.cs | 14 +- OctoAwesome/OctoAwesome/Rx/Relay.cs | 14 +- .../Serialization/ChunkColumnDbContext.cs | 14 +- .../Serialization/ChunkDiffDbContext.cs | 11 +- .../OctoAwesome/Serialization/ChunkDiffTag.cs | 16 +- .../ComponentContainerComponentDbContext.cs | 16 +- .../Entities/ComponentContainerDbContext.cs | 29 +- .../Entities/ComponentContainerDefinition.cs | 28 +- .../Serialization/IDatabaseProvider.cs | 2 + .../Serialization/IIdentification.cs | 6 +- .../Serialization/ISerializable.cs | 2 + .../Serialization/ISerializableEnumerable.cs | 8 +- .../Serialization/IdDatabaseContext.cs | 5 - .../OctoAwesome/Serialization/Index2Tag.cs | 12 +- .../OctoAwesome/Serialization/Index3Tag.cs | 13 +- .../Serialization/SerializableCollection.cs | 9 +- .../SerializableDatabaseContext.cs | 10 +- .../Serialization/SerializationIdAttribute.cs | 11 +- .../OctoAwesome/Serialization/Serializer.cs | 15 +- .../Serialization/TypeExtension.cs | 6 +- .../SerializationIdTypeProvider.cs | 20 +- .../Services/BlockCollectionService.cs | 22 +- .../OctoAwesome/Services/BlockVolumeState.cs | 15 +- OctoAwesome/OctoAwesome/Simulation.cs | 43 +- .../OctoAwesome/StandaloneTypeContainer.cs | 90 ++- OctoAwesome/OctoAwesome/Startup.cs | 38 +- OctoAwesome/OctoAwesome/SumTypes/Selection.cs | 6 +- .../Threading/CountedScopeSemaphore.cs | 63 +-- .../OctoAwesome/Threading/LockSemaphore.cs | 17 +- OctoAwesome/OctoAwesome/TypeContainer.cs | 63 +-- OctoAwesome/OctoAwesome/Universe.cs | 3 - OctoAwesome/OctoAwesome/UpdateableEntity.cs | 12 - OctoAwesome/OctoAwesome/Wall.cs | 7 +- 353 files changed, 2251 insertions(+), 5266 deletions(-) delete mode 100644 OctoAwesome/OctoAwesome.Basics/Noise/PerlinNoiseGenerator.cs rename OctoAwesome/OctoAwesome.Database/Checks/{KeyInvalidException.cs => InvalidKeyException.cs} (67%) delete mode 100644 OctoAwesome/OctoAwesome/Components/Comparer.cs create mode 100644 OctoAwesome/OctoAwesome/Components/IComponentContainer.cs delete mode 100644 OctoAwesome/OctoAwesome/Components/IContainsComponents.cs delete mode 100644 OctoAwesome/OctoAwesome/Expressions/ArrayOfList.cs rename OctoAwesome/OctoAwesome/{InstanceBehaviour.cs => InstanceBehavior.cs} (69%) diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/BiomeBase.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/BiomeBase.cs index f7fcda99..ece1f0a3 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/BiomeBase.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/BiomeBase.cs @@ -1,31 +1,27 @@ -using OctoAwesome.Noise; - -using System; -using System.Buffers; +using System.Buffers; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { + public abstract class BiomeBase : IBiome { - public IPlanet Planet { get; private set; } - - public List SubBiomes { get; protected set; } - - public INoise BiomeNoiseGenerator { get; protected set; } - - public float MinValue { get; protected set; } - - public float MaxValue { get; protected set; } - - public float ValueRangeOffset { get; protected set; } - - public float ValueRange { get; protected set; } - - public BiomeBase(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange) + public IPlanet Planet { get; } + + public List SubBiomes { get; } + + public INoise BiomeNoiseGenerator { get; } + + public float MinValue { get; } + + public float MaxValue { get; } + + public float ValueRangeOffset { get; } + + public float ValueRange { get; } + + protected BiomeBase(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange, INoise biomeNoiseGenerator) { SubBiomes = new List(); Planet = planet; @@ -33,11 +29,11 @@ public BiomeBase(IPlanet planet, float minValue, float maxValue, float valueRang MaxValue = maxValue; ValueRangeOffset = valueRangeOffset; ValueRange = valueRange; + BiomeNoiseGenerator = biomeNoiseGenerator; } - - public virtual float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) + + public virtual void GetHeightmap(Index2 chunkIndex, float[] heightmap) { - chunkIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y); float[] heights = ArrayPool.Shared.Rent(Chunk.CHUNKSIZE_X * Chunk.CHUNKSIZE_Y); for (int i = 0; i < heights.Length; i++) @@ -52,7 +48,6 @@ public virtual float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) } } ArrayPool.Shared.Return(heights); - return heightmap; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/FlatlandBiome.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/FlatlandBiome.cs index 85bec8eb..43c5b831 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/FlatlandBiome.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/FlatlandBiome.cs @@ -1,18 +1,13 @@ -using OctoAwesome.Noise; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { - class FlatlandBiome : BiomeBase + public class FlatlandBiome : BiomeBase { public FlatlandBiome(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange) - : base(planet, minValue, maxValue, valueRangeOffset, valueRange) + : base(planet, minValue, maxValue, valueRangeOffset, valueRange, + new SimplexNoiseGenerator(planet.Seed + 2) { FrequencyX = 1f / 256, FrequencyY = 1f / 256, Persistence = 0.25f, Octaves = 3, Factor = 1f }) { - BiomeNoiseGenerator = new SimplexNoiseGenerator(planet.Seed + 2) { FrequencyX = 1f / 256, FrequencyY = 1f / 256, Persistance = 0.25f, Octaves = 3, Factor = 1f }; - } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/HighMountainBiome.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/HighMountainBiome.cs index b9b9aab3..1cd69673 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/HighMountainBiome.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/HighMountainBiome.cs @@ -1,17 +1,13 @@ -using OctoAwesome.Noise; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { - class HighMountainBiome : BiomeBase + public class HighMountainBiome : BiomeBase { public HighMountainBiome(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange) - : base(planet, minValue, maxValue, valueRangeOffset, valueRange) + : base(planet, minValue, maxValue, valueRangeOffset, valueRange, + new SimplexNoiseGenerator(planet.Seed + 2) { FrequencyX = 1f / 256, FrequencyY = 1f / 256, FrequencyZ = 1f / 256, Persistence = 0.5f, Octaves = 6, Factor = 1f }) { - BiomeNoiseGenerator = new SimplexNoiseGenerator(planet.Seed + 2) { FrequencyX = 1f / 256, FrequencyY = 1f / 256, FrequencyZ = 1f / 256, Persistance = 0.5f, Octaves = 6, Factor = 1f }; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/HillsBiome.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/HillsBiome.cs index 3a4cbdd4..47ef9a33 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/HillsBiome.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/HillsBiome.cs @@ -1,17 +1,13 @@ -using OctoAwesome.Noise; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { public class HillsBiome : BiomeBase { public HillsBiome(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange) - : base(planet, minValue, maxValue, valueRangeOffset, valueRange) + : base(planet, minValue, maxValue, valueRangeOffset, valueRange, + new SimplexNoiseGenerator(planet.Seed + 2) { FrequencyX = 1f / 256, FrequencyY = 1f / 256, FrequencyZ = 1f / 256, Persistence = 0.4f, Octaves = 4, Factor = 1f }) { - BiomeNoiseGenerator = new SimplexNoiseGenerator(planet.Seed + 2) { FrequencyX = 1f / 256, FrequencyY = 1f / 256, FrequencyZ = 1f / 256, Persistance = 0.4f, Octaves = 4, Factor = 1f }; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/IBiome.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/IBiome.cs index a306bebc..94fe2914 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/IBiome.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/IBiome.cs @@ -1,23 +1,19 @@ -using OctoAwesome.Noise; - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { + public interface IBiome { + IPlanet Planet { get; } float MinValue { get; } float MaxValue { get; } - float ValueRangeOffset { get; } float ValueRange { get; } - + INoise BiomeNoiseGenerator { get; } - float[] GetHeightmap(Index2 chunkIndex, float[] heightmap); + void GetHeightmap(Index2 chunkIndex, float[] heightmap); } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/LandBiomeGenerator.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/LandBiomeGenerator.cs index 9d250c92..b5ec7d80 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/LandBiomeGenerator.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/LandBiomeGenerator.cs @@ -1,32 +1,24 @@ -using OctoAwesome.Noise; - -using System; +using System; using System.Buffers; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { + public class LandBiomeGenerator : LargeBiomeBase { - public LandBiomeGenerator(IPlanet planet, float minVal, float maxVal, float valueRangeOffset, float valueRange) - : base(planet, valueRangeOffset, valueRange) + public LandBiomeGenerator(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange) + : base(planet, minValue, maxValue, valueRangeOffset, valueRange, + new SimplexNoiseGenerator(planet.Seed + 1) { FrequencyX = 1f / 1000, FrequencyY = 1f / 1000, Persistence = 0.25f, Octaves = 5, Factor = 1f }) { - BiomeNoiseGenerator = new SimplexNoiseGenerator(planet.Seed + 1) { FrequencyX = 1f / 1000, FrequencyY = 1f / 1000, Persistance = 0.25f, Octaves = 5, Factor = 1f }; - - MinValue = minVal; - MaxValue = maxVal; - SubBiomes.Add(new FlatlandBiome(planet, 0f, 0.2f, 0f, 0.1f)); SubBiomes.Add(new HillsBiome(planet, 0.3f, 0.5f, 0.1f, 0.4f)); SubBiomes.Add(new HighMountainBiome(planet, 0.8f, 1f, 0.2f, 0.8f)); SortSubBiomes(); } - - public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) + + public override void GetHeightmap(Index2 chunkIndex, float[] heightmap) { Index2 blockIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y); @@ -54,7 +46,7 @@ public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) int biome2; int biome1 = ChooseBiome(region, out biome2); - float interpolationValue = 0f; + float interpolationValue; if (biome2 != -1) { interpolationValue = CalculateInterpolationValue(region, SubBiomes[biome1], SubBiomes[biome2]); @@ -66,7 +58,6 @@ public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) } ArrayPool.Shared.Return(regions); ArrayPool.Shared.Return(biomeValues); - return heightmap; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/LargeBiomeBase.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/LargeBiomeBase.cs index 6802a207..f156f361 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/LargeBiomeBase.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/LargeBiomeBase.cs @@ -1,32 +1,28 @@ -using OctoAwesome.Noise; - -using System; -using System.Collections.Generic; +using System; +using System.Diagnostics; using System.Linq; -using System.Text; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { + public abstract class LargeBiomeBase : BiomeBase { - - public LargeBiomeBase(IPlanet planet, float valueRangeOffset, float valueRange) - : base(planet, 0, 0, valueRangeOffset, valueRange) + public LargeBiomeBase(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange, INoise biomeNoiseGenerator) + : base(planet, minValue, maxValue, valueRangeOffset, valueRange, biomeNoiseGenerator) { } - protected void SortSubBiomes() { - SubBiomes = SubBiomes.OrderBy(a => a.MinValue).ToList(); + SubBiomes.Sort((a, b) => a.MinValue.CompareTo(b.MinValue)); if (SubBiomes.Count > 0 && (SubBiomes.First().MinValue > 0f || SubBiomes.Last().MaxValue < 1f)) { throw new InvalidOperationException("MinValue oder MaxValue der Biome nicht in gültigem Bereich"); } } - - protected IBiome ChooseBiome(float value, out IBiome secondBiome) + protected IBiome? ChooseBiome(float value, out IBiome? secondBiome) { secondBiome = null; bool betweenPossible = false; @@ -43,7 +39,6 @@ protected IBiome ChooseBiome(float value, out IBiome secondBiome) } return null; } - protected int ChooseBiome(float value, out int secondBiome) { secondBiome = -1; @@ -61,35 +56,28 @@ protected int ChooseBiome(float value, out int secondBiome) } return -1; } - - protected float CalculateInterpolationValue(float region, out IBiome biome1, out IBiome biome2) + protected float CalculateInterpolationValue(float region, out IBiome? biome1, out IBiome? biome2) { biome1 = ChooseBiome(region, out biome2); return CalculateInterpolationValue(region, biome1, biome2); } - - protected float CalculateInterpolationValue(float region, IBiome biome1, IBiome biome2) + protected float CalculateInterpolationValue(float region, IBiome? biome1, IBiome? biome2) { if (biome2 != null) { + Debug.Assert(biome1 != null, nameof(biome1) + " != null"); float diff = biome2.MinValue - biome1.MaxValue; region -= biome1.MaxValue; region /= diff; return CurveFunction(region); } - else if (biome1 != null) - { - return 0f; - } + return 0f; } - protected virtual float CurveFunction(float inputValue) { return inputValue; } - - public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) => base.GetHeightmap(chunkIndex, heightmap); } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/OceanBiomeGenerator.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/OceanBiomeGenerator.cs index af3312be..364a446d 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/OceanBiomeGenerator.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/OceanBiomeGenerator.cs @@ -1,22 +1,13 @@ -using OctoAwesome.Noise; - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OctoAwesome.Basics.Biomes +namespace OctoAwesome.Basics.Biomes { + public class OceanBiomeGenerator : LargeBiomeBase { - public OceanBiomeGenerator(IPlanet planet, float minVal, float maxVal, float valueRangeOffset, float valueRange) - : base(planet, valueRangeOffset, valueRange) + public OceanBiomeGenerator(IPlanet planet, float minValue, float maxValue, float valueRangeOffset, float valueRange) + : base(planet, minValue, maxValue, valueRangeOffset, valueRange, null!) // TODO: currently no noise value is used for the biome floor { - MinValue = minVal; - MaxValue = maxVal; } - - public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) + public override void GetHeightmap(Index2 chunkIndex, float[] heightmap) { chunkIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y); @@ -28,7 +19,6 @@ public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) heightmap[(y * Chunk.CHUNKSIZE_X) + x] = 0f; } } - return heightmap; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Biomes/SurfaceBiomeGenerator.cs b/OctoAwesome/OctoAwesome.Basics/Biomes/SurfaceBiomeGenerator.cs index 3b39266a..fd1638fb 100644 --- a/OctoAwesome/OctoAwesome.Basics/Biomes/SurfaceBiomeGenerator.cs +++ b/OctoAwesome/OctoAwesome.Basics/Biomes/SurfaceBiomeGenerator.cs @@ -1,27 +1,22 @@ -using OctoAwesome.Noise; - -using System; +using System; using System.Buffers; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Biomes { + public class SurfaceBiomeGenerator : LargeBiomeBase { public int SeaLevel { get; - private set; } - public SurfaceBiomeGenerator(IPlanet planet, int seaLevel) - : base(planet, 0f, 1f) + : base(planet, 0f, 1f, 0f, 1f, + new SimplexNoiseGenerator(planet.Seed) { FrequencyX = 1f / 10000, FrequencyY = 1f / 10000, Factor = 1f }) { SeaLevel = seaLevel; - BiomeNoiseGenerator = new SimplexNoiseGenerator(planet.Seed) { FrequencyX = 1f / 10000, FrequencyY = 1f / 10000, Factor = 1f }; float offset = (float)seaLevel / (Planet.Size.Z * Chunk.CHUNKSIZE_Z); @@ -30,7 +25,6 @@ public SurfaceBiomeGenerator(IPlanet planet, int seaLevel) SortSubBiomes(); } - protected override float CurveFunction(float inputValue) { return CurveFunction(inputValue, -0.08f, 200); @@ -43,8 +37,7 @@ private float CurveFunction(float inputValue, float brightness, int contrast) inputValue = (factor * (inputValue - 0.5f)) + 0.5f; return Math.Min(Math.Max(inputValue, 0f), 1f); } - - public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) + public override void GetHeightmap(Index2 chunkIndex, float[] heightmap) { Index2 blockIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y); @@ -53,7 +46,7 @@ public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) regions[i] = 0; BiomeNoiseGenerator.GetTileableNoiseMap2D(blockIndex.X, blockIndex.Y, Chunk.CHUNKSIZE_X, Chunk.CHUNKSIZE_Y, Planet.Size.X * Chunk.CHUNKSIZE_X, Planet.Size.Y * Chunk.CHUNKSIZE_Y, regions); - float[] biomeValues = ArrayPool.Shared.Rent(SubBiomes.Count * Chunk.CHUNKSIZE_X * Chunk.CHUNKSIZE_Y); //float[SubBiomes.COunt][,] + float[] biomeValues = ArrayPool.Shared.Rent(SubBiomes.Count * Chunk.CHUNKSIZE_X * Chunk.CHUNKSIZE_Y); //float[SubBiomes.Count][,] var tempArray = ArrayPool.Shared.Rent(Chunk.CHUNKSIZE_X * Chunk.CHUNKSIZE_Y); for (int i = 0; i < SubBiomes.Count; i++) @@ -72,7 +65,7 @@ public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) int biome2; int biome1 = ChooseBiome(region, out biome2); - float interpolationValue = 0f; + float interpolationValue; if (biome2 != -1) { interpolationValue = CalculateInterpolationValue(region, SubBiomes[biome1], SubBiomes[biome2]); @@ -84,7 +77,6 @@ public override float[] GetHeightmap(Index2 chunkIndex, float[] heightmap) } ArrayPool.Shared.Return(regions); ArrayPool.Shared.Return(biomeValues); - return heightmap; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Climate/ComplexClimateMap.cs b/OctoAwesome/OctoAwesome.Basics/Climate/ComplexClimateMap.cs index 7e222b6a..73e3dfbf 100644 --- a/OctoAwesome/OctoAwesome.Basics/Climate/ComplexClimateMap.cs +++ b/OctoAwesome/OctoAwesome.Basics/Climate/ComplexClimateMap.cs @@ -1,24 +1,22 @@ -using OctoAwesome.Noise; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System; +using OctoAwesome.Basics.Noise; namespace OctoAwesome.Basics.Climate { + public class ComplexClimateMap : IClimateMap { + public IPlanet Planet => planet; - ComplexPlanet planet; - private INoise tempFluctuationGenerator; + private readonly ComplexPlanet planet; + private readonly INoise tempFluctuationGenerator; public ComplexClimateMap(ComplexPlanet planet) { this.planet = planet; tempFluctuationGenerator = new SimplexNoiseGenerator(planet.Seed - 1, 1f / 64, 1f / 64) { Octaves = 3}; } - public float GetTemperature(Index3 blockIndex) { int equator = (Planet.Size.Y * Chunk.CHUNKSIZE_Y) / 2; @@ -34,7 +32,6 @@ public float GetTemperature(Index3 blockIndex) height = height*height; return temperature - height * temperatureDecreasePerBlock; } - public int GetPrecipitation(Index3 blockIndex) { int maxPrecipitation = 100; diff --git a/OctoAwesome/OctoAwesome.Basics/ComplexPlanet.cs b/OctoAwesome/OctoAwesome.Basics/ComplexPlanet.cs index 8950a08e..22ecdf22 100644 --- a/OctoAwesome/OctoAwesome.Basics/ComplexPlanet.cs +++ b/OctoAwesome/OctoAwesome.Basics/ComplexPlanet.cs @@ -1,5 +1,6 @@ using OctoAwesome.Basics.Biomes; using System; +using System.Diagnostics; using System.IO; namespace OctoAwesome.Basics @@ -9,13 +10,15 @@ public class ComplexPlanet : Planet // Die Gravitationskonstante ist absichtlich so "groß", vgl. Issue #220 private const double GravitationalConstant = 6.67e-7; - public int HEIGHTMAPDETAILS = 8; - - public float[,] Heightmap { get; private set; } - - public float[,,] CloudMap { get; private set; } - - public SurfaceBiomeGenerator BiomeGenerator { get; private set; } + private SurfaceBiomeGenerator? biomeGenerator; + public SurfaceBiomeGenerator BiomeGenerator + { + get + { + Debug.Assert(biomeGenerator != null, nameof(biomeGenerator) + " != null"); + return biomeGenerator; + } + } /// /// Konstruktor des komplexen Map-Generators @@ -35,24 +38,22 @@ public ComplexPlanet(int id, Guid universe, Index3 size, IMapGenerator generator // der Annahme einer Kugel mit gleicher Oberfläche wie der rechteckige Planet. var radius = Math.Sqrt((Size.X * Size.Y) / (16 * Math.PI)); Gravity = (float)((4f / 3f) * Math.PI * GravitationalConstant * averageDensity * radius); - Initalize(); + Initialize(); } - - public ComplexPlanet() : base() + public ComplexPlanet() { //Initalize(); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); - Initalize(); + Initialize(); } - private void Initalize() + private void Initialize() { - BiomeGenerator = new SurfaceBiomeGenerator(this, 40); - ClimateMap = new Climate.ComplexClimateMap(this); + biomeGenerator = new SurfaceBiomeGenerator(this, 40); + climateMap = new Climate.ComplexClimateMap(this); } } } diff --git a/OctoAwesome/OctoAwesome.Basics/ComplexPlanetGenerator.cs b/OctoAwesome/OctoAwesome.Basics/ComplexPlanetGenerator.cs index 9390d494..8ba5e6a3 100644 --- a/OctoAwesome/OctoAwesome.Basics/ComplexPlanetGenerator.cs +++ b/OctoAwesome/OctoAwesome.Basics/ComplexPlanetGenerator.cs @@ -4,12 +4,12 @@ using System; using System.Buffers; -using System.Collections.Generic; using System.IO; using System.Linq; namespace OctoAwesome.Basics { + public class ComplexPlanetGenerator : IMapGenerator { private readonly ChunkPool chunkPool; @@ -17,10 +17,8 @@ public ComplexPlanetGenerator() { chunkPool = TypeContainer.Get(); } - public IPlanet GeneratePlanet(Guid universe, int id, int seed) => new ComplexPlanet(id, universe, new Index3(13, 13, 4), this, seed); - public IChunkColumn GenerateColumn(IDefinitionManager definitionManager, IPlanet planet, Index2 index) { IDefinition[] definitions = definitionManager.Definitions; @@ -54,7 +52,7 @@ public IChunkColumn GenerateColumn(IDefinitionManager definitionManager, IPlanet IChunk[] chunks = new IChunk[planet.Size.Z]; for (int i = 0; i < planet.Size.Z; i++) - chunks[i] = chunkPool.Get(new Index3(index, i), planet); + chunks[i] = chunkPool.Rent(new Index3(index, i), planet); int obersteSchicht; bool surfaceBlock; @@ -148,7 +146,6 @@ public IChunkColumn GenerateColumn(IDefinitionManager definitionManager, IPlanet column.CalculateHeights(); return column; } - public IPlanet GeneratePlanet(Stream stream) { IPlanet planet = new ComplexPlanet(); @@ -157,7 +154,6 @@ public IPlanet GeneratePlanet(Stream stream) planet.Generator = this; return planet; } - public IChunkColumn GenerateColumn(Stream stream, IPlanet planet, Index2 index) { IChunkColumn column = new ChunkColumn(planet); diff --git a/OctoAwesome/OctoAwesome.Basics/DebugMapGenerator.cs b/OctoAwesome/OctoAwesome.Basics/DebugMapGenerator.cs index 845a5868..abfe866b 100644 --- a/OctoAwesome/OctoAwesome.Basics/DebugMapGenerator.cs +++ b/OctoAwesome/OctoAwesome.Basics/DebugMapGenerator.cs @@ -1,23 +1,21 @@ -using OctoAwesome.Basics; -using System; -using System.Collections.Generic; +using System; using System.Linq; -using System.Text; using System.IO; using OctoAwesome.Basics.Definitions.Blocks; using OctoAwesome.Definitions; namespace OctoAwesome.Basics { + public class DebugMapGenerator : IMapGenerator { + public IPlanet GeneratePlanet(Guid universe, int id, int seed) { Planet planet = new Planet(id, universe, new Index3(5, 5, 4), seed); planet.Generator = this; return planet; } - public IChunkColumn GenerateColumn(IDefinitionManager definitionManager, IPlanet planet, Index2 index) { IDefinition[] definitions = definitionManager.Definitions.ToArray(); @@ -28,8 +26,6 @@ public IChunkColumn GenerateColumn(IDefinitionManager definitionManager, IPlanet IChunk[] result = new IChunk[planet.Size.Z]; ChunkColumn column = new ChunkColumn(result, planet, index); - - for (int layer = 0; layer < planet.Size.Z; layer++) result[layer] = new Chunk(new Index3(index.X, index.Y, layer), planet); @@ -58,7 +54,6 @@ public IChunkColumn GenerateColumn(IDefinitionManager definitionManager, IPlanet column.CalculateHeights(); return column; } - public IPlanet GeneratePlanet(Stream stream) { IPlanet planet = new Planet(); @@ -66,9 +61,6 @@ public IPlanet GeneratePlanet(Stream stream) planet.Deserialize(reader); return planet; } - - - public IChunkColumn GenerateColumn(Stream stream, IPlanet planet, Index2 index) { IChunkColumn column = new ChunkColumn(planet); diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BirchWoodBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BirchWoodBlockDefinition.cs index f6bb25f1..9fd6784a 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BirchWoodBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BirchWoodBlockDefinition.cs @@ -1,35 +1,20 @@ using OctoAwesome.Basics.Definitions.Materials; -using OctoAwesome.Basics.Properties; using OctoAwesome.Definitions; -using OctoAwesome.Information; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class BirchWoodBlockDefinition : BlockDefinition { public override string Name => Languages.OctoBasics.BirchWood; - public override string Icon => "birch_wood_top"; - public override bool HasMetaData => true; - - public override string[] Textures{ get; } = new[] { - "birch_wood_top", - "birch_wood_side" }; - + public override string[] Textures{ get; } = { "birch_wood_top", + "birch_wood_side" }; public override IMaterialDefinition Material { get; } - - public BirchWoodBlockDefinition(WoodMaterialDefinition material) { Material = material; } - public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, int x, int y, int z) { @@ -95,7 +80,6 @@ public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, // Assert here return -1; } - public override int GetTextureRotation(Wall wall, ILocalChunkCache manager, int x, int y, int z) { OrientationFlags orientation = (OrientationFlags)manager.GetBlockMeta(x, y, z); diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BlueCottonBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BlueCottonBlockDefinition.cs index 585e46a1..bc62c815 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BlueCottonBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BlueCottonBlockDefinition.cs @@ -1,27 +1,14 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class BlueCottonBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.BlueCotton; } - } - - public override string Icon - { - get { return "cotton_blue"; } - } - - - public override string[] Textures { get; } = new[] {"cotton_blue"}; - + public override string Name => Languages.OctoBasics.BlueCotton; + public override string Icon => "cotton_blue"; + public override string[] Textures { get; } = {"cotton_blue"}; public override IMaterialDefinition Material { get; } - public BlueCottonBlockDefinition(CottonMaterialDefinition material) { Material = material; diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BrickBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BrickBlockDefinition.cs index 98fee953..cf2d5bcb 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BrickBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/BrickBlockDefinition.cs @@ -1,25 +1,13 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class BrickBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Brick; } - } - - public override string Icon - { - get { return "brick_red"; } - } - - - public override string[] Textures { get; } =new[] {"brick_red",}; - + public override string Name => Languages.OctoBasics.Brick; + public override string Icon => "brick_red"; + public override string[] Textures { get; } = {"brick_red",}; public override IMaterialDefinition Material { get; } public BrickBlockDefinition(BrickMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/CactusBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/CactusBlockDefinition.cs index 11d61ed2..4ee3823a 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/CactusBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/CactusBlockDefinition.cs @@ -1,26 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { + public class CactusBlockDefinition : BlockDefinition { public override string Icon => "cactus_inside"; - + public override string Name => Languages.OctoBasics.Cactus; + + public override string[] Textures { get; } = {"cactus_inside","cactus_side","cactus_top" }; + + public override IMaterialDefinition Material { get; } - public override string[] Textures { get; } - - public CactusBlockDefinition() + public CactusBlockDefinition(CactusMaterialDefinition material) { - Textures = new[] {"cactus_inside","cactus_side","cactus_top" }; + Material = material; } - public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, int x, int y, int z) { @@ -157,7 +154,6 @@ public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, // Assert here return -1; } - public override int GetTextureRotation(Wall wall, ILocalChunkCache manager, int x, int y, int z) { @@ -199,12 +195,5 @@ public override int GetTextureRotation(Wall wall, ILocalChunkCache manager, int return base.GetTextureRotation(wall, manager, x, y, z); //should never ever happen } } - - public override IMaterialDefinition Material { get; } - - public CactusBlockDefinition(CactusMaterialDefinition material) : this() - { - Material = material; - } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/DirtBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/DirtBlockDefinition.cs index 5c3235de..ee5d6848 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/DirtBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/DirtBlockDefinition.cs @@ -1,27 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class DirtBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Ground; } - } - - public override string Icon - { - get { return "dirt"; } - } - - - public override string[] Textures { get; } = new[] { "dirt" }; - - - + public override string Name => Languages.OctoBasics.Ground; + + public override string Icon => "dirt"; + + public override string[] Textures { get; } = { "dirt" }; + public override IMaterialDefinition Material { get; } public DirtBlockDefinition(DirtMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GrassBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GrassBlockDefinition.cs index 5435a8cc..22e5a9a0 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GrassBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GrassBlockDefinition.cs @@ -1,49 +1,32 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class GrassBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Grass; } - } - - public override string Icon - { - get { return "grass_top"; } - } - - public override string[] Textures { get; } = new[] { - "grass_top", - "dirt", - "dirt_grass", - }; - + public override string Name => Languages.OctoBasics.Grass; + + public override string Icon => "grass_top"; + + public override string[] Textures { get; } = { "grass_top", + "dirt", + "dirt_grass" }; + public override IMaterialDefinition Material { get; } public GrassBlockDefinition(DirtMaterialDefinition material) { Material = material; } - public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, int x, int y, int z) { - if (wall == Wall.Top) - { - return 0; - } - else if (wall == Wall.Bottom) - { - return 1; - } - else + return wall switch { - return 2; - } + Wall.Top => 0, + Wall.Bottom => 1, + _ => 2 + }; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GravelBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GravelBlockDefinition.cs index 9592fb52..87c95a1c 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GravelBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GravelBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class GravelBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Gravel; } - } - - public override string Icon - { - get { return "gravel"; } - } - - - public override string[] Textures { get; } = new[] {"gravel"}; - + public override string Name => Languages.OctoBasics.Gravel; + + public override string Icon => "gravel"; + + public override string[] Textures { get; } = {"gravel"}; + public override IMaterialDefinition Material { get; } public GravelBlockDefinition(GravelMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreenCottonBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreenCottonBlockDefinition.cs index 9bb49eec..abafeabc 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreenCottonBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreenCottonBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class GreenCottonBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.GreenCotton; } - } - - public override string Icon - { - get { return "cotton_green"; } - } - - - public override string[] Textures { get; } = new[] {"cotton_green"}; - + public override string Name => Languages.OctoBasics.GreenCotton; + + public override string Icon => "cotton_green"; + + public override string[] Textures { get; } = {"cotton_green"}; + public override IMaterialDefinition Material { get; } public GreenCottonBlockDefinition(CottonMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreystoneBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreystoneBlockDefinition.cs index 412eb45e..8ccc81b2 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreystoneBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/GreystoneBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class GreystoneBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Greystone; } - } - - public override string Icon - { - get { return "greystone"; } - } - - - public override string[] Textures { get; } = new[] { "greystone" }; - + public override string Name => Languages.OctoBasics.Greystone; + + public override string Icon => "greystone"; + + public override string[] Textures { get; } = { "greystone" }; + public override IMaterialDefinition Material { get; } public GreystoneBlockDefinition(StoneMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/IceBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/IceBlockDefinition.cs index 07c82dba..2b302391 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/IceBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/IceBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class IceBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Ice; } - } - - public override string Icon - { - get { return "ice"; } - } - - - public override string[] Textures { get; } = new[] { "ice" }; - + public override string Name => Languages.OctoBasics.Ice; + + public override string Icon => "ice"; + + public override string[] Textures { get; } = { "ice" }; + public override IMaterialDefinition Material { get; } public IceBlockDefinition(IceMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/LeavesBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/LeavesBlockDefinition.cs index 2a9ec4c2..dc59088c 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/LeavesBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/LeavesBlockDefinition.cs @@ -1,26 +1,16 @@ -using OctoAwesome.Information; -using OctoAwesome.Definitions; -using System; -using System.Drawing; +using OctoAwesome.Definitions; using OctoAwesome.Basics.Definitions.Materials; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class LeavesBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Leaves; } - } - - public override string Icon - { - get { return "leaves"; } - } - - - public override string[] Textures { get; } = new[] {"leaves"}; - + public override string Name => Languages.OctoBasics.Leaves; + + public override string Icon => "leaves"; + + public override string[] Textures { get; } = {"leaves"}; + public override IMaterialDefinition Material { get; } public LeavesBlockDefinition(LeaveMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/OrangeLeavesBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/OrangeLeavesBlockDefinition.cs index ef74f1ce..b5851311 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/OrangeLeavesBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/OrangeLeavesBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class OrangeLeavesBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.OrangeLeaves; } - } - - public override string Icon - { - get { return "leaves_orange"; } - } - - - public override string[] Textures { get; } = new[] {"leaves_orange"}; - + public override string Name => Languages.OctoBasics.OrangeLeaves; + + public override string Icon => "leaves_orange"; + + public override string[] Textures { get; } = {"leaves_orange"}; + public override IMaterialDefinition Material { get; } public OrangeLeavesBlockDefinition(LeaveMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/PlankBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/PlankBlockDefinition.cs index 85af13a9..c1ba2194 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/PlankBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/PlankBlockDefinition.cs @@ -1,31 +1,18 @@ -using OctoAwesome.Basics.Properties; -using OctoAwesome.Information; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; -using OctoAwesome.Definitions; +using OctoAwesome.Definitions; using OctoAwesome.Basics.Definitions.Materials; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class PlankBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Plank; } - } - - public override string Icon - { - get { return "planks_red"; } - } - - public override bool HasMetaData { get { return true; } } - - public override string[] Textures { get; } = new[] {"planks_red"}; - + public override string Name => Languages.OctoBasics.Plank; + + public override string Icon => "planks"; + + public override bool HasMetaData => true; + + public override string[] Textures { get; } = {"planks"}; + public override IMaterialDefinition Material { get; } public PlankBlockDefinition(WoodMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedCottonBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedCottonBlockDefinition.cs index 1fab4541..848e400a 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedCottonBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedCottonBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class RedCottonBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.RedCotton; } - } - - public override string Icon - { - get { return "cotton_red"; } - } - - - public override string[] Textures { get; } = new[] {"cotton_red"}; - + public override string Name => Languages.OctoBasics.RedCotton; + + public override string Icon => "cotton_red"; + + public override string[] Textures { get; } = {"cotton_red"}; + public override IMaterialDefinition Material { get; } public RedCottonBlockDefinition(CottonMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedPlankBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedPlankBlockDefinition.cs index fad88e67..f6f303d6 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedPlankBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/RedPlankBlockDefinition.cs @@ -1,31 +1,18 @@ -using OctoAwesome.Basics.Properties; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; -using OctoAwesome.Definitions; +using OctoAwesome.Definitions; using OctoAwesome.Basics.Definitions.Materials; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class RedPlankBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.RedPlank; } - } - - public override string Icon - { - get { return "planks"; } - } - - public override bool HasMetaData { get { return true; } } - - public override string[] Textures { get; } = new[] { "planks" }; - + public override string Name => Languages.OctoBasics.RedPlank; + + public override string Icon => "planks_red"; + + public override bool HasMetaData => true; + + public override string[] Textures { get; } = { "planks_red" }; + public override IMaterialDefinition Material { get; } public RedPlankBlockDefinition(WoodMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SandBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SandBlockDefinition.cs index 8a61fd57..123a5358 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SandBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SandBlockDefinition.cs @@ -1,24 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class SandBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Sand; } - } - - public override string Icon - { - get { return "sand"; } - } - - public override string[] Textures { get; } = new[] {"sand"}; - + public override string Name => Languages.OctoBasics.Sand; + + public override string Icon => "sand"; + + public override string[] Textures { get; } = {"sand"}; + public override IMaterialDefinition Material { get; } public SandBlockDefinition(SandMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SnowBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SnowBlockDefinition.cs index ace2a8aa..fb25eb60 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SnowBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/SnowBlockDefinition.cs @@ -1,54 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public class SnowBlockDefinition : BlockDefinition { - public override string Name - { - get - { - return Languages.OctoBasics.Snow; - } - } - - public override string Icon - { - get - { - return "snow"; - } - } - - public override string[] Textures { get; } = new[] {"snow","dirt","dirt_snow",}; - + public override string Name => Languages.OctoBasics.Snow; + + public override string Icon => "snow"; + + public override string[] Textures { get; } = {"snow","dirt","dirt_snow",}; + public override IMaterialDefinition Material { get; } public SnowBlockDefinition(SnowMaterialDefinition material) { Material = material; } - public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, int x, int y, int z) { - if (wall == Wall.Top) - { - return 0; - } - else if (wall == Wall.Bottom) - { - return 1; - } - else + return wall switch { - return 2; - } + Wall.Top => 0, + Wall.Bottom => 1, + _ => 2 + }; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBlockDefinition.cs index 43bac0b7..7bbb7944 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBlockDefinition.cs @@ -1,26 +1,16 @@ -using OctoAwesome.Information; -using System; -using System.Drawing; -using OctoAwesome.Definitions; +using OctoAwesome.Definitions; using OctoAwesome.Basics.Definitions.Materials; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class StoneBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.Stone; } - } - - public override string Icon - { - get { return "stone"; } - } - - - public override string[] Textures { get; } = new[] { "stone", }; - + public override string Name => Languages.OctoBasics.Stone; + + public override string Icon => "stone"; + + public override string[] Textures { get; } = { "stone", }; + public override IMaterialDefinition Material { get; } public StoneBlockDefinition(StoneMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBrickBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBrickBlockDefinition.cs index 4b24556b..476f603f 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBrickBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/StoneBrickBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class StoneBrickBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.StoneBrick; } - } - - public override string Icon - { - get { return "brick_grey"; } - } - - - public override string[] Textures { get; } = new[] {"brick_grey",}; - + public override string Name => Languages.OctoBasics.StoneBrick; + + public override string Icon => "brick_grey"; + + public override string[] Textures { get; } = {"brick_grey",}; + public override IMaterialDefinition Material { get; } public StoneBrickBlockDefinition(StoneMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/TanCottonBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/TanCottonBlockDefinition.cs index 6cb047b5..a5070637 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/TanCottonBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/TanCottonBlockDefinition.cs @@ -1,25 +1,16 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class TanCottonBlockDefinition : BlockDefinition { - public override string Name - { - get { return Languages.OctoBasics.TanCotton; } - } - - public override string Icon - { - get { return "cotton_tan"; } - } - - - public override string[] Textures { get; } = new[] {"cotton_tan"}; - + public override string Name => Languages.OctoBasics.TanCotton; + + public override string Icon => "cotton_tan"; + + public override string[] Textures { get; } = {"cotton_tan"}; + public override IMaterialDefinition Material { get; } public TanCottonBlockDefinition(CottonMaterialDefinition material) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WaterBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WaterBlockDefinition.cs index 2ff8864e..2a754d59 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WaterBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WaterBlockDefinition.cs @@ -1,27 +1,24 @@ -using System; -using System.Drawing; -using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Definitions.Materials; using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Blocks { + public sealed class WaterBlockDefinition : BlockDefinition { public override string Name => Languages.OctoBasics.Water; - + public override uint SolidWall => 0; - + public override string Icon => "water"; - + + public override string[] Textures { get; } = { "water" }; + public override IMaterialDefinition Material { get; } - - + public WaterBlockDefinition(WaterMaterialDefinition material) { Material = material; } - - - public override string[] Textures { get; } = new[] { "water" }; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WoodBlockDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WoodBlockDefinition.cs index 6bfd7686..142026d0 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WoodBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Blocks/WoodBlockDefinition.cs @@ -1,32 +1,25 @@ -using OctoAwesome.Basics.Properties; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; +using OctoAwesome.Basics.Definitions.Materials; +using OctoAwesome.Basics.Languages; using OctoAwesome.Definitions; -using OctoAwesome.Basics.Definitions.Materials; namespace OctoAwesome.Basics.Definitions.Blocks { public sealed class WoodBlockDefinition : BlockDefinition { - public override string Name => Languages.OctoBasics.Wood; - + public override string Name => OctoBasics.Wood; + public override string Icon => "wood_top"; - + public override bool HasMetaData => true; - - public override string[] Textures { get; } = new[] { "wood_top", "wood_side" }; - + + public override string[] Textures { get; } = { "wood_top", "wood_side" }; + public override IMaterialDefinition Material { get; } public WoodBlockDefinition(WoodMaterialDefinition material) { Material = material; } - public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, int x, int y, int z) { OrientationFlags orientation = (OrientationFlags)manager.GetBlockMeta(x, y, z); @@ -88,7 +81,6 @@ public override int GetTextureIndex(Wall wall, ILocalChunkCache manager, int x, // Assert this return -1; } - public override int GetTextureRotation(Wall wall, ILocalChunkCache manager, int x, int y, int z) { OrientationFlags orientation = (OrientationFlags)manager.GetBlockMeta(x, y, z); diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Axe.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Axe.cs index c5ef54e8..f4f73df6 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Axe.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Axe.cs @@ -1,14 +1,10 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; using OctoAwesome.OctoMath; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { + public class Axe : Item { @@ -23,13 +19,11 @@ public Axe() : base(null, null) { } - public Axe(AxeDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) { } - public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decimal volumeRemaining, int volumePerHit) { //⁅𝑥^2/800+3𝑥/8+(−𝑥^3)/320000⁆ diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/AxeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/AxeDefinition.cs index cc34094d..de860144 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/AxeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/AxeDefinition.cs @@ -1,35 +1,18 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { public class AxeDefinition : IItemDefinition - { - - public string Name { get; } - public string Icon { get; } - - public AxeDefinition() - { - Name = "Axe"; - Icon = "axe_iron"; - } - + { + public string Name => "Axe"; + public string Icon => "axe_iron"; + public bool CanMineMaterial(IMaterialDefinition material) { - if (material is ISolidMaterialDefinition solid) - { - return true; - } - - return false; + return material is ISolidMaterialDefinition; } - + public Item Create(IMaterialDefinition material) => new Axe(this, material); } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Bucket.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Bucket.cs index d554bb22..1d25e110 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Bucket.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Bucket.cs @@ -1,25 +1,18 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class Bucket : Item, IFluidInventory + public class Bucket : Item, IFluidInventory { public int Quantity { get; private set; } - public IBlockDefinition FluidBlock { get; private set; } + public IBlockDefinition? FluidBlock { get; private set; } public int MaxQuantity { get; } - public Bucket(BucketDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) { MaxQuantity = 125; } - public void AddFluid(int quantity, IBlockDefinition fluidBlock) { if (!Definition.CanMineMaterial(fluidBlock.Material)) @@ -28,7 +21,6 @@ public void AddFluid(int quantity, IBlockDefinition fluidBlock) Quantity += quantity; FluidBlock = fluidBlock; } - public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decimal volumeRemaining, int volumePerHit) { if (!Definition.CanMineMaterial(material)) @@ -44,8 +36,6 @@ public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decim return volumePerHit; } - - return base.Hit(material, blockInfo, volumeRemaining, volumePerHit); } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/BucketDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/BucketDefinition.cs index 9afb063f..82df9a96 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/BucketDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/BucketDefinition.cs @@ -1,34 +1,18 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class BucketDefinition : IItemDefinition + public class BucketDefinition : IItemDefinition { - public string Name { get; } - public string Icon { get; } - - public BucketDefinition() - { - Name = "Bucket"; - Icon = "bucket"; - } - + public string Name => "Bucket"; + public string Icon => "bucket"; + public bool CanMineMaterial(IMaterialDefinition material) { - if (material is IFluidMaterialDefinition fluid) - { - return true; - } - - return false; + return material is IFluidMaterialDefinition; } - + public Item Create(IMaterialDefinition material) => new Bucket(this, material); } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItem.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItem.cs index 1f6af671..2ddcfa52 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItem.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItem.cs @@ -5,23 +5,13 @@ using OctoAwesome.Notifications; using OctoAwesome.Rx; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { public class ChestItem : Item, IDisposable { - public override int VolumePerUnit => base.VolumePerUnit; - - public override int StackLimit => base.StackLimit; - - private readonly Relay simulationRelay; private readonly IDisposable simulationSource; - public ChestItem(ChestItemDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) { @@ -30,7 +20,6 @@ public ChestItem(ChestItemDefinition definition, IMaterialDefinition materialDef simulationSource = updateHub.AddSource(simulationRelay, DefaultChannels.Simulation); } - public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decimal volumeRemaining, int volumePerHit) { //TODO: Implement Place Chest and remove this item @@ -45,11 +34,10 @@ public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decim simulationRelay.OnNext(notification); return 0; } - public void Dispose() { simulationSource.Dispose(); - simulationRelay?.Dispose(); + simulationRelay.Dispose(); } } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItemDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItemDefinition.cs index 13b602a3..e80313aa 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItemDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ChestItemDefinition.cs @@ -1,27 +1,16 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { public class ChestItemDefinition : IItemDefinition { - public string Name { get; } - public string Icon { get; } - - public ChestItemDefinition() - { - Name = "Chest"; - Icon = "chest"; - } - + public string Name => "Chest"; + public string Icon => "chest"; + public bool CanMineMaterial(IMaterialDefinition material) => false; - + public Item Create(IMaterialDefinition material) => new ChestItem(this, material); } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hammer.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hammer.cs index 77e80350..7a8919cf 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hammer.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hammer.cs @@ -1,14 +1,9 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class Hammer : Item + public class Hammer : Item { public Hammer(HammerDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HammerDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HammerDefinition.cs index 06bf1562..5cdbe917 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HammerDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HammerDefinition.cs @@ -1,29 +1,17 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class HammerDefinition : IItemDefinition + public class HammerDefinition : IItemDefinition { - public string Name { get; } - public string Icon { get; } - - public HammerDefinition() - { - Name = "Hammer"; - Icon = "hammer_iron"; - } - + public string Name => "Hammer"; + public string Icon => "hammer_iron"; + public bool CanMineMaterial(IMaterialDefinition material) { return false; } - public Item Create(IMaterialDefinition material) => new Hammer(this, material); } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hoe.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hoe.cs index dc0ca6aa..e28f06f9 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hoe.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Hoe.cs @@ -1,14 +1,9 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class Hoe : Item + public class Hoe : Item { public Hoe(HoeDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HoeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HoeDefinition.cs index af4ec53f..741d1560 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HoeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/HoeDefinition.cs @@ -1,29 +1,17 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class HoeDefinition : IItemDefinition + public class HoeDefinition : IItemDefinition { - public string Name { get; } - public string Icon { get; } - - public HoeDefinition() - { - Name = "Hoe"; - Icon = "hoe_iron"; - } - + public string Name => "Hoe"; + public string Icon => "hoe_iron"; + public bool CanMineMaterial(IMaterialDefinition material) { return false; } - public Item Create(IMaterialDefinition material) => new Hoe(this, material); } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/PickAxeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/PickAxeDefinition.cs index 049b31df..b3e5b426 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/PickAxeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/PickAxeDefinition.cs @@ -1,60 +1,19 @@ -using OctoAwesome.Basics.Properties; -using OctoAwesome.Information; -using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; +using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; namespace OctoAwesome.Basics.Definitions.Items { public class PickaxeDefinition : IItemDefinition { - public string Icon - { - get - { - return "pick_iron"; - } - } - - public string Name - { - get - { - return "Pickaxe"; - } - } - - public int StackLimit - { - get - { - return 1; - } - } - - public float VolumePerUnit - { - get - { - return 10; - } - } - - + public string Icon => "pick_iron"; + + public string Name => "Pickaxe"; + public bool CanMineMaterial(IMaterialDefinition material) { - if(material is ISolidMaterialDefinition solid) - { - return true; - } - - return false; + return material is ISolidMaterialDefinition; } - + public Item Create(IMaterialDefinition material) { return new Pickaxe(this, material); diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Pickaxe.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Pickaxe.cs index 256e9125..5ba6f8c0 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Pickaxe.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Pickaxe.cs @@ -1,10 +1,8 @@ -using OctoAwesome.Basics.Definitions.Items; -using OctoAwesome.Definitions; +using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; using OctoAwesome.OctoMath; -using System; -namespace OctoAwesome.Basics +namespace OctoAwesome.Basics.Definitions.Items { public class Pickaxe : Item { @@ -14,13 +12,11 @@ static Pickaxe() { polynomial = new Polynomial(150, 0, -1f / 400f); } - public Pickaxe(PickaxeDefinition pickaxeDefinition, IMaterialDefinition materialDefinition) : base(pickaxeDefinition, materialDefinition) { } - public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decimal volumeRemaining, int volumePerHit) { //⁅((−𝑥^2)/400)+150⁆ diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Shovel.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Shovel.cs index 63d8fe91..f7667c99 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Shovel.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Shovel.cs @@ -1,21 +1,16 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class Shovel : Item + public class Shovel : Item { public Shovel(ShovelDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) { } - public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decimal volumeRemaining, int volumePerHit) { if (!Definition.CanMineMaterial(material)) @@ -29,7 +24,7 @@ public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decim //if (solid * 1.2f < material.Hardness) // return 0; - return (int)(Math.Sin(solid.Granularity / 40) * 2 * volumePerHit); + return (int)(Math.Sin(solid.Granularity / 40f) * 2 * volumePerHit); } return 0; diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ShovelDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ShovelDefinition.cs index 8e0629de..5469e2e7 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ShovelDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/ShovelDefinition.cs @@ -1,34 +1,18 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class ShovelDefinition : IItemDefinition + public class ShovelDefinition : IItemDefinition { - public string Name { get; } - public string Icon { get; } - - public ShovelDefinition() - { - Name = "Shovel"; - Icon = "shovel_iron"; - } - + public string Name => "Shovel"; + public string Icon => "shovel_iron"; + public bool CanMineMaterial(IMaterialDefinition material) { - if (material is ISolidMaterialDefinition solid) - { - return true; - } - - return false; + return material is ISolidMaterialDefinition; } - + public Item Create(IMaterialDefinition material) => new Shovel(this, material); } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Sword.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Sword.cs index 4457f236..ddfb5e01 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Sword.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/Sword.cs @@ -1,14 +1,9 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class Sword : Item + public class Sword : Item { public Sword(SwordDefinition definition, IMaterialDefinition materialDefinition) : base(definition, materialDefinition) diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/SwordDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/SwordDefinition.cs index acf128b3..dd77b73b 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Items/SwordDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Items/SwordDefinition.cs @@ -1,29 +1,17 @@ using OctoAwesome.Definitions; using OctoAwesome.Definitions.Items; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Items { - class SwordDefinition : IItemDefinition + public class SwordDefinition : IItemDefinition { - public string Name { get; } - public string Icon { get; } - - public SwordDefinition() - { - Name = "Sword"; - Icon = "sword_iron"; - } - + public string Name => "Sword"; + public string Icon => "sword_iron"; + public bool CanMineMaterial(IMaterialDefinition material) { return false; } - public Item Create(IMaterialDefinition material) => new Sword(this, material); } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/BrickMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/BrickMaterialDefinition.cs index f729c488..7b170bd4 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/BrickMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/BrickMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class BrickMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 45; + public int Hardness => 45; public int Density => 1800; - public int Granularity => 1; - public int FractureToughness => 2; - public string Name => "Brick"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CactusMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CactusMaterialDefinition.cs index c679aeb8..2ee7b60c 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CactusMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CactusMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class CactusMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 25; + public int Hardness => 25; public int Density => 850; - public int Granularity => 1; - public int FractureToughness => 300; - public string Name => "Cactus"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/ClayMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/ClayMaterialDefinition.cs index 14d130d9..b2aa2928 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/ClayMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/ClayMaterialDefinition.cs @@ -1,25 +1,17 @@  using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class ClayMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 3; + public int Hardness => 3; public int Density => 2000; - public int Granularity => 25; - public int FractureToughness => 60; - public string Name => "Clay"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CottonMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CottonMaterialDefinition.cs index dda7d6c7..cb4c7406 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CottonMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/CottonMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class CottonMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 4; + public int Hardness => 4; public int Density => 132; - public int Granularity => 10; - public int FractureToughness => 600; - public string Name => "Cotton"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/DirtMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/DirtMaterialDefinition.cs index 953c4b91..e6bd61aa 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/DirtMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/DirtMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class DirtMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 10; + public int Hardness => 10; public int Density => 1400; - public int Granularity => 50; - public int FractureToughness => 50; - public string Name => "Dirt"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GlassMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GlassMaterialDefinition.cs index f08f9afd..14e6aebb 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GlassMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GlassMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class GlassMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 55; + public int Hardness => 55; public int Density => 2500; - public int Granularity => 1; - public int FractureToughness => 50; - public string Name => "Glass"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GravelMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GravelMaterialDefinition.cs index 42d8a136..a8ff8abe 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GravelMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/GravelMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class GravelMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 60; + public int Hardness => 60; public int Density => 1440; - public int Granularity => 70; - public int FractureToughness => 0; - public string Name => "Gravel"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/IceMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/IceMaterialDefinition.cs index 88534847..f9fa2f9a 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/IceMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/IceMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class IceMaterialDefinition : ISolidMaterialDefinition { - public int Granularity => 1; + public int Granularity => 1; public int FractureToughness => 20; - public int Hardness => 15; - public int Density => 934; - public string Name => "Ice"; - public string Icon => ""; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/LeaveMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/LeaveMaterialDefinition.cs index 248916f2..098bcb6e 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/LeaveMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/LeaveMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class LeaveMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 1; + public int Hardness => 1; public int Density => 200; - public int Granularity => 40; - public int FractureToughness => 0; - public string Name => "Leave"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SandMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SandMaterialDefinition.cs index ea70761d..86a6e6fa 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SandMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SandMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class SandMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 70; + public int Hardness => 70; public int Density => 1600; - public int Granularity => 90; - public int FractureToughness => 0; - public string Name => "Sand"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SnowMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SnowMaterialDefinition.cs index 99e763fe..d3608b30 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SnowMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/SnowMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class SnowMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 1; + public int Hardness => 1; public int Density => 250; - public int Granularity => 50; - public int FractureToughness => 5; - public string Name => "Snow"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/StoneMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/StoneMaterialDefinition.cs index 5d3b3ea0..4525803b 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/StoneMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/StoneMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class StoneMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 60; + public int Hardness => 60; public int Density => 2700; - public int Granularity => 1; - public int FractureToughness => 4; - public string Name => "Stone"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WaterMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WaterMaterialDefinition.cs index ce56a1cb..0f004b45 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WaterMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WaterMaterialDefinition.cs @@ -1,23 +1,15 @@ -using OctoAwesome.Common; -using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using OctoAwesome.Definitions; namespace OctoAwesome.Basics.Definitions.Materials { + public class WaterMaterialDefinition : IFluidMaterialDefinition { - public int Hardness => 0; + public int Hardness => 0; public int Density => 997; - public string Name => "Water"; - public string Icon => string.Empty; - public int Viscosity => 1008; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WoodMaterialDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WoodMaterialDefinition.cs index fc3d7d3c..a45f06eb 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WoodMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Materials/WoodMaterialDefinition.cs @@ -1,24 +1,16 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.Definitions.Materials { + public class WoodMaterialDefinition : ISolidMaterialDefinition { - public int Hardness => 35; + public int Hardness => 35; public int Density => 680; - public int Granularity => 1; - public int FractureToughness => 200; - public string Name => "Wood"; - public string Icon => string.Empty; } } diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/BirchTreeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/BirchTreeDefinition.cs index 118be2b8..086ccaa7 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/BirchTreeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/BirchTreeDefinition.cs @@ -1,9 +1,6 @@ using OctoAwesome.Basics.Definitions.Blocks; using OctoAwesome.Definitions; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Basics.Definitions.Trees { @@ -12,43 +9,23 @@ public class BirchTreeDefinition : TreeDefinition private ushort wood; private ushort leave; private ushort water; - - public override int Order - { - get - { - return 15; - } - } - - public override float MaxTemperature - { - get - { - return 30; - } - } - - public override float MinTemperature - { - get - { - return -5; - } - } - + + public override int Order => 15; + + public override float MaxTemperature => 30; + + public override float MinTemperature => -5; + public override int GetDensity(IPlanet planet, Index3 index) { return 4; } - public override void Init(IDefinitionManager definitionManager) { wood = definitionManager.GetDefinitionIndex(); leave = definitionManager.GetDefinitionIndex(); water = definitionManager.GetDefinitionIndex(); } - public override void PlantTree(IPlanet planet, Index3 index, LocalBuilder builder, int seed) { ushort ground = builder.GetBlock(0, 0, -1); diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/CactusTreeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/CactusTreeDefinition.cs index 8f5aec48..e340958a 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/CactusTreeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/CactusTreeDefinition.cs @@ -1,42 +1,28 @@ using OctoAwesome.Basics.Definitions.Blocks; using OctoAwesome.Definitions; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Basics.Definitions.Trees { public class CactusTreeDefinition : TreeDefinition { private ushort cactus, water; - - public override float MaxTemperature - { - get { return 45; } - } - - public override float MinTemperature - { - get { return 32; } - } - - public override int Order - { - get { return 20; } - } - + + public override float MaxTemperature => 45; + + public override float MinTemperature => 32; + + public override int Order => 20; + public override int GetDensity(IPlanet planet, Index3 index) { return 2; } - public override void Init(IDefinitionManager definitionManager) { cactus = definitionManager.GetDefinitionIndex(); water = definitionManager.GetDefinitionIndex(); } - public override void PlantTree(IPlanet planet, Index3 index, LocalBuilder builder, int seed) { ushort ground = builder.GetBlock(0, 0, -1); diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/OakTreeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/OakTreeDefinition.cs index d2e2b080..2156ab32 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/OakTreeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/OakTreeDefinition.cs @@ -1,9 +1,6 @@ using OctoAwesome.Basics.Definitions.Blocks; using OctoAwesome.Definitions; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Basics.Definitions.Trees { @@ -12,43 +9,23 @@ public class OakTreeDefinition : TreeDefinition private ushort wood; private ushort leave; private ushort water; - - public override int Order - { - get - { - return 10; - } - } - - public override float MaxTemperature - { - get - { - return 27; - } - } - - public override float MinTemperature - { - get - { - return -5; - } - } - + + public override int Order => 10; + + public override float MaxTemperature => 27; + + public override float MinTemperature => -5; + public override void Init(IDefinitionManager definitionManager) { wood = definitionManager.GetDefinitionIndex(); leave = definitionManager.GetDefinitionIndex(); water = definitionManager.GetDefinitionIndex(); } - public override int GetDensity(IPlanet planet, Index3 index) { return 4; } - public override void PlantTree(IPlanet planet, Index3 index, LocalBuilder builder, int seed) { ushort ground = builder.GetBlock(0, 0, -1); diff --git a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/SpruceTreeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/SpruceTreeDefinition.cs index 259896df..7752ad48 100644 --- a/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/SpruceTreeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/Definitions/Trees/SpruceTreeDefinition.cs @@ -1,9 +1,6 @@ using OctoAwesome.Basics.Definitions.Blocks; using OctoAwesome.Definitions; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Basics.Definitions.Trees { @@ -12,43 +9,23 @@ public class SpruceTreeDefinition : TreeDefinition private ushort wood; private ushort leave; private ushort water; - - public override int Order - { - get - { - return 15; - } - } - - public override float MaxTemperature - { - get - { - return 25; - } - } - - public override float MinTemperature - { - get - { - return -5; - } - } - + + public override int Order => 15; + + public override float MaxTemperature => 25; + + public override float MinTemperature => -5; + public override int GetDensity(IPlanet planet, Index3 index) { return 4; } - public override void Init(IDefinitionManager definitionManager) { wood = definitionManager.GetDefinitionIndex(); leave = definitionManager.GetDefinitionIndex(); water = definitionManager.GetDefinitionIndex(); } - public override void PlantTree(IPlanet planet, Index3 index, LocalBuilder builder, int seed) { ushort ground = builder.GetBlock(0, 0, -1); diff --git a/OctoAwesome/OctoAwesome.Basics/Entities/WauziEntity.cs b/OctoAwesome/OctoAwesome.Basics/Entities/WauziEntity.cs index bfd2f30f..5696a3af 100644 --- a/OctoAwesome/OctoAwesome.Basics/Entities/WauziEntity.cs +++ b/OctoAwesome/OctoAwesome.Basics/Entities/WauziEntity.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using engenious; using OctoAwesome.Basics.EntityComponents; using OctoAwesome.EntityComponents; @@ -10,18 +6,15 @@ namespace OctoAwesome.Basics.Entities { + [SerializationId(1, 2)] public class WauziEntity : UpdateableEntity { - public int JumpTime { get; set; } - - public WauziEntity() : base() - { - } + public int JumpTime { get; set; } public override void Update(GameTime gameTime) { - BodyPowerComponent body = Components.GetComponent(); + _ = Components.GetComponent(); ControllableComponent controller = Components.GetComponent(); controller.MoveInput = new Vector2(0.5f, 0.5f) ; @@ -40,10 +33,9 @@ public override void Update(GameTime gameTime) controller.JumpInput = false; } } - public override void RegisterDefault() { - var posComponent = Components.GetComponent() ?? new PositionComponent() { Position = new Coordinate(0, new Index3(0, 0, 200), new Vector3(0, 0, 0)) }; + var posComponent = Components.GetComponent() ?? new PositionComponent() { Position = new Coordinate(0, new Index3(0, 0, 200), new Vector3(0, 0)) }; Components.AddComponent(posComponent); Components.AddComponent(new GravityComponent()); diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/BodyPowerComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/BodyPowerComponent.cs index ed1b9663..5048e16a 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/BodyPowerComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/BodyPowerComponent.cs @@ -1,24 +1,18 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.IO; namespace OctoAwesome.Basics.EntityComponents { + public sealed class BodyPowerComponent : PowerComponent { - public int JumpTime { get; set; } - + public int JumpTime { get; set; } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(JumpTime); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/EntityCollisionComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/EntityCollisionComponent.cs index 03de9267..1d925171 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/EntityCollisionComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/EntityCollisionComponent.cs @@ -1,12 +1,8 @@ using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.EntityComponents { + public sealed class EntityCollisionComponent : CollisionComponent { } diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/ForceComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/ForceComponent.cs index 02c0a743..b66a8873 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/ForceComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/ForceComponent.cs @@ -1,18 +1,12 @@ using engenious; using OctoAwesome.Components; -using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.EntityComponents { + public abstract class ForceComponent : Component, IEntityComponent { - public Vector3 Force { get; set; } - + public Vector3 Force { get; set; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/GravityComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/GravityComponent.cs index bc20c88b..7f8f6667 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/GravityComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/GravityComponent.cs @@ -1,11 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Basics.EntityComponents +namespace OctoAwesome.Basics.EntityComponents { + public sealed class GravityComponent : ForceComponent { } diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/MassComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/MassComponent.cs index 383b1f29..dbbd1b0c 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/MassComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/MassComponent.cs @@ -1,15 +1,11 @@ using OctoAwesome.Components; -using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.EntityComponents { + public sealed class MassComponent : Component, IEntityComponent { + public float Mass { get; set; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/MoveableComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/MoveableComponent.cs index 8c373a9a..23ae6ca7 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/MoveableComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/MoveableComponent.cs @@ -1,22 +1,15 @@ using engenious; using OctoAwesome.Components; -using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.EntityComponents { + public sealed class MoveableComponent : Component, IEntityComponent { - public Vector3 Velocity { get; set; } + public Vector3 Velocity { get; set; } public Vector3 PositionMove { get; set; } - public Vector3 ExternalForces { get; set; } - public Vector3 ExternalPowers { get; set; } } } diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/PowerComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/PowerComponent.cs index 6518e902..226c8b5c 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/PowerComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/PowerComponent.cs @@ -1,21 +1,15 @@ using engenious; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.IO; -using OctoAwesome.EntityComponents; using OctoAwesome.Components; namespace OctoAwesome.Basics.EntityComponents { + public abstract class PowerComponent : Component, IEntityComponent { - public float Power { get; set; } + public float Power { get; set; } public Vector3 Direction { get; set; } - public override void Serialize(BinaryWriter writer) { @@ -23,7 +17,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(Power); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/TransferUIComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/TransferUIComponent.cs index a987c2a8..5309407e 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/TransferUIComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/TransferUIComponent.cs @@ -4,18 +4,14 @@ using OctoAwesome.EntityComponents; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.EntityComponents.UIComponents { public class TransferUIComponent : UIComponent { - public event EventHandler Closed; + public event EventHandler? Closed; - private TransferScreen transferScreen; + private TransferScreen? transferScreen; private readonly InventoryComponent chestInventory; public TransferUIComponent(InventoryComponent chestInventory) @@ -24,7 +20,7 @@ public TransferUIComponent(InventoryComponent chestInventory) } - private void TransferScreen_Closed(object sender, NavigationEventArgs e) + private void TransferScreen_Closed(object? sender, NavigationEventArgs e) { Closed?.Invoke(sender, e); } diff --git a/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/UIComponent.cs b/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/UIComponent.cs index 98490514..5a9d1dd0 100644 --- a/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/UIComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/EntityComponents/UIComponents/UIComponent.cs @@ -1,11 +1,6 @@ using engenious.UI; using OctoAwesome.Client.UI.Components; using OctoAwesome.Components; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.EntityComponents.UIComponents { @@ -13,8 +8,8 @@ public abstract class UIComponent : Component, IEntityComponent, IFunctionalBloc { protected BaseScreenComponent ScreenComponent { get; } public AssetComponent AssetComponent { get; } - - public UIComponent() + + protected UIComponent() { ScreenComponent = TypeContainer.Get(); AssetComponent = TypeContainer.Get(); diff --git a/OctoAwesome/OctoAwesome.Basics/Extension.cs b/OctoAwesome/OctoAwesome.Basics/Extension.cs index c7123da0..da06af47 100644 --- a/OctoAwesome/OctoAwesome.Basics/Extension.cs +++ b/OctoAwesome/OctoAwesome.Basics/Extension.cs @@ -1,10 +1,8 @@ -using OctoAwesome.Basics.Definitions.Blocks; -using OctoAwesome.Basics.Entities; +using OctoAwesome.Basics.Entities; using OctoAwesome.Basics.EntityComponents; using OctoAwesome.Basics.SimulationComponents; using OctoAwesome.EntityComponents; using System.Reflection; -using System.Linq; using System; using engenious; using OctoAwesome.Services; @@ -14,18 +12,17 @@ namespace OctoAwesome.Basics { + public sealed class Extension : IExtension { - public string Description => Languages.OctoBasics.ExtensionDescription; + public string Description => Languages.OctoBasics.ExtensionDescription; public string Name => Languages.OctoBasics.ExtensionName; - public void Register(ITypeContainer typeContainer) { - + } - public void Register(IExtensionLoader extensionLoader, ITypeContainer typeContainer) { typeContainer.Register(); @@ -49,7 +46,7 @@ public void Register(IExtensionLoader extensionLoader, ITypeContainer typeContai extensionLoader.RegisterEntityExtender((player) => { var p = (Player)player; - var posComponent = new PositionComponent { Position = new Coordinate(0, new Index3(0, 0, 200), new Vector3(0, 0, 0)) }; + var posComponent = new PositionComponent { Position = new Coordinate(0, new Index3(0, 0, 200), new Vector3(0, 0)) }; p.Components.AddComponent(posComponent); p.Components.AddComponent(new BodyComponent() { Mass = 50f, Height = 3.5f, Radius = 0.75f }); @@ -71,7 +68,7 @@ public void Register(IExtensionLoader extensionLoader, ITypeContainer typeContai if (!c.ContainsComponent()) { - var pos = new Coordinate(0, new Index3(0, 0, 200), new Vector3(0, 0, 0)); + var pos = new Coordinate(0, new Index3(0, 0, 200), new Vector3(0, 0)); c.Components.AddComponent(new PositionComponent() { Position = pos @@ -90,11 +87,8 @@ public void Register(IExtensionLoader extensionLoader, ITypeContainer typeContai if (!c.Components.TryGetComponent(out var inventoryComponent)) { inventoryComponent = new InventoryComponent(); - c.inventoryComponent = inventoryComponent; c.Components.AddComponent(inventoryComponent); } - else - c.inventoryComponent = inventoryComponent; if (!c.ContainsComponent()) { @@ -102,15 +96,11 @@ public void Register(IExtensionLoader extensionLoader, ITypeContainer typeContai c.transferUiComponent.Closed += c.TransferUiComponentClosed; c.Components.AddComponent(c.transferUiComponent, true); } - - c.Components.AddComponent(new BodyComponent() { Height = 0.4f, Radius = 0.2f }, true); - c.Components.AddComponent(new BoxCollisionComponent(new[] { new BoundingBox(new Vector3(0, 0, 0), new Vector3(1, 1, 1)) }), true); + c.Components.AddComponent(new BoxCollisionComponent(new[] { new BoundingBox(new Vector3(0, 0), new Vector3(1, 1, 1)) }), true); c.Components.AddComponent(new RenderComponent() { Name = "Chest", ModelName = "chest", TextureName = "texchestmodel", BaseZRotation = -90 }, true); }); - - extensionLoader.RegisterSimulationExtender((s) => { s.Components.AddComponent(new WattMoverComponent()); diff --git a/OctoAwesome/OctoAwesome.Basics/FunctionBlocks/Chest.cs b/OctoAwesome/OctoAwesome.Basics/FunctionBlocks/Chest.cs index 1167b6d2..5c98bf43 100644 --- a/OctoAwesome/OctoAwesome.Basics/FunctionBlocks/Chest.cs +++ b/OctoAwesome/OctoAwesome.Basics/FunctionBlocks/Chest.cs @@ -1,21 +1,15 @@ using engenious; -using OctoAwesome.Basics.EntityComponents; using OctoAwesome.Basics.EntityComponents.UIComponents; using OctoAwesome.EntityComponents; using OctoAwesome.Serialization; -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Basics.FunctionBlocks { + [SerializationId(1, 3)] public class Chest : FunctionalBlock { - internal InventoryComponent inventoryComponent; internal AnimationComponent animationComponent; internal TransferUIComponent transferUiComponent; @@ -23,7 +17,6 @@ public Chest() { } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); @@ -37,16 +30,13 @@ public Chest(Coordinate position) { Position = position }); - - //Simulation.Entities.FirstOrDefault(x=>x.) } - internal void TransferUiComponentClosed(object sender, engenious.UI.NavigationEventArgs e) + internal void TransferUiComponentClosed(object? sender, engenious.UI.NavigationEventArgs e) { animationComponent.AnimationSpeed = -60f; } - protected override void OnInteract(GameTime gameTime, Entity entity) { if (entity is Player p) diff --git a/OctoAwesome/OctoAwesome.Basics/ITreeDefinition.cs b/OctoAwesome/OctoAwesome.Basics/ITreeDefinition.cs index 32946c6d..4b424c9e 100644 --- a/OctoAwesome/OctoAwesome.Basics/ITreeDefinition.cs +++ b/OctoAwesome/OctoAwesome.Basics/ITreeDefinition.cs @@ -1,8 +1,4 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Basics { diff --git a/OctoAwesome/OctoAwesome.Basics/Noise/INoise.cs b/OctoAwesome/OctoAwesome.Basics/Noise/INoise.cs index 9e7b5e3b..6e31d2b3 100644 --- a/OctoAwesome/OctoAwesome.Basics/Noise/INoise.cs +++ b/OctoAwesome/OctoAwesome.Basics/Noise/INoise.cs @@ -1,10 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OctoAwesome.Noise +namespace OctoAwesome.Basics.Noise { + public interface INoise { /// @@ -39,7 +35,9 @@ public interface INoise /// Höhe der Kachel /// Array in der größé sizeX * sizeY /// Gibt ein 2D-float-Array einer 2D-Noise zurück, welche kachelbar ist - float[] GetTileableNoiseMap2D(int startX, int startY, int width, int height, int tileSizeX, int tileSizeY, float[] noiseArray); + void GetTileableNoiseMap2D(int startX, int startY, int width, int height, int tileSizeX, int tileSizeY, + float[] noiseArray); + /// /// Gibt ein 3D-float-Array einer 3D-Noise im angegebem Bereich zurück @@ -79,14 +77,14 @@ public interface INoise /// Dicke(Tiefe 2.Grades) der Noise-Map /// Gibt ein 4D-float-Array einer 4D-Noise zurück float[,,,] GetNoiseMap4D(int startX, int startY, int startZ, int startW, int width, int height, int depth, int thickness); - + /// /// Gibt ein float-Wert einer 1D-Noise an gegebener Position zurück /// /// Position, für welche die Noise ausgegeben wird /// Gibt ein float-Wert einer 1D Noise zurück float GetNoise(int x); - + /// /// Gibt ein float-Wert einer 2D-Noise an gegebener Position zurück /// @@ -103,7 +101,7 @@ public interface INoise /// Höhe der Kachel /// Gibt ein float-Wert einer 2D Noise zurück, welche kachelbar ist float GetTileableNoise2D(int x, int y, int tileSizeX, int tileSizeY); - + /// /// Gibt ein float-Wert einer 3D-Noise an gegebener Position zurück /// diff --git a/OctoAwesome/OctoAwesome.Basics/Noise/PerlinNoiseGenerator.cs b/OctoAwesome/OctoAwesome.Basics/Noise/PerlinNoiseGenerator.cs deleted file mode 100644 index b624ff6b..00000000 --- a/OctoAwesome/OctoAwesome.Basics/Noise/PerlinNoiseGenerator.cs +++ /dev/null @@ -1,535 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace OctoAwesome.Noise -{ - public class PerlinNoiseGenerator : INoise - { - #region Interface - - public float[] GetNoiseMap(int startX, int width) - { - return PerlinNoise(startX, width); - } - - public float[,] GetNoiseMap2D(int startX, int startY, int width, int heigth) - { - return PerlinNoise2(startX, startY, width, heigth); - } - - public float[,,] GetNoiseMap3D(int startX, int startY, int startZ, int width, int heigth, int depth) - { - return PerlinNoise3(startX, startY, startZ, width, heigth, depth); - } - - #endregion - - #region NoiseCode - - - public float Smoothfactor { get; set; } - public float Persistance { get; set; } - public int Octaves { get; set; } - public int Sizefactor { get; set; } - public int Seed { get; private set; } - - - public PerlinNoiseGenerator(int seed, float smoothfactor = 0, float persistance = 0.25f, int octaves = 3, int sizefactor = 64) - { - Seed = seed; - Smoothfactor = smoothfactor; - Persistance = persistance; - Octaves = octaves; - Sizefactor = sizefactor; - } - - - #region Noise - - public float Noise(int x) - { - unchecked - { - int n = x * Seed; - n = (n << 13) ^ n; - n *= n * 15731; - n += 789221; - n *= n; - n += 1376312589; - n = n & 0x7fffffff; - - return (float)(1.0 - (n / 1073741824.0)); - } - } - - public float Noise2(int x, int y) - { - unchecked - { - int n = x + (y * 57 * Seed); - n = (n << 13) ^ n; - n *= n * 15731; - n += 789221; - n *= n; - n += 1376312589; - n = n & 0x7fffffff; - - return (float)(1.0 - (n / 1073741824.0)); - } - } - - public float Noise3(int x, int y, int z) - { - unchecked - { - int n = x + (y * 29) + (z * 37 * Seed); - n = (n << 13) ^ n; - n *= n * 15731; - n += 789221; - n *= n; - n += 1376312589; - n = n & 0x7fffffff; - - return (float)(1.0 - (n / 1073741824.0)); - } - } - - #endregion - - #region LinearInterpolation - - private float LinearInterpolation(float a, float b, float x) - { - return (a * (1 - x)) + (b * x); - } - - private float LinearInterpolation2(float a, float b, float c, float d, float x, float y) - { - float v1 = LinearInterpolation(a, b, x); - float v2 = LinearInterpolation(c, d, x); - return LinearInterpolation(v1, v2, y); - } - - private float LinearInterpolation3(float a, float b, float c, float d, float e, float f, float g, float h, float x, float y, float z) - { - float v1 = LinearInterpolation2(a, b, c, d, x, y); - float v2 = LinearInterpolation2(e, f, g, h, x, y); - return LinearInterpolation(v1, v2, z); - } - - #endregion - - #region InterpolatedNoise - - private float InterpolatedNoise(float x) - { - - int integer_X = (int)x; - float fractional_X = x - integer_X; - - float v1 = Noise(integer_X); - float v2 = Noise(integer_X + 1); - - - return LinearInterpolation(v1, v2, fractional_X); - } - - private float InterpolatedNoise2(float x, float y) - { - - int integer_X = (int)x; - float fractional_X = x - integer_X; - - int integer_Y = (int)y; - float fractional_Y = y - integer_Y; - - float v1 = Noise2(integer_X, integer_Y); - float v2 = Noise2(integer_X + 1, integer_Y); - float v3 = Noise2(integer_X, integer_Y + 1); - float v4 = Noise2(integer_X + 1, integer_Y + 1); - - - return LinearInterpolation2(v1, v2, v3, v4, fractional_X, fractional_Y); - } - - private float InterpolatedNoise3(float x, float y, float z) - { - - int integer_X = (int)x; - float fractional_X = x - integer_X; - - int integer_Y = (int)y; - float fractional_Y = y - integer_Y; - - int integer_Z = (int)z; - float fractional_Z = z - integer_Z; - - float v1 = Noise3(integer_X, integer_Y, integer_Z); - float v2 = Noise3(integer_X + 1, integer_Y, integer_Z); - float v3 = Noise3(integer_X, integer_Y + 1, integer_Z); - float v4 = Noise3(integer_X + 1, integer_Y + 1, integer_Z); - - float v5 = Noise3(integer_X, integer_Y, integer_Z + 1); - float v6 = Noise3(integer_X + 1, integer_Y, integer_Z + 1); - float v7 = Noise3(integer_X, integer_Y + 1, integer_Z + 1); - float v8 = Noise3(integer_X + 1, integer_Y + 1, integer_Z + 1); - - return LinearInterpolation3(v1, v2, v3, v4, v5, v6, v7, v8, fractional_X, fractional_Y, fractional_Z); - } - - #endregion - - #region SmoothedNoise - - public float SmoothedNoise(int x) - { - if (Smoothfactor == 0) return Noise(x); - - return Noise(x) * ((Noise(x + 1) - Noise(x - 1)) / Smoothfactor); - } - - public float SmoothedNoise2(int x, int y) - { - - if (Smoothfactor == 0) return Noise2(x, y); - - float sides = (Noise2(x + 1, y) + Noise2(x - 1, y) + Noise2(x, y + 1) + Noise2(x, y - 1)) / (4 * Smoothfactor); - float corners = (Noise2(x + 1, y + 1) + Noise2(x - 1, y - 1) + Noise2(x - 1, y + 1) + Noise2(x + 1, y - 1)) / (4 * (float)Math.Sqrt(2) * Smoothfactor); - float center = Noise2(x, y) / (2 * Smoothfactor); - - return center + sides + corners; - - } - - public float SmoothedNoise3(int x, int y, int z) - { - - if (Smoothfactor == 0) return Noise3(x, y, z); - - float directSides = (Noise3(x + 1, y, z) + Noise3(x - 1, y, z) + Noise3(x, y + 1, z) + Noise3(x, y - 1, z) + Noise3(x, y, z - 1) + Noise3(x, y, z + 1)) / (6 * Smoothfactor); - - float indirectSides = (Noise3(x + 1, y + 1, z) + Noise3(x - 1, y - 1, z) + Noise3(x - 1, y + 1, z) + Noise3(x + 1, y - 1, z) + - Noise3(x + 1, y, z - 1) + Noise3(x - 1, y, z - 1) + Noise3(x, y + 1, z - 1) + Noise3(x, y - 1, z - 1) + - Noise3(x + 1, y, z + 1) + Noise3(x - 1, y, z + 1) + Noise3(x, y + 1, z + 1) + Noise3(x, y - 1, z + 1)) / - (12 * (float)Math.Sqrt(2) * Smoothfactor); - - float corners = (Noise3(x + 1, y + 1, z - 1) + Noise3(x - 1, y - 1, z - 1) + Noise3(x - 1, y + 1, z - 1) + Noise3(x + 1, y - 1, z - 1) + - Noise3(x + 1, y + 1, z + 1) + Noise3(x - 1, y - 1, z + 1) + Noise3(x - 1, y + 1, z + 1) + Noise3(x + 1, y - 1, z + 1)) / - (8 * (float)Math.Sqrt(3) * Smoothfactor); - - - float center = Noise3(x, y, z) / (3 * Smoothfactor); - - return center + directSides + indirectSides + corners; - - } - - #endregion - - #region InterpolatedSNoise - - private float InterpolatedSNoise(float x) - { - - int integer_X = (int)x; - if (x < 0) integer_X--; - float fractional_X = x - integer_X; - - float v1 = SmoothedNoise(integer_X); - float v2 = SmoothedNoise(integer_X + 1); - - - return LinearInterpolation(v1, v2, fractional_X); - } - - private float InterpolatedSNoise2(float x, float y) - { - - int integer_X = (int)x; - if (x < 0) integer_X--; - float fractional_X = x - integer_X; - - - int integer_Y = (int)y; - if (y < 0) integer_Y--; - float fractional_Y = y - integer_Y; - - float v1 = SmoothedNoise2(integer_X, integer_Y); - float v2 = SmoothedNoise2(integer_X + 1, integer_Y); - float v3 = SmoothedNoise2(integer_X, integer_Y + 1); - float v4 = SmoothedNoise2(integer_X + 1, integer_Y + 1); - - - return LinearInterpolation2(v1, v2, v3, v4, fractional_X, fractional_Y); - } - - private float InterpolatedSNoise3(float x, float y, float z) - { - - int integer_X = (int)x; - if (x < 0) integer_X--; - float fractional_X = x - integer_X; - - int integer_Y = (int)y; - if (y < 0) integer_Y--; - float fractional_Y = y - integer_Y; - - int integer_Z = (int)z; - if (z < 0) integer_Z--; - float fractional_Z = z - integer_Z; - - float v1 = SmoothedNoise3(integer_X, integer_Y, integer_Z); - float v2 = SmoothedNoise3(integer_X + 1, integer_Y, integer_Z); - float v3 = SmoothedNoise3(integer_X, integer_Y + 1, integer_Z); - float v4 = SmoothedNoise3(integer_X + 1, integer_Y + 1, integer_Z); - - float v5 = SmoothedNoise3(integer_X, integer_Y, integer_Z + 1); - float v6 = SmoothedNoise3(integer_X + 1, integer_Y, integer_Z + 1); - float v7 = SmoothedNoise3(integer_X, integer_Y + 1, integer_Z + 1); - float v8 = SmoothedNoise3(integer_X + 1, integer_Y + 1, integer_Z + 1); - - return LinearInterpolation3(v1, v2, v3, v4, v5, v6, v7, v8, fractional_X, fractional_Y, fractional_Z); - } - - #endregion - - #region PerlinAlgorithm - - public float[] PerlinNoise(int startX, int width) - { - - float[,] noiseLayers = new float[Octaves, width]; - - if (Sizefactor < 1) Sizefactor = 1; - - - for (int i = 0; i < Octaves; i++) - { - - float frequency = (float)Math.Pow(2, i); - float amplitude = (float)Math.Pow(Persistance, i); - - for (int x = 0; x < width; x++) - { - noiseLayers[i, x] = InterpolatedSNoise((float)(x + startX) / Sizefactor * frequency) * amplitude; - } - } - - float[] finishLayer = new float[width]; - - for (int x = 0; x < width; x++) - { - for (int i = 0; i < Octaves; i++) - { - finishLayer[x] += noiseLayers[i, x]; - } - } - - return finishLayer; - } - - public float[,] PerlinNoise2(int startX, int startY, int width, int heigth) - { - - float[,,] noiseLayers = new float[Octaves, width, heigth]; - - if (Sizefactor < 1) Sizefactor = 1; - - - for (int i = 0; i < Octaves; i++) - { - - float frequency = (float)Math.Pow(2, i); - float amplitude = (float)Math.Pow(Persistance, i); - - for (int x = 0; x < width; x++) - { - for (int y = 0; y < heigth; y++) - { - noiseLayers[i, x, y] = InterpolatedSNoise2((float)(x + startX) / Sizefactor * frequency, (float)(y + startY) / Sizefactor * frequency) * amplitude; - } - } - } - - float[,] finishLayer = new float[width, heigth]; - - for (int x = 0; x < width; x++) - { - for (int y = 0; y < heigth; y++) - { - for (int i = 0; i < Octaves; i++) - { - finishLayer[x, y] += noiseLayers[i, x, y]; - } - } - } - - return finishLayer; - } - - public float[,,] PerlinNoise3(int startX, int startY, int startZ, int width, int heigth, int depth) - { - - float[,,,] noiseLayers = new float[Octaves, width, heigth, depth]; - - if (Sizefactor < 1) Sizefactor = 1; - - - for (int i = 0; i < Octaves; i++) - { - - float frequency = (float)Math.Pow(2, i); - float amplitude = (float)Math.Pow(Persistance, i); - - for (int x = 0; x < width; x++) - { - for (int y = 0; y < heigth; y++) - { - for (int z = 0; z < depth; z++) - { - noiseLayers[i, x, y, z] = InterpolatedSNoise3((float)(x + startX) / Sizefactor * frequency, (float)(y + startY) / Sizefactor * frequency, (float)(z + startZ) / Sizefactor * frequency) * amplitude; - } - } - } - } - - float[,,] finishLayer = new float[width, heigth, depth]; - - for (int x = 0; x < width; x++) - { - for (int y = 0; y < heigth; y++) - { - for (int z = 0; z < depth; z++) - { - for (int i = 0; i < Octaves; i++) - { - finishLayer[x, y, z] += noiseLayers[i, x, y, z]; - } - } - } - } - - return finishLayer; - } - - public float PerlinNoise3Web(float x, float y, float z) - { - - float total = 0; - - for (int i = 0; i < Octaves; i++) - { - float frequency = (float)Math.Pow(2, i); - float amplitude = (float)Math.Pow(Persistance, i); - - total += InterpolatedSNoise3(x * frequency, y * frequency, z * frequency) * amplitude; - } - return total; - } - - - //public float[,,] PerlinNoiseTest2(float persistance, int octaves, int sizefactor, int width, int heigth) - //{ - - // float[, ,] noiseLayers = new float[octaves + 1, width, heigth]; - - // if (sizefactor < 1) sizefactor = 1; - - - // for (int i = 0; i < octaves; i++) - // { - - // int frequency = (int)Math.Pow(2, i); - // float amplitude = (float)Math.Pow(persistance, octaves - i); - - // for (int x = 0; x < width; x++) - // { - // for (int y = 0; y < heigth; y++) - // { - - // noiseLayers[i, x, y] = InterpolatedSNoise2(((float)x) / frequency / sizefactor, ((float)y) / frequency / sizefactor) * amplitude; - - // } - // } - // } - - // //float[,] finishLayer = new float[width, heigth]; - - // for (int x = 0; x < width; x++) - // { - // for (int y = 0; y < heigth; y++) - // { - // for (int i = 0; i < octaves; i++) - // { - - - // noiseLayers[octaves, x, y] += noiseLayers[i, x, y]; - - // } - // } - // } - - // return noiseLayers; - //} - - #endregion - - #endregion - - - public float[,,,] GetNoiseMap4D(int startX, int startY, int startZ, int startW, int width, int height, int depth, int wDepth) - { - throw new NotImplementedException(); - } - - public float[] GetTileableNoiseMap2D(int startX, int startY, int width, int height, int tileSizeX, int tileSizeY, float[] noiseArray) - { - throw new NotImplementedException(); - } - - public float[,,] GetTileableNoiseMap3D(int startX, int startY, int startZ, int width, int height, int depth, int tileSizeX, int tileSizeY) - { - throw new NotImplementedException(); - } - - public float GetNoise(int x) - { - throw new NotImplementedException(); - } - - public float GetNoise2D(int x, int y) - { - throw new NotImplementedException(); - } - - public float GetTileableNoise2D(int x, int y, int tileSizeX, int tileSizeY) - { - throw new NotImplementedException(); - } - - public float GetNoise3D(int x, int y, int z) - { - throw new NotImplementedException(); - } - - public float GetTileableNoise3D(int x, int y, int z, int tileSizeX, int tileSizeY, int tileSizeZ) - { - throw new NotImplementedException(); - } - - public float GetNoise4D(int x, int y, int z, int w) - { - throw new NotImplementedException(); - } - - - public float GetTileableNoise3D(int x, int y, int z, int tileSizeX, int tileSizeY) - { - throw new NotImplementedException(); - } - - - } -} diff --git a/OctoAwesome/OctoAwesome.Basics/Noise/SimplexNoiseGenerator.cs b/OctoAwesome/OctoAwesome.Basics/Noise/SimplexNoiseGenerator.cs index b372ac29..3ab8141a 100644 --- a/OctoAwesome/OctoAwesome.Basics/Noise/SimplexNoiseGenerator.cs +++ b/OctoAwesome/OctoAwesome.Basics/Noise/SimplexNoiseGenerator.cs @@ -1,12 +1,10 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; -using System.Diagnostics; -namespace OctoAwesome.Noise +namespace OctoAwesome.Basics.Noise { + public class SimplexNoiseGenerator : INoise { @@ -15,39 +13,29 @@ public class SimplexNoiseGenerator : INoise private byte[] permutations; private static readonly byte[] range = { 0, 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 }; private int octaves; - private float persistance; - - public int Seed { get; private set; } - + private float persistence; + public int Seed { get; } public float FrequencyX { get; set; } public float FrequencyY { get; set; } public float FrequencyZ { get; set; } public float FrequencyW { get; set; } public float Factor { get; set; } - public int Octaves { - get - { - return octaves; - } + get => octaves; set { octaves = value; RecalcMax(); } } - - public float Persistance + public float Persistence { - get - { - return persistance; - } + get => persistence; set { - persistance = value; + persistence = value; RecalcMax(); } } @@ -60,41 +48,31 @@ private void CreatePermutations() } - public float MaxValue { get; private set; } + private float MaxValue { get; set; } private void RecalcMax() { MaxValue = 0f; for (int i = 0; i < Octaves; i++) { - MaxValue += (float)Math.Pow(Persistance, i); + MaxValue += (float)Math.Pow(Persistence, i); } } - - #endregion public SimplexNoiseGenerator(int seed, float frequencyX = 1f, float frequencyY = 1f, float frequencyZ = 1f, float frequencyW = 1f) { Seed = seed; Octaves = 5; - Persistance = 0.5f; + Persistence = 0.5f; FrequencyX = frequencyX; FrequencyY = frequencyY; FrequencyZ = frequencyZ; FrequencyW = frequencyW; Factor = 1; CreatePermutations(); - } #region NoiseMaps - - /// - /// Gibt ein float-Array einer 1D-Noise im angegebenem Bereich zurück - /// - /// Startposition, ab welcher die Noise Werte ausgegeben werden - /// Anzahl der gewollten Noise-Werte - /// Gibt ein float-Array einer 1D Noise zurück public float[] GetNoiseMap(int startX, int width) { float[] noise = new float[width]; @@ -105,7 +83,7 @@ public float[] GetNoiseMap(int startX, int width) for (int i = 0; i < Octaves; i++) { noise[x] += Noise((x + startX) * frequencyX) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; } noise[x] = noise[x] * Factor / MaxValue; @@ -135,7 +113,7 @@ public float[] GetNoiseMap(int startX, int width) for (int i = 0; i < Octaves; i++) { noise[x, y] += Noise2D((x + startX) * frequencyX, (y + startY) * frequencyZ) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; frequencyZ *= 2f; } @@ -155,10 +133,9 @@ public float[] GetNoiseMap(int startX, int width) /// Breite der Kachel /// Höhe der Kachel /// Gibt ein 2D-float-Array einer 2D-Noise zurück, welche kachelbar ist - public float[] GetTileableNoiseMap2D(int startX, int startY, int sizeX, int sizeY, int tileSizeX, int tileSizeY, float[] array) + public void GetTileableNoiseMap2D(int startX, int startY, int sizeX, int sizeY, int tileSizeX, int tileSizeY, + float[] array) { - //float[,] noise = new float[sizeX, sizeY]; - Parallel.For(0, sizeX, x => { for (int y = 0; y < sizeY; y++) @@ -179,15 +156,13 @@ public float[] GetTileableNoiseMap2D(int startX, int startY, int sizeX, int size { array[(y * Chunk.CHUNKSIZE_X) + x] += Noise4D(nx * frequencyX, ny * frequencyY, nz * frequencyX, nw * frequencyY) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; frequencyY *= 2f; } array[(y * Chunk.CHUNKSIZE_X) + x] = array[(y * Chunk.CHUNKSIZE_X) + x] * Factor / MaxValue; } }); - - return array; } /// @@ -203,8 +178,6 @@ public float[] GetTileableNoiseMap2D(int startX, int startY, int sizeX, int size public float[,,] GetNoiseMap3D(int startX, int startY, int startZ, int width, int height, int depth) { float[,,] noise = new float[width, height, depth]; - - Parallel.For(0, width, x => //for (int x = 0; x < width; x++) { @@ -220,7 +193,7 @@ public float[] GetTileableNoiseMap2D(int startX, int startY, int sizeX, int size { noise[x, y, z] += Noise3D((x + startX) * frequencyX, (y + startY) * frequencyY, (z + startZ) * frequencyZ) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2; frequencyY *= 2; frequencyZ *= 2; @@ -274,7 +247,7 @@ public float[] GetTileableNoiseMap2D(int startX, int startY, int sizeX, int size { noise[x, y, z] += Noise5D(nx * frequencyX, ny * frequencyY, z * frequencyZ, nw * frequencyX, nv * frequencyY) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; frequencyY *= 2f; frequencyZ *= 2f; @@ -321,7 +294,7 @@ public float[] GetTileableNoiseMap2D(int startX, int startY, int sizeX, int size for (int i = 0; i < Octaves; i++) { noise[x, y, z, w] += Noise4D((x + startX) * frequencyX, (y + startY) * frequencyY, (z + startZ) * frequencyZ, (w + startW) * frequencyW) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2; frequencyY *= 2; frequencyZ *= 2; @@ -352,7 +325,7 @@ public float GetNoise(int x) for (int i = 0; i < Octaves; i++) { noise += Noise(x * frequencyX) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2; } @@ -374,7 +347,7 @@ public float GetNoise2D(int x, int y) for (int i = 0; i < Octaves; i++) { noise += Noise2D(x * frequencyX, y * frequencyY) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2; frequencyY *= 2; @@ -408,7 +381,7 @@ public float GetTileableNoise2D(int x, int y, int tileSizeX, int tileSizeY) { noise += Noise4D(nx * frequencyX, ny * frequencyY, nz * frequencyX, nw * frequencyY) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; frequencyY *= 2f; @@ -435,7 +408,7 @@ public float GetNoise3D(int x, int y, int z) { noise += Noise3D(x * frequencyX, y * frequencyY, z * frequencyZ) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; frequencyY *= 2f; frequencyZ *= 2f; @@ -471,7 +444,7 @@ public float GetTileableNoise3D(int x, int y, int z, int tileSizeX, int tileSize { noise += Noise5D(nx * frequencyX, ny * frequencyY, z * frequencyZ, nw * frequencyX, nv * frequencyY) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; frequencyY *= 2f; frequencyZ *= 2f; @@ -501,7 +474,7 @@ public float GetNoise4D(int x, int y, int z, int w) { noise += Noise4D(x * frequencyX, y * frequencyY, z * frequencyZ, w * frequencyW) * amplitude; - amplitude *= Persistance; + amplitude *= Persistence; frequencyX *= 2f; frequencyY *= 2f; frequencyZ *= 2f; @@ -514,25 +487,25 @@ public float GetNoise4D(int x, int y, int z, int w) #region Noise Implementation - private static readonly int[] grad3 = new int[] { 1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1, 0, 1, 0, 1, -1, 0, 1, 1, 0, -1, -1, 0, -1, 0, 1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1 }; - private static readonly int[] grad4 = new int[] { 0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1, 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1, -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0 }; - private static readonly int[] grad5 = new int[] { 0, -1, -1, -1, -1, 0, -1, -1, -1, 1, 0, -1, -1, 1, -1, 0, -1, -1, 1, 1, 0, -1, 1, -1, -1, 0, -1, 1, -1, 1, 0, -1, 1, 1, -1, 0, -1, 1, 1, 1, 0, 1, -1, -1, -1, 0, 1, -1, -1, 1, 0, 1, -1, 1, -1, 0, 1, -1, 1, 1, 0, 1, 1, -1, -1, 0, 1, 1, -1, 1, 0, 1, 1, 1, -1, 0, 1, 1, 1, 1, -1, 0, -1, -1, -1, -1, 0, -1, -1, 1, -1, 0, -1, 1, -1, -1, 0, -1, 1, 1, -1, 0, 1, -1, -1, -1, 0, 1, -1, 1, -1, 0, 1, 1, -1, -1, 0, 1, 1, 1, 1, 0, -1, -1, -1, 1, 0, -1, -1, 1, 1, 0, -1, 1, -1, 1, 0, -1, 1, 1, 1, 0, 1, -1, -1, 1, 0, 1, -1, 1, 1, 0, 1, 1, -1, 1, 0, 1, 1, 1, -1, -1, 0, -1, -1, -1, -1, 0, -1, 1, -1, -1, 0, 1, -1, -1, -1, 0, 1, 1, -1, 1, 0, -1, -1, -1, 1, 0, -1, 1, -1, 1, 0, 1, -1, -1, 1, 0, 1, 1, 1, -1, 0, -1, -1, 1, -1, 0, -1, 1, 1, -1, 0, 1, -1, 1, -1, 0, 1, 1, 1, 1, 0, -1, -1, 1, 1, 0, -1, 1, 1, 1, 0, 1, -1, 1, 1, 0, 1, 1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 1, -1, -1, 1, 0, -1, -1, -1, 1, 0, 1, -1, 1, -1, 0, -1, -1, 1, -1, 0, 1, -1, 1, 1, 0, -1, -1, 1, 1, 0, 1, 1, -1, -1, 0, -1, 1, -1, -1, 0, 1, 1, -1, 1, 0, -1, 1, -1, 1, 0, 1, 1, 1, -1, 0, -1, 1, 1, -1, 0, 1, 1, 1, 1, 0, -1, 1, 1, 1, 0, 1, -1, -1, -1, -1, 0, -1, -1, -1, 1, 0, -1, -1, 1, -1, 0, -1, -1, 1, 1, 0, -1, 1, -1, -1, 0, -1, 1, -1, 1, 0, -1, 1, 1, -1, 0, -1, 1, 1, 1, 0, 1, -1, -1, -1, 0, 1, -1, -1, 1, 0, 1, -1, 1, -1, 0, 1, -1, 1, 1, 0, 1, 1, -1, -1, 0, 1, 1, -1, 1, 0, 1, 1, 1, -1, 0, 1, 1, 1, 1, 0 }; + private static readonly int[] Grad3 = { 1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1, 0, 1, 0, 1, -1, 0, 1, 1, 0, -1, -1, 0, -1, 0, 1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1 }; + private static readonly int[] Grad4 = { 0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1, 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1, -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0 }; + private static readonly int[] Grad5 = { 0, -1, -1, -1, -1, 0, -1, -1, -1, 1, 0, -1, -1, 1, -1, 0, -1, -1, 1, 1, 0, -1, 1, -1, -1, 0, -1, 1, -1, 1, 0, -1, 1, 1, -1, 0, -1, 1, 1, 1, 0, 1, -1, -1, -1, 0, 1, -1, -1, 1, 0, 1, -1, 1, -1, 0, 1, -1, 1, 1, 0, 1, 1, -1, -1, 0, 1, 1, -1, 1, 0, 1, 1, 1, -1, 0, 1, 1, 1, 1, -1, 0, -1, -1, -1, -1, 0, -1, -1, 1, -1, 0, -1, 1, -1, -1, 0, -1, 1, 1, -1, 0, 1, -1, -1, -1, 0, 1, -1, 1, -1, 0, 1, 1, -1, -1, 0, 1, 1, 1, 1, 0, -1, -1, -1, 1, 0, -1, -1, 1, 1, 0, -1, 1, -1, 1, 0, -1, 1, 1, 1, 0, 1, -1, -1, 1, 0, 1, -1, 1, 1, 0, 1, 1, -1, 1, 0, 1, 1, 1, -1, -1, 0, -1, -1, -1, -1, 0, -1, 1, -1, -1, 0, 1, -1, -1, -1, 0, 1, 1, -1, 1, 0, -1, -1, -1, 1, 0, -1, 1, -1, 1, 0, 1, -1, -1, 1, 0, 1, 1, 1, -1, 0, -1, -1, 1, -1, 0, -1, 1, 1, -1, 0, 1, -1, 1, -1, 0, 1, 1, 1, 1, 0, -1, -1, 1, 1, 0, -1, 1, 1, 1, 0, 1, -1, 1, 1, 0, 1, 1, -1, -1, -1, 0, -1, -1, -1, -1, 0, 1, -1, -1, 1, 0, -1, -1, -1, 1, 0, 1, -1, 1, -1, 0, -1, -1, 1, -1, 0, 1, -1, 1, 1, 0, -1, -1, 1, 1, 0, 1, 1, -1, -1, 0, -1, 1, -1, -1, 0, 1, 1, -1, 1, 0, -1, 1, -1, 1, 0, 1, 1, 1, -1, 0, -1, 1, 1, -1, 0, 1, 1, 1, 1, 0, -1, 1, 1, 1, 0, 1, -1, -1, -1, -1, 0, -1, -1, -1, 1, 0, -1, -1, 1, -1, 0, -1, -1, 1, 1, 0, -1, 1, -1, -1, 0, -1, 1, -1, 1, 0, -1, 1, 1, -1, 0, -1, 1, 1, 1, 0, 1, -1, -1, -1, 0, 1, -1, -1, 1, 0, 1, -1, 1, -1, 0, 1, -1, 1, 1, 0, 1, 1, -1, -1, 0, 1, 1, -1, 1, 0, 1, 1, 1, -1, 0, 1, 1, 1, 1, 0 }; - private static float Dotproduct(int dIndex, float x, float y) + private static float DotProduct(int dIndex, float x, float y) { - return (grad3[dIndex] * x) + (grad3[dIndex + 1] * y); + return (Grad3[dIndex] * x) + (Grad3[dIndex + 1] * y); } - private static float Dotproduct(int dIndex, float x, float y, float z) + private static float DotProduct(int dIndex, float x, float y, float z) { - return (grad3[dIndex] * x) + (grad3[dIndex + 1] * y) + (grad3[dIndex + 2] * z); + return (Grad3[dIndex] * x) + (Grad3[dIndex + 1] * y) + (Grad3[dIndex + 2] * z); } - private static float Dotproduct(int dIndex, float x, float y, float z, float w) + private static float DotProduct(int dIndex, float x, float y, float z, float w) { - return (grad4[dIndex] * x) + (grad4[dIndex + 1] * y) + (grad4[dIndex + 2] * z) + (grad4[dIndex + 3] * w); + return (Grad4[dIndex] * x) + (Grad4[dIndex + 1] * y) + (Grad4[dIndex + 2] * z) + (Grad4[dIndex + 3] * w); } - private static float Dotproduct(int dIndex, float x, float y, float z, float w, float v) + private static float DotProduct(int dIndex, float x, float y, float z, float w, float v) { - return (grad5[dIndex] * x) + (grad5[dIndex + 1] * y) + (grad5[dIndex + 2] * z) + (grad5[dIndex + 3] * w) + (grad5[dIndex + 4] * v); + return (Grad5[dIndex] * x) + (Grad5[dIndex + 1] * y) + (Grad5[dIndex + 2] * z) + (Grad5[dIndex + 3] * w) + (Grad5[dIndex + 4] * v); } private static readonly float F2 = (float)(0.5f * (Math.Sqrt(3.0f) - 1.0f)); private static readonly float G2 = (float)(3.0f - Math.Sqrt(3.0f)) / 6.0f; @@ -543,7 +516,7 @@ private static float Dotproduct(int dIndex, float x, float y, float z, float w, private static readonly float F5 = (float)((Math.Sqrt(6.0) - 1) / 5.0); private static readonly float G5 = (float)((6.0 - Math.Sqrt(6.0)) / 30.0); - public static int Fastfloor(float val) + private static int FastFloor(float val) { return val > 0 ? (int)val : (int)val - 1; } @@ -575,8 +548,6 @@ private float Noise(float x) float v1 = NoiseFunction(integer_X); float v2 = NoiseFunction(integer_X + 1); - - return LinearInterpolation(v1, v2, fractional_X); } @@ -586,8 +557,8 @@ private float Noise2D(float xin, float yin) float s = (xin + yin) * F2; - int i = Fastfloor(xin + s); - int j = Fastfloor(yin + s); + int i = FastFloor(xin + s); + int j = FastFloor(yin + s); float t = (i + j) * G2; float X0 = i - t; @@ -621,21 +592,21 @@ private float Noise2D(float xin, float yin) else { t0 *= t0; - n0 = t0 * t0 * Dotproduct(gi0 * 3, x0, y0); + n0 = t0 * t0 * DotProduct(gi0 * 3, x0, y0); } float t1 = 0.5f - (x1 * x1) - (y1 * y1); if (t1 <= 0) n1 = 0.0f; else { t1 *= t1; - n1 = t1 * t1 * Dotproduct(gi1 * 3, x1, y1); + n1 = t1 * t1 * DotProduct(gi1 * 3, x1, y1); } float t2 = 0.5f - (x2 * x2) - (y2 * y2); if (t2 <= 0) n2 = 0.0f; else { t2 *= t2; - n2 = t2 * t2 * Dotproduct(gi2 * 3, x2, y2); + n2 = t2 * t2 * DotProduct(gi2 * 3, x2, y2); } return 70.0f * (n0 + n1 + n2); } @@ -644,9 +615,9 @@ private float Noise3D(float x, float y, float z) { float n0, n1, n2, n3; float s = (x + y + z) * F3; - int i = Fastfloor(x + s); - int j = Fastfloor(y + s); - int k = Fastfloor(z + s); + int i = FastFloor(x + s); + int j = FastFloor(y + s); + int k = FastFloor(z + s); float t = (i + j + k) * G3; float X0 = i - t; float Y0 = j - t; @@ -695,28 +666,28 @@ private float Noise3D(float x, float y, float z) else { t0 *= t0; - n0 = t0 * t0 * Dotproduct(gi0 * 3, x0, y0, z0); + n0 = t0 * t0 * DotProduct(gi0 * 3, x0, y0, z0); } float t1 = 0.6f - (x1 * x1) - (y1 * y1) - (z1 * z1); if (t1 <= 0) n1 = 0.0f; else { t1 *= t1; - n1 = t1 * t1 * Dotproduct(gi1 * 3, x1, y1, z1); + n1 = t1 * t1 * DotProduct(gi1 * 3, x1, y1, z1); } float t2 = 0.6f - (x2 * x2) - (y2 * y2) - (z2 * z2); if (t2 <= 0) n2 = 0.0f; else { t2 *= t2; - n2 = t2 * t2 * Dotproduct(gi2 * 3, x2, y2, z2); + n2 = t2 * t2 * DotProduct(gi2 * 3, x2, y2, z2); } float t3 = 0.6f - (x3 * x3) - (y3 * y3) - (z3 * z3); if (t3 <= 0) n3 = 0.0f; else { t3 *= t3; - n3 = t3 * t3 * Dotproduct(gi3 * 3, x3, y3, z3); + n3 = t3 * t3 * DotProduct(gi3 * 3, x3, y3, z3); } return 32.0f * (n0 + n1 + n2 + n3); @@ -728,10 +699,10 @@ private float Noise4D(float x, float y, float z, float w) float n0, n1, n2, n3, n4; float s = (x + y + z + w) * F4; - int i = Fastfloor(x + s); - int j = Fastfloor(y + s); - int k = Fastfloor(z + s); - int l = Fastfloor(w + s); + int i = FastFloor(x + s); + int j = FastFloor(y + s); + int k = FastFloor(z + s); + int l = FastFloor(w + s); float t = (i + j + k + l) * G4; float X0 = i - t; float Y0 = j - t; @@ -803,35 +774,35 @@ private float Noise4D(float x, float y, float z, float w) else { t0 *= t0; - n0 = t0 * t0 * Dotproduct(gi0 * 4, x0, y0, z0, w0); + n0 = t0 * t0 * DotProduct(gi0 * 4, x0, y0, z0, w0); } float t1 = 0.6f - (x1 * x1) - (y1 * y1) - (z1 * z1) - (w1 * w1); if (t1 < 0) n1 = 0.0f; else { t1 *= t1; - n1 = t1 * t1 * Dotproduct(gi1 * 4, x1, y1, z1, w1); + n1 = t1 * t1 * DotProduct(gi1 * 4, x1, y1, z1, w1); } float t2 = 0.6f - (x2 * x2) - (y2 * y2) - (z2 * z2) - (w2 * w2); if (t2 < 0) n2 = 0.0f; else { t2 *= t2; - n2 = t2 * t2 * Dotproduct(gi2 * 4, x2, y2, z2, w2); + n2 = t2 * t2 * DotProduct(gi2 * 4, x2, y2, z2, w2); } float t3 = 0.6f - (x3 * x3) - (y3 * y3) - (z3 * z3) - (w3 * w3); if (t3 < 0) n3 = 0.0f; else { t3 *= t3; - n3 = t3 * t3 * Dotproduct(gi3 * 4, x3, y3, z3, w3); + n3 = t3 * t3 * DotProduct(gi3 * 4, x3, y3, z3, w3); } float t4 = 0.6f - (x4 * x4) - (y4 * y4) - (z4 * z4) - (w4 * w4); if (t4 < 0) n4 = 0.0f; else { t4 *= t4; - n4 = t4 * t4 * Dotproduct(gi4 * 4, x4, y4, z4, w4); + n4 = t4 * t4 * DotProduct(gi4 * 4, x4, y4, z4, w4); } return 27.0f * (n0 + n1 + n2 + n3 + n4); @@ -842,11 +813,11 @@ private float Noise5D(float x, float y, float z, float w, float v) float n0, n1, n2, n3, n4, n5; float s = (x + y + z + w + v) * F5; - int i = Fastfloor(x + s); - int j = Fastfloor(y + s); - int k = Fastfloor(z + s); - int l = Fastfloor(w + s); - int m = Fastfloor(v + s); + int i = FastFloor(x + s); + int j = FastFloor(y + s); + int k = FastFloor(z + s); + int l = FastFloor(w + s); + int m = FastFloor(v + s); float t = (i + j + k + l + m) * G5; float X0 = i - t; float Y0 = j - t; @@ -952,131 +923,47 @@ private float Noise5D(float x, float y, float z, float w, float v) else { t0 *= t0; - n0 = t0 * t0 * Dotproduct(gi0 * 5, x0, y0, z0, w0, v0); + n0 = t0 * t0 * DotProduct(gi0 * 5, x0, y0, z0, w0, v0); } float t1 = 0.6f - (x1 * x1) - (y1 * y1) - (z1 * z1) - (w1 * w1) - (v1 * v1); if (t1 < 0) n1 = 0.0f; else { t1 *= t1; - n1 = t1 * t1 * Dotproduct(gi1 * 5, x1, y1, z1, w1, v1); + n1 = t1 * t1 * DotProduct(gi1 * 5, x1, y1, z1, w1, v1); } float t2 = 0.6f - (x2 * x2) - (y2 * y2) - (z2 * z2) - (w2 * w2) - (v2 * v2); if (t2 < 0) n2 = 0.0f; else { t2 *= t2; - n2 = t2 * t2 * Dotproduct(gi2 * 5, x2, y2, z2, w2, v2); + n2 = t2 * t2 * DotProduct(gi2 * 5, x2, y2, z2, w2, v2); } float t3 = 0.6f - (x3 * x3) - (y3 * y3) - (z3 * z3) - (w3 * w3) - (v3 * v3); if (t3 < 0) n3 = 0.0f; else { t3 *= t3; - n3 = t3 * t3 * Dotproduct(gi3 * 5, x3, y3, z3, w3, v3); + n3 = t3 * t3 * DotProduct(gi3 * 5, x3, y3, z3, w3, v3); } float t4 = 0.6f - (x4 * x4) - (y4 * y4) - (z4 * z4) - (w4 * w4) - (v4 * v4); if (t4 < 0) n4 = 0.0f; else { t4 *= t4; - n4 = t4 * t4 * Dotproduct(gi4 * 5, x4, y4, z4, w4, v4); + n4 = t4 * t4 * DotProduct(gi4 * 5, x4, y4, z4, w4, v4); } float t5 = 0.6f - (x5 * x5) - (y5 * y5) - (z5 * z5) - (w5 * w5) - (v5 * v5); if (t5 < 0) n5 = 0.0f; else { t5 *= t5; - n5 = t5 * t5 * Dotproduct(gi5 * 5, x5, y5, z5, w5, v5); + n5 = t5 * t5 * DotProduct(gi5 * 5, x5, y5, z5, w5, v5); } return 18.0f * (n0 + n1 + n2 + n3 + n4 + n5); } #endregion - - #region Sonstiges - - //List grads = new List(); - // for (int i = 0; i < 5; i++) - // { - // for (int x = -1; x <= 1; x += 2) - // { - // for (int y = -1; y <= 1; y += 2) - // { - // for (int z = -1; z <= 1; z += 2) - // { - // for (int w = -1; w <= 1; w += 2) - // { - // for (int v = -1; v <= 1; v += 2) - // { - // int[] grad = new int[] { x, y, z, w, v }; - // grad[i] = 0; - - // grads.Add(grad); - // } - // } - // } - // } - // } - // } - - // grads = grads.Distinct(new comp()).ToList(); - - // Debug.Write("{"); - // foreach (int[] grad in grads) - // Debug.Write(String.Join(",", grad) + ","); - - //class comp : EqualityComparer - //{ - - // public override bool Equals(int[] x, int[] y) - // { - // if (x == null || y == null) - // return false; - // if (x.Length != y.Length) - // return false; - // for (int i = 0; i < x.Length; i++) - // { - // if (x[i] != y[i]) - // return false; - // } - // return true; - // } - - // public override int GetHashCode(int[] obj) - // { - // return obj[0]; - // } - //} - - //float min = float.MaxValue, max = float.MinValue; - // SimplexNoiseGenerator gen = new SimplexNoiseGenerator(0); - - // for (int x = -10; x <= 10; x ++) - // { - // for (int y = -10; y <= 10; y ++) - // { - // for (int z = -10; z <= 10; z ++) - // { - // for (int w = -10; w <= 10; w ++) - // { - // for (int v = -10; v <= 10; v ++) - // { - // float val = gen.Noise5D(x, y, z, w); - - // min = Math.Min(val, min); - // max = Math.Max(val, max); - // } - // } - // } - // } - // } - // min = 1f / min; - // max = 1f / max; - - #endregion - - } } diff --git a/OctoAwesome/OctoAwesome.Basics/OctoAwesome.Basics.csproj b/OctoAwesome/OctoAwesome.Basics/OctoAwesome.Basics.csproj index ca69b10f..3d3779db 100644 --- a/OctoAwesome/OctoAwesome.Basics/OctoAwesome.Basics.csproj +++ b/OctoAwesome/OctoAwesome.Basics/OctoAwesome.Basics.csproj @@ -2,14 +2,14 @@ net5.0 - warnings + enable True - - + + diff --git a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/AccelerationComponent.cs b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/AccelerationComponent.cs index 6b27b592..eb6906b8 100644 --- a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/AccelerationComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/AccelerationComponent.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; using engenious; using OctoAwesome.Basics.EntityComponents; using OctoAwesome.Components; @@ -12,6 +10,7 @@ namespace OctoAwesome.Basics.SimulationComponents { + public sealed class AccelerationComponent : SimulationComponent< Entity, AccelerationComponent.AcceleratedEntity, @@ -46,8 +45,6 @@ protected override void UpdateValue(GameTime gameTime, AcceleratedEntity entity) var a3 = a2 * (float)gameTime.ElapsedGameTime.TotalSeconds; //DEBUGGING - - // Calculate Velocity change Vector3 velocityChange = ((2.0f / entity.Body.Mass) * power) * (float)gameTime.ElapsedGameTime.TotalSeconds; @@ -61,14 +58,11 @@ protected override void UpdateValue(GameTime gameTime, AcceleratedEntity entity) // Calculate Move Vector for the upcoming frame entity.Move.PositionMove = entity.Move.Velocity * (float)gameTime.ElapsedGameTime.TotalSeconds; } - protected override AcceleratedEntity OnAdd(Entity entity) => new AcceleratedEntity( entity, entity.Components.GetComponent(), entity.Components.GetComponent()); - - public record AcceleratedEntity(Entity Entity, MoveableComponent Move, BodyComponent Body) : SimulationComponentRecord(Entity, Move, Body); } diff --git a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/BlockInteractionComponent.cs b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/BlockInteractionComponent.cs index fb3f6d71..69f47c54 100644 --- a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/BlockInteractionComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/BlockInteractionComponent.cs @@ -1,17 +1,13 @@ using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Diagnostics; using engenious; using OctoAwesome.Services; -using OctoAwesome.Definitions.Items; using OctoAwesome.Definitions; using OctoAwesome.Components; namespace OctoAwesome.Basics.SimulationComponents { + public class BlockInteractionComponent : SimulationComponent< Entity, SimulationComponentRecord, @@ -21,13 +17,11 @@ public class BlockInteractionComponent : SimulationComponent< private readonly Simulation simulation; private readonly BlockCollectionService service; - public BlockInteractionComponent(Simulation simulation, BlockCollectionService interactionService) { this.simulation = simulation; service = interactionService; } - protected override void UpdateValue(GameTime gameTime, SimulationComponentRecord value) { var entity = value.Value; @@ -115,35 +109,34 @@ private void InteractWith(BlockInfo lastBlock, InventoryComponent inventory, Too { if (!lastBlock.IsEmpty && lastBlock.Block != 0) { - IItem activeItem; + IItem activeItem = null!; if (toolbar.ActiveTool.Item is IItem item) { activeItem = item; } - else + else if(toolbar.HandSlot.Item is IItem handItem) { - activeItem = toolbar.HandSlot.Item as IItem; + activeItem = handItem; } + + Debug.Assert(activeItem != null, nameof(activeItem) + " != null"); var blockHitInformation = service.Hit(lastBlock, activeItem, cache); - if (blockHitInformation.Valid) - foreach (var (Quantity, Definition) in blockHitInformation.List) + if (blockHitInformation.Valid && blockHitInformation.List != null) + foreach (var (quantity, definition) in blockHitInformation.List) { if (activeItem is IFluidInventory fluidInventory - && Definition is IBlockDefinition fluidBlock - && fluidBlock.Material is IFluidMaterialDefinition) + && definition is IBlockDefinition { Material: IFluidMaterialDefinition } fluidBlock) { - fluidInventory.AddFluid(Quantity, fluidBlock); + fluidInventory.AddFluid(quantity, fluidBlock); } - else if (Definition is IInventoryable invDef) + else if (definition is IInventoryable invDef) { - inventory.AddUnit(Quantity, invDef); + inventory.AddUnit(quantity, invDef); } } - - } } } diff --git a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/CollisionComponent.cs b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/CollisionComponent.cs index 27300d27..90d08eeb 100644 --- a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/CollisionComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/CollisionComponent.cs @@ -3,8 +3,10 @@ namespace OctoAwesome.Basics.SimulationComponents { + public sealed class CollisionComponent : SimulationComponent { + public override void Update(GameTime gameTime) { } protected override void OnAdd(Entity value) => throw new System.NotImplementedException(); protected override void OnRemove(Entity value) => throw new System.NotImplementedException(); diff --git a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/FunctionalBlockInteractionComponent.cs b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/FunctionalBlockInteractionComponent.cs index 961cf17e..22d2b343 100644 --- a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/FunctionalBlockInteractionComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/FunctionalBlockInteractionComponent.cs @@ -1,17 +1,11 @@ using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using engenious; using OctoAwesome.Services; -using OctoAwesome.Definitions.Items; -using OctoAwesome.Definitions; using OctoAwesome.Components; namespace OctoAwesome.Basics.SimulationComponents { + public class FunctionalBlockInteractionComponent : SimulationComponent< Entity, SimulationComponentRecord, @@ -20,13 +14,11 @@ public class FunctionalBlockInteractionComponent : SimulationComponent< { private readonly Simulation simulation; private readonly BlockCollectionService service; - public FunctionalBlockInteractionComponent(Simulation simulation, BlockCollectionService interactionService) { this.simulation = simulation; service = interactionService; } - protected override void UpdateValue(GameTime gameTime, SimulationComponentRecord value) { var entity = value.Value; diff --git a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/MoveComponent.cs b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/MoveComponent.cs index 9e1e15b5..9fa0a631 100644 --- a/OctoAwesome/OctoAwesome.Basics/SimulationComponents/MoveComponent.cs +++ b/OctoAwesome/OctoAwesome.Basics/SimulationComponents/MoveComponent.cs @@ -1,19 +1,20 @@ using System; using engenious; using OctoAwesome.Basics.EntityComponents; -using System.Linq; using OctoAwesome.EntityComponents; using engenious.Helper; using OctoAwesome.Components; namespace OctoAwesome.Basics.SimulationComponents { + public sealed class MoveComponent : SimulationComponent< Entity, SimulationComponentRecord, MoveableComponent, PositionComponent> { + protected override SimulationComponentRecord OnAdd(Entity entity) { var poscomp = entity.Components.GetComponent(); @@ -25,7 +26,6 @@ protected override SimulationComponentRecord(entity, movecomp, poscomp); } - protected override void UpdateValue(GameTime gameTime, SimulationComponentRecord value) { var entity = value.Value; @@ -85,8 +85,6 @@ private void CheckBoxCollision(GameTime gameTime, Entity entity, MoveableCompone return; BodyComponent bc = entity.Components.GetComponent(); - - Coordinate position = poscomp.Position; Vector3 move = movecomp.PositionMove; diff --git a/OctoAwesome/OctoAwesome.Basics/TreePopulator.cs b/OctoAwesome/OctoAwesome.Basics/TreePopulator.cs index 6d314b76..6c352fac 100644 --- a/OctoAwesome/OctoAwesome.Basics/TreePopulator.cs +++ b/OctoAwesome/OctoAwesome.Basics/TreePopulator.cs @@ -1,20 +1,19 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace OctoAwesome.Basics { + public class TreePopulator : MapPopulator { - private IEnumerable treeDefinitions = null; - + private IEnumerable? treeDefinitions = null; public TreePopulator() { Order = 10; } - private static IChunkColumn getColumn(IChunkColumn column00, IChunkColumn column10, IChunkColumn column01, IChunkColumn column11, int x, int y) + private static IChunkColumn GetColumn(IChunkColumn column00, IChunkColumn column10, IChunkColumn column01, IChunkColumn column11, int x, int y) { IChunkColumn column; if (x >= Chunk.CHUNKSIZE_X && y >= Chunk.CHUNKSIZE_Y) @@ -25,14 +24,11 @@ private static IChunkColumn getColumn(IChunkColumn column00, IChunkColumn column column = column10; else column = column00; - - return column; } - public override void Populate(IResourceManager resourceManager, IPlanet planet, IChunkColumn column00, IChunkColumn column10, IChunkColumn column01, IChunkColumn column11) { - // Tree Definitions initialisieren + // Initialize tree definitions if (treeDefinitions == null) { treeDefinitions = resourceManager.DefinitionManager.GetDefinitions().OrderBy(d => d.Order).ToArray(); diff --git a/OctoAwesome/OctoAwesome.Basics/UI/Screens/TransferScreen.cs b/OctoAwesome/OctoAwesome.Basics/UI/Screens/TransferScreen.cs index 18b8e08c..47d81287 100644 --- a/OctoAwesome/OctoAwesome.Basics/UI/Screens/TransferScreen.cs +++ b/OctoAwesome/OctoAwesome.Basics/UI/Screens/TransferScreen.cs @@ -7,13 +7,12 @@ using OctoAwesome.Client.UI.Controls; using OctoAwesome.EntityComponents; using System; -using System.Collections.Generic; namespace OctoAwesome.Basics.UI.Screens { public class TransferScreen : Screen { - public event EventHandler Closed; + public event EventHandler? Closed; private readonly AssetComponent assetComponent; private readonly Texture2D panelBackground; @@ -25,7 +24,6 @@ public class TransferScreen : Screen private InventoryComponent componentA; private InventoryComponent componentB; - public TransferScreen(BaseScreenComponent manager, AssetComponent assetComponent, InventoryComponent inventoryComponentA, InventoryComponent inventoryComponentB) : base(manager) { Background = new BorderBrush(Color.Black * 0.3f); @@ -113,7 +111,6 @@ internal void Rebuild(InventoryComponent inventoryComponentA, InventoryComponent inventoryA.Rebuild(componentA.Inventory); inventoryB.Rebuild(componentB.Inventory); } - protected override void OnKeyDown(KeyEventArgs args) { @@ -125,7 +122,6 @@ protected override void OnKeyDown(KeyEventArgs args) base.OnKeyDown(args); } - protected override void OnNavigatedFrom(NavigationEventArgs args) { base.OnNavigatedFrom(args); diff --git a/OctoAwesome/OctoAwesome.Basics/WauziPopulator.cs b/OctoAwesome/OctoAwesome.Basics/WauziPopulator.cs index d21bd807..c53fa998 100644 --- a/OctoAwesome/OctoAwesome.Basics/WauziPopulator.cs +++ b/OctoAwesome/OctoAwesome.Basics/WauziPopulator.cs @@ -1,31 +1,17 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using engenious; using OctoAwesome.Basics.Entities; -using OctoAwesome.Basics.FunctionBlocks; using OctoAwesome.EntityComponents; namespace OctoAwesome.Basics { public class WauziPopulator : IMapPopulator { - - Random r = new Random(); - - public int Order - { - get - { - return 11; - } - } + private readonly Random r = new(); + public int Order => 11; int ispop = 10; - - public void Populate(IResourceManager resourcemanager, IPlanet planet, IChunkColumn column00, IChunkColumn column01, IChunkColumn column10, IChunkColumn column11) + public void Populate(IResourceManager resourceManager, IPlanet planet, IChunkColumn column00, IChunkColumn column01, IChunkColumn column10, IChunkColumn column11) { //HACK: Activate Wauzi return; diff --git a/OctoAwesome/OctoAwesome.Client.UI/Components/AssetComponent.cs b/OctoAwesome/OctoAwesome.Client.UI/Components/AssetComponent.cs index f904849a..4a872487 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Components/AssetComponent.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Components/AssetComponent.cs @@ -1,8 +1,6 @@ using engenious; using engenious.Graphics; using engenious.UI; -using OctoAwesome.Client.UI; - using System; using System.Collections.Generic; using System.Drawing; @@ -13,15 +11,13 @@ namespace OctoAwesome.Client.UI.Components { + public sealed class AssetComponent : DrawableGameComponent { private readonly BaseScreenComponent screenComponent; private readonly ISettings settings; - public const string INFOFILENAME = "packinfo.xml"; - public const string SETTINGSKEY = "ActiveResourcePacks"; - public const string RESOURCEPATH = "Resources"; readonly Dictionary textures; readonly Dictionary bitmaps; @@ -48,7 +44,6 @@ public sealed class AssetComponent : DrawableGameComponent /// Auflistung aller aktuell aktiven Resource Packs. /// public IEnumerable ActiveResourcePacks => activePacks.AsEnumerable(); - public AssetComponent(BaseScreenComponent screenComponent, ISettings settings) : base(screenComponent.Game) { this.screenComponent = screenComponent; @@ -77,7 +72,6 @@ public AssetComponent(BaseScreenComponent screenComponent, ISettings settings) : ApplyResourcePacks(toLoad); } - public void ScanForResourcePacks() { loadedPacks.Clear(); @@ -191,14 +185,13 @@ public Bitmap LoadBitmap(Type baseType, string key) return bitmap; } - public Stream LoadStream(Type baseType, string key, params string[] fileTypes) { return Load(baseType, key, fileTypes, null, (stream) => { var result = new MemoryStream(); var buffer = new byte[1024]; - var count = 0; + int count; do { count = stream.Read(buffer, 0, buffer.Length); diff --git a/OctoAwesome/OctoAwesome.Client.UI/Controls/CompassControl.cs b/OctoAwesome/OctoAwesome.Client.UI/Controls/CompassControl.cs index 1c5a6eb9..3066349c 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Controls/CompassControl.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Controls/CompassControl.cs @@ -7,32 +7,32 @@ namespace OctoAwesome.Client.UI.Controls { + public class CompassControl : Control { private readonly Texture2D compassTexture; private readonly AssetComponent assets; - public HeadComponent HeadComponent { get; set; } + private readonly HeadComponent headComponent; public CompassControl(BaseScreenComponent screenManager, AssetComponent assets, HeadComponent headComponent ) : base(screenManager) { this.assets = assets; - HeadComponent = headComponent; + this.headComponent = headComponent; Padding = Border.All(7); Texture2D background = assets.LoadTexture( "buttonLong_brown_pressed"); Background = NineTileBrush.FromSingleTexture(background, 7, 7); compassTexture = assets.LoadTexture(GetType(), "compass"); } - protected override void OnDrawContent(SpriteBatch batch, Rectangle contentArea, GameTime gameTime, float alpha) { - if (HeadComponent is null || !assets.Ready) + if (headComponent is null || !assets.Ready) return; - float compassValue = HeadComponent.Angle / (float)(2 * Math.PI); + float compassValue = headComponent.Angle / (float)(2 * Math.PI); compassValue %= 1f; if (compassValue < 0) compassValue += 1f; diff --git a/OctoAwesome/OctoAwesome.Client.UI/Controls/CrosshairControl.cs b/OctoAwesome/OctoAwesome.Client.UI/Controls/CrosshairControl.cs index dff0a909..148e55b5 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Controls/CrosshairControl.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Controls/CrosshairControl.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using engenious.UI; using engenious; using engenious.Graphics; @@ -9,13 +6,13 @@ namespace OctoAwesome.Client.UI.Controls { + public class CrosshairControl : Control { - public Texture2D Texture; - public float Transparency; - public Color Color; + private readonly Texture2D texture; + private readonly float transparency; - AssetComponent assets; + private readonly AssetComponent assets; private static int crosshairSize = 8; @@ -38,26 +35,23 @@ public static int CrosshairSize /// Maximum Größe des Crosshair /// public const int MaxSize = 100; - - public CrosshairControl(BaseScreenComponent manager, AssetComponent asset) : base(manager) { assets = asset; - Transparency = 0.5f; + transparency = 0.5f; - Texture = assets.LoadTexture(GetType(), "octocross"); + texture = assets.LoadTexture(GetType(), "octocross"); } - protected override void OnDrawContent(SpriteBatch batch, Rectangle contentArea, GameTime gameTime, float alpha) { if (!assets.Ready) return; - Color = CrosshairColor; + var color = CrosshairColor; Width = Height = CrosshairSize; - batch.Draw(Texture, contentArea, Color * Transparency); + batch.Draw(texture, contentArea, color * transparency); } } } diff --git a/OctoAwesome/OctoAwesome.Client.UI/Controls/GroupBox.cs b/OctoAwesome/OctoAwesome.Client.UI/Controls/GroupBox.cs index 99d16bc2..e602c467 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Controls/GroupBox.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Controls/GroupBox.cs @@ -3,10 +3,10 @@ namespace OctoAwesome.Client.UI.Controls { + public class GroupBox : Control { private Brush borderColor = SolidColorBrush.Black; - public Brush BorderColor { get => borderColor; @@ -19,7 +19,6 @@ public Brush BorderColor } private Border border = Border.All(2); - public Border Border { get => border; @@ -31,7 +30,6 @@ public Border Border } } private Orientation orientation = Orientation.Vertical; - public Orientation Orientation { get => orientation; @@ -44,48 +42,43 @@ public Orientation Orientation } private string headline; - public string Headline { get => headline; set { + headline = value ?? string.Empty; if (headlineLabel is not null) { - headlineLabel.Height = string.IsNullOrEmpty(value) ? 0 : null; - headlineLabel.Text = value; + headlineLabel.Height = string.IsNullOrEmpty(headline) ? 0 : null; + headlineLabel.Text = headline; } - headline = value; } } - public new ControlCollection Children => contentPanel.Controls; private readonly StackPanel outerPanel; - private readonly StackPanel innerPanel; private readonly StackPanel contentPanel; - private readonly StackPanel headlinePanel; private readonly Label headlineLabel; - public GroupBox(BaseScreenComponent manager, string style = "") : base(manager, style) { outerPanel = new(manager) - { - Padding = Border, - Background = BorderColor - }; - - innerPanel = new StackPanel(manager) - { - Orientation = Orientation.Vertical, - Background = SolidColorBrush.White, - }; - - headlinePanel = new(manager) - { - Orientation= Orientation.Vertical, - HorizontalAlignment = HorizontalAlignment.Stretch, - }; + { + Padding = Border, + Background = BorderColor + }; + + var innerPanel = new StackPanel(manager) + { + Orientation = Orientation.Vertical, + Background = SolidColorBrush.White, + }; + + StackPanel headlinePanel = new(manager) + { + Orientation= Orientation.Vertical, + HorizontalAlignment = HorizontalAlignment.Stretch, + }; headlineLabel = new Label(manager) { diff --git a/OctoAwesome/OctoAwesome.Client.UI/Controls/HealthBarControl.cs b/OctoAwesome/OctoAwesome.Client.UI/Controls/HealthBarControl.cs index e8ddc9e5..0bc40f00 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Controls/HealthBarControl.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Controls/HealthBarControl.cs @@ -1,14 +1,12 @@ using engenious.UI; using engenious.UI.Controls; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Client.UI.Controls { + public class HealthBarControl : ProgressBar { + public HealthBarControl(BaseScreenComponent manager, string style = "") : base(manager, style) { Background = Skin.Current.HorizontalScrollBackgroundBrush; diff --git a/OctoAwesome/OctoAwesome.Client.UI/Controls/InventoryControl.cs b/OctoAwesome/OctoAwesome.Client.UI/Controls/InventoryControl.cs index b6d702b3..31071e69 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Controls/InventoryControl.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Controls/InventoryControl.cs @@ -2,12 +2,13 @@ using engenious.Graphics; using engenious.UI; using engenious.UI.Controls; -using OctoAwesome.Definitions; using OctoAwesome.Client.UI.Components; using System.Collections.Generic; +using System.Globalization; namespace OctoAwesome.Client.UI.Controls { + public sealed class InventoryControl : Panel { private const int COLUMNS = 8; @@ -20,7 +21,6 @@ public sealed class InventoryControl : Panel private Grid grid; private readonly ScrollContainer scroll; private readonly AssetComponent assets; - public InventoryControl(BaseScreenComponent manager, AssetComponent assets, List inventorySlots, int columns = COLUMNS) : base(manager) { scroll = new ScrollContainer(manager) @@ -42,7 +42,6 @@ public InventoryControl(BaseScreenComponent manager, AssetComponent assets, List Controls.Add(scroll); Rebuild(inventorySlots, columns); } - public void Rebuild(List inventorySlots, int columns = COLUMNS) { grid = new Grid(ScreenManager) @@ -68,19 +67,17 @@ public void Rebuild(List inventorySlots, int columns = COLUMNS) continue; else texture = assets.LoadTexture(inventorySlot.Definition.GetType(), inventorySlot.Definition.Icon); - - var image = new Image(ScreenManager) { Texture = texture, Width = 42, Height = 42, VerticalAlignment = VerticalAlignment.Center }; - image.MouseEnter += (s, e) => { HoveredSlot = inventorySlot; }; - image.MouseLeave += (s, e) => { HoveredSlot = null; }; - image.StartDrag += (c, e) => + image.MouseEnter += (_, _) => { HoveredSlot = inventorySlot; }; + image.MouseLeave += (_, _) => { HoveredSlot = null; }; + image.StartDrag += (_, e) => { e.Handled = true; e.Icon = texture; e.Content = inventorySlot; e.Sender = image; }; - var label = new Label(ScreenManager) { Text = inventorySlot.Amount.ToString(), HorizontalAlignment = HorizontalAlignment.Right, VerticalTextAlignment = VerticalAlignment.Bottom, Background = new BorderBrush(Color.White) }; + var label = new Label(ScreenManager) { Text = inventorySlot.Amount.ToString(CultureInfo.CurrentCulture), HorizontalAlignment = HorizontalAlignment.Right, VerticalTextAlignment = VerticalAlignment.Bottom, Background = new BorderBrush(Color.White) }; grid.AddControl(image, column, row); grid.AddControl(label, column, row); diff --git a/OctoAwesome/OctoAwesome.Client.UI/Controls/Line.cs b/OctoAwesome/OctoAwesome.Client.UI/Controls/Line.cs index d2eb1fe8..33fad3a8 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Controls/Line.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Controls/Line.cs @@ -2,10 +2,11 @@ namespace OctoAwesome.Client.UI.Controls { + public class Line : Control { - public Brush Color { get => Background; set => Background = value; } + public Brush Color { get => Background; set => Background = value; } public Line(BaseScreenComponent manager, string style = "") : base(manager, style) { Height = 1; diff --git a/OctoAwesome/OctoAwesome.Client.UI/OctoAwesome.Client.UI.csproj b/OctoAwesome/OctoAwesome.Client.UI/OctoAwesome.Client.UI.csproj index 63dba645..6c9d4010 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/OctoAwesome.Client.UI.csproj +++ b/OctoAwesome/OctoAwesome.Client.UI/OctoAwesome.Client.UI.csproj @@ -2,6 +2,7 @@ net5.0 + True @@ -10,7 +11,7 @@ - + diff --git a/OctoAwesome/OctoAwesome.Client.UI/ResourcePack.cs b/OctoAwesome/OctoAwesome.Client.UI/ResourcePack.cs index 34149be4..f0ce0db0 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/ResourcePack.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/ResourcePack.cs @@ -1,25 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Serialization; +using System.Xml.Serialization; namespace OctoAwesome.Client.UI { + public sealed class ResourcePack { + [XmlIgnore] public string Path { get; set; } - public string Name { get; set; } - public string Author { get; set; } - public string Description { get; set; } - public string Version { get; set; } - public string Icon { get; set; } } } diff --git a/OctoAwesome/OctoAwesome.Client.UI/Tools.cs b/OctoAwesome/OctoAwesome.Client.UI/Tools.cs index 43314f85..b9422d23 100644 --- a/OctoAwesome/OctoAwesome.Client.UI/Tools.cs +++ b/OctoAwesome/OctoAwesome.Client.UI/Tools.cs @@ -2,6 +2,7 @@ namespace OctoAwesome.Client.UI { + public static class Tools { /// @@ -13,7 +14,7 @@ public static void OpenUrl(string url) Process.Start(new ProcessStartInfo(url) { UseShellExecute = true - }).Dispose(); + })?.Dispose(); } } } diff --git a/OctoAwesome/OctoAwesome.Client/Cache/ChunkRendererDbContext.cs b/OctoAwesome/OctoAwesome.Client/Cache/ChunkRendererDbContext.cs index b495d152..b3ebae59 100644 --- a/OctoAwesome/OctoAwesome.Client/Cache/ChunkRendererDbContext.cs +++ b/OctoAwesome/OctoAwesome.Client/Cache/ChunkRendererDbContext.cs @@ -1,11 +1,7 @@ -using OctoAwesome.Database; +using System; +using OctoAwesome.Database; using OctoAwesome.Serialization; - -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Client.Cache { @@ -15,32 +11,34 @@ public ChunkRendererDbContext(Database database) : base(database) { } - public override void AddOrUpdate(VerticesForChunk value) + public override void AddOrUpdate(VerticesForChunk? value) { + if (value == null) + throw new ArgumentNullException(nameof(value)); using (Database.Lock(Operation.Write)) Database.AddOrUpdate(new Index3Tag(value.ChunkPosition), new Value(Serializer.Serialize(value))); } - public VerticesForChunk Get(Index3 key) + public VerticesForChunk? Get(Index3 key) => Get(new Index3Tag(key)); - public override VerticesForChunk Get(Index3Tag key) + public override VerticesForChunk? Get(Index3Tag key) { if (!Database.ContainsKey(key)) return null; var verticesForChunk = new VerticesForChunk(); - using (var stream = new MemoryStream(Database.GetValue(key).Content)) - using (var buffered = new BufferedStream(stream)) - using (var reader = new BinaryReader(buffered)) - { - verticesForChunk.Deserialize(reader); - return verticesForChunk; - } + using var stream = new MemoryStream(Database.GetValue(key).Content); + using var buffered = new BufferedStream(stream); + using var reader = new BinaryReader(buffered); + verticesForChunk.Deserialize(reader); + return verticesForChunk; } - public override void Remove(VerticesForChunk value) + public override void Remove(VerticesForChunk? value) { + if (value == null) + throw new ArgumentNullException(nameof(value)); using (Database.Lock(Operation.Write)) Database.Remove(new Index3Tag(value.ChunkPosition)); } diff --git a/OctoAwesome/OctoAwesome.Client/Cache/VerticesForChunk.cs b/OctoAwesome/OctoAwesome.Client/Cache/VerticesForChunk.cs index ea229135..2b556de0 100644 --- a/OctoAwesome/OctoAwesome.Client/Cache/VerticesForChunk.cs +++ b/OctoAwesome/OctoAwesome.Client/Cache/VerticesForChunk.cs @@ -7,11 +7,11 @@ namespace OctoAwesome.Client.Cache { - internal partial class VerticesForChunk : IDisposable, ISerializable + internal class VerticesForChunk : IDisposable, ISerializable { public int Version { get; set; } public Index3 ChunkPosition { get; set; } - public VertexPositionNormalTextureLight[] Vertices { get; set; } + public VertexPositionNormalTextureLight[]? Vertices { get; set; } public VerticesForChunk() { @@ -23,8 +23,6 @@ public VerticesForChunk(int version, Index3 chunkPosition, VertexPositionNormalT ChunkPosition = chunkPosition; Vertices = vertices; } - - public void Deserialize(BinaryReader reader) { Version = reader.ReadInt32(); @@ -48,6 +46,13 @@ public void Serialize(BinaryWriter writer) writer.Write(ChunkPosition.X); writer.Write(ChunkPosition.Y); writer.Write(ChunkPosition.Z); + + if (Vertices == null) + { + writer.Write(0); + return; + } + writer.Write(Vertices.Length); foreach (var vert in Vertices) { diff --git a/OctoAwesome/OctoAwesome.Client/Components/CameraComponent.cs b/OctoAwesome/OctoAwesome.Client/Components/CameraComponent.cs index caf9a337..e6d32dad 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/CameraComponent.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/CameraComponent.cs @@ -8,12 +8,11 @@ namespace OctoAwesome.Client.Components internal sealed class CameraComponent : DrawableGameComponent { private PlayerComponent player; - - public CameraComponent(OctoGame game) : base(game) { player = game.Player; + Frustum = new BoundingFrustum(Matrix.Identity); } public override void Initialize() @@ -83,7 +82,7 @@ public override void Update(GameTime gameTime) Vector3 direction = farPoint - nearPoint; direction.Normalize(); PickRay = new Ray(nearPoint, direction); - Frustum = new BoundingFrustum(Projection*View); + Frustum.Matrix = Projection*View; } public Index3 CameraChunk { get; private set; } diff --git a/OctoAwesome/OctoAwesome.Client/Components/ChunkRenderer.cs b/OctoAwesome/OctoAwesome.Client/Components/ChunkRenderer.cs index be53124a..19d84132 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/ChunkRenderer.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/ChunkRenderer.cs @@ -1,29 +1,20 @@ using OctoAwesome.Client.Controls; using System.Collections.Generic; using engenious.Graphics; -using System.Linq; using engenious; using System; -using System.Threading; using OctoAwesome.Threading; -using engenious.UserDefined; -using OctoAwesome.Client.Cache; -using OctoAwesome.Expressions; -using OctoAwesome.Runtime; -using System.IO; -using OctoAwesome.Serialization; -using System.Collections.ObjectModel; +using System.Diagnostics; using System.Runtime.InteropServices; using OctoAwesome.Definitions; -using engenious.Helper; using engenious.Utility; namespace OctoAwesome.Client.Components { internal sealed class ChunkRenderer : IDisposable { - public VertexBuffer VertexBuffer { get; private set; } - public static IndexBuffer IndexBuffer { get; private set; } + public VertexBuffer? VertexBuffer { get; private set; } + public static IndexBuffer? IndexBuffer { get; private set; } public static float OverrideLightLevel { get; set; } public static bool WireFrame { get; set; } @@ -32,27 +23,25 @@ internal sealed class ChunkRenderer : IDisposable private readonly Texture2DArray textures; - - private static readonly RasterizerState wireFrameState; private static readonly Vector2[] uvOffsets; /// /// Referenz auf den aktuellen Chunk (falls vorhanden) /// - private IChunk centerChunk; + private IChunk? centerChunk; private readonly IChunk[] chunks; - private readonly IBlockDefinition[] blockDefinitions; + private readonly IBlockDefinition?[] blockDefinitions; private readonly Action chunkChanged; - private IPlanet planet; + private IPlanet? planet; public bool Loaded { get; set; } = false; public bool CanRender => VertexBuffer != null && VertexCount > 0; - public int VertexCount => (int)VertexBuffer.VertexCount; + public int VertexCount => (int)VertexBuffer?.VertexCount; private int indexCount => VertexCount / 4 * 6; - private ILocalChunkCache _manager; + private ILocalChunkCache? _manager; private Index3 _shift; private Index3 _cameraPos; @@ -78,8 +67,6 @@ private set NeedsUpdate = value != null; } } - - static ChunkRenderer() { wireFrameState = new RasterizerState() { FillMode = PolygonMode.Line, CullMode = CullMode.CounterClockwise }; @@ -127,8 +114,6 @@ public ChunkRenderer(SceneControl sceneControl, IDefinitionManager definitionMan //simple.Ambient.AmbientColor = Color.White.ToVector4(); //dbProvier = new DatabaseProvider(Path.Combine("cache", "chunkverticescache"), null); - - } public Index3 GetShift(Index3 chunkOffset, IPlanet planet) @@ -144,7 +129,7 @@ public Index3 GetShift(Index3 chunkOffset, IPlanet planet) return _shift; } - public void SetChunk(ILocalChunkCache manager, Index3? newPosition, IPlanet planet) + public void SetChunk(ILocalChunkCache? manager, Index3? newPosition, IPlanet? planet) { if (_manager == manager && newPosition == ChunkPosition) { @@ -170,8 +155,6 @@ public void SetChunk(ILocalChunkCache manager, Index3? newPosition, IPlanet plan } public bool NeedsUpdate = false; - - private void OnChunkChanged(IChunk c) { NeedsUpdate = true; @@ -195,8 +178,6 @@ public void Draw(Matrix viewProj, Index3 shift) simple.Parameters["AmbientIntensity"].SetValue(0.4f); simple.Parameters["AmbientColor"].SetValue(Color.White.ToVector4()); - - lock (this) { if (VertexBuffer == null) @@ -205,7 +186,7 @@ public void Draw(Matrix viewProj, Index3 shift) graphicsDevice.RasterizerState = WireFrame ? wireFrameState : RasterizerState.CullCounterClockwise; graphicsDevice.VertexBuffer = VertexBuffer; - foreach (var pass in simple.CurrentTechnique.Passes) + foreach (var pass in simple.CurrentTechnique!.Passes) { pass.Apply(); graphicsDevice.DrawIndexedPrimitives(PrimitiveType.Triangles, 0, 0, VertexCount, 0, indexCount / 3); @@ -246,7 +227,8 @@ public unsafe bool RegenerateVertexBuffer() return false; using (semaphore.Wait()) { - IChunk chunk = centerChunk; + Debug.Assert(_manager != null, nameof(_manager) + " != null"); + IChunk? chunk = centerChunk; // Chunk nachladen if (chunk == null) { @@ -282,7 +264,7 @@ public unsafe bool RegenerateVertexBuffer() { for (int x = 0; x < Chunk.CHUNKSIZE_X; x++) { - GenerateVertices(chunk, chunks, uvOffsets, x, y, z, chunkPos, blockDefinitions, true); + GenerateVertices(chunk, x, y, z, chunkPos, true); } } } @@ -293,7 +275,7 @@ public unsafe bool RegenerateVertexBuffer() { for (int x = 0; x < Chunk.CHUNKSIZE_X; x++) { - GenerateVertices(chunk, chunks, uvOffsets, x, y, z, chunkPos, blockDefinitions, true); + GenerateVertices(chunk, x, y, z, chunkPos, true); } } @@ -305,7 +287,7 @@ public unsafe bool RegenerateVertexBuffer() { for (int x = Chunk.CHUNKSIZE_X - 1; x >= 0; x -= Chunk.CHUNKSIZE.X - 1) { - GenerateVertices(chunk, chunks, uvOffsets, x, y, z, chunkPos, blockDefinitions, true); + GenerateVertices(chunk, x, y, z, chunkPos, true); } } } @@ -316,7 +298,7 @@ public unsafe bool RegenerateVertexBuffer() { for (int x = 1; x < Chunk.CHUNKSIZE_X - 1; x++) { - GenerateVertices(chunk, chunks, uvOffsets, x, y, z, chunkPos, blockDefinitions, true); + GenerateVertices(chunk, x, y, z, chunkPos, true); } } } @@ -350,7 +332,7 @@ private unsafe bool RegisterNewVertices(IChunk chunk) } lock (this) { - if (chunk != null && chunk.Index != ChunkPosition) + if (chunk.Index != ChunkPosition) { return Loaded; } @@ -361,32 +343,26 @@ private unsafe bool RegisterNewVertices(IChunk chunk) } } - private void GenerateVertices(IChunk centerChunk, IChunk[] chunks, Vector2[] uvOffsets, int z, int y, int x, Index3 chunkPosition, IBlockDefinition[] blockDefinitions, bool getFromManager) + private void GenerateVertices(IChunk centerChunk, int z, int y, int x, Index3 chunkPosition, bool getFromManager) { ushort block = centerChunk.GetBlock(x, y, z); - var manager = _manager; - - if (block == 0 || manager is null) + if (block == 0 || _manager is null) return; - - - IBlockDefinition blockDefinition = (IBlockDefinition)definitionManager.GetBlockDefinitionByIndex(block); + + var manager = _manager; + var blockDefinition = definitionManager.GetBlockDefinitionByIndex(block); if (blockDefinition is null) return; - int textureIndex; - if (!textureOffsets.TryGetValue(blockDefinition, out textureIndex)) + if (!textureOffsets.TryGetValue(blockDefinition, out var textureIndex)) return; if (vertices.Count == 0) vertices.Capacity = 4096; - - Span blocks = stackalloc ushort[27]; - - ushort topBlock, bottomBlock, southBlock, northBlock, westBlock, eastBlock; + if (getFromManager) { @@ -407,29 +383,29 @@ private void GenerateVertices(IChunk centerChunk, IChunk[] chunks, Vector2[] uvO } } - - - topBlock = blocks[(((2 * 3) + 1) * 3) + 1]; - bottomBlock = blocks[(((0 * 3) + 1) * 3) + 1]; - southBlock = blocks[(((1 * 3) + 2) * 3) + 1]; - northBlock = blocks[(((1 * 3) + 0) * 3) + 1]; - westBlock = blocks[(((1 * 3) + 1) * 3) + 0]; - eastBlock = blocks[(((1 * 3) + 1) * 3) + 2]; + var topBlock = blocks[(((2 * 3) + 1) * 3) + 1]; + var bottomBlock = blocks[(((0 * 3) + 1) * 3) + 1]; + var southBlock = blocks[(((1 * 3) + 2) * 3) + 1]; + var northBlock = blocks[(((1 * 3) + 0) * 3) + 1]; + var westBlock = blocks[(((1 * 3) + 1) * 3) + 0]; + var eastBlock = blocks[(((1 * 3) + 1) * 3) + 2]; for (int zOffset = -1; zOffset <= 1; zOffset++) for (int yOffset = -1; yOffset <= 1; yOffset++) for (int xOffset = -1; xOffset <= 1; xOffset++) { - blockDefinitions[GetIndex(zOffset, yOffset, xOffset)] = + var blockDef = definitionManager.GetBlockDefinitionByIndex(blocks[GetIndex(zOffset, yOffset, xOffset)]); + + blockDefinitions[GetIndex(zOffset, yOffset, xOffset)] = blockDef; } - IBlockDefinition topBlockDefintion = blockDefinitions[(((2 * 3) + 1) * 3) + 1]; - IBlockDefinition bottomBlockDefintion = blockDefinitions[(((0 * 3) + 1) * 3) + 1]; - IBlockDefinition southBlockDefintion = blockDefinitions[(((1 * 3) + 2) * 3) + 1]; - IBlockDefinition northBlockDefintion = blockDefinitions[(((1 * 3) + 0) * 3) + 1]; - IBlockDefinition westBlockDefintion = blockDefinitions[(((1 * 3) + 1) * 3) + 0]; - IBlockDefinition eastBlockDefintion = blockDefinitions[(((1 * 3) + 1) * 3) + 2]; + var topBlockDefintion = blockDefinitions[(((2 * 3) + 1) * 3) + 1]; + var bottomBlockDefintion = blockDefinitions[(((0 * 3) + 1) * 3) + 1]; + var southBlockDefintion = blockDefinitions[(((1 * 3) + 2) * 3) + 1]; + var northBlockDefintion = blockDefinitions[(((1 * 3) + 0) * 3) + 1]; + var westBlockDefintion = blockDefinitions[(((1 * 3) + 1) * 3) + 0]; + var eastBlockDefintion = blockDefinitions[(((1 * 3) + 1) * 3) + 2]; var globalX = x + centerChunk.Index.X * Chunk.CHUNKSIZE_X; var globalY = y + centerChunk.Index.Y * Chunk.CHUNKSIZE_Y; var globalZ = z + centerChunk.Index.Z * Chunk.CHUNKSIZE_Z; @@ -522,8 +498,6 @@ private void GenerateVertices(IChunk centerChunk, IChunk[] chunks, Vector2[] uvO vertices.Add(vert); } } - - // South if (southBlock == 0 || (!southBlockDefintion.IsSolidWall(Wall.Front) && southBlock != block)) { @@ -543,8 +517,6 @@ private void GenerateVertices(IChunk centerChunk, IChunk[] chunks, Vector2[] uvO new Vector3(x + 0, y + 1, z + 1), new Vector3(0, 1, 0), uvOffsets[(5 + rotation) % 4], front, AmbientToBrightness(valueYZ)); var vertXYZ = new VertexPositionNormalTextureLight( new Vector3(x + 1, y + 1, z + 1), new Vector3(0, 1, 0), uvOffsets[(4 + rotation) % 4], front, AmbientToBrightness(valueXYZ)); - - if (valueY + valueXYZ >= valueYZ + valueXY) { vertices.Add(vertY); @@ -561,8 +533,6 @@ private void GenerateVertices(IChunk centerChunk, IChunk[] chunks, Vector2[] uvO } } - - // North if (northBlock == 0 || (!northBlockDefintion.IsSolidWall(Wall.Back) && northBlock != block)) { @@ -597,8 +567,6 @@ private void GenerateVertices(IChunk centerChunk, IChunk[] chunks, Vector2[] uvO vertices.Add(vert); } } - - // West if (westBlock == 0 || (!westBlockDefintion.IsSolidWall(Wall.Right) && westBlock != block)) { @@ -678,7 +646,7 @@ private static int VertexAO(int side1, int side2, int corner) private uint AmbientToBrightness(uint ambient) => (0xFFFFFF / 2) + (0xFFFFFF / 6 * ambient); - private static /*unsafe */uint VertexAO(IBlockDefinition[] blockDefinitions, int cornerIndex, int side1Index, Wall side1Wall, int side2Index, Wall side2Wall) + private static /*unsafe */uint VertexAO(IBlockDefinition?[] blockDefinitions, int cornerIndex, int side1Index, Wall side1Wall, int side2Index, Wall side2Wall) { var cornerBlock = blockDefinitions[cornerIndex]?.SolidWall ?? 0; var side1Def = blockDefinitions[side1Index]; diff --git a/OctoAwesome/OctoAwesome.Client/Components/EntityGameComponent.cs b/OctoAwesome/OctoAwesome.Client/Components/EntityGameComponent.cs index 72dcef8f..26b14c4a 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/EntityGameComponent.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/EntityGameComponent.cs @@ -3,13 +3,9 @@ using engenious.Helper; using OctoAwesome.EntityComponents; - -using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Client.Components { @@ -24,11 +20,7 @@ private struct ModelInfo private GraphicsDevice graphicsDevice; private BasicEffect effect; public SimulationComponent Simulation { get; private set; } - - private Dictionary models = new Dictionary(); - - public List Entities { get; set; } public List FunctionalBlocks { get; set; } @@ -51,7 +43,7 @@ public void Draw(GameTime gameTime, Matrix view, Matrix projection, Index3 chunk effect.TextureEnabled = true; graphicsDevice.RasterizerState = RasterizerState.CullClockwise; using (var writer = File.AppendText(Path.Combine(".", "render.log"))) - foreach (var pass in effect.CurrentTechnique.Passes) + foreach (var pass in effect.CurrentTechnique!.Passes) { pass.Apply(); i++; @@ -63,8 +55,6 @@ public void Draw(GameTime gameTime, Matrix view, Matrix projection, Index3 chunk } var rendercomp = entity.Components.GetComponent(); - - if (!models.TryGetValue(rendercomp.Name, out ModelInfo modelinfo)) { modelinfo = new ModelInfo() @@ -110,8 +100,6 @@ public void Draw(GameTime gameTime, Matrix view, Matrix projection, Index3 chunk } var rendercomp = functionalBlock.Components.GetComponent(); - - if (!models.TryGetValue(rendercomp.Name, out ModelInfo modelinfo)) { modelinfo = new ModelInfo() diff --git a/OctoAwesome/OctoAwesome.Client/Components/KeyMapper.cs b/OctoAwesome/OctoAwesome.Client/Components/KeyMapper.cs index 1c3f6c18..00afe311 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/KeyMapper.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/KeyMapper.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using engenious.UI; using KeyEventArgs = engenious.UI.KeyEventArgs; using Keys = engenious.Input.Keys; @@ -36,7 +35,7 @@ public void RegisterBinding(string id, string displayName) { if (bindings.ContainsKey(id)) return; - bindings.Add(id, new Binding() { Id = id, DisplayName = displayName }); + bindings.Add(id, new Binding(id, displayName)); } /// @@ -56,10 +55,10 @@ public void UnregisterBinding(string id) /// The Key public void AddKey(string id, Keys key) { - Binding binding; - if (bindings.TryGetValue(id, out binding)) + if (bindings.TryGetValue(id, out var binding)) { - if (!binding.Keys.Contains(key)) binding.Keys.Add(key); + if (!binding.Keys.Contains(key)) + binding.Keys.Add(key); } } @@ -70,8 +69,7 @@ public void AddKey(string id, Keys key) /// The Key public void RemoveKey(string id, Keys key) { - Binding binding; - if (bindings.TryGetValue(id, out binding)) + if (bindings.TryGetValue(id, out var binding)) { if (binding.Keys.Contains(key)) binding.Keys.Remove(key); } @@ -84,8 +82,7 @@ public void RemoveKey(string id, Keys key) /// The Action public void AddAction(string id, Action action) { - Binding binding; - if (bindings.TryGetValue(id, out binding)) + if (bindings.TryGetValue(id, out var binding)) { if (!binding.Actions.Contains(action)) binding.Actions.Add(action); } @@ -98,8 +95,7 @@ public void AddAction(string id, Action action) /// The Action public void RemoveAction(string id, Action action) { - Binding binding; - if (bindings.TryGetValue(id, out binding)) + if (bindings.TryGetValue(id, out var binding)) { if (binding.Actions.Contains(action)) binding.Actions.Remove(action); } @@ -112,8 +108,7 @@ public void RemoveAction(string id, Action action) /// The new DisplayName public void SetDisplayName(string id, string displayName) { - Binding binding; - if (bindings.TryGetValue(id, out binding)) + if (bindings.TryGetValue(id, out var binding)) binding.DisplayName = displayName; } @@ -150,8 +145,6 @@ public List GetBindings() bindings.Add(binding.Value); return bindings; } - - #region KeyEvents protected void KeyPressed(KeyEventArgs args) @@ -194,16 +187,18 @@ protected void KeyUp(KeyEventArgs args) public class Binding { - public string Id { get; set; } + public string Id { get; } public string DisplayName { get; set; } - public List Keys { get; set; } + public List Keys { get; } - public List> Actions { get; set; } + public List> Actions { get; } - public Binding() + public Binding(string id, string displayName) { + Id = id; + DisplayName = displayName; Keys = new List(); Actions = new List>(); } diff --git a/OctoAwesome/OctoAwesome.Client/Components/PlayerComponent.cs b/OctoAwesome/OctoAwesome.Client/Components/PlayerComponent.cs index e9039d9b..e383d1bd 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/PlayerComponent.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/PlayerComponent.cs @@ -1,8 +1,6 @@ -using OctoAwesome.Runtime; -using System; -using System.Collections.Generic; +using System; +using System.Diagnostics; using System.Linq; -using System.Text; using engenious; using OctoAwesome.EntityComponents; using OctoAwesome.SumTypes; @@ -37,20 +35,61 @@ internal sealed class PlayerComponent : GameComponent #endregion - public Entity CurrentEntity { get; private set; } + public Entity? CurrentEntity { get; private set; } - public HeadComponent CurrentEntityHead { get; private set; } + private HeadComponent? currentEntityHead; + private ControllableComponent? currentController; + private InventoryComponent? inventory; + private ToolBarComponent? toolbar; + private PositionComponent? position; - public ControllableComponent CurrentController { get; private set; } + public HeadComponent CurrentEntityHead + { + get + { + Debug.Assert(currentEntityHead != null, nameof(currentEntityHead) + " != null"); + return currentEntityHead; + } + } - public InventoryComponent Inventory { get; private set; } + public ControllableComponent CurrentController + { + get + { + Debug.Assert(currentController != null, nameof(currentController) + " != null"); + return currentController; + } + } - public ToolBarComponent Toolbar { get; private set; } + public InventoryComponent Inventory + { + get + { + Debug.Assert(inventory != null, nameof(inventory) + " != null"); + return inventory; + } + } - public PositionComponent Position { get; private set; } + public ToolBarComponent Toolbar + { + get + { + Debug.Assert(toolbar != null, nameof(toolbar) + " != null"); + return toolbar; + } + } + + public PositionComponent Position + { + get + { + Debug.Assert(position != null, nameof(position) + " != null"); + return position; + } + } // public ActorHost ActorHost { get; private set; } - public Selection Selection { get; set; } + public Selection? Selection { get; set; } public Index3? SelectedBox { get; set; } public Vector2? SelectedPoint { get; set; } @@ -68,34 +107,33 @@ public PlayerComponent(OctoGame game, IResourceManager resourceManager) Game = game; } - public void SetEntity(Entity entity) + public void SetEntity(Entity? entity) { - if (entity == null) { - CurrentEntityHead = null; + currentEntityHead = null; } else { // Map other Components - CurrentController = entity.Components.GetComponent(); + currentController = entity.Components.GetComponent(); - CurrentEntityHead = entity.Components.GetComponent(); - if (CurrentEntityHead is null) - CurrentEntityHead = new() { Offset = new(0, 0, 3.2f) }; + currentEntityHead = entity.Components.GetComponent(); + if (currentEntityHead is null) + currentEntityHead = new() { Offset = new(0, 0, 3.2f) }; - Inventory = entity.Components.GetComponent(); - if (Inventory is null) - Inventory = new(); + inventory = entity.Components.GetComponent(); + if (inventory is null) + inventory = new(); - Toolbar = entity.Components.GetComponent(); - if (Toolbar is null) - Toolbar = new(); + toolbar = entity.Components.GetComponent(); + if (toolbar is null) + toolbar = new(); - Position = entity.Components.GetComponent(); - if (Position is null) - Position = new() { Position = new Coordinate(0, new Index3(0, 0, 0), new Vector3(0, 0, 0)) }; + position = entity.Components.GetComponent(); + if (position is null) + position = new() { Position = new Coordinate(0, new Index3(0, 0, 0), new Vector3(0, 0, 0)) }; } CurrentEntity = entity; } @@ -108,6 +146,9 @@ public override void Update(GameTime gameTime) if (CurrentEntity == null) return; + Debug.Assert(CurrentEntityHead != null, $"{nameof(CurrentEntityHead)} not set despite {nameof(CurrentEntity)} being set"); + Debug.Assert(CurrentController != null, $"{nameof(CurrentEntityHead)} not set despite {nameof(CurrentEntity)} being set"); + CurrentEntityHead.Angle += (float)gameTime.ElapsedGameTime.TotalSeconds * HeadInput.X; CurrentEntityHead.Tilt += (float)gameTime.ElapsedGameTime.TotalSeconds * HeadInput.Y; CurrentEntityHead.Tilt = Math.Min(1.5f, Math.Max(-1.5f, CurrentEntityHead.Tilt)); @@ -150,7 +191,7 @@ public override void Update(GameTime gameTime) } } - //Index des aktiven Werkzeugs ermitteln + // Determine index of the active tool if (SlotLeftInput) { Toolbar.ActiveIndex--; @@ -162,8 +203,6 @@ public override void Update(GameTime gameTime) Toolbar.ActiveIndex++; } SlotRightInput = false; - - } /// @@ -171,7 +210,7 @@ public override void Update(GameTime gameTime) /// internal void AllBlocksDebug() { - var inventory = CurrentEntity.Components.GetComponent(); + var inventory = CurrentEntity?.Components.GetComponent(); if (inventory == null) return; diff --git a/OctoAwesome/OctoAwesome.Client/Components/SimulationComponent.cs b/OctoAwesome/OctoAwesome.Client/Components/SimulationComponent.cs index 7738c96c..00850fed 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/SimulationComponent.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/SimulationComponent.cs @@ -1,5 +1,4 @@ -using OctoAwesome.Runtime; -using System; +using System; using engenious; using OctoAwesome.EntityComponents; using OctoAwesome.Common; @@ -12,19 +11,11 @@ internal sealed class SimulationComponent : GameComponent private readonly IResourceManager resourceManager; - public Simulation Simulation { get; private set; } + public Simulation? Simulation { get; private set; } public IGameService Service { get; } - public SimulationState State - { - get - { - if (Simulation != null) - return Simulation.State; - return SimulationState.Undefined; - } - } + public SimulationState State => Simulation?.State ?? SimulationState.Undefined; public SimulationComponent(OctoGame game, IExtensionResolver extensionResolver, IResourceManager resourceManager) : base(game) { @@ -83,8 +74,6 @@ public Player LoginPlayer(string playerName) player.Components.AddComponent(new RenderComponent() { Name = "Wauzi", ModelName = "dog", TextureName = "texdog", BaseZRotation = -90 }, true); Simulation.Add(player); - - return player; } diff --git a/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTextureLight.cs b/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTextureLight.cs index 4b316634..7cbe4152 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTextureLight.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTextureLight.cs @@ -1,9 +1,7 @@ using engenious; using engenious.Graphics; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; + namespace OctoAwesome.Client.Components { [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential,Pack=1)] diff --git a/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTexturePacked.cs b/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTexturePacked.cs index 11231d45..9390ca39 100644 --- a/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTexturePacked.cs +++ b/OctoAwesome/OctoAwesome.Client/Components/VertexPositionNormalTexturePacked.cs @@ -1,9 +1,6 @@ using engenious; using engenious.Graphics; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Client.Components { diff --git a/OctoAwesome/OctoAwesome.Client/ContainerResourceManager.cs b/OctoAwesome/OctoAwesome.Client/ContainerResourceManager.cs index ebb776d9..6a10478b 100644 --- a/OctoAwesome/OctoAwesome.Client/ContainerResourceManager.cs +++ b/OctoAwesome/OctoAwesome.Client/ContainerResourceManager.cs @@ -1,42 +1,54 @@  using OctoAwesome.Components; using OctoAwesome.Definitions; -using OctoAwesome.EntityComponents; using OctoAwesome.Network; using OctoAwesome.Notifications; using OctoAwesome.Runtime; using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Client { - /// - /// This is only temporary - /// + public class ContainerResourceManager : IResourceManager, IDisposable { - public IDefinitionManager DefinitionManager => resourceManager.DefinitionManager; - public IUniverse CurrentUniverse => resourceManager.CurrentUniverse; + + public IDefinitionManager DefinitionManager => ResourceManager.DefinitionManager; + public IUniverse CurrentUniverse => ResourceManager.CurrentUniverse; - public bool IsMultiplayer { get; private set; } - public Player CurrentPlayer => resourceManager.CurrentPlayer; + public bool IsMultiplayer { get; private set; } + public Player CurrentPlayer => ResourceManager.CurrentPlayer; public IUpdateHub UpdateHub { get; } + public ConcurrentDictionary Planets + { + get + { + Debug.Assert(ResourceManager != null, nameof(ResourceManager) + " != null"); + return ResourceManager.Planets; + } + } - public ConcurrentDictionary Planets => resourceManager.Planets; + private ResourceManager ResourceManager + { + get + { + Debug.Assert(resourceManager != null, nameof(resourceManager) + " != null"); + return resourceManager; + } + } private readonly IExtensionResolver extensionResolver; private readonly IDefinitionManager definitionManager; private readonly ISettings settings; private readonly ITypeContainer typeContainer; - private ResourceManager resourceManager; - private NetworkUpdateManager networkUpdateManager; + private ResourceManager? resourceManager; + private NetworkUpdateManager? networkUpdateManager; public ContainerResourceManager(ITypeContainer typeContainer, IUpdateHub updateHub, IExtensionResolver extensionResolver, IDefinitionManager definitionManager, ISettings settings) { @@ -45,7 +57,6 @@ public ContainerResourceManager(ITypeContainer typeContainer, IUpdateHub updateH this.extensionResolver = extensionResolver; this.definitionManager = definitionManager; this.settings = settings; - } public void CreateManager(bool multiplayer) @@ -62,15 +73,12 @@ public void CreateManager(bool multiplayer) resourceManager = null; } - - if (multiplayer) { var rawIpAddress = settings.Get("server").Trim(); string host; - IPAddress iPAddress; int port = -1; - if (rawIpAddress[0] == '[' || !IPAddress.TryParse(rawIpAddress, out iPAddress)) //IPV4 || IPV6 without port + if (rawIpAddress[0] == '[' || !IPAddress.TryParse(rawIpAddress, out var iPAddress)) //IPV4 || IPV6 without port { string stringIpAddress; if (rawIpAddress[0] == '[') // IPV6 with Port @@ -124,63 +132,37 @@ public void CreateManager(bool multiplayer) // networkPersistence.SendChangedChunkColumn(c); // }; //} - - } + public void DeleteUniverse(Guid id) => ResourceManager.DeleteUniverse(id); + public IPlanet GetPlanet(int planetId) => ResourceManager.GetPlanet(planetId); - public void DeleteUniverse(Guid id) => resourceManager.DeleteUniverse(id); - - public IPlanet GetPlanet(int planetId) => resourceManager.GetPlanet(planetId); - - public IUniverse GetUniverse() => resourceManager.GetUniverse(); - - public IUniverse[] ListUniverses() => resourceManager.ListUniverses(); - - public Player LoadPlayer(string playername) => resourceManager.LoadPlayer(playername); - - public bool TryLoadUniverse(Guid universeId) => resourceManager.TryLoadUniverse(universeId); - - public Guid NewUniverse(string name, int seed) => resourceManager.NewUniverse(name, seed); - + public IUniverse[] ListUniverses() => ResourceManager.ListUniverses(); + public Player LoadPlayer(string playerName) => ResourceManager.LoadPlayer(playerName); + public bool TryLoadUniverse(Guid universeId) => ResourceManager.TryLoadUniverse(universeId); + public Guid NewUniverse(string name, int seed) => ResourceManager.NewUniverse(name, seed); public void SaveComponentContainer(TContainer container) where TContainer : ComponentContainer where TComponent : IComponent - => resourceManager.SaveComponentContainer(container); - - - public void SavePlayer(Player player) => resourceManager.SavePlayer(player); - - public void UnloadUniverse() => resourceManager.UnloadUniverse(); - public void SaveChunkColumn(IChunkColumn chunkColumn) => resourceManager.SaveChunkColumn(chunkColumn); - public IChunkColumn LoadChunkColumn(IPlanet planet, Index2 index) => resourceManager.LoadChunkColumn(planet, index); + => ResourceManager.SaveComponentContainer(container); + public void SavePlayer(Player player) => ResourceManager.SavePlayer(player); + public void UnloadUniverse() => ResourceManager.UnloadUniverse(); + public void SaveChunkColumn(IChunkColumn chunkColumn) => ResourceManager.SaveChunkColumn(chunkColumn); + public IChunkColumn LoadChunkColumn(IPlanet planet, Index2 index) => ResourceManager.LoadChunkColumn(planet, index); public void Dispose() { - if (resourceManager is IDisposable disposable) + if (ResourceManager is IDisposable disposable) disposable.Dispose(); } - public Entity LoadEntity(Guid entityId) - => resourceManager.LoadEntity(entityId); - + => ResourceManager.LoadEntity(entityId); public TContainer LoadComponentContainer(Guid id) where TContainer : ComponentContainer where TComponent : IComponent - => resourceManager.LoadComponentContainer(id); - - public IEnumerable LoadEntitiesWithComponent() where T : IEntityComponent - => resourceManager.LoadEntitiesWithComponent(); - public IEnumerable GetEntityIdsFromComponent() where T : IEntityComponent - => resourceManager.GetEntityIdsFromComponent(); - - - public (Guid Id, T Component)[] GetEntityComponents(Guid[] entityIds) where T : IEntityComponent, new() - => resourceManager.GetEntityComponents(entityIds); - + => ResourceManager.LoadComponentContainer(id); public (Guid Id, T Component)[] GetAllComponents() where T : IComponent, new() - => resourceManager.GetAllComponents(); - + => ResourceManager.GetAllComponents(); public T GetComponent(Guid id) where T : IComponent, new() - => resourceManager.GetComponent(id); + => ResourceManager.GetComponent(id); } } diff --git a/OctoAwesome/OctoAwesome.Client/Control/BindingsOptionControl.cs b/OctoAwesome/OctoAwesome.Client/Control/BindingsOptionControl.cs index d844209c..4ebd868c 100644 --- a/OctoAwesome/OctoAwesome.Client/Control/BindingsOptionControl.cs +++ b/OctoAwesome/OctoAwesome.Client/Control/BindingsOptionControl.cs @@ -66,10 +66,9 @@ public BindingsOptionControl(BaseScreenComponent manager, AssetComponent assets, private void BindingKeyLabel_LeftMouseClick(Control sender, MouseEventArgs args) { - object[] data = (object[])sender.Tag; - - if (data is null) + if (sender.Tag is null) return; + object[] data = (object[])sender.Tag; string id = (string)data[0]; Keys oldKey = (Keys)data[1]; diff --git a/OctoAwesome/OctoAwesome.Client/Control/DebugControl.cs b/OctoAwesome/OctoAwesome.Client/Control/DebugControl.cs index d622d972..96012c6b 100644 --- a/OctoAwesome/OctoAwesome.Client/Control/DebugControl.cs +++ b/OctoAwesome/OctoAwesome.Client/Control/DebugControl.cs @@ -1,4 +1,5 @@ -using engenious; +using System; +using engenious; using engenious.Graphics; using engenious.Helper; using engenious.UI; @@ -6,12 +7,8 @@ using OctoAwesome.Client.Components; using OctoAwesome.Client.UI.Components; using OctoAwesome.Definitions; -using OctoAwesome.EntityComponents; -using OctoAwesome.Runtime; -using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Linq; +using OctoAwesome.EntityComponents; namespace OctoAwesome.UI.Controls { @@ -28,7 +25,7 @@ internal class DebugControl : Panel private readonly IResourceManager resourceManager; private readonly IDefinitionManager definitionManager; - public PlayerComponent Player { get; set; } + public PlayerComponent Player { get; } private readonly StackPanel leftView, rightView; private readonly Label devText, position, rotation, fps, box, controlInfo, targetedBlockName, targetedBlockPosition, loadedChunks, loadedTextures, activeTool, toolCount, loadedInfo, flyInfo, temperatureInfo, precipitationInfo, gravityInfo; @@ -157,7 +154,7 @@ protected override void OnDrawContent(SpriteBatch batch, Rectangle contentArea, if (!Visible || !Enabled || !assets.Ready) return; - if (Player == null || Player.CurrentEntity == null) + if (Player.CurrentEntity == null || Player.CurrentEntityHead == null) return; //Calculate FPS @@ -174,7 +171,7 @@ protected override void OnDrawContent(SpriteBatch batch, Rectangle contentArea, bufferindex %= buffersize; //Draw Control Info - controlInfo.Text = Client.UI.Languages.OctoClient.ActiveControls + ": " + ScreenManager.ActiveScreen.Controls.Count; + controlInfo.Text = Client.UI.Languages.OctoClient.ActiveControls + ": " + ScreenManager.ActiveScreen!.Controls.Count; // Draw targeted block info Player.Selection?.Visit( @@ -214,8 +211,7 @@ void SetTargetedBlockInfo(ComponentContainer container) resourceManager.GetPlanet(Player.Position.Position.Planet).GlobalChunkCache.LoadedChunkColumns); // Draw Loaded Textures - loadedTextures.Text = string.Format("Loaded Textures: {0}", - assets.LoadedTextures); + loadedTextures.Text = $"Loaded Textures: {assets.LoadedTextures}"; //Get Number of Loaded Items/Blocks loadedInfo.Text = "" + definitionManager.ItemDefinitions.Count() + " " + Client.UI.Languages.OctoClient.Items + " - " + @@ -244,14 +240,10 @@ void SetTargetedBlockInfo(ComponentContainer container) gravityInfo.Text = "Gravity" + ": " + planet.Gravity; //Draw Box Information - if (Player.SelectedBox.HasValue && Player.SelectedPoint.HasValue) + if (Player.SelectedBox.HasValue) { - var selection = "box: " + - Player.SelectedBox.Value.ToString() + " on " + - Player.SelectedSide.ToString() + " (" + - Player.SelectedPoint.Value.X.ToString("0.000000") + "/" + - Player.SelectedPoint.Value.Y.ToString("0.000000") + ") -> " + - Player.SelectedEdge.ToString() + " -> " + Player.SelectedCorner.ToString(); + var selection = + $"box: {Player.SelectedBox.Value} on {Player.SelectedSide} ({Player.SelectedPoint?.X:0.000000}/{Player.SelectedPoint?.Y:0.000000}) -> {Player.SelectedEdge} -> {Player.SelectedCorner}"; box.Text = selection; } else diff --git a/OctoAwesome/OctoAwesome.Client/Control/ExtensionsOptionControl.cs b/OctoAwesome/OctoAwesome.Client/Control/ExtensionsOptionControl.cs index bcdc7e05..30eb681f 100644 --- a/OctoAwesome/OctoAwesome.Client/Control/ExtensionsOptionControl.cs +++ b/OctoAwesome/OctoAwesome.Client/Control/ExtensionsOptionControl.cs @@ -2,6 +2,7 @@ using engenious.UI; using engenious.UI.Controls; using System; +using System.Diagnostics; namespace OctoAwesome.Client.Controls { @@ -94,7 +95,9 @@ public ExtensionsOptionControl(BaseScreenComponent manager, IExtensionLoader ext enableButton.LeftMouseClick += (s, e) => { - IExtension ext = loadedExtensionsList.SelectedItem; + var ext = loadedExtensionsList.SelectedItem; + if (ext == null) + throw new NullReferenceException("Enable button should not be clickable when no item is selected."); loadedExtensionsList.Items.Remove(ext); activeExtensionsList.Items.Add(ext); activeExtensionsList.SelectedItem = ext; @@ -102,7 +105,9 @@ public ExtensionsOptionControl(BaseScreenComponent manager, IExtensionLoader ext disableButton.LeftMouseClick += (s, e) => { - IExtension ext = activeExtensionsList.SelectedItem; + var ext = activeExtensionsList.SelectedItem; + if (ext == null) + throw new NullReferenceException("Disable button should not be clickable when no item is selected."); activeExtensionsList.Items.Remove(ext); loadedExtensionsList.Items.Add(ext); loadedExtensionsList.SelectedItem = ext; @@ -128,14 +133,15 @@ public ExtensionsOptionControl(BaseScreenComponent manager, IExtensionLoader ext } } - private Control ListTemplateGenerator(IExtension ext) + private Control ListTemplateGenerator(IExtension? ext) { + Debug.Assert(ext != null, nameof(ext) + " != null"); return new Label(ScreenManager) - { - Text = ext.Name, - HorizontalAlignment = HorizontalAlignment.Stretch, - HorizontalTextAlignment = HorizontalAlignment.Left - }; + { + Text = ext.Name, + HorizontalAlignment = HorizontalAlignment.Stretch, + HorizontalTextAlignment = HorizontalAlignment.Left + }; } private void loadedList_SelectedItemChanged(Control control, SelectionEventArgs e) @@ -172,10 +178,10 @@ private void activeList_SelectedItemChanged(Control control, SelectionEventArgs< } } - private void SetPackInfo(IExtension ext) + private void SetPackInfo(IExtension? ext) { if (ext != null) - infoLabel.Text = string.Format("{0}{1}{2}", ext.Name, Environment.NewLine, ext.Description); + infoLabel.Text = $"{ext.Name}{Environment.NewLine}{ext.Description}"; else infoLabel.Text = string.Empty; } diff --git a/OctoAwesome/OctoAwesome.Client/Control/OptionsOptionControl.cs b/OctoAwesome/OctoAwesome.Client/Control/OptionsOptionControl.cs index 1c405750..5a26e449 100644 --- a/OctoAwesome/OctoAwesome.Client/Control/OptionsOptionControl.cs +++ b/OctoAwesome/OctoAwesome.Client/Control/OptionsOptionControl.cs @@ -5,6 +5,7 @@ using OctoAwesome.Client.UI.Components; using OctoAwesome.Client.UI.Controls; using System; +using System.Diagnostics; namespace OctoAwesome.Client.Controls { @@ -76,17 +77,22 @@ public OptionsOptionControl(BaseScreenComponent manager, OptionsScreen optionsSc }; crosshairGroupBox.Children.Add(crosshairColor); crosshairColor.TemplateGenerator = item => - { - return new Panel(manager) - { - Background = new SolidColorBrush(item), - HorizontalAlignment = HorizontalAlignment.Stretch, - VerticalAlignment = VerticalAlignment.Stretch, - Height = 20, - }; - }; - - crosshairColor.SelectedItemChanged += (s, e) => CrosshairControl.CrosshairColor = e.NewItem; + { + Debug.Assert(item != null, nameof(item) + " != null"); + return new Panel(manager) + { + Background = new SolidColorBrush(item), + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Stretch, + Height = 20, + }; + }; + + crosshairColor.SelectedItemChanged += (s, e) => + { + if (e.NewItem != null) + CrosshairControl.CrosshairColor = e.NewItem; + }; crosshairColor.Items.Add(Color.White); crosshairColor.Items.Add(Color.Black); diff --git a/OctoAwesome/OctoAwesome.Client/Control/ResourcePacksOptionControl.cs b/OctoAwesome/OctoAwesome.Client/Control/ResourcePacksOptionControl.cs index 5ce522d5..8aac4d2f 100644 --- a/OctoAwesome/OctoAwesome.Client/Control/ResourcePacksOptionControl.cs +++ b/OctoAwesome/OctoAwesome.Client/Control/ResourcePacksOptionControl.cs @@ -1,4 +1,6 @@ -using engenious; +using System; +using System.Diagnostics; +using engenious; using engenious.UI; using engenious.UI.Controls; using OctoAwesome.Client.UI; @@ -142,7 +144,9 @@ public ResourcePacksOptionControl(BaseScreenComponent manager, AssetComponent as addButton.LeftMouseClick += (s, e) => { - ResourcePack pack = loadedPacksList.SelectedItem; + var pack = loadedPacksList.SelectedItem; + if (pack == null) + throw new NullReferenceException("Add button should not be clickable when no item is selected."); loadedPacksList.Items.Remove(pack); activePacksList.Items.Add(pack); activePacksList.SelectedItem = pack; @@ -150,7 +154,9 @@ public ResourcePacksOptionControl(BaseScreenComponent manager, AssetComponent as removeButton.LeftMouseClick += (s, e) => { - ResourcePack pack = activePacksList.SelectedItem; + var pack = activePacksList.SelectedItem; + if (pack == null) + throw new NullReferenceException("Remove button should not be clickable when no item is selected."); activePacksList.Items.Remove(pack); loadedPacksList.Items.Add(pack); loadedPacksList.SelectedItem = pack; @@ -158,7 +164,7 @@ public ResourcePacksOptionControl(BaseScreenComponent manager, AssetComponent as moveUpButton.LeftMouseClick += (s, e) => { - ResourcePack pack = activePacksList.SelectedItem; + var pack = activePacksList.SelectedItem; if (pack == null) return; @@ -173,8 +179,9 @@ public ResourcePacksOptionControl(BaseScreenComponent manager, AssetComponent as moveDownButton.LeftMouseClick += (s, e) => { - ResourcePack pack = activePacksList.SelectedItem; - if (pack == null) return; + var pack = activePacksList.SelectedItem; + if (pack == null) + return; int index = activePacksList.Items.IndexOf(pack); if (index < activePacksList.Items.Count - 1) @@ -191,7 +198,7 @@ public ResourcePacksOptionControl(BaseScreenComponent manager, AssetComponent as Program.Restart(); }; - // Daten laden + // List loaded resource packs AssetComponent assets = asset; foreach (var item in assets.LoadedResourcePacks) @@ -205,14 +212,15 @@ public ResourcePacksOptionControl(BaseScreenComponent manager, AssetComponent as } } - private Control ListTemplateGenerator(ResourcePack pack) + private Control ListTemplateGenerator(ResourcePack? pack) { + Debug.Assert(pack != null, nameof(pack) + " != null"); return new Label(ScreenManager) - { - Text = pack.Name, - HorizontalAlignment = HorizontalAlignment.Stretch, - HorizontalTextAlignment = HorizontalAlignment.Left - }; + { + Text = pack.Name, + HorizontalAlignment = HorizontalAlignment.Stretch, + HorizontalTextAlignment = HorizontalAlignment.Left + }; } private void loadedList_SelectedItemChanged(Control control, SelectionEventArgs e) @@ -251,10 +259,10 @@ private void activeList_SelectedItemChanged(Control control, SelectionEventArgs< } } - private void SetPackInfo(ResourcePack pack) + private void SetPackInfo(ResourcePack? pack) { if (pack != null) - infoLabel.Text = string.Format("{0} ({1})\r\n{2}\r\n{3}", pack.Name, pack.Version, pack.Author, pack.Description); + infoLabel.Text = $"{pack.Name} ({pack.Version})\r\n{pack.Author}\r\n{pack.Description}"; else infoLabel.Text = string.Empty; } diff --git a/OctoAwesome/OctoAwesome.Client/Control/SceneControl.cs b/OctoAwesome/OctoAwesome.Client/Control/SceneControl.cs index 7b498621..a8002fc6 100644 --- a/OctoAwesome/OctoAwesome.Client/Control/SceneControl.cs +++ b/OctoAwesome/OctoAwesome.Client/Control/SceneControl.cs @@ -8,11 +8,8 @@ using engenious.Graphics; using engenious.Helper; using engenious.UI; -using engenious.UserDefined; -using OctoAwesome.Definitions; using System.Threading.Tasks; using System.Diagnostics; -using System.Linq; using OctoAwesome.EntityComponents; using OctoAwesome.Client.UI.Components; @@ -49,8 +46,6 @@ internal sealed class SceneControl : Control, IDisposable private readonly IndexBuffer selectionIndexBuffer; private readonly VertexBuffer selectionLines; private readonly VertexBuffer billboardVertexbuffer; - //private VertexPositionColor[] selectionLines; - //private VertexPositionTexture[] billboardVertices; private Index2 currentChunk = new Index2(-1, -1); @@ -62,31 +57,31 @@ internal sealed class SceneControl : Control, IDisposable private readonly Task[] _additionalRegenerationThreads; public RenderTarget2D MiniMapTexture { get; set; } - public RenderTarget2D ControlTexture { get; set; } + public RenderTarget2D? ControlTexture { get; set; } private float sunPosition = 0f; - public event EventHandler OnCenterChanged; + public event EventHandler? OnCenterChanged; private readonly VertexPositionColor[] selectionVertices = { - new VertexPositionColor(new Vector3(-0.001f, +1.001f, +1.001f), Color.Black * 0.5f), - new VertexPositionColor(new Vector3(+1.001f, +1.001f, +1.001f), Color.Black * 0.5f), - new VertexPositionColor(new Vector3(-0.001f, -0.001f, +1.001f), Color.Black * 0.5f), - new VertexPositionColor(new Vector3(+1.001f, -0.001f, +1.001f), Color.Black * 0.5f), - new VertexPositionColor(new Vector3(-0.001f, +1.001f, -0.001f), Color.Black * 0.5f), - new VertexPositionColor(new Vector3(+1.001f, +1.001f, -0.001f), Color.Black * 0.5f), - new VertexPositionColor(new Vector3(-0.001f, -0.001f, -0.001f), Color.Black * 0.5f), - new VertexPositionColor(new Vector3(+1.001f, -0.001f, -0.001f), Color.Black * 0.5f), + new(new Vector3(-0.001f, +1.001f, +1.001f), Color.Black * 0.5f), + new(new Vector3(+1.001f, +1.001f, +1.001f), Color.Black * 0.5f), + new(new Vector3(-0.001f, -0.001f, +1.001f), Color.Black * 0.5f), + new(new Vector3(+1.001f, -0.001f, +1.001f), Color.Black * 0.5f), + new(new Vector3(-0.001f, +1.001f, -0.001f), Color.Black * 0.5f), + new(new Vector3(+1.001f, +1.001f, -0.001f), Color.Black * 0.5f), + new(new Vector3(-0.001f, -0.001f, -0.001f), Color.Black * 0.5f), + new(new Vector3(+1.001f, -0.001f, -0.001f), Color.Black * 0.5f), }; private readonly VertexPositionTexture[] billboardVertices = { - new VertexPositionTexture(new Vector3(-0.5f, 0.5f, 0), new Vector2(0, 0)), - new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)), - new VertexPositionTexture(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)), - new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)), - new VertexPositionTexture(new Vector3(0.5f, -0.5f, 0), new Vector2(1, 1)), - new VertexPositionTexture(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)), + new(new Vector3(-0.5f, 0.5f, 0), new Vector2(0, 0)), + new(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)), + new(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)), + new(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)), + new(new Vector3(0.5f, -0.5f, 0), new Vector2(1, 1)), + new(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)), }; private readonly float sphereRadius; @@ -117,7 +112,9 @@ public SceneControl(ScreenComponent manager, string style = "") : sphereRadius = tmpSphereRadius - (chunkDiag / 2); sphereRadiusSquared = tmpSphereRadius * tmpSphereRadius; - simpleShader = manager.Game.Content.Load("simple"); + var loadedShader = manager.Game.Content.Load("simple"); + Debug.Assert(loadedShader != null, nameof(loadedShader) + " != null"); + simpleShader = loadedShader; sunTexture = assets.LoadTexture("sun"); //List bitmaps = new List(); @@ -148,7 +145,7 @@ public SceneControl(ScreenComponent manager, string style = "") : planet = Manager.Game.ResourceManager.GetPlanet(player.Position.Position.Planet); - // TODO: evtl. Cache-Size (Dimensions) VIEWRANGE + 1 + // TODO: perhaps Cache-Size (Dimensions) VIEWRANGE + 1 int range = ((int)Math.Pow(2, VIEWRANGE) - 2) / 2; localChunkCache = new LocalChunkCache(planet.GlobalChunkCache, VIEWRANGE, range); @@ -198,9 +195,7 @@ public SceneControl(ScreenComponent manager, string style = "") : } - - - var selectionVertices = new[] + ReadOnlySpan selectionVertices = stackalloc[] { new VertexPositionColor(new Vector3(-0.001f, +1.001f, +1.001f), Color.Black * 0.5f), new VertexPositionColor(new Vector3(+1.001f, +1.001f, +1.001f), Color.Black * 0.5f), @@ -212,7 +207,7 @@ public SceneControl(ScreenComponent manager, string style = "") : new VertexPositionColor(new Vector3(+1.001f, -0.001f, -0.001f), Color.Black * 0.5f), }; - var billboardVertices = new[] + ReadOnlySpan billboardVertices = stackalloc[] { new VertexPositionTexture(new Vector3(-0.5f, 0.5f, 0), new Vector2(0, 0)), new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)), @@ -237,8 +232,6 @@ public SceneControl(ScreenComponent manager, string style = "") : billboardVertexbuffer = new VertexBuffer(manager.GraphicsDevice, VertexPositionTexture.VertexDeclaration, billboardVertices.Length); billboardVertexbuffer.SetData(billboardVertices); - - sunEffect = new BasicEffect(manager.GraphicsDevice) { TextureEnabled = true @@ -289,14 +282,13 @@ protected override void OnUpdate(GameTime gameTime) var selBlock = GetSelectedBlock(centerblock, renderOffset, out selected, out selectedAxis, out selectionPoint); var funcBlock = GetSelectedFunctionalBlock(centerblock, renderOffset, out var selectedFunc, out var selectedFuncAxis, out var selectionFuncPoint); - - //TODO Distance check, so entity doesnt always get selected if a block is in front of it if (selectedFunc.HasValue && selectionFuncPoint.HasValue) { selected = selectedFunc; selectionPoint = selectionFuncPoint; selectedAxis = selectedFuncAxis; + Debug.Assert(funcBlock != null, nameof(funcBlock) + " != null while selectedFunc has value"); player.Selection = funcBlock; } else @@ -364,7 +356,7 @@ protected override void OnUpdate(GameTime gameTime) Index2 destinationChunk = new Index2(player.Position.Position.ChunkIndex); - // Nur ausführen wenn der Spieler den Chunk gewechselt hat + // Only execute when player changed the current chunk if (destinationChunk != currentChunk) { fillResetEvent.Set(); @@ -393,8 +385,9 @@ private BlockInfo GetSelectedBlock(Index3 centerblock, Index3 renderOffset, out var localBlock = localChunkCache.GetBlockInfo(pos); if (localBlock.Block == 0) continue; - IBlockDefinition blockDefinition = Manager.Game.DefinitionManager.GetBlockDefinitionByIndex(localBlock.Block); + var blockDefinition = Manager.Game.DefinitionManager.GetBlockDefinitionByIndex(localBlock.Block); + Debug.Assert(blockDefinition != null, nameof(blockDefinition) + " != null"); float? distance = Block.Intersect(blockDefinition.GetCollisionBoxes(localChunkCache, pos.X, pos.Y, pos.Z), pos - renderOffset, camera.PickRay, out Axis? collisionAxis); if (distance.HasValue && distance.Value < bestDistance) @@ -422,13 +415,13 @@ private BlockInfo GetSelectedBlock(Index3 centerblock, Index3 renderOffset, out return block; } - private FunctionalBlock GetSelectedFunctionalBlock(Index3 centerblock, Index3 renderOffset, out Index3? selected, out Axis? selectedAxis, out Vector3? selectionPoint) + private FunctionalBlock? GetSelectedFunctionalBlock(Index3 centerblock, Index3 renderOffset, out Index3? selected, out Axis? selectedAxis, out Vector3? selectionPoint) { selected = null; selectedAxis = null; selectionPoint = null; float bestDistance = 9999; - FunctionalBlock functionalBlock = null; + FunctionalBlock? functionalBlock = null; //Index3 centerblock = player.Position.Position.GlobalBlockIndex; //Index3 renderOffset = player.Position.Position.ChunkIndex * Chunk.CHUNKSIZE; @@ -477,8 +470,6 @@ protected override void OnPreDraw(GameTime gameTime) if (ControlTexture == null) ControlTexture = new RenderTarget2D(Manager.GraphicsDevice, ActualClientArea.Width, ActualClientArea.Height, PixelInternalFormat.Rgb8); - - float octoDaysPerEarthDay = 360f; float inclinationVariance = MathHelper.Pi / 3f; @@ -544,8 +535,6 @@ protected override void OnPreDraw(GameTime gameTime) //sunEffect.View = camera.View; //sunEffect.Projection = camera.Projection; //sunEffect.CurrentTechnique.Passes[0].Apply(); - - Manager.GraphicsDevice.VertexBuffer = billboardVertexbuffer; Manager.GraphicsDevice.DrawPrimitives(PrimitiveType.Triangles, 0, 2); @@ -577,18 +566,16 @@ protected override void OnPreDraw(GameTime gameTime) selectionEffect.Projection = camera.Projection; Manager.GraphicsDevice.VertexBuffer = selectionLines; Manager.GraphicsDevice.IndexBuffer = selectionIndexBuffer; - foreach (var pass in selectionEffect.CurrentTechnique.Passes) + foreach (var pass in selectionEffect.CurrentTechnique!.Passes) { pass.Apply(); Manager.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.Lines, 0, 0, 8, 0, 12); - //Manager.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.Lines, selectionLines, 0, 8, selectionIndeces, 0, 12); + //Manager.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.Lines, selectionLines, 0, 8, selectionIndices, 0, 12); } } Manager.GraphicsDevice.SetRenderTarget(null); } - - private void DrawChunks(Index3 chunkOffset, Matrix viewProj) { var spherePos = camera.PickRay.Position + (camera.PickRay.Direction * sphereRadius); @@ -618,7 +605,7 @@ private void FillChunkRenderer() Index2 destinationChunk = new Index2(player.Position.Position.ChunkIndex); - // Nur ausführen wenn der Spieler den Chunk gewechselt hat + // Only execute when player changed the current chunk if (destinationChunk != currentChunk) { localChunkCache.SetCenter( @@ -684,7 +671,7 @@ private void RegenerateAll(int start) } } - private void BackgroundLoop(object state) + private void BackgroundLoop(object? state) { var token = state is CancellationToken stateToken ? stateToken : CancellationToken.None; @@ -696,8 +683,9 @@ private void BackgroundLoop(object state) } } - private void AdditionalFillerBackgroundLoop(object state) + private void AdditionalFillerBackgroundLoop(object? state) { + Debug.Assert(state != null, nameof(state) + " != null"); var (@event, n, token) = ((AutoResetEvent Event, int N, CancellationToken Token))state; while (true) @@ -708,7 +696,7 @@ private void AdditionalFillerBackgroundLoop(object state) } } - private void ForceUpdateBackgroundLoop(object state) + private void ForceUpdateBackgroundLoop(object? state) { var token = state is CancellationToken stateToken ? stateToken : CancellationToken.None; @@ -719,7 +707,7 @@ private void ForceUpdateBackgroundLoop(object state) while (!forcedRenders.IsEmpty) { - while (forcedRenders.TryDequeue(out ChunkRenderer r)) + while (forcedRenders.TryDequeue(out var r)) { r.RegenerateVertexBuffer(); } diff --git a/OctoAwesome/OctoAwesome.Client/Control/ToolbarControl.cs b/OctoAwesome/OctoAwesome.Client/Control/ToolbarControl.cs index 0364c0dd..25ecc585 100644 --- a/OctoAwesome/OctoAwesome.Client/Control/ToolbarControl.cs +++ b/OctoAwesome/OctoAwesome.Client/Control/ToolbarControl.cs @@ -6,12 +6,8 @@ using OctoAwesome.Client.UI.Components; using OctoAwesome.Definitions; using OctoAwesome.EntityComponents; -using OctoAwesome.Runtime; -using System; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; +using System.Diagnostics; namespace OctoAwesome.Client.Controls { @@ -114,24 +110,20 @@ protected override void OnUpdate(GameTime gameTime) var newText = ""; // Aktualisierung des ActiveTool Labels - if (Player.Toolbar.ActiveTool != null) - { - newText = Player.Toolbar.ActiveTool.Definition.Name; + newText = Player.Toolbar.ActiveTool.Definition?.Name ?? string.Empty; - if (Player.Toolbar.ActiveTool.Amount > 1) - newText += $" ({Player.Toolbar.ActiveTool.Amount})"; - } + if (Player.Toolbar.ActiveTool.Amount > 1) + newText += $" ({Player.Toolbar.ActiveTool.Amount})"; activeToolLabel.Text = newText; - - activeToolLabel.Visible = !(activeToolLabel.Text == string.Empty); + activeToolLabel.Visible = activeToolLabel.Text != string.Empty; base.OnUpdate(gameTime); } - private void SetTexture(InventorySlot inventorySlot, int index) + private void SetTexture(InventorySlot? inventorySlot, int index) { - if (inventorySlot is null) + if (inventorySlot?.Definition is null) { images[index].Texture = null; return; @@ -139,10 +131,8 @@ private void SetTexture(InventorySlot inventorySlot, int index) var definitionName = inventorySlot.Definition.GetType().FullName; - if (toolTextures.TryGetValue(definitionName, out Texture2D texture)) - images[index].Texture = texture; - else - images[index].Texture = null; + Debug.Assert(definitionName != null, nameof(definitionName) + " != null"); + images[index].Texture = toolTextures.TryGetValue(definitionName, out var texture) ? texture : null; } } } diff --git a/OctoAwesome/OctoAwesome.Client/Crew/CrewMember.cs b/OctoAwesome/OctoAwesome.Client/Crew/CrewMember.cs index cfaf7c89..7c1f1630 100644 --- a/OctoAwesome/OctoAwesome.Client/Crew/CrewMember.cs +++ b/OctoAwesome/OctoAwesome.Client/Crew/CrewMember.cs @@ -1,53 +1,73 @@ using System.Collections.Generic; using System.Xml.Serialization; using System.IO; -using engenious.UI; using OctoAwesome.Client.Components; using System; namespace OctoAwesome.Client.Crew { + public class CrewMember { + public enum Achievements { + Patron, + Streamer, + HardwareDealer, + Coder, + Livegast, + Tools, + EmailJoker, + Contributor, + Musik, + Grafik, + WikiAdmin, + DatenbankFreigeschaltet }; - public string Username { get; set; } public string Alias { get; set; } public string Description { get; set; } + public Achievements[] AchievementList { get; set; } - public List AchievementList { get; set; } - - public string PictureFilename { get; set; } - - public List Links { get; set; } - - public CrewMember() { } - - internal static List getCrew(ScreenComponent manager) + public string? PictureFilename { get; set; } + public Link[] Links { get; set; } + public CrewMember() { + Username = string.Empty; + Alias = string.Empty; + Description = string.Empty; + PictureFilename = null; + Links = Array.Empty(); + AchievementList = Array.Empty(); + } + internal static List GetCrew(ScreenComponent manager) + { using (Stream stream = manager.Game.Assets.LoadStream(typeof(CrewMember), "Crew.crew", "xml")) { try { XmlSerializer serializer = new XmlSerializer(typeof(List)); - return (List)serializer.Deserialize(stream); + var res = serializer.Deserialize(stream); + if (res != null) + { + return (List)res; + } } catch (Exception) { } @@ -55,17 +75,20 @@ internal static List getCrew(ScreenComponent manager) return new List(); } } - public override string ToString() { return Username; } - public class Link { + + public Link() + { + Title = string.Empty; + Url = string.Empty; + } [XmlAttribute] public string Title { get; set; } - [XmlAttribute] public string Url { get; set; } } diff --git a/OctoAwesome/OctoAwesome.Client/OctoAwesome.Client.csproj b/OctoAwesome/OctoAwesome.Client/OctoAwesome.Client.csproj index 7bdfc686..fb94e217 100644 --- a/OctoAwesome/OctoAwesome.Client/OctoAwesome.Client.csproj +++ b/OctoAwesome/OctoAwesome.Client/OctoAwesome.Client.csproj @@ -3,11 +3,12 @@ WinExe net5.0 - warnings + enable true octoawesome.ico true + True @@ -36,9 +37,9 @@ - - - + + + diff --git a/OctoAwesome/OctoAwesome.Client/OctoGame.cs b/OctoAwesome/OctoAwesome.Client/OctoGame.cs index 4b609cb1..800ed601 100644 --- a/OctoAwesome/OctoAwesome.Client/OctoGame.cs +++ b/OctoAwesome/OctoAwesome.Client/OctoGame.cs @@ -1,10 +1,7 @@ -using OctoAwesome; -using OctoAwesome.Client.Components; +using OctoAwesome.Client.Components; using OctoAwesome.Client.Controls; using OctoAwesome.Runtime; using System; -using System.Configuration; -using System.Linq; using engenious.UI; using EventArgs = System.EventArgs; using engenious; @@ -26,29 +23,29 @@ internal class OctoGame : Game //GraphicsDeviceManager graphics; - public CameraComponent Camera { get; private set; } + public CameraComponent Camera { get; } - public PlayerComponent Player { get; private set; } + public PlayerComponent Player { get; } - public SimulationComponent Simulation { get; private set; } + public SimulationComponent Simulation { get; } - public GameService Service { get; private set; } + public GameService Service { get; } - public ScreenComponent Screen { get; private set; } + public ScreenComponent Screen { get; } - public KeyMapper KeyMapper { get; private set; } + public KeyMapper KeyMapper { get; } - public AssetComponent Assets { get; private set; } + public AssetComponent Assets { get; } - public Settings Settings { get; private set; } + public Settings Settings { get; } - public IDefinitionManager DefinitionManager { get; private set; } + public IDefinitionManager DefinitionManager { get; } - public IResourceManager ResourceManager { get; private set; } + public IResourceManager ResourceManager { get; } - public ExtensionLoader ExtensionLoader { get; private set; } + public ExtensionLoader ExtensionLoader { get; } - public EntityGameComponent Entity { get; private set; } + public EntityGameComponent Entity { get; } public OctoGame() : base() { @@ -103,21 +100,15 @@ public OctoGame() : base() SceneControl.VIEWRANGE = viewrange; } - - Components.Add(Assets); Components.Add(Screen); - - #region GameComponents DefinitionManager = typeContainer.Get(); //var persistenceManager = new DiskPersistenceManager(ExtensionLoader, DefinitionManager, Settings); //ResourceManager = new ResourceManager(ExtensionLoader, DefinitionManager, Settings, persistenceManager); ResourceManager = typeContainer.Get(); - - Player = new PlayerComponent(this, ResourceManager); Player.UpdateOrder = 2; Components.Add(Player); @@ -154,20 +145,20 @@ public OctoGame() : base() private static void Register(ITypeContainer typeContainer) { - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); } private void SetKeyBindings() diff --git a/OctoAwesome/OctoAwesome.Client/Program.cs b/OctoAwesome/OctoAwesome.Client/Program.cs index f795f6cb..3d5afef9 100644 --- a/OctoAwesome/OctoAwesome.Client/Program.cs +++ b/OctoAwesome/OctoAwesome.Client/Program.cs @@ -1,10 +1,9 @@ #region Using Statements -using OctoAwesome.Client.Cache; + using OctoAwesome.Logging; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; + #endregion namespace OctoAwesome.Client @@ -14,7 +13,7 @@ namespace OctoAwesome.Client /// public static class Program { - static OctoGame game; + static OctoGame? game; /// /// The main entry point for the application. /// @@ -34,7 +33,11 @@ static void Main() Path.Combine(".", "logs", $"client-dump-{DateTime.Now:ddMMyy_hhmmss}.txt"), e.ExceptionObject.ToString()); - logger.Fatal($"Unhandled Exception: {e.ExceptionObject}", e.ExceptionObject as Exception); + string message = $"Unhandled Exception: {e.ExceptionObject}"; + if (e.ExceptionObject is Exception exception) + logger.Fatal(message, exception); + else + logger.Fatal(message); logger.Flush(); }; @@ -42,10 +45,9 @@ static void Main() game.Run(60, 60); } } - public static void Restart() { - game.Exit(); + game?.Exit(); using (game = new OctoGame()) game.Run(60, 60); } diff --git a/OctoAwesome/OctoAwesome.Client/Screens/BaseScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/BaseScreen.cs index 7a0bb6d6..254b083c 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/BaseScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/BaseScreen.cs @@ -10,31 +10,28 @@ internal abstract class BaseScreen : Screen { private readonly AssetComponent assets; - protected Button BackButton; + protected readonly Button BackButton; public BaseScreen(ScreenComponent manager) : base(manager) { assets = manager.Game.Assets; + BackButton = new TextButton(Manager, UI.Languages.OctoClient.Back) + { + VerticalAlignment = VerticalAlignment.Top, + HorizontalAlignment = HorizontalAlignment.Left, + TabStop = false, + }; + BackButton.LeftMouseClick += (s, e) => + { + Manager.NavigateBack(); + }; + BackButton.Margin = new Border(10, 10, 10, 10); + Controls.Add(BackButton); } protected override void OnNavigatedTo(NavigationEventArgs args) { - if (Manager.CanGoBack) - { - BackButton = new TextButton(Manager, UI.Languages.OctoClient.Back) - { - VerticalAlignment = VerticalAlignment.Top, - HorizontalAlignment = HorizontalAlignment.Left, - TabStop = false, - }; - BackButton.LeftMouseClick += (s, e) => - { - Manager.NavigateBack(); - }; - BackButton.Margin = new Border(10, 10, 10, 10); - Controls.Add(BackButton); - } - + BackButton.Visible = Manager.CanGoBack; } protected void SetDefaultBackground() diff --git a/OctoAwesome/OctoAwesome.Client/Screens/ConnectionScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/ConnectionScreen.cs index 1fcbbc41..f32ff17e 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/ConnectionScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/ConnectionScreen.cs @@ -52,7 +52,7 @@ public ConnectionScreen(ScreenComponent manager) : base(manager) var playerNameInput = new Textbox(manager) { - Text = game.Settings.Get("player", "USERNAME"), + Text = game.Settings.Get("player", "USERNAME")!, HorizontalAlignment = HorizontalAlignment.Stretch, Background = new BorderBrush(Color.LightGray, LineType.Solid, Color.Black) diff --git a/OctoAwesome/OctoAwesome.Client/Screens/CreateUniverseScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/CreateUniverseScreen.cs index db8f7101..1314f34b 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/CreateUniverseScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/CreateUniverseScreen.cs @@ -1,17 +1,12 @@ using engenious; -using engenious.Graphics; using engenious.UI; using engenious.UI.Controls; using OctoAwesome.Client.Components; using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; namespace OctoAwesome.Client.Screens { - class CreateUniverseScreen : BaseScreen + internal class CreateUniverseScreen : BaseScreen { new readonly ScreenComponent Manager; private readonly Textbox nameInput; @@ -55,10 +50,6 @@ public CreateUniverseScreen(ScreenComponent manager) : base(manager) grid.Columns.Add(new ColumnDefinition() { Width = 1, ResizeMode = ResizeMode.Parts }); nameInput = GetTextbox(); - nameInput.TextChanged += (s, e) => - { - createButton.Visible = !string.IsNullOrEmpty(e.NewValue); - }; nameInput.TabOrder = 1; AddLabeledControl(grid, string.Format("{0}: ", UI.Languages.OctoClient.Name), nameInput); @@ -92,6 +83,11 @@ public CreateUniverseScreen(ScreenComponent manager) : base(manager) manager.NavigateToScreen(new LoadingScreen(manager)); }; + + nameInput.TextChanged += (s, e) => + { + createButton.Visible = !string.IsNullOrEmpty(e.NewValue); + }; panel.Controls.Add(createButton); } diff --git a/OctoAwesome/OctoAwesome.Client/Screens/CreditsScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/CreditsScreen.cs index b1946965..d0c3a6f5 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/CreditsScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/CreditsScreen.cs @@ -1,16 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Collections.Generic; using OctoAwesome.Client.Components; using engenious.UI; -using engenious; using OctoAwesome.Client.Crew; using engenious.UI.Controls; namespace OctoAwesome.Client.Screens { - class CreditsScreen : BaseScreen + internal class CreditsScreen : BaseScreen { public CreditsScreen(ScreenComponent manager) : base(manager) { @@ -20,7 +16,7 @@ public CreditsScreen(ScreenComponent manager) : base(manager) SetDefaultBackground(); - List crew = CrewMember.getCrew(manager); + List crew = CrewMember.GetCrew(manager); ScrollContainer crewScroll = new ScrollContainer(manager) { diff --git a/OctoAwesome/OctoAwesome.Client/Screens/CrewMemberScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/CrewMemberScreen.cs index 044f227a..41aa0ef4 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/CrewMemberScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/CrewMemberScreen.cs @@ -1,11 +1,8 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using engenious.UI; using OctoAwesome.Client.Components; using engenious.Graphics; -using System.Diagnostics; using OctoAwesome.Client.Crew; using engenious.UI.Controls; using OctoAwesome.Client.UI.Components; @@ -25,7 +22,7 @@ public CrewMemberScreen(ScreenComponent manager, CrewMember member) : base(manag Title = UI.Languages.OctoClient.CreditsCrew + ": " + member.Username; - SpriteFont boldFont = manager.Content.Load("Fonts/BoldFont"); + SpriteFont boldFont = Skin.Current.BoldFont; Padding = new Border(0, 0, 0, 0); @@ -48,8 +45,6 @@ public CrewMemberScreen(ScreenComponent manager, CrewMember member) : base(manag Orientation = Orientation.Horizontal }; panel.Controls.Add(horizontalStack); - - //The Profile Image Image profileImage = new Image(manager) { @@ -76,7 +71,7 @@ public CrewMemberScreen(ScreenComponent manager, CrewMember member) : base(manag Label username = new Label(manager) { Text = usernameText, - Font = manager.Content.Load("Fonts/HeadlineFont"), + Font = Skin.Current.HeadlineFont, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }; @@ -146,8 +141,7 @@ public CrewMemberScreen(ScreenComponent manager, CrewMember member) : base(manag private bool CheckHttpUrl(string url) { - Uri tmp; - return Uri.TryCreate(url, UriKind.Absolute, out tmp) && (tmp.Scheme == Uri.UriSchemeHttp || tmp.Scheme == Uri.UriSchemeHttps); + return Uri.TryCreate(url, UriKind.Absolute, out var tmp) && (tmp.Scheme == Uri.UriSchemeHttp || tmp.Scheme == Uri.UriSchemeHttps); } } } diff --git a/OctoAwesome/OctoAwesome.Client/Screens/GameScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/GameScreen.cs index de396c5f..8418aaf1 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/GameScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/GameScreen.cs @@ -181,8 +181,6 @@ protected override void OnNavigateFrom(NavigationEventArgs args) Manager.Player.InteractInput = false; base.OnNavigateFrom(args); } - - #endregion #region Keyboard Input diff --git a/OctoAwesome/OctoAwesome.Client/Screens/InventoryScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/InventoryScreen.cs index 6b0f740c..73f3e0bb 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/InventoryScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/InventoryScreen.cs @@ -3,6 +3,7 @@ using engenious.Graphics; using engenious.Input; using System.Collections.Generic; +using System.Diagnostics; using engenious; using OctoAwesome.EntityComponents; using engenious.UI.Controls; @@ -124,7 +125,8 @@ public InventoryScreen(ScreenComponent manager) : base(manager) image.StartDrag += (c,e) => { - InventorySlot slot = player.Toolbar.Tools[(int)image.Tag]; + Debug.Assert(image.Tag != null, nameof(image.Tag) + " != null"); + var slot = player.Toolbar.Tools[(int)image.Tag]; if (slot != null) { e.Handled = true; @@ -139,23 +141,26 @@ public InventoryScreen(ScreenComponent manager) : base(manager) image.EndDrop += (c,e) => { e.Handled = true; + + Debug.Assert(image.Tag != null, nameof(image.Tag) + " != null"); - if (e.Sender is Grid) // && ShiftPressed + if (e.Sender is Grid && e.Content is InventorySlot sourceSlot) // && ShiftPressed { // Swap int targetIndex = (int)image.Tag; - InventorySlot targetSlot = player.Toolbar.Tools[targetIndex]; + var targetSlot = player.Toolbar.Tools[targetIndex]; - InventorySlot sourceSlot = e.Content as InventorySlot; - int sourceIndex = player.Toolbar.GetSlotIndex(sourceSlot); + if (targetSlot != null) + { + int sourceIndex = player.Toolbar.GetSlotIndex(sourceSlot); - player.Toolbar.SetTool(sourceSlot, targetIndex); - player.Toolbar.SetTool(targetSlot, sourceIndex); + player.Toolbar.SetTool(sourceSlot, targetIndex); + player.Toolbar.SetTool(targetSlot, sourceIndex); + } } - else + else if(e.Content is InventorySlot slot) { // Inventory Drop - InventorySlot slot = e.Content as InventorySlot; player.Toolbar.SetTool(slot, (int)image.Tag); } }; @@ -171,9 +176,8 @@ protected override void OnEndDrop(DragEventArgs args) { base.OnEndDrop(args); - if (args.Sender is Grid) + if (args.Sender is Grid && args.Content is InventorySlot slot) { - InventorySlot slot = args.Content as InventorySlot; player.Toolbar.RemoveSlot(slot); } } @@ -212,12 +216,14 @@ protected override void OnUpdate(GameTime gameTime) // Aktualisierung des aktiven Buttons for (int i = 0; i < ToolBarComponent.TOOLCOUNT; i++) { - if (player.Toolbar.Tools != null && - player.Toolbar.Tools.Length > i && - player.Toolbar.Tools[i] != null && - player.Toolbar.Tools[i].Item != null) + var tool = player.Toolbar.Tools != null && player.Toolbar.Tools.Length > i ? player.Toolbar.Tools[i] : null; + if (tool != null) { - images[i].Texture = toolTextures[player.Toolbar.Tools[i].Definition.GetType().FullName]; + Debug.Assert(tool.Definition != null, nameof(tool.Definition) + " != null"); + var toolName = tool.Definition.GetType().FullName; + + Debug.Assert(toolName != null, nameof(toolName) + " != null"); + images[i].Texture = toolTextures[toolName]; } else { diff --git a/OctoAwesome/OctoAwesome.Client/Screens/LoadScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/LoadScreen.cs index a7d74dfd..2310eaf8 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/LoadScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/LoadScreen.cs @@ -1,10 +1,8 @@ using engenious.UI; using OctoAwesome.Client.Components; -using OctoAwesome.Runtime; using System; -using System.Collections.Generic; +using System.Diagnostics; using System.Linq; -using System.Text; using engenious; using engenious.Input; using engenious.UI.Controls; @@ -58,26 +56,13 @@ public LoadScreen(ScreenComponent manager) : base(manager) { var li = new Label(manager) { - Text = string.Format("{0} ({1})", x.Name, x.Seed), + Text = $"{x!.Name} ({x.Seed})", HorizontalAlignment = HorizontalAlignment.Stretch, Padding = Border.All(10), }; li.LeftMouseDoubleClick += (s, e) => Play(); return li; }; - levelList.SelectedItemChanged += (s, e) => - { - seedLabel.Text = ""; - if (levelList.SelectedItem != null) - { - seedLabel.Text = "Seed: " + levelList.SelectedItem.Seed; - deleteButton.Enabled = true; - } - else - { - deleteButton.Enabled = false; - } - }; mainStack.AddControl(levelList, 0, 0); //Sidebar @@ -111,6 +96,7 @@ public LoadScreen(ScreenComponent manager) : base(manager) deleteButton.LeftMouseClick += (s, e) => { // Sicherstellen, dass universe nicht geladen ist + Debug.Assert(levelList.SelectedItem != null, "levelList.SelectedItem != null"); if (Manager.Game.ResourceManager.CurrentUniverse != null && Manager.Game.ResourceManager.CurrentUniverse.Id == levelList.SelectedItem.Id) return; @@ -121,6 +107,21 @@ public LoadScreen(ScreenComponent manager) : base(manager) levelList.InvalidateDimensions(); settings.Set("LastUniverse", ""); }; + + + levelList.SelectedItemChanged += (s, e) => + { + seedLabel.Text = ""; + if (levelList.SelectedItem != null) + { + seedLabel.Text = "Seed: " + levelList.SelectedItem.Seed; + deleteButton.Enabled = true; + } + else + { + deleteButton.Enabled = false; + } + }; createButton = GetButton(UI.Languages.OctoClient.Create); createButton.LeftMouseClick += (s, e) => manager.NavigateToScreen(new CreateUniverseScreen(manager)); @@ -157,8 +158,6 @@ public LoadScreen(ScreenComponent manager) : base(manager) } } - - protected override void OnKeyDown(KeyEventArgs args) { if (args.Key == Keys.Enter) @@ -174,6 +173,7 @@ protected override void OnKeyDown(KeyEventArgs args) private void Play() { + Debug.Assert(levelList.SelectedItem != null, "levelList.SelectedItem != null"); Manager.Player.SetEntity(null); Manager.Game.Simulation.LoadGame(levelList.SelectedItem.Id); diff --git a/OctoAwesome/OctoAwesome.Client/Screens/LoadingScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/LoadingScreen.cs index 9a4bc3fb..ab2ee35a 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/LoadingScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/LoadingScreen.cs @@ -1,14 +1,10 @@ using engenious; -using engenious.Input; using engenious.UI; using engenious.UI.Controls; using OctoAwesome.Client.Components; using System; -using System.Collections.Generic; using System.Diagnostics; using System.IO; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -81,8 +77,6 @@ public LoadingScreen(ScreenComponent manager) : base(manager) quoteUpdate = Task.Run(async () => await UpdateLabel(text, loadingQuoteProvider, TimeSpan.FromSeconds(1.5), tokenSource.Token)); mainGrid.AddControl(text, 1, 1); - - //Buttons var buttonStack = new StackPanel(manager) { @@ -109,11 +103,9 @@ public LoadingScreen(ScreenComponent manager) : base(manager) gameScreen.Unload(); manager.NavigateBack(); }; - - } - private void SwitchToGame(object sender, System.EventArgs args) + private void SwitchToGame(object? sender, System.EventArgs args) { Manager.Invoke(() => { diff --git a/OctoAwesome/OctoAwesome.Client/Screens/MainScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/MainScreen.cs index cdc3b0bc..d682f956 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/MainScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/MainScreen.cs @@ -2,8 +2,6 @@ using engenious.UI.Controls; using OctoAwesome.Client.Components; using OctoAwesome.Client.UI.Components; -using OctoAwesome.Runtime; -using System.Diagnostics; namespace OctoAwesome.Client.Screens { diff --git a/OctoAwesome/OctoAwesome.Client/Screens/MessageScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/MessageScreen.cs index 58015925..068f0f02 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/MessageScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/MessageScreen.cs @@ -1,8 +1,6 @@ using engenious; -using engenious.Graphics; using engenious.UI; using engenious.UI.Controls; -using OctoAwesome.Client.Components; using OctoAwesome.Client.UI.Components; using System; @@ -12,7 +10,7 @@ internal sealed class MessageScreen : Screen { private readonly Panel panel; - public MessageScreen(BaseScreenComponent manager, AssetComponent assets, string title, string content, string buttonText = "OK", Action buttonClick = null) : base(manager) + public MessageScreen(BaseScreenComponent manager, AssetComponent assets, string title, string content, string buttonText = "OK", Action? buttonClick = null) : base(manager) { IsOverlay = true; Background = new BorderBrush(Color.Black * 0.5f); diff --git a/OctoAwesome/OctoAwesome.Client/Screens/OptionsScreen.cs b/OctoAwesome/OctoAwesome.Client/Screens/OptionsScreen.cs index 3fa3a0e3..3d3abafa 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/OptionsScreen.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/OptionsScreen.cs @@ -1,12 +1,7 @@ using engenious.UI; using OctoAwesome.Client.Components; using OctoAwesome.Client.Controls; -using System; -using System.Collections.Generic; -using System.Linq; using engenious.Graphics; -using engenious; -using engenious.Input; using engenious.UI.Controls; using OctoAwesome.Client.UI.Components; diff --git a/OctoAwesome/OctoAwesome.Client/Screens/QuoteProvider.cs b/OctoAwesome/OctoAwesome.Client/Screens/QuoteProvider.cs index 784cc730..756b51b7 100644 --- a/OctoAwesome/OctoAwesome.Client/Screens/QuoteProvider.cs +++ b/OctoAwesome/OctoAwesome.Client/Screens/QuoteProvider.cs @@ -1,13 +1,10 @@ using OctoAwesome.Threading; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Client.Screens { + public sealed class QuoteProvider { private readonly FileInfo fileInfo; @@ -22,6 +19,7 @@ public QuoteProvider(FileInfo fileInfo) this.fileInfo = fileInfo; random = new Random(); semaphoreExtended = new LockSemaphore(1, 1); + quotes = Array.Empty(); } public string GetRandomQuote() diff --git a/OctoAwesome/OctoAwesome.Client/Settings.cs b/OctoAwesome/OctoAwesome.Client/Settings.cs index b64d9c06..1b77f221 100644 --- a/OctoAwesome/OctoAwesome.Client/Settings.cs +++ b/OctoAwesome/OctoAwesome.Client/Settings.cs @@ -1,27 +1,19 @@ using System; -using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; -using System.Runtime.Serialization; namespace OctoAwesome.Client { - /// - /// Verwaltet die Anwendungseinstellungen. - /// + public class Settings : ISettings { private Configuration _config; - /// - /// Erzeugt eine neue Instanz der Klasse Settings, die auf die Konfigurationsdatei der aktuell laufenden Anwendung zugreift. - /// - /// Bei UnitTests ist Assembly.GetEntryAssembly null, Gründe dazu gibts auf StackOverflow. - /// Um Schmerzen zu vermeiden wurde eine Variable eingeführt, die unabhängig testet. - internal Settings(bool debug) + public Settings() { - if (debug) + var entryAssembly = Assembly.GetEntryAssembly(); + if (entryAssembly == null) // Can happen in tests { ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" }; _config = ConfigurationManager.OpenMappedExeConfiguration(map, @@ -29,35 +21,16 @@ internal Settings(bool debug) } else { - _config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly()!.Location); + _config = ConfigurationManager.OpenExeConfiguration(entryAssembly.Location); } } + - /// - /// Erzeugt eine neue Instanz der Klasse Settings, die auf die Konfigurationsdatei der aktuell laufenden Anwendung zugreift. - /// - public Settings() - { - _config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly()!.Location); - } - - /// - /// Gibt den Wert einer Einstellung zurück. - /// - /// Der Schlüssel der Einstellung. - /// Der Wert der Einstellung. - public T Get(string key) + public T? Get(string key) { - return Get(key, default(T)); + return Get(key, default); } - - /// - /// Gibt den Wert einer Einstellung zurück. - /// - /// Der Schlüssel der Einstellung. - /// Default-Wert, der zurückgegeben wird, wenn der key nicht vorhanden ist. - /// Der Wert der Einstellung oder der Default-Wert. - public T Get(string key, T defaultValue) + public T? Get(string key, T? defaultValue) { var settingElement = _config.AppSettings.Settings[key]; if (settingElement == null) @@ -66,35 +39,16 @@ public T Get(string key, T defaultValue) return (T)Convert.ChangeType(valueConfig, typeof(T)); } - - /// - /// Gibt das Array einer Einstellung zurück - /// - /// Art der Einstellung - /// Schlüssel der Einstellung - /// Das Array der Einstellung public T[] GetArray(string key) { var valueConfig = _config.AppSettings.Settings[key].Value; return DeserializeArray(valueConfig); } - - /// - /// Überprüft, ob die angegebene Einstellung existeiert. - /// - /// Der Schlüssel der Einstellung. - /// public bool KeyExists(string key) { return _config.AppSettings.Settings.AllKeys.Contains(key); } - - /// - /// Setzt den Wert einer Eigenschaft. - /// - /// Der Schlüssel der Einstellung. - /// Der Wert der Einstellung. public void Set(string key, string value) { if (_config.AppSettings.Settings.AllKeys.Contains(key)) @@ -103,48 +57,23 @@ public void Set(string key, string value) _config.AppSettings.Settings.Add(key, value); _config.Save(ConfigurationSaveMode.Modified, false); } - - /// - /// Setzt den Wert einer Eigenschaft. - /// - /// Der Schlüssel der Einstellung. - /// Der Wert der Einstellung. public void Set(string key, int value) { Set(key, Convert.ToString(value)); } - - /// - /// Setzt den Wert einer Eigenschaft. - /// - /// Der Schlüssel der Einstellung. - /// Der Wert der Einstellung. public void Set(string key, bool value) { Set(key, Convert.ToString(value)); } - - /// - /// Setzt den Wert einer Eigenschaft. - /// - /// Der Schlüssel der Einstellung. - /// Der Wert der Einstellung. public void Set(string key, string[] values) { - // Wir bauen das Array in eine Art serialisierten String um. - // Wenn eine Zeichenkette, die wir aus den Einstellugen lesen mit einer - // eckigen Klammer anfängt, ist es ein Array. + // For string array serialization we serialize a string in json array format. + // If a string setting starts with a square bracket it is in fact an array setting. // [value1, value2, value3] - string writeString = "[" + String.Join(",", values) + "]"; + string writeString = "[" + string.Join(",", values) + "]"; Set(key, writeString); } - - /// - /// Setzt den Wert einer Eigenschaft. - /// - /// Der Schlüssel der Einstellung. - /// Der Wert der Einstellung. public void Set(string key, int[] values) { string[] strValues = new string[values.Length]; @@ -152,12 +81,6 @@ public void Set(string key, int[] values) strValues[i] = Convert.ToString(values[i]); Set(key, strValues); } - - /// - /// Setzt den Wert einer Eigenschaft. - /// - /// Der Schlüssel der Einstellung. - /// Der Wert der Einstellung. public void Set(string key, bool[] values) { string[] stringValues = new string[values.Length]; @@ -165,14 +88,9 @@ public void Set(string key, bool[] values) stringValues[i] = Convert.ToString(values[i]); Set(key, stringValues); } - - private T[] DeserializeArray(string arrayString) { - // Wir müssten, um beide Klammern zu entfernen, - 3 rechnen. Ich lasse die letzte Klammer stellvertretend für das Komma, was folgen würde, stehen. - // Das wird in der for-Schleife auseinander gepflückt. - - arrayString = arrayString.Substring(1, arrayString.Length - 2 /*- 1*/); + arrayString = arrayString.Substring(1, arrayString.Length - 2); string[] partsString = arrayString.Split(','); T[] tArray = new T[partsString.Length]; @@ -181,11 +99,6 @@ private T[] DeserializeArray(string arrayString) return tArray; } - - /// - /// Löscht eine Eigenschaft aus den Einstellungen - /// - /// Der Schlüssel der Einstellung public void Delete(string key) { _config.AppSettings.Settings.Remove(key); diff --git a/OctoAwesome/OctoAwesome.Database/Checks/ICheckable.cs b/OctoAwesome/OctoAwesome.Database/Checks/ICheckable.cs index 4d55904a..8659abe0 100644 --- a/OctoAwesome/OctoAwesome.Database/Checks/ICheckable.cs +++ b/OctoAwesome/OctoAwesome.Database/Checks/ICheckable.cs @@ -1,7 +1,6 @@ -using System.IO; - -namespace OctoAwesome.Database.Checks +namespace OctoAwesome.Database.Checks { + public interface ICheckable { void Check(); diff --git a/OctoAwesome/OctoAwesome.Database/Checks/KeyInvalidException.cs b/OctoAwesome/OctoAwesome.Database/Checks/InvalidKeyException.cs similarity index 67% rename from OctoAwesome/OctoAwesome.Database/Checks/KeyInvalidException.cs rename to OctoAwesome/OctoAwesome.Database/Checks/InvalidKeyException.cs index 70c51593..91b56dd6 100644 --- a/OctoAwesome/OctoAwesome.Database/Checks/KeyInvalidException.cs +++ b/OctoAwesome/OctoAwesome.Database/Checks/InvalidKeyException.cs @@ -1,21 +1,19 @@ using System; -using System.Collections.Generic; -using System.Text; namespace OctoAwesome.Database.Checks { [Serializable] - public class KeyInvalidException : Exception + public sealed class InvalidKeyException : Exception { public long Position { get; } - public KeyInvalidException(string message, long position) : base($"{message} on Position {position}") + public InvalidKeyException(string message, long position) : base($"{message} on Position {position}") { Position = position; Data.Add(nameof(Position), position); } - protected KeyInvalidException( + private InvalidKeyException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } diff --git a/OctoAwesome/OctoAwesome.Database/Checks/ValueFileCheck.cs b/OctoAwesome/OctoAwesome.Database/Checks/ValueFileCheck.cs index 7dd33a4f..a2f43010 100644 --- a/OctoAwesome/OctoAwesome.Database/Checks/ValueFileCheck.cs +++ b/OctoAwesome/OctoAwesome.Database/Checks/ValueFileCheck.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Text; namespace OctoAwesome.Database.Checks { @@ -13,39 +11,36 @@ public ValueFileCheck(FileInfo fileInfo) { this.fileInfo = fileInfo; } - public void Check() { - using (var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.None)) + using var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.None); + var keyBuffer = new byte[Key.KEY_SIZE]; + do { - var keyBuffer = new byte[Key.KEY_SIZE]; - int length = 0; - do - { - fileStream.Read(keyBuffer, 0, keyBuffer.Length); - var key = Key.FromBytes(keyBuffer, 0); + fileStream.Read(keyBuffer, 0, keyBuffer.Length); + var key = Key.FromBytes(keyBuffer, 0); - if (!key.Validate()) - throw new KeyInvalidException($"Key is not valid", fileStream.Position); + if (!key.Validate()) + throw new InvalidKeyException($"Key is not valid", fileStream.Position); - if (key.Index != fileStream.Position - Key.KEY_SIZE) - throw new KeyInvalidException($"Key is on the wrong Position", fileStream.Position); + if (key.Index != fileStream.Position - Key.KEY_SIZE) + throw new InvalidKeyException($"Key is at the wrong position", fileStream.Position); - if (key.IsEmpty) - { - var intBuffer = new byte[sizeof(int)]; - fileStream.Read(intBuffer, 0, sizeof(int)); - length = BitConverter.ToInt32(intBuffer, 0) - sizeof(int); - } - else - { - length = key.ValueLength; - } + int length; + if (key.IsEmpty) + { + var intBuffer = new byte[sizeof(int)]; + fileStream.Read(intBuffer, 0, sizeof(int)); + length = BitConverter.ToInt32(intBuffer, 0) - sizeof(int); + } + else + { + length = key.ValueLength; + } - fileStream.Seek(length, SeekOrigin.Current); + fileStream.Seek(length, SeekOrigin.Current); - } while (fileStream.Position != fileStream.Length); - } + } while (fileStream.Position != fileStream.Length); } } } diff --git a/OctoAwesome/OctoAwesome.Database/Database.cs b/OctoAwesome/OctoAwesome.Database/Database.cs index c870ef38..4d8f22ad 100644 --- a/OctoAwesome/OctoAwesome.Database/Database.cs +++ b/OctoAwesome/OctoAwesome.Database/Database.cs @@ -1,25 +1,22 @@ using OctoAwesome.Database.Checks; using OctoAwesome.Database.Threading; using System; -using System.Collections; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Text; using System.Threading; namespace OctoAwesome.Database { + public abstract class Database : IDisposable { + public Type TagType { get; } protected Database(Type tagType) { TagType = tagType; } - public abstract void Open(); public abstract void Close(); public abstract void Dispose(); @@ -33,6 +30,7 @@ protected Database(Type tagType) public sealed class Database : Database where TTag : ITag, new() { + public bool FixedValueLength => valueStore.FixedValueLength; public IReadOnlyList Keys { @@ -42,7 +40,6 @@ public IReadOnlyList Keys return keyStore.Tags; } } - public bool IsOpen { get; private set; } /// @@ -64,7 +61,7 @@ public IReadOnlyList Keys private readonly DatabaseLockMonitor databaseLockMonitor; private readonly SemaphoreSlim dbLockSemaphore; - public Database(FileInfo keyFile, FileInfo valueFile, bool fixedValueLength) : base(typeof(TTag)) + public Database(FileInfo keyFile, FileInfo valueFile, bool fixedValueLength = false) : base(typeof(TTag)) { dbLockSemaphore = new SemaphoreSlim(1, 1); databaseLockMonitor = new DatabaseLockMonitor(); @@ -78,11 +75,6 @@ public Database(FileInfo keyFile, FileInfo valueFile, bool fixedValueLength) : b startDefragFunc = defragmentation.StartDefragmentation; checkFunc = fileCheck.Check; } - public Database(FileInfo keyFile, FileInfo valueFile) : this(keyFile, valueFile, false) - { - - } - public override void Open() { IsOpen = true; @@ -95,7 +87,7 @@ public override void Open() keyStore.Open(); } catch (Exception ex) - when (ex is KeyInvalidException || ex is ArgumentException) + when (ex is InvalidKeyException || ex is ArgumentException) { keyStore.Close(); defragmentation.RecreateKeyFile(); @@ -105,22 +97,18 @@ public override void Open() valueStore.Open(); if (Threshold >= 0 && keyStore.EmptyKeys >= Threshold) - Defragmentation(); + Defragment(); } - public override void Close() { IsOpen = false; keyStore.Close(); valueStore.Close(); } - public void Validate() => ExecuteOperationOnKeyValueStore(checkFunc); - - public void Defragmentation() + public void Defragment() => ExecuteOperationOnKeyValueStore(startDefragFunc); - public Value GetValue(TTag tag) { using (databaseLockMonitor.StartOperation(Operation.Read)) @@ -129,7 +117,6 @@ public Value GetValue(TTag tag) return valueStore.GetValue(key); } } - public void AddOrUpdate(TTag tag, Value value) { using (databaseLockMonitor.StartOperation(Operation.Write)) @@ -157,7 +144,6 @@ public void AddOrUpdate(TTag tag, Value value) keyStore.Add(newKey); } } - public bool ContainsKey(TTag tag) { using (databaseLockMonitor.StartOperation(Operation.Read)) @@ -172,7 +158,6 @@ public void Remove(TTag tag) valueStore.Remove(key); } } - public override DatabaseLock Lock(Operation mode) { //Read -> Blocks Write && Other read is ok @@ -197,7 +182,6 @@ public override DatabaseLock Lock(Operation mode) dbLockSemaphore.Release(); } } - public override void Dispose() { keyStore.Dispose(); diff --git a/OctoAwesome/OctoAwesome.Database/DatabaseContext.cs b/OctoAwesome/OctoAwesome.Database/DatabaseContext.cs index 7212bf67..8f158f78 100644 --- a/OctoAwesome/OctoAwesome.Database/DatabaseContext.cs +++ b/OctoAwesome/OctoAwesome.Database/DatabaseContext.cs @@ -1,22 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OctoAwesome.Database +namespace OctoAwesome.Database { - public abstract class DatabaseContext : IDatabaseContext where Tag : ITag, new() + + public abstract class DatabaseContext : IDatabaseContext where TTag : ITag, new() { - protected Database Database { get; } - protected DatabaseContext(Database database) + protected Database Database { get; } + + protected DatabaseContext(Database database) { Database = database; } - - public abstract TObject Get(Tag key); - + public abstract TObject? Get(TTag key); public abstract void AddOrUpdate(TObject value); - public abstract void Remove(TObject value); } } diff --git a/OctoAwesome/OctoAwesome.Database/Defragmentation.cs b/OctoAwesome/OctoAwesome.Database/Defragmentation.cs index ef33c1d5..5fa0da98 100644 --- a/OctoAwesome/OctoAwesome.Database/Defragmentation.cs +++ b/OctoAwesome/OctoAwesome.Database/Defragmentation.cs @@ -1,9 +1,6 @@ using System; -using System.Buffers; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; namespace OctoAwesome.Database { @@ -11,13 +8,11 @@ namespace OctoAwesome.Database { private readonly FileInfo keyStoreFile; private readonly FileInfo valueStoreFile; - public Defragmentation(FileInfo keyStoreFile, FileInfo valueStoreFile) { this.keyStoreFile = keyStoreFile; this.valueStoreFile = valueStoreFile; } - public void StartDefragmentation() { var newValueStoreFile = new FileInfo(Path.GetTempFileName()); @@ -31,7 +26,6 @@ public void StartDefragmentation() valueStoreFile.Delete(); newValueStoreFile.MoveTo(valueStoreFile.FullName); } - public void RecreateKeyFile() { var keyBuffer = new byte[Key.KEY_SIZE]; diff --git a/OctoAwesome/OctoAwesome.Database/Expressions/InstanceCreator.cs b/OctoAwesome/OctoAwesome.Database/Expressions/InstanceCreator.cs index f01af06a..b3f6fe56 100644 --- a/OctoAwesome/OctoAwesome.Database/Expressions/InstanceCreator.cs +++ b/OctoAwesome/OctoAwesome.Database/Expressions/InstanceCreator.cs @@ -1,14 +1,12 @@ using System; -using System.Collections.Generic; using System.Linq.Expressions; -using System.Text; namespace OctoAwesome.Database.Expressions { public static class InstanceCreator where T : new() { public static Func CreateInstance { get; } - + static InstanceCreator() { var body = Expression.New(typeof(T)); diff --git a/OctoAwesome/OctoAwesome.Database/GuidTag.cs b/OctoAwesome/OctoAwesome.Database/GuidTag.cs index 7fd92598..ad9ef952 100644 --- a/OctoAwesome/OctoAwesome.Database/GuidTag.cs +++ b/OctoAwesome/OctoAwesome.Database/GuidTag.cs @@ -1,44 +1,37 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Linq; namespace OctoAwesome.Database { + public struct GuidTag : ITag, IEquatable> { - public Guid Tag { get; private set; } + public Guid Id { get; private set; } public int Length => 16; public GuidTag(Guid id) { - Tag = id; + Id = id; } - public byte[] GetBytes() - => Tag.ToByteArray(); - + => Id.ToByteArray(); public void FromBytes(byte[] array, int startIndex) - => Tag = new Guid(array.Skip(startIndex).Take(Length).ToArray()); - - public override bool Equals(object obj) + => Id = new Guid(array.Skip(startIndex).Take(Length).ToArray()); + public override bool Equals(object? obj) => obj is GuidTag tag && Equals(tag); - public bool Equals(GuidTag other) - => Length == other.Length && Tag.Equals(other.Tag); - + => Length == other.Length && Id.Equals(other.Id); public override int GetHashCode() { int hashCode = 139101280; - hashCode = hashCode * -1521134295 + Tag.GetHashCode(); + hashCode = hashCode * -1521134295 + Id.GetHashCode(); hashCode = hashCode * -1521134295 + Length.GetHashCode(); return hashCode; } - public void WriteBytes(Span span) { - Tag.TryWriteBytes(span); + Id.TryWriteBytes(span); } public static bool operator ==(GuidTag left, GuidTag right) diff --git a/OctoAwesome/OctoAwesome.Database/IDatabaseContext.cs b/OctoAwesome/OctoAwesome.Database/IDatabaseContext.cs index c3cf25dd..2c5fed95 100644 --- a/OctoAwesome/OctoAwesome.Database/IDatabaseContext.cs +++ b/OctoAwesome/OctoAwesome.Database/IDatabaseContext.cs @@ -1,9 +1,9 @@ namespace OctoAwesome.Database { - public interface IDatabaseContext where Tag : ITag, new() + public interface IDatabaseContext where TTag : ITag, new() { void AddOrUpdate(TObject value); - TObject Get(Tag key); + TObject? Get(TTag key); void Remove(TObject value); } } \ No newline at end of file diff --git a/OctoAwesome/OctoAwesome.Database/ITag.cs b/OctoAwesome/OctoAwesome.Database/ITag.cs index aa9fa4d7..708e1a58 100644 --- a/OctoAwesome/OctoAwesome.Database/ITag.cs +++ b/OctoAwesome/OctoAwesome.Database/ITag.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace OctoAwesome.Database { @@ -8,9 +6,9 @@ public interface ITag { int Length { get; } - byte[] GetBytes(); + byte[] GetBytes(); // TODO: code deduplication: Use WriteBytes to create array + void FromBytes(byte[] array, int startIndex); // TODO: use span - void FromBytes(byte[] array, int startIndex); void WriteBytes(Span span); } } diff --git a/OctoAwesome/OctoAwesome.Database/IdManager.cs b/OctoAwesome/OctoAwesome.Database/IdManager.cs index 4e5b5079..9e021e8f 100644 --- a/OctoAwesome/OctoAwesome.Database/IdManager.cs +++ b/OctoAwesome/OctoAwesome.Database/IdManager.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace OctoAwesome.Database { @@ -10,14 +9,10 @@ public sealed class IdManager private readonly Queue freeIds; private readonly HashSet reservedIds; private int nextId; - - public IdManager() : this(Array.Empty()) - { - } - public IdManager(IEnumerable alreadyUsedIds) + + public IdManager(IEnumerable? alreadyUsedIds = null) { - if (alreadyUsedIds == null) - alreadyUsedIds = Array.Empty(); + alreadyUsedIds ??= Array.Empty(); freeIds = new Queue(); reservedIds = new HashSet(); diff --git a/OctoAwesome/OctoAwesome.Database/IdTag.cs b/OctoAwesome/OctoAwesome.Database/IdTag.cs index 96b5a28d..8c51665e 100644 --- a/OctoAwesome/OctoAwesome.Database/IdTag.cs +++ b/OctoAwesome/OctoAwesome.Database/IdTag.cs @@ -1,43 +1,34 @@ using System; -using System.Collections.Generic; -using System.Text; namespace OctoAwesome.Database { public struct IdTag : ITag, IEquatable> { - public int Tag { get; private set; } - + public int Id { get; private set; } public int Length => sizeof(int); public IdTag(int id) { - Tag = id; + Id = id; } - public byte[] GetBytes() - => BitConverter.GetBytes(Tag); - + => BitConverter.GetBytes(Id); public void FromBytes(byte[] array, int startIndex) - => Tag = BitConverter.ToInt32(array, startIndex); - - public override bool Equals(object obj) + => Id = BitConverter.ToInt32(array, startIndex); + public override bool Equals(object? obj) => obj is IdTag tag && Equals(tag); - public bool Equals(IdTag other) - => Length == other.Length && Tag == other.Tag; - + => Length == other.Length && Id == other.Id; public override int GetHashCode() { int hashCode = 139101280; - hashCode = hashCode * -1521134295 + Tag.GetHashCode(); + hashCode = hashCode * -1521134295 + Id.GetHashCode(); hashCode = hashCode * -1521134295 + Length.GetHashCode(); return hashCode; } - public void WriteBytes(Span span) { - BitConverter.TryWriteBytes(span, Tag); + BitConverter.TryWriteBytes(span, Id); } public static bool operator ==(IdTag left, IdTag right) diff --git a/OctoAwesome/OctoAwesome.Database/Key.cs b/OctoAwesome/OctoAwesome.Database/Key.cs index a1e479fc..f6ee5a20 100644 --- a/OctoAwesome/OctoAwesome.Database/Key.cs +++ b/OctoAwesome/OctoAwesome.Database/Key.cs @@ -2,13 +2,12 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; namespace OctoAwesome.Database { public readonly struct Key : IEquatable> where TTag : ITag, new() { + public const int BASE_KEY_SIZE = sizeof(long) + sizeof(int); public static int KEY_SIZE { get; } public static Key Empty { get; } @@ -19,29 +18,12 @@ static Key() KEY_SIZE = emptyTag.Length + BASE_KEY_SIZE; Empty = new Key(); } - - /// - /// The uniqe identification object for this key - /// public TTag Tag { get; } - /// - /// The current position of this Key and the referenced in the value file - /// public long Index { get; } - /// - /// The length of the referenced in the value file - /// public int ValueLength { get; } - /// - /// The current position of the key in the file - /// public long Position { get; } - /// - /// Returns true if the Key is not valid. Comparing with default should have the same result - /// public bool IsEmpty => ValueLength == 0 && Tag == null; - public Key(TTag tag, long index, int length, long position) { Tag = tag; @@ -50,10 +32,6 @@ public Key(TTag tag, long index, int length, long position) Position = position; } - public Key(TTag tag, long index, int length) : this(tag, index, length, -1) - { - } - public byte[] GetBytes() { var byteArray = new byte[KEY_SIZE]; @@ -77,9 +55,9 @@ public void WriteBytes(Writer writer, long position, bool flush = false) Tag.WriteBytes(byteArray[BASE_KEY_SIZE..(BASE_KEY_SIZE + Tag.Length)]); if (flush) - writer.WriteAndFlush(byteArray, position); + writer.WriteAndFlush(byteArray, position); else - writer.Write(byteArray, position); + writer.Write(byteArray, position); } public void WriteBytes(Writer writer, bool flush = false) { @@ -92,28 +70,25 @@ public void WriteBytes(Writer writer, bool flush = false) Tag.WriteBytes(byteArray[BASE_KEY_SIZE..(BASE_KEY_SIZE + Tag.Length)]); if (flush) - writer.WriteAndFlush(byteArray); + writer.WriteAndFlush(byteArray); else - writer.Write(byteArray); + writer.Write(byteArray); } - - public static Key FromBytes(byte[] array, int index) + public static Key FromBytes(byte[] array, int startIndex) { - var localIndex = BitConverter.ToInt64(array, index); - var length = BitConverter.ToInt32(array, index + sizeof(long)); + var localIndex = BitConverter.ToInt64(array, startIndex); + var length = BitConverter.ToInt32(array, startIndex + sizeof(long)); var tag = InstanceCreator.CreateInstance(); - tag.FromBytes(array, index + BASE_KEY_SIZE); + tag.FromBytes(array, startIndex + BASE_KEY_SIZE); - return new Key(tag, localIndex, length, index); + return new Key(tag, localIndex, length, startIndex); } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is Key key && Equals(key); public bool Equals(Key other) => EqualityComparer.Default.Equals(Tag, other.Tag) && ValueLength == other.ValueLength; - public override int GetHashCode() { var hashCode = 139101280; @@ -130,6 +105,7 @@ public bool Validate() public static bool operator ==(Key left, Key right) => left.Equals(right); + public static bool operator !=(Key left, Key right) => !(left == right); } diff --git a/OctoAwesome/OctoAwesome.Database/KeyStore.cs b/OctoAwesome/OctoAwesome.Database/KeyStore.cs index df76110a..88db5291 100644 --- a/OctoAwesome/OctoAwesome.Database/KeyStore.cs +++ b/OctoAwesome/OctoAwesome.Database/KeyStore.cs @@ -1,11 +1,7 @@ using OctoAwesome.Database.Checks; using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Database { @@ -39,7 +35,7 @@ public void Open() var key = Key.FromBytes(buffer, i); if (!key.Validate()) - throw new KeyInvalidException("Key is not valid", i); + throw new InvalidKeyException("Key is not valid", i); if (key.IsEmpty) { diff --git a/OctoAwesome/OctoAwesome.Database/OctoAwesome.Database.csproj b/OctoAwesome/OctoAwesome.Database/OctoAwesome.Database.csproj index 80e79838..d34d42da 100644 --- a/OctoAwesome/OctoAwesome.Database/OctoAwesome.Database.csproj +++ b/OctoAwesome/OctoAwesome.Database/OctoAwesome.Database.csproj @@ -2,7 +2,8 @@ net5.0 - warnings + enable + True diff --git a/OctoAwesome/OctoAwesome.Database/Operation.cs b/OctoAwesome/OctoAwesome.Database/Operation.cs index e68d5e1b..6375621a 100644 --- a/OctoAwesome/OctoAwesome.Database/Operation.cs +++ b/OctoAwesome/OctoAwesome.Database/Operation.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace OctoAwesome.Database { diff --git a/OctoAwesome/OctoAwesome.Database/Reader.cs b/OctoAwesome/OctoAwesome.Database/Reader.cs index b76fe19b..c1a2ed08 100644 --- a/OctoAwesome/OctoAwesome.Database/Reader.cs +++ b/OctoAwesome/OctoAwesome.Database/Reader.cs @@ -1,8 +1,5 @@ using System; -using System.Buffers; -using System.Collections.Generic; using System.IO; -using System.Text; namespace OctoAwesome.Database { @@ -10,17 +7,17 @@ public sealed class Reader { private readonly FileInfo fileInfo; - public Reader(FileInfo fileInfo) { this.fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo)); } + public Reader(string path) : this(new FileInfo(path)) { } - internal byte[] Read(long index, int length) + public byte[] Read(long position, int length) { if (length < 0) { @@ -31,7 +28,7 @@ internal byte[] Read(long index, int length) var array = new byte[length]; using (var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { - fileStream.Seek(index, SeekOrigin.Begin); + fileStream.Seek(position, SeekOrigin.Begin); fileStream.Read(array, 0, length); } return array; diff --git a/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLock.cs b/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLock.cs index ad723f73..fc1e2f91 100644 --- a/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLock.cs +++ b/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLock.cs @@ -1,40 +1,31 @@ using System; using System.Collections.Generic; -using System.Text; namespace OctoAwesome.Database.Threading { + public readonly struct DatabaseLock : IDisposable, IEquatable { - public static DatabaseLock Empty = default; - - public bool IsEmpty => this == default; - private readonly DatabaseLockMonitor lockMonitor; private readonly Operation currentOperation; - public DatabaseLock(DatabaseLockMonitor lockMonitor, Operation operation) { this.lockMonitor = lockMonitor; currentOperation = operation; } - public void Enter() { - lockMonitor.SetLock(currentOperation); + lockMonitor.AcquireLock(currentOperation); } - public void Dispose() { lockMonitor.ReleaseLock(currentOperation); } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is DatabaseLock @lock && Equals(@lock); public bool Equals(DatabaseLock other) => EqualityComparer.Default.Equals(lockMonitor, other.lockMonitor) && currentOperation == other.currentOperation; - public override int GetHashCode() { var hashCode = 1919164243; @@ -43,9 +34,10 @@ public override int GetHashCode() return hashCode; } - public static bool operator ==(DatabaseLock left, DatabaseLock right) + public static bool operator ==(DatabaseLock left, DatabaseLock right) => left.Equals(right); - public static bool operator !=(DatabaseLock left, DatabaseLock right) + + public static bool operator !=(DatabaseLock left, DatabaseLock right) => !(left == right); } } diff --git a/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLockMonitor.cs b/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLockMonitor.cs index 4fce09a8..b93207ec 100644 --- a/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLockMonitor.cs +++ b/OctoAwesome/OctoAwesome.Database/Threading/DatabaseLockMonitor.cs @@ -1,10 +1,9 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading; namespace OctoAwesome.Database.Threading { + public sealed class DatabaseLockMonitor : IDisposable { private int readLocks; @@ -18,7 +17,6 @@ public sealed class DatabaseLockMonitor : IDisposable private readonly ManualResetEvent writeEvent; private readonly ManualResetEvent exclusiveEvent; private readonly SemaphoreSlim semaphoreSlim; - public DatabaseLockMonitor() { readEvent = new ManualResetEvent(true); @@ -32,7 +30,6 @@ public DatabaseLockMonitor() writeOperations = 0; exclusiveLocks = false; } - public bool CheckLock(Operation operation) { semaphoreSlim.Wait(); @@ -111,7 +108,7 @@ internal void StopOperation(Operation operation) } } - public void SetLock(Operation operation) + public void AcquireLock(Operation operation) { semaphoreSlim.Wait(); try @@ -168,7 +165,6 @@ public void ReleaseLock(Operation operation) semaphoreSlim.Release(); } } - public void Dispose() { readEvent.Dispose(); diff --git a/OctoAwesome/OctoAwesome.Database/Threading/DatabaseOperation.cs b/OctoAwesome/OctoAwesome.Database/Threading/DatabaseOperation.cs index 13c794ae..a64920bf 100644 --- a/OctoAwesome/OctoAwesome.Database/Threading/DatabaseOperation.cs +++ b/OctoAwesome/OctoAwesome.Database/Threading/DatabaseOperation.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; namespace OctoAwesome.Database.Threading { @@ -24,7 +23,7 @@ public void Dispose() lockMonitor.StopOperation(currentOperation); } - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is DatabaseOperation @lock && Equals(@lock); public bool Equals(DatabaseOperation other) => EqualityComparer.Default.Equals(lockMonitor, other.lockMonitor) diff --git a/OctoAwesome/OctoAwesome.Database/Value.cs b/OctoAwesome/OctoAwesome.Database/Value.cs index dc7d7970..679dd084 100644 --- a/OctoAwesome/OctoAwesome.Database/Value.cs +++ b/OctoAwesome/OctoAwesome.Database/Value.cs @@ -1,11 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace OctoAwesome.Database +namespace OctoAwesome.Database { public readonly struct Value { + public byte[] Content { get; } public Value(byte[] buffer) diff --git a/OctoAwesome/OctoAwesome.Database/ValueStore.cs b/OctoAwesome/OctoAwesome.Database/ValueStore.cs index e5278781..460207ae 100644 --- a/OctoAwesome/OctoAwesome.Database/ValueStore.cs +++ b/OctoAwesome/OctoAwesome.Database/ValueStore.cs @@ -1,8 +1,4 @@ using System; -using System.Buffers; -using System.Collections.Generic; -using System.IO; -using System.Text; namespace OctoAwesome.Database { @@ -32,8 +28,7 @@ public ValueStore(Writer writer, Reader reader) : this(writer, reader, false) internal Key AddValue(TTag tag, Value value) where TTag : ITag, new() { - - var key = new Key(tag, writer.ToEnd(), value.Content.Length); + var key = new Key(tag, writer.ToEnd(), value.Content.Length, -1); //TODO: Hash, Sync key.WriteBytes(writer); writer.WriteAndFlush(value.Content, 0, value.Content.Length); diff --git a/OctoAwesome/OctoAwesome.Database/Writer.cs b/OctoAwesome/OctoAwesome.Database/Writer.cs index 0a33b636..d5139331 100644 --- a/OctoAwesome/OctoAwesome.Database/Writer.cs +++ b/OctoAwesome/OctoAwesome.Database/Writer.cs @@ -1,81 +1,91 @@ using System; -using System.Collections.Generic; +using System.Diagnostics; using System.IO; -using System.Text; namespace OctoAwesome.Database { public sealed class Writer : IDisposable { private readonly FileInfo fileInfo; - private FileStream fileStream; - + private FileStream? fileStream; public Writer(FileInfo fileInfo) { this.fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo)); } + public Writer(string path) : this(new FileInfo(path)) { } - public void Open() { fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); } - public void Close() { - fileStream.Dispose(); + fileStream?.Dispose(); fileStream = null; } public void Write(ReadOnlySpan data) - => fileStream.Write(data); + { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); + fileStream.Write(data); + } public void Write(ReadOnlySpan data, long position) { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); fileStream.Seek(position, SeekOrigin.Begin); Write(data); } - public void WriteAndFlush(ReadOnlySpan data) { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); Write(data); fileStream.Flush(); } + public void WriteAndFlush(ReadOnlySpan data, long position) { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); Write(data, position); fileStream.Flush(); } - + public void Write(ReadOnlySpan data, int offset, int length) - => fileStream.Write(data[offset..(offset+length)]); + { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); + fileStream.Write(data[offset..(offset + length)]); + } public void Write(ReadOnlySpan data, int offset, int length, long position) { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); fileStream.Seek(position, SeekOrigin.Begin); Write(data[offset..(offset + length)]); } - public void WriteAndFlush(ReadOnlySpan data, int offset, int length) { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); Write(data[offset..(offset + length)]); fileStream.Flush(); } + public void WriteAndFlush(ReadOnlySpan data, int offset, int length, long position) { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); Write(data[offset..(offset + length)], position); fileStream.Flush(); } internal long ToEnd() - => fileStream.Seek(0, SeekOrigin.End); + { + Debug.Assert(fileStream != null, nameof(fileStream) + " is not open!"); + return fileStream.Seek(0, SeekOrigin.End); + } #region IDisposable Support private bool disposedValue = false; - - public void Dispose() { if (disposedValue) diff --git a/OctoAwesome/OctoAwesome.GameServer/CommandParameter.cs b/OctoAwesome/OctoAwesome.GameServer/CommandParameter.cs index a8ce1743..89234601 100644 --- a/OctoAwesome/OctoAwesome.GameServer/CommandParameter.cs +++ b/OctoAwesome/OctoAwesome.GameServer/CommandParameter.cs @@ -1,17 +1,11 @@ -using OctoAwesome.Network; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.GameServer +namespace OctoAwesome.GameServer { + public struct CommandParameter { + public uint ClientId { get; } public byte[] Data { get; } - public CommandParameter(uint clientId, byte[] data) { ClientId = clientId; diff --git a/OctoAwesome/OctoAwesome.GameServer/Commands/ChunkCommands.cs b/OctoAwesome/OctoAwesome.GameServer/Commands/ChunkCommands.cs index 570df78d..ffe6a844 100644 --- a/OctoAwesome/OctoAwesome.GameServer/Commands/ChunkCommands.cs +++ b/OctoAwesome/OctoAwesome.GameServer/Commands/ChunkCommands.cs @@ -1,16 +1,13 @@ using CommandManagementSystem.Attributes; using OctoAwesome.Network; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.GameServer.Commands { - public class ChunkCommands + public static class ChunkCommands { + [Command((ushort)OfficialCommand.LoadColumn)] public static byte[] LoadColumn(CommandParameter parameter) { @@ -35,7 +32,6 @@ public static byte[] LoadColumn(CommandParameter parameter) return memoryStream.ToArray(); } } - [Command((ushort)OfficialCommand.SaveColumn)] public static byte[] SaveColumn(CommandParameter parameter) { diff --git a/OctoAwesome/OctoAwesome.GameServer/Commands/GeneralCommands.cs b/OctoAwesome/OctoAwesome.GameServer/Commands/GeneralCommands.cs index d32b17f4..f9a7ac0e 100644 --- a/OctoAwesome/OctoAwesome.GameServer/Commands/GeneralCommands.cs +++ b/OctoAwesome/OctoAwesome.GameServer/Commands/GeneralCommands.cs @@ -1,18 +1,14 @@ using CommandManagementSystem.Attributes; using OctoAwesome.Network; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.GameServer.Commands { public static class GeneralCommands { [Command((ushort)OfficialCommand.GetUniverse)] - public static byte[] GetUniverse(CommandParameter parameter) + public static byte[] GetUniverse(CommandParameter parameter) // TODO: use parameter for multi universe server? { var universe = TypeContainer.Get().GetUniverse(); @@ -23,9 +19,8 @@ public static byte[] GetUniverse(CommandParameter parameter) return memoryStream.ToArray(); } } - [Command((ushort)OfficialCommand.GetPlanet)] - public static byte[] GetPlanet(CommandParameter parameter) + public static byte[] GetPlanet(CommandParameter parameter) // TODO: use parameter for actual planet server? { Console.WriteLine("Just got in here"); diff --git a/OctoAwesome/OctoAwesome.GameServer/Commands/NotificationCommands.cs b/OctoAwesome/OctoAwesome.GameServer/Commands/NotificationCommands.cs index aa0cf5b8..78317a1b 100644 --- a/OctoAwesome/OctoAwesome.GameServer/Commands/NotificationCommands.cs +++ b/OctoAwesome/OctoAwesome.GameServer/Commands/NotificationCommands.cs @@ -5,13 +5,10 @@ using OctoAwesome.Rx; using OctoAwesome.Serialization; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.GameServer.Commands { + public static class NotificationCommands { private static readonly IPool entityNotificationPool; @@ -40,7 +37,6 @@ static NotificationCommands() networkChannelSub = updateHub.AddSource(networkChannel, DefaultChannels.Network); chunkChannelSub = updateHub.AddSource(chunkChannel, DefaultChannels.Chunk); } - [Command((ushort)OfficialCommand.EntityNotification)] public static byte[] EntityNotification(CommandParameter parameter) { @@ -53,7 +49,6 @@ public static byte[] EntityNotification(CommandParameter parameter) entityNotification.Release(); return null; } - [Command((ushort)OfficialCommand.ChunkNotification)] public static byte[] ChunkNotification(CommandParameter parameter) { diff --git a/OctoAwesome/OctoAwesome.GameServer/Commands/PlayerCommands.cs b/OctoAwesome/OctoAwesome.GameServer/Commands/PlayerCommands.cs index 6c354a44..bac14cf9 100644 --- a/OctoAwesome/OctoAwesome.GameServer/Commands/PlayerCommands.cs +++ b/OctoAwesome/OctoAwesome.GameServer/Commands/PlayerCommands.cs @@ -2,21 +2,16 @@ using engenious; using OctoAwesome.EntityComponents; using OctoAwesome.Network; -using OctoAwesome.Network.ServerNotifications; using OctoAwesome.Notifications; using OctoAwesome.Pooling; using OctoAwesome.Rx; using OctoAwesome.Serialization; using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.NetworkInformation; using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.GameServer.Commands { + public static class PlayerCommands { private static readonly ConcurrentRelay simulationChannel; @@ -34,7 +29,6 @@ static PlayerCommands() simulationChannelSub = updateHub.AddSource(simulationChannel, DefaultChannels.Simulation); networkChannelSub = updateHub.AddSource(networkChannel, DefaultChannels.Network); } - [Command((ushort)OfficialCommand.Whoami)] public static byte[] Whoami(CommandParameter parameter) { @@ -42,21 +36,19 @@ public static byte[] Whoami(CommandParameter parameter) string playername = Encoding.UTF8.GetString(parameter.Data); var player = new Player(); var entityNotificationPool = TypeContainer.Get>(); - var entityNotification = entityNotificationPool.Get(); + var entityNotification = entityNotificationPool.Rent(); entityNotification.Entity = player; entityNotification.Type = EntityNotification.ActionType.Add; simulationChannel.OnNext(entityNotification); entityNotification.Release(); - - var remotePlayer = new RemoteEntity(player); remotePlayer.Components.AddComponent(new PositionComponent() { Position = new Coordinate(0, new Index3(0, 0, 78), new Vector3(0, 0, 0)) }); remotePlayer.Components.AddComponent(new RenderComponent() { Name = "Wauzi", ModelName = "dog", TextureName = "texdog", BaseZRotation = -90 }, true); remotePlayer.Components.AddComponent(new BodyComponent() { Mass = 50f, Height = 2f, Radius = 1.5f }); Console.WriteLine(playername); - entityNotification = entityNotificationPool.Get(); + entityNotification = entityNotificationPool.Rent(); entityNotification.Entity = remotePlayer; entityNotification.Type = EntityNotification.ActionType.Add; diff --git a/OctoAwesome/OctoAwesome.GameServer/OctoAwesome.GameServer.csproj b/OctoAwesome/OctoAwesome.GameServer/OctoAwesome.GameServer.csproj index 12237330..39111745 100644 --- a/OctoAwesome/OctoAwesome.GameServer/OctoAwesome.GameServer.csproj +++ b/OctoAwesome/OctoAwesome.GameServer/OctoAwesome.GameServer.csproj @@ -5,6 +5,7 @@ net5.0 warnings Linux + True diff --git a/OctoAwesome/OctoAwesome.GameServer/Program.cs b/OctoAwesome/OctoAwesome.GameServer/Program.cs index c62ffdd1..0cdeeb7f 100644 --- a/OctoAwesome/OctoAwesome.GameServer/Program.cs +++ b/OctoAwesome/OctoAwesome.GameServer/Program.cs @@ -1,11 +1,7 @@ -using CommandManagementSystem; -using Newtonsoft.Json; -using OctoAwesome.Logging; +using OctoAwesome.Logging; using OctoAwesome.Network; using System; -using System.Collections.Generic; using System.IO; -using System.Net; using System.Threading; namespace OctoAwesome.GameServer @@ -31,7 +27,12 @@ private static void Main(string[] args) Path.Combine(".", "logs", $"server-dump-{DateTime.Now:ddMMyy_hhmmss}.txt"), e.ExceptionObject.ToString()); - logger.Fatal($"Unhandled Exception: {e.ExceptionObject}", e.ExceptionObject as Exception); + string message = $"Unhandled Exception: {e.ExceptionObject}"; + if (e.ExceptionObject is Exception ex) + logger.Fatal(message, ex); + else + logger.Fatal(message); + logger.Flush(); }; @@ -59,7 +60,7 @@ private static void Main(string[] args) typeContainer.Register(settings); typeContainer.Register(settings); - typeContainer.Register(InstanceBehaviour.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); typeContainer.Get().Start(); Console.CancelKeyPress += (s, e) => manualResetEvent.Set(); @@ -67,7 +68,5 @@ private static void Main(string[] args) settings.Save(); } } - - } } diff --git a/OctoAwesome/OctoAwesome.GameServer/ServerHandler.cs b/OctoAwesome/OctoAwesome.GameServer/ServerHandler.cs index f0006507..16f09c4f 100644 --- a/OctoAwesome/OctoAwesome.GameServer/ServerHandler.cs +++ b/OctoAwesome/OctoAwesome.GameServer/ServerHandler.cs @@ -4,29 +4,25 @@ using OctoAwesome.Notifications; using System; using System.Net; -using System.Threading.Tasks; using OctoAwesome.Rx; - - namespace OctoAwesome.GameServer { public class ServerHandler { - public SimulationManager SimulationManager { get; set; } - public IUpdateHub UpdateHub { get; private set; } + public SimulationManager SimulationManager { get; } + public IUpdateHub UpdateHub { get; } private readonly ILogger logger; private readonly Server server; private readonly DefaultCommandManager defaultManager; - public ServerHandler() { logger = (TypeContainer.GetOrNull() ?? NullLogger.Default).As(typeof(ServerHandler)); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); SimulationManager = TypeContainer.Get(); UpdateHub = TypeContainer.Get(); @@ -34,7 +30,6 @@ public ServerHandler() defaultManager = new DefaultCommandManager(typeof(ServerHandler).Namespace + ".Commands"); } - public void Start() { SimulationManager.Start(); //Temp @@ -45,7 +40,7 @@ public void Start() private void ServerOnClientConnected(object sender, ConnectedClient e) { logger.Debug("Hurra ein neuer Spieler"); - e.ServerSubscription = e.Packages.Subscribe(e => OnNext(e), ex => logger.Error(ex.Message, ex)); + e.ServerSubscription = e.Packages.Subscribe(OnNext, ex => logger.Error(ex.Message, ex)); } public void OnNext(Package value) diff --git a/OctoAwesome/OctoAwesome.Network.Tests/SimulationManagerTests.cs b/OctoAwesome/OctoAwesome.Network.Tests/SimulationManagerTests.cs index ef74790e..39424e3c 100644 --- a/OctoAwesome/OctoAwesome.Network.Tests/SimulationManagerTests.cs +++ b/OctoAwesome/OctoAwesome.Network.Tests/SimulationManagerTests.cs @@ -39,8 +39,6 @@ public void RuntimeTest() }; timer.Elapsed += (s, e) => reset.Set(); - - simulationManager.Start(); timer.Start(); diff --git a/OctoAwesome/OctoAwesome.Network/BaseClient.cs b/OctoAwesome/OctoAwesome.Network/BaseClient.cs index c6632964..b06e32b5 100644 --- a/OctoAwesome/OctoAwesome.Network/BaseClient.cs +++ b/OctoAwesome/OctoAwesome.Network/BaseClient.cs @@ -9,6 +9,7 @@ namespace OctoAwesome.Network { + public abstract class BaseClient : IDisposable { private static uint NextId => ++nextId; @@ -18,10 +19,9 @@ static BaseClient() { nextId = 0; } - public uint Id { get; } + public uint Id { get; } public IObservable Packages => packages; - protected Socket Socket; protected readonly SocketAsyncEventArgs ReceiveArgs; @@ -37,7 +37,6 @@ static BaseClient() private readonly CancellationTokenSource cancellationTokenSource; private readonly ConcurrentRelay packages; - protected BaseClient() { packages = new ConcurrentRelay(); @@ -56,6 +55,7 @@ protected BaseClient() Id = NextId; } + protected BaseClient(Socket socket) : this() { Socket = socket; @@ -72,7 +72,6 @@ public Task Start() Receive(ReceiveArgs); }, cancellationTokenSource.Token); } - public void Stop() { cancellationTokenSource.Cancel(); @@ -100,14 +99,14 @@ public async Task SendPackageAsync(Package package) package.SerializePackage(bytes, 0); await SendAsync(bytes, bytes.Length); } - - public async Task SendPackageAndRelaseAsync(Package package) + + public async Task SendPackageAndReleaseAsync(Package package) { await SendPackageAsync(package); package.Release(); } - - public void SendPackageAndRelase(Package package) + + public void SendPackageAndRelease(Package package) { var task = Task.Run(async () => await SendPackageAsync(package)); task.Wait(); @@ -164,7 +163,7 @@ private void OnSent(object sender, SocketAsyncEventArgs e) SendInternal(data, len); } - private void OnReceived(object sender, SocketAsyncEventArgs e) + private void OnReceived(object? sender, SocketAsyncEventArgs e) { Receive(e); } @@ -229,8 +228,7 @@ private int DataReceived(byte[] buffer, int length, int bufferOffset) return offset; } - - public void Dispose() + public virtual void Dispose() { packages?.Dispose(); ReceiveArgs?.Dispose(); diff --git a/OctoAwesome/OctoAwesome.Network/Client.cs b/OctoAwesome/OctoAwesome.Network/Client.cs index 835de53a..5a3497ea 100644 --- a/OctoAwesome/OctoAwesome.Network/Client.cs +++ b/OctoAwesome/OctoAwesome.Network/Client.cs @@ -1,18 +1,11 @@ using System; -using System.Collections.Generic; -using System.Collections; -using System.IO; using System.Net.Sockets; -using System.Threading.Tasks; -using System.Buffers; using System.Net; -using System.Text; using System.Linq; -using System.Threading; -using System.Net.NetworkInformation; namespace OctoAwesome.Network { + public class Client : BaseClient { public void Connect(string host, ushort port) diff --git a/OctoAwesome/OctoAwesome.Network/ConnectedClient.cs b/OctoAwesome/OctoAwesome.Network/ConnectedClient.cs index aa661414..a30d4626 100644 --- a/OctoAwesome/OctoAwesome.Network/ConnectedClient.cs +++ b/OctoAwesome/OctoAwesome.Network/ConnectedClient.cs @@ -1,23 +1,16 @@ using OctoAwesome.Network.Pooling; -using OctoAwesome.Network.ServerNotifications; using OctoAwesome.Notifications; -using OctoAwesome.Pooling; using OctoAwesome.Rx; using OctoAwesome.Serialization; using System; -using System.Buffers; -using System.IO; using System.Net.Sockets; -using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace OctoAwesome.Network { - public sealed class ConnectedClient : BaseClient, IDisposable + public sealed class ConnectedClient : BaseClient { private readonly IDisposable networkSubscription; - public IDisposable ServerSubscription { get; set; } + public IDisposable? ServerSubscription { get; set; } private readonly PackagePool packagePool; @@ -27,8 +20,6 @@ public ConnectedClient(Socket socket) : base(socket) var updateHub = TypeContainer.Get(); networkSubscription = updateHub.ListenOn(DefaultChannels.Network).Subscribe(OnNext, OnError); } - - private void OnError(Exception error) { Socket.Close(); @@ -52,7 +43,7 @@ private void OnNext(Notification value) case BlocksChangedNotification _: case BlockChangedNotification _: command = OfficialCommand.ChunkNotification; - payload = Serializer.Serialize(value as SerializableNotification); + payload = Serializer.Serialize((SerializableNotification)value); break; default: return; @@ -63,14 +54,15 @@ private void OnNext(Notification value) private void BuildAndSendPackage(byte[] data, OfficialCommand officialCommand) { - var package = packagePool.Get(); + var package = packagePool.Rent(); package.Payload = data; package.Command = (ushort)officialCommand; - SendPackageAndRelase(package); + SendPackageAndRelease(package); } - - public void Dispose() + public override void Dispose() { + base.Dispose(); + ServerSubscription?.Dispose(); networkSubscription.Dispose(); } } diff --git a/OctoAwesome/OctoAwesome.Network/NetworkPersistenceManager.cs b/OctoAwesome/OctoAwesome.Network/NetworkPersistenceManager.cs index f6acdbcf..48444f84 100644 --- a/OctoAwesome/OctoAwesome.Network/NetworkPersistenceManager.cs +++ b/OctoAwesome/OctoAwesome.Network/NetworkPersistenceManager.cs @@ -5,17 +5,15 @@ using System.Linq; using System.Text; using OctoAwesome.Components; -using OctoAwesome.Database; using OctoAwesome.Logging; using OctoAwesome.Network.Pooling; using OctoAwesome.Pooling; -using OctoAwesome.Runtime; using OctoAwesome.Rx; using OctoAwesome.Serialization; -using OctoAwesome.Serialization.Entities; namespace OctoAwesome.Network { + public class NetworkPersistenceManager : IPersistenceManager, IDisposable { private readonly Client client; @@ -26,11 +24,10 @@ public class NetworkPersistenceManager : IPersistenceManager, IDisposable private readonly IPool awaiterPool; private readonly PackagePool packagePool; private readonly ITypeContainer typeContainer; - public NetworkPersistenceManager(ITypeContainer typeContainer, Client client) { this.client = client; - subscription = client.Packages.Subscribe(package => OnNext(package), ex => OnError(ex)); + subscription = client.Packages.Subscribe(OnNext, OnError); this.typeContainer = typeContainer; packages = new ConcurrentDictionary(); @@ -38,17 +35,14 @@ public NetworkPersistenceManager(ITypeContainer typeContainer, Client client) awaiterPool = TypeContainer.Get>(); packagePool = TypeContainer.Get(); } - public void DeleteUniverse(Guid universeGuid) { //throw new NotImplementedException(); } - public Awaiter Load(out SerializableCollection universes) => throw new NotImplementedException(); - public Awaiter Load(out IChunkColumn column, Guid universeGuid, IPlanet planet, Index2 columnIndex) { - var package = packagePool.Get(); + var package = packagePool.Rent(); package.Command = (ushort)OfficialCommand.LoadColumn; using (var memoryStream = new MemoryStream()) @@ -64,87 +58,74 @@ public Awaiter Load(out IChunkColumn column, Guid universeGuid, IPlanet planet, column = new ChunkColumn(planet); var awaiter = GetAwaiter(column, package.UId); - client.SendPackageAndRelase(package); + client.SendPackageAndRelease(package); return awaiter; } - public Awaiter Load(out IPlanet planet, Guid universeGuid, int planetId) { - var package = packagePool.Get(); + var package = packagePool.Rent(); package.Command = (ushort)OfficialCommand.GetPlanet; planet = typeContainer.Get(); var awaiter = GetAwaiter(planet, package.UId); - client.SendPackageAndRelase(package); + client.SendPackageAndRelease(package); return awaiter; } - - public Awaiter Load(out Player player, Guid universeGuid, string playername) + public Awaiter? Load(out Player player, Guid universeGuid, string playerName) { - var playernameBytes = Encoding.UTF8.GetBytes(playername); + var playerNameBytes = Encoding.UTF8.GetBytes(playerName); - var package = packagePool.Get(); + var package = packagePool.Rent(); package.Command = (ushort)OfficialCommand.Whoami; - package.Payload = playernameBytes; + package.Payload = playerNameBytes; player = new Player(); var awaiter = GetAwaiter(player, package.UId); - client.SendPackageAndRelase(package); + client.SendPackageAndRelease(package); return awaiter; } - public Awaiter Load(out IUniverse universe, Guid universeGuid) { - var package = packagePool.Get(); + var package = packagePool.Rent(); package.Command = (ushort)OfficialCommand.GetUniverse; universe = new Universe(); var awaiter = GetAwaiter(universe, package.UId); - client.SendPackageAndRelase(package); + client.SendPackageAndRelease(package); return awaiter; } - public Awaiter Load(out Entity entity, Guid universeGuid, Guid entityId) { entity = null; return null; } - public Awaiter Load(out TContainer componentContainer, Guid universeGuid, Guid id) where TContainer : ComponentContainer where TComponent : IComponent { - var package = packagePool.Get(); + var package = packagePool.Rent(); package.Command = (ushort)OfficialCommand.GetUniverse; componentContainer = null; //var awaiter = GetAwaiter(universe, package.UId); - client.SendPackageAndRelase(package); + client.SendPackageAndRelease(package); return null; } - - public IEnumerable LoadEntitiesWithComponent(Guid universeGuid) where T : IEntityComponent - => Enumerable.Empty(); - - public IEnumerable GetEntityIdsFromComponent(Guid universeGuid) where T : IEntityComponent - => Enumerable.Empty(); public IEnumerable GetEntityIds(Guid universeGuid) => Enumerable.Empty(); - public IEnumerable<(Guid Id, T Component)> GetEntityComponents(Guid universeGuid, Guid[] entityIds) where T : IEntityComponent, new() => Enumerable.Empty<(Guid Id, T Component)>(); - public IEnumerable<(Guid Id, T Component)> GetAllComponents(Guid universeGuid) where T : IComponent, new() => Enumerable.Empty<(Guid Id, T Component)>(); private Awaiter GetAwaiter(ISerializable serializable, uint packageUId) { - var awaiter = awaiterPool.Get(); - awaiter.Serializable = serializable; + var awaiter = awaiterPool.Rent(); + awaiter.Result = serializable; if (!packages.TryAdd(packageUId, awaiter)) { @@ -153,27 +134,22 @@ private Awaiter GetAwaiter(ISerializable serializable, uint packageUId) return awaiter; } - public void SaveColumn(Guid universeGuid, IPlanet planet, IChunkColumn column) { //throw new NotImplementedException(); } - public void SavePlanet(Guid universeGuid, IPlanet planet) { //throw new NotImplementedException(); } - public void SavePlayer(Guid universeGuid, Player player) { //throw new NotImplementedException(); } - public void SaveUniverse(IUniverse universe) { //throw new NotImplementedException(); } - public void Save(TContainer container, Guid universe) where TContainer : ComponentContainer where TComponent : IComponent @@ -190,8 +166,6 @@ public void SendChangedChunkColumn(IChunkColumn chunkColumn) // chunkColumn.Serialize(bw, definitionManager); // package.Payload = ms.ToArray(); //} - - //client.SendPackage(package); } @@ -226,12 +200,10 @@ public void OnError(Exception error) { logger.Error(error.Message, error); } - public void Dispose() { subscription?.Dispose(); } - public T GetComponent(Guid universeGuid, Guid id) where T : IComponent, new() { //TODO diff --git a/OctoAwesome/OctoAwesome.Network/NetworkUpdateManager.cs b/OctoAwesome/OctoAwesome.Network/NetworkUpdateManager.cs index 5ede8ed7..1ea858a3 100644 --- a/OctoAwesome/OctoAwesome.Network/NetworkUpdateManager.cs +++ b/OctoAwesome/OctoAwesome.Network/NetworkUpdateManager.cs @@ -1,5 +1,4 @@ using OctoAwesome.Logging; -using OctoAwesome.Network; using OctoAwesome.Network.Pooling; using OctoAwesome.Notifications; using OctoAwesome.Pooling; @@ -9,6 +8,7 @@ namespace OctoAwesome.Network { + public class NetworkUpdateManager : IDisposable { private readonly Client client; @@ -24,7 +24,6 @@ public class NetworkUpdateManager : IDisposable private readonly Relay simulation; private readonly Relay chunk; - public NetworkUpdateManager(Client client, IUpdateHub updateHub) { this.client = client; @@ -101,17 +100,16 @@ public void OnNext(Notification value) default: return; } - var package = packagePool.Get(); + var package = packagePool.Rent(); package.Command = command; package.Payload = payload; - client.SendPackageAndRelase(package); + client.SendPackageAndRelease(package); } public void OnError(Exception error) { logger.Error(error.Message, error); } - public void Dispose() { hubSubscription?.Dispose(); diff --git a/OctoAwesome/OctoAwesome.Network/OctoAwesome.Network.csproj b/OctoAwesome/OctoAwesome.Network/OctoAwesome.Network.csproj index cee01b86..f56985ce 100644 --- a/OctoAwesome/OctoAwesome.Network/OctoAwesome.Network.csproj +++ b/OctoAwesome/OctoAwesome.Network/OctoAwesome.Network.csproj @@ -2,8 +2,8 @@ net5.0 - warnings - + enable + True @@ -11,7 +11,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + diff --git a/OctoAwesome/OctoAwesome.Network/OctoNetworkStream.cs b/OctoAwesome/OctoAwesome.Network/OctoNetworkStream.cs index cdeb000b..70b46110 100644 --- a/OctoAwesome/OctoAwesome.Network/OctoNetworkStream.cs +++ b/OctoAwesome/OctoAwesome.Network/OctoNetworkStream.cs @@ -4,8 +4,6 @@ namespace OctoAwesome.Network { public class OctoNetworkStream { - public int Length => writeBuffer.Length; - private byte[] readBuffer; private byte[] writeBuffer; @@ -38,7 +36,6 @@ public OctoNetworkStream(int capacity = 1024) readLock = new object(); writeLock = new object(); } - public int Write(byte[] buffer, int offset, int count) { writingProcess = true; @@ -65,7 +62,6 @@ public int Write(byte[] buffer, int offset, int count) return count; } - public int Write(byte data) { writingProcess = true; @@ -85,7 +81,6 @@ public int Write(byte data) return 1; } - public int Read(byte[] buffer, int offset, int count) { if (!writingProcess) @@ -106,7 +101,6 @@ public int Read(byte[] buffer, int offset, int count) return count; } - public int DataAvailable(int count) { if (!writingProcess) @@ -129,19 +123,15 @@ private void SwapBuffer() lock (writeLock) { if (readPosition > maxReadCount) - throw new IndexOutOfRangeException("ReadPositin is greater than MaxReadCount in OctoNetworkStream"); - else if (readPosition < maxReadCount) + throw new IndexOutOfRangeException("ReadPosition is greater than MaxReadCount in OctoNetworkStream"); + if (readPosition < maxReadCount) return; - var refBuf = writeBuffer; - writeBuffer = readBuffer; - readBuffer = refBuf; + (writeBuffer, readBuffer) = (readBuffer, writeBuffer); maxReadCount = writePosition; writePosition = 0; readPosition = 0; } } - - } } diff --git a/OctoAwesome/OctoAwesome.Network/OfficialCommand.cs b/OctoAwesome/OctoAwesome.Network/OfficialCommand.cs index 893c0422..cd6f8ad9 100644 --- a/OctoAwesome/OctoAwesome.Network/OfficialCommand.cs +++ b/OctoAwesome/OctoAwesome.Network/OfficialCommand.cs @@ -1,21 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Network +namespace OctoAwesome.Network { public enum OfficialCommand : ushort { //0 - 100 System Commands //100 - 200 General Commands + Whoami = 101, GetUniverse = 102, GetPlanet = 103, LoadColumn = 104, SaveColumn = 105, //400 - 500 Notifications + EntityNotification = 401, ChunkNotification = 402 } diff --git a/OctoAwesome/OctoAwesome.Network/Package.cs b/OctoAwesome/OctoAwesome.Network/Package.cs index f1a4bafb..8c84b606 100644 --- a/OctoAwesome/OctoAwesome.Network/Package.cs +++ b/OctoAwesome/OctoAwesome.Network/Package.cs @@ -1,5 +1,6 @@ using OctoAwesome.Pooling; using System; +using System.Threading; namespace OctoAwesome.Network { @@ -10,33 +11,28 @@ public sealed class Package : IPoolElement /// public const int HEAD_LENGTH = sizeof(ushort) + sizeof(int) + sizeof(uint); - public static uint NextUId => nextUid++; - private volatile static uint nextUid; + private static uint nextUid; + public static uint NextUId => Interlocked.Increment(ref nextUid) - 1; public BaseClient BaseClient { get; set; } public OfficialCommand OfficialCommand => (OfficialCommand)Command; public ushort Command { get; set; } - public byte[] Payload { get; set; } - public uint UId { get; set; } - public bool IsComplete => internalOffset == Payload.Length; - public int PayloadRest => Payload.Length - internalOffset; private int internalOffset; private IPool pool; - public Package(ushort command, int size) : this() { Command = command; Payload = new byte[size]; } - public Package() : this(true) { } + public Package(bool setUid) { if (setUid) @@ -45,11 +41,12 @@ public Package(bool setUid) public Package(byte[] data) : this(0, data.Length) { + // TODO: actually use data } public bool TryDeserializeHeader(byte[] buffer, int offset) { - if (buffer.Length < HEAD_LENGTH) + if (buffer.Length - offset < HEAD_LENGTH) return false; Command = (ushort)((buffer[offset] << 8) | buffer[offset + 1]); @@ -58,7 +55,6 @@ public bool TryDeserializeHeader(byte[] buffer, int offset) internalOffset = 0; return true; } - public int DeserializePayload(byte[] buffer, int offset, int count) { if (internalOffset + count > Payload.Length) @@ -69,12 +65,6 @@ public int DeserializePayload(byte[] buffer, int offset, int count) return count; } - public void DeserializePackage(byte[] buffer, int offset) - { - TryDeserializeHeader(buffer, offset); - Buffer.BlockCopy(buffer, offset + HEAD_LENGTH, Payload, 0, Payload.Length); - internalOffset = Payload.Length; - } public int SerializePackage(byte[] buffer, int offset) { @@ -87,13 +77,11 @@ public int SerializePackage(byte[] buffer, int offset) Buffer.BlockCopy(Payload, 0, buffer, offset + HEAD_LENGTH, Payload.Length); return Payload.Length + HEAD_LENGTH; } - public void Init(IPool pool) { Payload = Array.Empty(); this.pool = pool; } - public void Release() { BaseClient = default; @@ -102,7 +90,7 @@ public void Release() UId = default; internalOffset = default; - pool.Push(this); + pool.Return(this); } } } diff --git a/OctoAwesome/OctoAwesome.Network/Pooling/PackagePool.cs b/OctoAwesome/OctoAwesome.Network/Pooling/PackagePool.cs index 4349e0c0..8c4c7cfc 100644 --- a/OctoAwesome/OctoAwesome.Network/Pooling/PackagePool.cs +++ b/OctoAwesome/OctoAwesome.Network/Pooling/PackagePool.cs @@ -2,9 +2,6 @@ using OctoAwesome.Threading; using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Network.Pooling { @@ -12,14 +9,13 @@ public sealed class PackagePool : IPool { private readonly Stack internalStack; private readonly LockSemaphore semaphoreExtended; - public PackagePool() { internalStack = new Stack(); semaphoreExtended = new LockSemaphore(1, 1); } - - public Package Get() + + public Package Rent() { Package obj; @@ -50,18 +46,16 @@ public Package GetBlank() obj.Init(this); return obj; } - - public void Push(Package obj) + public void Return(Package obj) { using (semaphoreExtended.Wait()) internalStack.Push(obj); } - - public void Push(IPoolElement obj) + public void Return(IPoolElement obj) { if (obj is Package package) { - Push(package); + Return(package); } else { diff --git a/OctoAwesome/OctoAwesome.Network/Server.cs b/OctoAwesome/OctoAwesome.Network/Server.cs index ac50ee88..1879a3b2 100644 --- a/OctoAwesome/OctoAwesome.Network/Server.cs +++ b/OctoAwesome/OctoAwesome.Network/Server.cs @@ -1,23 +1,20 @@ using System; -using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Sockets; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Network { public class Server //TODO: Should use a base class or interface { - public event EventHandler OnClientConnected; + public event EventHandler? OnClientConnected; private readonly Socket ipv4Socket; private readonly Socket ipv6Socket; private readonly List connectedClients; private readonly object lockObj; - public Server() { ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); @@ -49,6 +46,7 @@ public void Start(params IPEndPoint[] endpoints) ipv6Socket.BeginAccept(OnClientAccepted, ipv6Socket); } } + public void Start(string host, ushort port) { var address = Dns.GetHostAddresses(host).Where( @@ -59,6 +57,7 @@ public void Start(string host, ushort port) private void OnClientAccepted(IAsyncResult ar) { + Debug.Assert(ar.AsyncState != null, "ar.AsyncState != null"); var socket = (Socket)ar.AsyncState; var tmpSocket = socket!.EndAccept(ar); diff --git a/OctoAwesome/OctoAwesome.Network/ServerNotifications/ServerDataNotification.cs b/OctoAwesome/OctoAwesome.Network/ServerNotifications/ServerDataNotification.cs index e4949363..39194677 100644 --- a/OctoAwesome/OctoAwesome.Network/ServerNotifications/ServerDataNotification.cs +++ b/OctoAwesome/OctoAwesome.Network/ServerNotifications/ServerDataNotification.cs @@ -1,25 +1,20 @@ -using OctoAwesome.Network; -using OctoAwesome.Notifications; -using System; +using OctoAwesome.Notifications; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Network.ServerNotifications { public class ServerDataNotification : Notification { public byte[] Data { get; set; } - public OfficialCommand OfficialCommand { get; set; } - - public HashSet PlayerIds { get; set; } + public OfficialCommand OfficialCommand { get; set; } + + public HashSet PlayerIds { get; } + public ServerDataNotification() { PlayerIds = new HashSet(); } - public override bool Match(T filter) { if (PlayerIds.Count < 1) diff --git a/OctoAwesome/OctoAwesome.Network/Settings.cs b/OctoAwesome/OctoAwesome.Network/Settings.cs index b79edb3e..4f5111d3 100644 --- a/OctoAwesome/OctoAwesome.Network/Settings.cs +++ b/OctoAwesome/OctoAwesome.Network/Settings.cs @@ -1,19 +1,15 @@ //using OpenTK; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; -using System.Configuration; using System.IO; using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; namespace OctoAwesome.Network { public class Settings : ISettings { - public FileInfo FileInfo { get; set; } + public FileInfo FileInfo { get; init; } private readonly Dictionary dictionary; public Settings(FileInfo fileInfo) @@ -21,6 +17,7 @@ public Settings(FileInfo fileInfo) FileInfo = fileInfo; dictionary = InternalLoad(fileInfo); } + public Settings() { dictionary = new Dictionary() @@ -30,28 +27,23 @@ public Settings() ["DisablePersistence"] = "false", ["LastUniverse"] = "" }; + FileInfo = null!; } - public void Delete(string key) => dictionary.Remove(key); - public T Get(string key) => (T)Convert.ChangeType(dictionary[key], typeof(T)); - public T Get(string key, T defaultValue) { - if (dictionary.TryGetValue(key, out string value)) + if (dictionary.TryGetValue(key, out var value)) return (T)Convert.ChangeType(value, typeof(T)); return defaultValue; } - public T[] GetArray(string key) => DeserializeArray(dictionary[key]); - public bool KeyExists(string key) => dictionary.ContainsKey(key); - public void Set(string key, string value) { if (dictionary.ContainsKey(key)) @@ -71,18 +63,19 @@ public void Set(string key, int[] values) => Set(key, values.Select(i => i.ToString()).ToArray()); public void Set(string key, bool[] values) => Set(key, values.Select(b => b.ToString()).ToArray()); - public void Load() { + if (FileInfo == null) + throw new ArgumentException("No file info was specified"); dictionary.Clear(); foreach (var entry in InternalLoad(FileInfo)) dictionary.Add(entry.Key, entry.Value); } - - public void Save() { + if (FileInfo == null) + throw new ArgumentException("No file info was specified"); FileInfo.Delete(); using (var writer = new StreamWriter(FileInfo.OpenWrite())) { @@ -100,10 +93,7 @@ private Dictionary InternalLoad(FileInfo fileInfo) private T[] DeserializeArray(string arrayString) { - // Wir müssten, um beide Klammern zu entfernen, - 3 rechnen. Ich lasse die letzte Klammer stellvertretend für das Komma, was folgen würde, stehen. - // Das wird in der for-Schleife auseinander gepflückt. - - arrayString = arrayString.Substring(1, arrayString.Length - 2 /*- 1*/); + arrayString = arrayString.Substring(1, arrayString.Length - 2); string[] partsString = arrayString.Split(','); T[] tArray = new T[partsString.Length]; diff --git a/OctoAwesome/OctoAwesome.Network/SimulationManager.cs b/OctoAwesome/OctoAwesome.Network/SimulationManager.cs index 7de6a690..efc3f770 100644 --- a/OctoAwesome/OctoAwesome.Network/SimulationManager.cs +++ b/OctoAwesome/OctoAwesome.Network/SimulationManager.cs @@ -3,9 +3,6 @@ using OctoAwesome.Notifications; using OctoAwesome.Runtime; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -14,27 +11,15 @@ namespace OctoAwesome.Network public class SimulationManager { public bool IsRunning { get; private set; } - - public Simulation Simulation - { - get - { - lock (mainLock) - return simulation; - } - set - { - lock (mainLock) - simulation = value; - } - } - + + public Simulation Simulation { get; } + public GameTime GameTime { get; private set; } - - public ResourceManager ResourceManager { get; private set; } + + public ResourceManager ResourceManager { get; } + public GameService Service { get; } - private Simulation simulation; private readonly ExtensionLoader extensionLoader; private Task backgroundTask; @@ -43,24 +28,21 @@ public Simulation Simulation private readonly ISettings settings; private readonly UpdateHub updateHub; private readonly object mainLock; - public SimulationManager(ISettings settings, UpdateHub updateHub) { mainLock = new object(); this.settings = settings; this.updateHub = updateHub; - - - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); - TypeContainer.Register(InstanceBehaviour.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); + TypeContainer.Register(InstanceBehavior.Singleton); extensionLoader = TypeContainer.Get(); extensionLoader.LoadExtensions(); @@ -68,13 +50,12 @@ public SimulationManager(ISettings settings, UpdateHub updateHub) ResourceManager = TypeContainer.Get(); Service = new GameService(ResourceManager); - simulation = new Simulation(ResourceManager, extensionLoader, Service) + Simulation = new Simulation(ResourceManager, extensionLoader, Service) { IsServerSide = true }; } - public void Start() { IsRunning = true; @@ -89,45 +70,43 @@ public void Start() if (string.IsNullOrWhiteSpace(universe)) { - var guid = simulation.NewGame("melmack", new Random().Next().ToString()); + var guid = Simulation.NewGame("melmack", new Random().Next().ToString()); settings.Set("LastUniverse", guid.ToString()); } else { - if (!simulation.TryLoadGame(new Guid(universe))) + if (!Simulation.TryLoadGame(new Guid(universe))) { - var guid = simulation.NewGame("melmack", new Random().Next().ToString()); + var guid = Simulation.NewGame("melmack", new Random().Next().ToString()); settings.Set("LastUniverse", guid.ToString()); } } backgroundTask.Start(); } - public void Stop() { IsRunning = false; - simulation.ExitGame(); + Simulation.ExitGame(); cancellationTokenSource?.Cancel(); cancellationTokenSource?.Dispose(); } public IUniverse GetUniverse() => ResourceManager.CurrentUniverse; - public IUniverse NewUniverse() { throw new NotImplementedException(); } - public IPlanet GetPlanet(int planetId) => ResourceManager.GetPlanet(planetId); - public IChunkColumn LoadColumn(IPlanet planet, Index2 index2) => planet.GlobalChunkCache.Subscribe(index2); + + public IChunkColumn LoadColumn(int planetId, Index2 index2) => LoadColumn(GetPlanet(planetId), index2); - private void SimulationLoop(object state) + private void SimulationLoop(object? state) { var token = state is CancellationToken stateToken ? stateToken : CancellationToken.None; diff --git a/OctoAwesome/OctoAwesome.Network/Startup.cs b/OctoAwesome/OctoAwesome.Network/Startup.cs index c5304ecc..5bd58699 100644 --- a/OctoAwesome/OctoAwesome.Network/Startup.cs +++ b/OctoAwesome/OctoAwesome.Network/Startup.cs @@ -1,18 +1,13 @@ using OctoAwesome.Network.Pooling; -using OctoAwesome.Pooling; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Network { + public static class Startup { public static void Register(ITypeContainer typeContainer) { - typeContainer.Register(InstanceBehaviour.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); } } } diff --git a/OctoAwesome/OctoAwesome.PoC/Cache.cs b/OctoAwesome/OctoAwesome.PoC/Cache.cs index b9f6cf76..00e152da 100644 --- a/OctoAwesome/OctoAwesome.PoC/Cache.cs +++ b/OctoAwesome/OctoAwesome.PoC/Cache.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics.SymbolStore; using System.Linq; namespace OctoAwesome.PoC diff --git a/OctoAwesome/OctoAwesome.PoC/CacheService.cs b/OctoAwesome/OctoAwesome.PoC/CacheService.cs index c22509b6..1b03a81d 100644 --- a/OctoAwesome/OctoAwesome.PoC/CacheService.cs +++ b/OctoAwesome/OctoAwesome.PoC/CacheService.cs @@ -8,8 +8,6 @@ public class CacheService private readonly DependencyAgent dependencyAgent; private readonly Dictionary caches; - - public CacheService(DependencyAgent dependencyAgent) { this.dependencyAgent = dependencyAgent; @@ -38,6 +36,6 @@ public TValue Get(TKey key) return cache.Get(key); } - //TODO: CleaupTask + //TODO: CleanupTask } } diff --git a/OctoAwesome/OctoAwesome.PoC/ComponentCache.cs b/OctoAwesome/OctoAwesome.PoC/ComponentCache.cs index 770fc70e..93a70385 100644 --- a/OctoAwesome/OctoAwesome.PoC/ComponentCache.cs +++ b/OctoAwesome/OctoAwesome.PoC/ComponentCache.cs @@ -1,5 +1,4 @@ -using Castle.DynamicProxy.Generators.Emitters.SimpleAST; -using OctoAwesome.EntityComponents; +using OctoAwesome.EntityComponents; using System; @@ -24,7 +23,7 @@ protected override Component Load(int key) public class EntityCache : Cache//, IKeyFinder { - //All Position Components of Entites + //All Position Components of Entities protected Entity Load(Index3 key) { @@ -35,8 +34,6 @@ protected override Entity Load(int key) { throw new NotImplementedException(); } - - } public class PositionComponentCache : ComponentCache//, IKeyFinder @@ -66,8 +63,6 @@ public PositionComponent TryFindFirst(T key) // _ => false //}; } - - public class Index3PositionConverter //IKeyConverter, IKeyConverter { protected PositionComponent Convert(Index3 key) @@ -81,8 +76,6 @@ protected PositionComponent Convert(Index2 key) } } - - public class ChunkColumnCache : Cache { protected override ChunkColumn Load(Index3 key) diff --git a/OctoAwesome/OctoAwesome.PoC/DependencyAgent.cs b/OctoAwesome/OctoAwesome.PoC/DependencyAgent.cs index 2c912a50..7dfc3c30 100644 --- a/OctoAwesome/OctoAwesome.PoC/DependencyAgent.cs +++ b/OctoAwesome/OctoAwesome.PoC/DependencyAgent.cs @@ -17,8 +17,6 @@ internal Dictionary GetDependencyTypeOrder(TKey key, Type typeO { return null; } - - public static bool TryCreateTree(IList dependencies, out DependencyTree tree) { if (dependencies is null) @@ -34,8 +32,6 @@ public static bool TryCreateTree(IList dependencies, out Depende tree = TopologicalSort(graph); return true; } - - private static bool HasCycle(IList dependencies) { HashSet visitedChildren = new(); @@ -64,8 +60,6 @@ private static bool CheckCycleForChildren(DependencyLeaf children, DependencyLea { return true; } - - foreach (var child in children.Children) { if (visitedChildren.Contains(child)) diff --git a/OctoAwesome/OctoAwesome.PoC/DependencyItem.cs b/OctoAwesome/OctoAwesome.PoC/DependencyItem.cs index 6232a8cb..c44b14df 100644 --- a/OctoAwesome/OctoAwesome.PoC/DependencyItem.cs +++ b/OctoAwesome/OctoAwesome.PoC/DependencyItem.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.PoC { diff --git a/OctoAwesome/OctoAwesome.PoC/DependencyLeaf.cs b/OctoAwesome/OctoAwesome.PoC/DependencyLeaf.cs index 2dbcffe1..5fdc4ac6 100644 --- a/OctoAwesome/OctoAwesome.PoC/DependencyLeaf.cs +++ b/OctoAwesome/OctoAwesome.PoC/DependencyLeaf.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.PoC { @@ -21,8 +19,6 @@ public class DependencyLeaf /// This loads after these items /// public List Parents { get; } - - public int Position { get; internal set; } private IReadOnlyList flattenedParents; @@ -35,8 +31,6 @@ public DependencyLeaf(DependencyItem item, List children, List dependencies) { HashSet visitedChildren = new(); @@ -77,8 +71,6 @@ private static bool CheckCycleForChildren(DependencyLeaf children, DependencyLea return false; } - - public override string ToString() => $"{Item.Name} loads Before: {string.Join(", ", Children.Select(x => x.Item.Name))} and loads After: {string.Join(", ", Parents.Select(x => x.Item.Name))} (BeforeCount: {Children.Count}, AfterCount: {Parents.Count})"; diff --git a/OctoAwesome/OctoAwesome.PoC/DependencyTree.cs b/OctoAwesome/OctoAwesome.PoC/DependencyTree.cs index 55ef3077..4611682a 100644 --- a/OctoAwesome/OctoAwesome.PoC/DependencyTree.cs +++ b/OctoAwesome/OctoAwesome.PoC/DependencyTree.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.PoC { diff --git a/OctoAwesome/OctoAwesome.PoC/Progam.cs b/OctoAwesome/OctoAwesome.PoC/Progam.cs index ff16d3c7..43f00130 100644 --- a/OctoAwesome/OctoAwesome.PoC/Progam.cs +++ b/OctoAwesome/OctoAwesome.PoC/Progam.cs @@ -1,11 +1,7 @@ using OctoAwesome.Caching; using OctoAwesome.Notifications; using OctoAwesome.PoC.Rx; -using OctoAwesome.Runtime; -using OpenTK.Graphics.ES11; using System; -using System.Reflection; -using System.Runtime.InteropServices; using System.Threading.Tasks; namespace OctoAwesome.PoC @@ -18,7 +14,7 @@ static void Main() object a = 12; var i - = GenericCaster + = GenericCaster .Cast(a); using var network = new Relay(); diff --git a/OctoAwesome/OctoAwesome.PoC/Rx/Relay.cs b/OctoAwesome/OctoAwesome.PoC/Rx/Relay.cs index ec4b279f..cdc2774f 100644 --- a/OctoAwesome/OctoAwesome.PoC/Rx/Relay.cs +++ b/OctoAwesome/OctoAwesome.PoC/Rx/Relay.cs @@ -1,10 +1,5 @@ -using OctoAwesome.Database; -using OctoAwesome.Network; -using System; +using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.PoC.Rx { @@ -62,8 +57,6 @@ private void Unsubscribe(RelaySubscription subscription) { subscriptions.Remove(subscription); } - - private class RelaySubscription : IDisposable { public IObserver Observer { get; } diff --git a/OctoAwesome/OctoAwesome.PoC/Rx/UpdateHub.cs b/OctoAwesome/OctoAwesome.PoC/Rx/UpdateHub.cs index 95e1a28f..fc75546a 100644 --- a/OctoAwesome/OctoAwesome.PoC/Rx/UpdateHub.cs +++ b/OctoAwesome/OctoAwesome.PoC/Rx/UpdateHub.cs @@ -1,5 +1,4 @@ using OctoAwesome.Notifications; -using OctoAwesome.PoC.Rx; using System; using System.Collections.Generic; diff --git a/OctoAwesome/OctoAwesome.Runtime/DatabaseProvider.cs b/OctoAwesome/OctoAwesome.Runtime/DatabaseProvider.cs index d240ea45..6675cf6d 100644 --- a/OctoAwesome/OctoAwesome.Runtime/DatabaseProvider.cs +++ b/OctoAwesome/OctoAwesome.Runtime/DatabaseProvider.cs @@ -5,11 +5,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Runtime { + public sealed class DatabaseProvider : IDisposable, IDatabaseProvider { private readonly string rootPath; @@ -20,7 +19,6 @@ public sealed class DatabaseProvider : IDisposable, IDatabaseProvider private readonly Dictionary<(Type Type, Guid Universe, int PlanetId), Database.Database> planetDatabaseRegister; private readonly Dictionary<(Type Type, Guid Universe), Database.Database> universeDatabaseRegister; private readonly Dictionary globalDatabaseRegister; - public DatabaseProvider(string rootPath, ILogger logger) { this.rootPath = rootPath; @@ -32,13 +30,12 @@ public DatabaseProvider(string rootPath, ILogger logger) universeDatabaseRegister = new Dictionary<(Type Type, Guid Universe), Database.Database>(); globalDatabaseRegister = new Dictionary(); } - public Database GetDatabase(bool fixedValueSize) where T : ITag, new() { Type key = typeof(T); using (globalSemaphore.Wait()) { - if (globalDatabaseRegister.TryGetValue(key, out Database.Database database)) + if (globalDatabaseRegister.TryGetValue(key, out var database)) { return database as Database; } @@ -61,13 +58,12 @@ public DatabaseProvider(string rootPath, ILogger logger) } } } - public Database GetDatabase(Guid universeGuid, bool fixedValueSize) where T : ITag, new() { (Type, Guid universeGuid) key = (typeof(T), universeGuid); using (universeSemaphore.Wait()) { - if (universeDatabaseRegister.TryGetValue(key, out Database.Database database)) + if (universeDatabaseRegister.TryGetValue(key, out var database)) { return database as Database; } @@ -90,13 +86,12 @@ public DatabaseProvider(string rootPath, ILogger logger) } } } - public Database GetDatabase(Guid universeGuid, int planetId, bool fixedValueSize) where T : ITag, new() { (Type, Guid universeGuid, int planetId) key = (typeof(T), universeGuid, planetId); using (planetSemaphore.Wait()) { - if (planetDatabaseRegister.TryGetValue(key, out Database.Database database)) + if (planetDatabaseRegister.TryGetValue(key, out var database)) { return database as Database; } @@ -118,7 +113,6 @@ public DatabaseProvider(string rootPath, ILogger logger) } } } - public void Dispose() { foreach (KeyValuePair<(Type Type, Guid Universe, int PlanetId), Database.Database> database in planetDatabaseRegister) @@ -139,7 +133,7 @@ public void Dispose() globalSemaphore.Dispose(); } - private Database CreateDatabase(string path, bool fixedValueSize, string typeName = null) where T : ITag, new() + private Database CreateDatabase(string path, bool fixedValueSize, string? typeName = null) where T : ITag, new() { if (!Directory.Exists(path)) Directory.CreateDirectory(path); diff --git a/OctoAwesome/OctoAwesome.Runtime/DefinitionManager.cs b/OctoAwesome/OctoAwesome.Runtime/DefinitionManager.cs index 8070b71e..e442a116 100644 --- a/OctoAwesome/OctoAwesome.Runtime/DefinitionManager.cs +++ b/OctoAwesome/OctoAwesome.Runtime/DefinitionManager.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Runtime.CompilerServices; namespace OctoAwesome.Runtime { @@ -46,7 +45,6 @@ public DefinitionManager(IExtensionResolver extensionResolver) /// /// public IBlockDefinition[] BlockDefinitions { get; } - public IMaterialDefinition[] MaterialDefinitions { get; } /// @@ -54,7 +52,7 @@ public DefinitionManager(IExtensionResolver extensionResolver) /// /// Index der BlockDefinition /// BlockDefinition - public IBlockDefinition GetBlockDefinitionByIndex(ushort index) + public IBlockDefinition? GetBlockDefinitionByIndex(ushort index) { if (index == 0) return null; @@ -80,20 +78,21 @@ public ushort GetDefinitionIndex(IDefinition definition) public ushort GetDefinitionIndex() where T : IDefinition { int i = 0; - IDefinition definition = default; + IDefinition? definition = default; foreach (var d in Definitions) { if (i > 0 && d.GetType() == typeof(T)) { throw new InvalidOperationException("Multiple Object where found that match the condition"); } - else if (i == 0 && d.GetType() == typeof(T)) + + if (i == 0 && d.GetType() == typeof(T)) { definition = d; ++i; } } - return GetDefinitionIndex(definition); + return definition == null ? (ushort)0 : GetDefinitionIndex(definition); } /// @@ -106,26 +105,25 @@ public IEnumerable GetDefinitions() where T : class, IDefinition // TODO: Caching (Generalisiertes IDefinition-Interface für Dictionary (+1 von Maxi am 07.04.2021)) return extensionResolver.GetDefinitions(); } - - public T GetDefinitionByTypeName(string typeName) where T : IDefinition + public T? GetDefinitionByTypeName(string typeName) where T : IDefinition { var searchedType = typeof(T); if (typeof(IBlockDefinition).IsAssignableFrom(searchedType)) { return GetDefinitionFromArrayByTypeName(typeName, BlockDefinitions); } - else if (typeof(IItemDefinition).IsAssignableFrom(searchedType)) + + if (typeof(IItemDefinition).IsAssignableFrom(searchedType)) { return GetDefinitionFromArrayByTypeName(typeName, ItemDefinitions); } - else if (typeof(IMaterialDefinition).IsAssignableFrom(searchedType)) + + if (typeof(IMaterialDefinition).IsAssignableFrom(searchedType)) { return GetDefinitionFromArrayByTypeName(typeName, MaterialDefinitions); } - else - { - return default; - } + + return default; } private static T GetDefinitionFromArrayByTypeName(string typeName, IDefinition[] array) where T : IDefinition diff --git a/OctoAwesome/OctoAwesome.Runtime/DiskPersistenceManager.cs b/OctoAwesome/OctoAwesome.Runtime/DiskPersistenceManager.cs index 5d832f71..47e1ad98 100644 --- a/OctoAwesome/OctoAwesome.Runtime/DiskPersistenceManager.cs +++ b/OctoAwesome/OctoAwesome.Runtime/DiskPersistenceManager.cs @@ -1,6 +1,5 @@ using OctoAwesome.Components; using OctoAwesome.Database; -using OctoAwesome.EntityComponents; using OctoAwesome.Logging; using OctoAwesome.Notifications; using OctoAwesome.Pooling; @@ -10,12 +9,10 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; -using System.Threading.Tasks; namespace OctoAwesome.Runtime { @@ -30,7 +27,7 @@ public class DiskPersistenceManager : IPersistenceManager, IDisposable private const string PlanetFilename = "planet.info"; - private DirectoryInfo root; + private DirectoryInfo? root; private IUniverse currentUniverse; private readonly ISettings settings; private readonly IPool awaiterPool; @@ -39,10 +36,10 @@ public class DiskPersistenceManager : IPersistenceManager, IDisposable private readonly IExtensionResolver extensionResolver; private readonly DatabaseProvider databaseProvider; - public DiskPersistenceManager(IExtensionResolver extensionResolver, ISettings Settings, IUpdateHub updateHub) + public DiskPersistenceManager(IExtensionResolver extensionResolver, ISettings settings, IUpdateHub updateHub) { this.extensionResolver = extensionResolver; - settings = Settings; + this.settings = settings; databaseProvider = new DatabaseProvider(GetRoot(), TypeContainer.Get()); awaiterPool = TypeContainer.Get>(); blockChangedNotificationPool = TypeContainer.Get>(); @@ -54,10 +51,10 @@ private string GetRoot() if (root != null) return root.FullName; - string appconfig = settings.Get("ChunkRoot"); - if (!string.IsNullOrEmpty(appconfig)) + string appConfig = settings.Get("ChunkRoot"); + if (!string.IsNullOrEmpty(appConfig)) { - root = new DirectoryInfo(appconfig); + root = new DirectoryInfo(appConfig); if (!root.Exists) root.Create(); return root.FullName; } @@ -156,7 +153,6 @@ public void SavePlayer(Guid universeGuid, Player player) } } } - public void Save(TContainer container, Guid universe) where TContainer : ComponentContainer where TComponent : IComponent @@ -173,9 +169,9 @@ var context public Awaiter Load(out SerializableCollection universes) { string root = GetRoot(); - var awaiter = awaiterPool.Get(); + var awaiter = awaiterPool.Rent(); universes = new SerializableCollection(); - awaiter.Serializable = universes; + awaiter.Result = universes; foreach (var folder in Directory.GetDirectories(root)) { string id = Path.GetFileNameWithoutExtension(folder);//folder.Replace(root + "\\", ""); @@ -195,7 +191,7 @@ public Awaiter Load(out SerializableCollection universes) /// /// Die Guid des Universums. /// Das geladene Universum. - public Awaiter Load(out IUniverse universe, Guid universeGuid) + public Awaiter? Load(out IUniverse universe, Guid universeGuid) { string file = Path.Combine(GetRoot(), universeGuid.ToString(), UniverseFilename); universe = new Universe(); @@ -207,7 +203,7 @@ public Awaiter Load(out IUniverse universe, Guid universeGuid) using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress)) using (var reader = new BinaryReader(zip)) { - var awaiter = awaiterPool.Get(); + var awaiter = awaiterPool.Rent(); universe.Deserialize(reader); awaiter.SetResult(universe); return awaiter; @@ -221,7 +217,7 @@ public Awaiter Load(out IUniverse universe, Guid universeGuid) /// Guid des Universums /// Index des Planeten /// - public Awaiter Load(out IPlanet planet, Guid universeGuid, int planetId) + public Awaiter? Load(out IPlanet planet, Guid universeGuid, int planetId) { string file = Path.Combine(GetRoot(), universeGuid.ToString(), planetId.ToString(), PlanetFilename); string generatorInfo = Path.Combine(GetRoot(), universeGuid.ToString(), planetId.ToString(), PlanetGeneratorInfo); @@ -229,25 +225,23 @@ public Awaiter Load(out IPlanet planet, Guid universeGuid, int planetId) if (!File.Exists(generatorInfo) || !File.Exists(file)) return null; - IMapGenerator generator = null; + IMapGenerator? generator = null; using (Stream stream = File.Open(generatorInfo, FileMode.Open, FileAccess.Read)) { using (BinaryReader bw = new BinaryReader(stream)) { string generatorName = bw.ReadString(); - generator = extensionResolver.GetMapGenerator().FirstOrDefault(g => g.GetType().FullName!.Equals(generatorName)); + generator = extensionResolver.GetMapGenerators().FirstOrDefault(g => g.GetType().FullName!.Equals(generatorName)); } } if (generator == null) throw new Exception("Unknown Generator"); - - using (Stream stream = File.Open(file, FileMode.Open, FileAccess.Read)) { using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress)) { - var awaiter = awaiterPool.Get(); + var awaiter = awaiterPool.Rent(); planet = generator.GeneratePlanet(zip); awaiter.SetResult(planet); return awaiter; @@ -262,7 +256,7 @@ public Awaiter Load(out IPlanet planet, Guid universeGuid, int planetId) /// Index des Planeten. /// Zu serialisierende ChunkColumn. /// Die neu geladene ChunkColumn. - public Awaiter Load(out IChunkColumn column, Guid universeGuid, IPlanet planet, Index2 columnIndex) + public Awaiter? Load(out IChunkColumn? column, Guid universeGuid, IPlanet planet, Index2 columnIndex) { var chunkColumContext = new ChunkColumnDbContext(databaseProvider.GetDatabase(universeGuid, planet.Id, false), planet); @@ -274,21 +268,19 @@ public Awaiter Load(out IChunkColumn column, Guid universeGuid, IPlanet planet, ApplyChunkDiff(column, universeGuid, planet); - var awaiter = awaiterPool.Get(); + var awaiter = awaiterPool.Rent(); awaiter.SetResult(column); return awaiter; } - public Awaiter Load(out Entity entity, Guid universeGuid, Guid entityId) { var entityContext = new ComponentContainerDbContext(databaseProvider, universeGuid); entity = entityContext.Get(new GuidTag(entityId)); - var awaiter = awaiterPool.Get(); + var awaiter = awaiterPool.Rent(); awaiter.SetResult(entity); return awaiter; } - public Awaiter Load(out TContainer componentContainer, Guid universeGuid, Guid id) where TContainer : ComponentContainer where TComponent : IComponent @@ -296,7 +288,7 @@ public Awaiter Load(out TContainer componentContainer, G var entityContext = new ComponentContainerDbContext(databaseProvider, universeGuid); componentContainer = entityContext.Get(new GuidTag(id)); - var awaiter = awaiterPool.Get(); + var awaiter = awaiterPool.Rent(); awaiter.SetResult(componentContainer); return awaiter; } @@ -307,9 +299,9 @@ public Awaiter Load(out TContainer componentContainer, G /// Die Guid des Universums. /// Der Name des Spielers. /// - public Awaiter Load(out Player player, Guid universeGuid, string playername) + public Awaiter? Load(out Player player, Guid universeGuid, string playerName) { - //TODO: Später durch Playername ersetzen + //TODO: Replace with player name later on. string file = Path.Combine(GetRoot(), universeGuid.ToString(), "player.info"); player = new Player(); if (!File.Exists(file)) @@ -321,13 +313,13 @@ public Awaiter Load(out Player player, Guid universeGuid, string playername) { try { - var awaiter = awaiterPool.Get(); - awaiter.Serializable = player; + var awaiter = awaiterPool.Rent(); + awaiter.Result = player; player.Deserialize(reader); awaiter.SetResult(player); return awaiter; } - catch (Exception ex) + catch (Exception) { // File.Delete(file); } @@ -336,21 +328,13 @@ public Awaiter Load(out Player player, Guid universeGuid, string playername) return null; } - - public IEnumerable LoadEntitiesWithComponent(Guid universeGuid) where T : IEntityComponent - => new ComponentContainerDbContext(databaseProvider, universeGuid).GetComponentContainerWithComponent().OfType(); - - public IEnumerable GetEntityIdsFromComponent(Guid universeGuid) where T : IEntityComponent - => new ComponentContainerDbContext(databaseProvider, universeGuid).GetComponentContainerIdsFromComponent().Select(i => i.Tag); public IEnumerable GetEntityIds(Guid universeGuid) - => new ComponentContainerDbContext(databaseProvider, universeGuid).GetAllKeys().Select(i => i.Tag); - + => new ComponentContainerDbContext(databaseProvider, universeGuid).GetAllKeys().Select(i => i.Id); public IEnumerable<(Guid Id, T Component)> GetEntityComponents(Guid universeGuid, Guid[] entityIds) where T : IEntityComponent, new() { foreach (var entityId in entityIds) yield return (entityId, new ComponentContainerComponentDbContext(databaseProvider, universeGuid).Get(entityId)); } - public IEnumerable<(Guid Id, T Component)> GetAllComponents(Guid universeGuid) where T : IComponent, new() { var context = new ComponentContainerComponentDbContext(databaseProvider, universeGuid); @@ -359,10 +343,9 @@ public IEnumerable GetEntityIds(Guid universeGuid) foreach (var key in keys) { - yield return (key.Tag, context.Get(key.Tag)); + yield return (key.Id, context.Get(key.Id)); } } - public T GetComponent(Guid universeGuid, Guid id) where T : IComponent, new() { var context @@ -370,7 +353,6 @@ var context return context.Get(id); } - public void Dispose() { databaseProvider.Dispose(); diff --git a/OctoAwesome/OctoAwesome.Runtime/ExtensionLoader.cs b/OctoAwesome/OctoAwesome.Runtime/ExtensionLoader.cs index 8e373676..9f9c2b85 100644 --- a/OctoAwesome/OctoAwesome.Runtime/ExtensionLoader.cs +++ b/OctoAwesome/OctoAwesome.Runtime/ExtensionLoader.cs @@ -15,8 +15,6 @@ namespace OctoAwesome.Runtime public sealed class ExtensionLoader : IExtensionLoader, IExtensionResolver { private const string SETTINGSKEY = "DisabledExtensions"; - - private readonly Dictionary>> componentContainerExtender; private readonly List> simulationExtender; @@ -165,7 +163,7 @@ public void RegisterDefinition(Type definition) } } - definitionTypeContainer.Register(definition, definition, InstanceBehaviour.Singleton); + definitionTypeContainer.Register(definition, definition, InstanceBehavior.Singleton); } /// @@ -200,15 +198,13 @@ public void RegisterSerializationType() public void RegisterEntityExtender(Action extenderDelegate) where T : ComponentContainer { Type type = typeof(T); - List> list; - if (!componentContainerExtender.TryGetValue(type, out list)) + if (!componentContainerExtender.TryGetValue(type, out var list)) { list = new List>(); componentContainerExtender.Add(type, list); } list.Add(extenderDelegate); } - public void RegisterDefaultEntityExtender() where T : ComponentContainer => RegisterEntityExtender((e) => e.RegisterDefault()); @@ -229,7 +225,6 @@ public void RegisterMapGenerator(IMapGenerator generator) // TODO: Checks mapGenerators.Add(generator); } - public void RegisterMapPopulator(IMapPopulator populator) { mapPopulators.Add(populator); @@ -254,7 +249,6 @@ public void RemoveMapGenerator(T item) where T : IMapGenerator { mapGenerators.Remove(item); } - public void RemoveMapPopulator(T item) where T : IMapPopulator { mapPopulators.Remove(item); @@ -293,8 +287,7 @@ public void ExtendEntity(ComponentContainer entity) foreach (var type in stack) { - List> list; - if (!componentContainerExtender.TryGetValue(type, out list)) + if (!componentContainerExtender.TryGetValue(type, out var list)) continue; foreach (var item in list) @@ -316,20 +309,12 @@ public IEnumerable GetDefinitions() where T : class, IDefinition } } - /// - /// Return a List of MapGenerators - /// - /// List of Generators - public IEnumerable GetMapGenerator() + public IEnumerable GetMapGenerators() { return mapGenerators; } - /// - /// Return a List of Populators - /// - /// List of Populators - public IEnumerable GetMapPopulator() + public IEnumerable GetMapPopulators() { return mapPopulators; } diff --git a/OctoAwesome/OctoAwesome.Runtime/GameService.cs b/OctoAwesome/OctoAwesome.Runtime/GameService.cs index 1bc538f2..34e1e3e8 100644 --- a/OctoAwesome/OctoAwesome.Runtime/GameService.cs +++ b/OctoAwesome/OctoAwesome.Runtime/GameService.cs @@ -2,8 +2,8 @@ using OctoAwesome.Common; using OctoAwesome.Definitions; using System; -using System.Collections.Generic; -using System.Linq; +using System.Diagnostics; + namespace OctoAwesome.Runtime { // sealed -> prevent abuse of third party´s @@ -39,7 +39,7 @@ public GameService(IResourceManager resourceManager) public ILocalChunkCache GetLocalCache(bool passive, int dimensions, int range) { //new LocalChunkCache(manager.GlobalChunkCache, false, 2, 1); - return null; + throw new NotImplementedException(); } /// /// Berechnet die Geschwindigkeit einer nach der Kollision mit der Welt. (Original Lassi) @@ -56,8 +56,7 @@ public ILocalChunkCache GetLocalCache(bool passive, int dimensions, int range) public Vector3 WorldCollision(GameTime gameTime, Coordinate position, ILocalChunkCache cache, float radius, float height, Vector3 deltaPosition, Vector3 velocity) { - if (cache == null) - throw new ArgumentNullException(nameof(cache)); + Debug.Assert(cache != null, nameof(cache) + " != null"); Vector3 move = deltaPosition; diff --git a/OctoAwesome/OctoAwesome.Runtime/IPlayerController.cs b/OctoAwesome/OctoAwesome.Runtime/IPlayerController.cs index 65c955e8..4ad518b1 100644 --- a/OctoAwesome/OctoAwesome.Runtime/IPlayerController.cs +++ b/OctoAwesome/OctoAwesome.Runtime/IPlayerController.cs @@ -1,6 +1,4 @@ using engenious; - - namespace OctoAwesome.Runtime { /// @@ -32,25 +30,9 @@ public interface IPlayerController /// Gibt an, ob der Spieler auf dem Boden steht. /// bool OnGround { get; } - - /// - /// Winkel der Kopfstellung. - /// float Tilt { get; } - - /// - /// Bewegungsvektor des Spielers. - /// Vector2 Move { get; set; } - - /// - /// Kopfbewegeungsvektor des Spielers. - /// Vector2 Head { get; set; } - - /// - /// Den Spieler hüpfen lassen. - /// void Jump(); /// diff --git a/OctoAwesome/OctoAwesome.Runtime/OctoAwesome.Runtime.csproj b/OctoAwesome/OctoAwesome.Runtime/OctoAwesome.Runtime.csproj index e4f28ac2..6b944982 100644 --- a/OctoAwesome/OctoAwesome.Runtime/OctoAwesome.Runtime.csproj +++ b/OctoAwesome/OctoAwesome.Runtime/OctoAwesome.Runtime.csproj @@ -1,7 +1,8 @@  net5.0 - warnings + enable + True full @@ -14,6 +15,6 @@ - + \ No newline at end of file diff --git a/OctoAwesome/OctoAwesome.Runtime/ResourceManager.cs b/OctoAwesome/OctoAwesome.Runtime/ResourceManager.cs index 0554908e..1aa3809d 100644 --- a/OctoAwesome/OctoAwesome.Runtime/ResourceManager.cs +++ b/OctoAwesome/OctoAwesome.Runtime/ResourceManager.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; -using System.Threading.Tasks; using OctoAwesome.Caching; using OctoAwesome.Components; using OctoAwesome.Definitions; @@ -20,33 +20,22 @@ namespace OctoAwesome.Runtime /// public class ResourceManager : IResourceManager { - public Player CurrentPlayer - { - get - { - if (player == null) - player = LoadPlayer(""); - return player; - } - private set => player = value; - } - - public IUpdateHub UpdateHub { get; private set; } + public Player CurrentPlayer => player ??= LoadPlayer(""); + public IUpdateHub UpdateHub { get; } - private readonly bool disablePersistence = false; - private readonly IPersistenceManager persistenceManager = null; + private readonly bool disablePersistence; + private readonly IPersistenceManager persistenceManager; private readonly ILogger logger; - private readonly List populators = null; - private Player player; + private readonly List? populators; + private Player? player; private readonly LockSemaphore semaphoreSlim; /// /// Das aktuell geladene Universum. /// - public IUniverse CurrentUniverse { get; private set; } - - public IDefinitionManager DefinitionManager { get; private set; } + public IUniverse? CurrentUniverse { get; private set; } + public IDefinitionManager DefinitionManager { get; } public ConcurrentDictionary Planets { get; } private readonly IExtensionResolver extensionResolver; @@ -71,7 +60,7 @@ public ResourceManager(IExtensionResolver extensionResolver, IDefinitionManager logger = (TypeContainer.GetOrNull() ?? NullLogger.Default).As(typeof(ResourceManager)); - populators = extensionResolver.GetMapPopulator().OrderBy(p => p.Order).ToList(); + populators = extensionResolver.GetMapPopulators().OrderBy(p => p.Order).ToList(); Planets = new ConcurrentDictionary(); UpdateHub = updateHub; @@ -157,10 +146,10 @@ public bool TryLoadUniverse(Guid universeId) /// public void UnloadUniverse() { - using (loadingSemaphore.EnterExclusivScope()) + using (loadingSemaphore.EnterExclusiveScope()) tokenSource.Cancel(); - using (loadingSemaphore.EnterExclusivScope()) + using (loadingSemaphore.EnterExclusiveScope()) { if (CurrentUniverse == null) return; @@ -181,13 +170,6 @@ public void UnloadUniverse() } } - /// - /// Gibt das aktuelle Universum zurück - /// - /// Das gewünschte Universum, falls es existiert - public IUniverse GetUniverse() - => CurrentUniverse; - /// /// Löscht ein Universum. /// @@ -209,14 +191,12 @@ public IPlanet GetPlanet(int id) { if (CurrentUniverse == null) throw new Exception("No Universe loaded"); - - using (semaphoreSlim.Wait()) using (loadingSemaphore.EnterCountScope()) { currentToken.ThrowIfCancellationRequested(); - if (!Planets.TryGetValue(id, out IPlanet planet)) + if (!Planets.TryGetValue(id, out var planet)) { // Versuch vorhandenen Planeten zu laden var awaiter = persistenceManager.Load(out planet, CurrentUniverse.Id, id); @@ -225,7 +205,7 @@ public IPlanet GetPlanet(int id) { // Keiner da -> neu erzeugen Random rand = new Random(CurrentUniverse.Seed + id); - var generators = extensionResolver.GetMapGenerator().ToArray(); + var generators = extensionResolver.GetMapGenerators().ToArray(); int index = rand.Next(generators.Length - 1); IMapGenerator generator = generators[index]; planet = generator.GeneratePlanet(CurrentUniverse.Id, id, CurrentUniverse.Seed + id); @@ -247,7 +227,7 @@ public IPlanet GetPlanet(int id) /// /// Der Name des Players. /// - public Player LoadPlayer(string playername) + public Player LoadPlayer(string playerName) { if (CurrentUniverse == null) throw new Exception("No Universe loaded"); @@ -255,12 +235,9 @@ public Player LoadPlayer(string playername) using (loadingSemaphore.EnterCountScope()) { currentToken.ThrowIfCancellationRequested(); - var awaiter = persistenceManager.Load(out Player player, CurrentUniverse.Id, playername); + var awaiter = persistenceManager.Load(out var player, CurrentUniverse.Id, playerName); - if (awaiter == null) - player = new Player(); - else - awaiter.WaitOnAndRelease(); + awaiter?.WaitOnAndRelease(); return player; } @@ -278,7 +255,6 @@ public void SavePlayer(Player player) using (loadingSemaphore.EnterCountScope()) persistenceManager.SavePlayer(CurrentUniverse.Id, player); } - public IChunkColumn LoadChunkColumn(IPlanet planet, Index2 index) { // Load from disk @@ -290,7 +266,8 @@ public IChunkColumn LoadChunkColumn(IPlanet planet, Index2 index) using (loadingSemaphore.EnterCountScope()) { currentToken.ThrowIfCancellationRequested(); - awaiter = persistenceManager.Load(out column11, CurrentUniverse.Id, planet, index); + + awaiter = persistenceManager.Load(out var loadedColumn, CurrentUniverse.Id, planet, index); if (awaiter == null) { IChunkColumn column = planet.Generator.GenerateColumn(DefinitionManager, planet, new Index2(index.X, index.Y)); @@ -299,25 +276,27 @@ public IChunkColumn LoadChunkColumn(IPlanet planet, Index2 index) else { awaiter.WaitOnAndRelease(); + Debug.Assert(loadedColumn != null, "loadedColumn != null"); + column11 = loadedColumn; } - if (awaiter?.Timeouted ?? false) + if (awaiter?.TimedOut ?? false) logger.Error("Awaiter timeout"); } - } while (awaiter != null && awaiter.Timeouted); + } while (awaiter != null && awaiter.TimedOut); - IChunkColumn column00 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(-1, -1), planet.Size)); - IChunkColumn column10 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(0, -1), planet.Size)); - IChunkColumn column20 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(1, -1), planet.Size)); + var column00 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(-1, -1), planet.Size)); + var column10 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(0, -1), planet.Size)); + var column20 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(1, -1), planet.Size)); - IChunkColumn column01 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(-1, 0), planet.Size)); - IChunkColumn column21 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(1, 0), planet.Size)); + var column01 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(-1, 0), planet.Size)); + var column21 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(1, 0), planet.Size)); - IChunkColumn column02 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(-1, 1), planet.Size)); - IChunkColumn column12 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(0, 1), planet.Size)); - IChunkColumn column22 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(1, 1), planet.Size)); + var column02 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(-1, 1), planet.Size)); + var column12 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(0, 1), planet.Size)); + var column22 = planet.GlobalChunkCache.Peek(Index2.NormalizeXY(index + new Index2(1, 1), planet.Size)); - // Zentrum + // Central chunk column if (!column11.Populated && column21 != null && column12 != null && column22 != null) { foreach (var populator in populators) @@ -370,8 +349,8 @@ public void SaveChunkColumn(IChunkColumn chunkColumn) using (loadingSemaphore.EnterCountScope()) persistenceManager.SaveColumn(CurrentUniverse.Id, chunkColumn.Planet, chunkColumn); } - - public Entity LoadEntity(Guid entityId) + + public Entity? LoadEntity(Guid entityId) { if (CurrentUniverse == null) throw new Exception("No Universe loaded"); @@ -389,7 +368,6 @@ public Entity LoadEntity(Guid entityId) return entity; } } - public void SaveComponentContainer(TContainer container) where TContainer : ComponentContainer where TComponent : IComponent @@ -406,8 +384,8 @@ public void SaveComponentContainer(TContainer container) persistenceManager.Save(container, CurrentUniverse.Id); } } - - public TContainer LoadComponentContainer(Guid id) + + public TContainer? LoadComponentContainer(Guid id) where TContainer : ComponentContainer where TComponent : IComponent { @@ -423,67 +401,34 @@ var awaiter if (awaiter == null) return null; - else - awaiter.WaitOnAndRelease(); + awaiter.WaitOnAndRelease(); return container; } } - public IEnumerable LoadEntitiesWithComponent() where T : IEntityComponent - { - using (loadingSemaphore.EnterCountScope()) - { - currentToken.ThrowIfCancellationRequested(); - return persistenceManager.LoadEntitiesWithComponent(CurrentUniverse.Id); - } - } - - public IEnumerable GetEntityIdsFromComponent() where T : IEntityComponent - { - using (loadingSemaphore.EnterCountScope()) - { - currentToken.ThrowIfCancellationRequested(); - return persistenceManager.GetEntityIdsFromComponent(CurrentUniverse.Id); - } - } - - - public (Guid Id, T Component)[] GetEntityComponents(Guid[] entityIds) where T : IEntityComponent, new() - { - using (loadingSemaphore.EnterCountScope()) - { - currentToken.ThrowIfCancellationRequested(); - return persistenceManager.GetEntityComponents(CurrentUniverse.Id, entityIds).ToArray(); //Hack wird noch geänder - } - } - class IdGuid { public const string PropertyName = "Id"; public static Type ForType = typeof(Guid); } - public (Guid Id, T Component)[] GetAllComponents() where T : IComponent, new() { using (loadingSemaphore.EnterCountScope()) { currentToken.ThrowIfCancellationRequested(); - - - var retValues = persistenceManager.GetAllComponents(CurrentUniverse.Id).ToArray(); //Hack wird noch geänder + var retValues = persistenceManager.GetAllComponents(CurrentUniverse.Id).ToArray(); //TODO: HACK will be changed if (typeof(T) == typeof(PositionComponent)) { foreach (var item in retValues) { - GenericCaster.Cast(item.Component).InstanceId = item.Id; + GenericCaster.Cast(item.Component).InstanceId = item.Id; } } return retValues; } } - public T GetComponent(Guid id) where T : IComponent, new() { using (loadingSemaphore.EnterCountScope()) diff --git a/OctoAwesome/OctoAwesome.Tests/CollisionTests.cs b/OctoAwesome/OctoAwesome.Tests/CollisionTests.cs index aa32396a..99ae12f7 100644 --- a/OctoAwesome/OctoAwesome.Tests/CollisionTests.cs +++ b/OctoAwesome/OctoAwesome.Tests/CollisionTests.cs @@ -52,8 +52,6 @@ public void CollisionFromEastToWestTest() blocks.Add(new Index3(10, 11, 9)); blocks.Add(new Index3(11, 11, 9)); - - Player.Velocity = new Vector3(-1, 0, -0.1f); Move(); AssertEx.Equal(Vector3.Zero, Player.Velocity); @@ -108,8 +106,6 @@ public void CollisionFromEastToWestIntMaxTest() blocks.Add(new Index3(max + 10, max + 11, max + 9)); blocks.Add(new Index3(max + 11, max + 11, max + 9)); - - Player.Velocity = new Vector3(-1, 0, -0.1f); Move(); AssertEx.Equal(Vector3.Zero, Player.Velocity); @@ -222,8 +218,6 @@ private void Move() if (!blocks.Contains(blockPos)) continue; - - var blockplane = CollisionPlane.GetBlockCollisionPlanes(pos, Player.Velocity).ToList(); var planes = from pp in playerplanes diff --git a/OctoAwesome/OctoAwesome.Tests/GlobalChunkCacheTest.cs b/OctoAwesome/OctoAwesome.Tests/GlobalChunkCacheTest.cs index 751adc7d..5fce7b1f 100644 --- a/OctoAwesome/OctoAwesome.Tests/GlobalChunkCacheTest.cs +++ b/OctoAwesome/OctoAwesome.Tests/GlobalChunkCacheTest.cs @@ -135,8 +135,6 @@ public GlobalChunkCacheTest() // //Change Chunk so that they get saved // result1.Chunks[0].SetBlock(Index3.Zero,0,0); - - // // Unload 1 // cache.Release(planet1, index1,false); // System.Threading.Thread.Sleep(150);//TODO: dirty fix wait till completly cleaned up @@ -203,8 +201,6 @@ public GlobalChunkCacheTest() // Assert.Equals(1, loadCallCounter); // Assert.Equals(0, saveCallCounter); - - // // Unload 1 // cache.Release(planet, index,false); // System.Threading.Thread.Sleep(150);//TODO: dirty fix wait till completly cleaned up diff --git a/OctoAwesome/OctoAwesome.Tests/Index2Tests.cs b/OctoAwesome/OctoAwesome.Tests/Index2Tests.cs index 3d1288c8..1151d1dc 100644 --- a/OctoAwesome/OctoAwesome.Tests/Index2Tests.cs +++ b/OctoAwesome/OctoAwesome.Tests/Index2Tests.cs @@ -19,11 +19,6 @@ public void Index2ConstructorTest() Assert.Equals(21, i2.X); Assert.Equals(32, i2.Y); - // Index2-Parameter - Index2 i3 = new Index2(new Index2(-2, 80)); - Assert.Equals(-2, i3.X); - Assert.Equals(80, i3.Y); - // Index3 Parameter Index2 i4 = new Index2(new Index3(int.MinValue, int.MaxValue, 0)); Assert.Equals(int.MinValue, i4.X); diff --git a/OctoAwesome/OctoAwesome.Tests/Index3Tests.cs b/OctoAwesome/OctoAwesome.Tests/Index3Tests.cs index cf9ed474..a97d225b 100644 --- a/OctoAwesome/OctoAwesome.Tests/Index3Tests.cs +++ b/OctoAwesome/OctoAwesome.Tests/Index3Tests.cs @@ -26,12 +26,6 @@ public void Index3ConstructorTest() Assert.Equals(-2, i3.X); Assert.Equals(80, i3.Y); Assert.Equals(76, i3.Z); - - // Index3 Parameter - Index3 i4 = new Index3(new Index3(int.MinValue, int.MaxValue, 3)); - Assert.Equals(int.MinValue, i4.X); - Assert.Equals(int.MaxValue, i4.Y); - Assert.Equals(3, i4.Z); } [Test] diff --git a/OctoAwesome/OctoAwesome.Tests/LocalChunkCacheTest.cs b/OctoAwesome/OctoAwesome.Tests/LocalChunkCacheTest.cs index b47e5dd1..fa402a89 100644 --- a/OctoAwesome/OctoAwesome.Tests/LocalChunkCacheTest.cs +++ b/OctoAwesome/OctoAwesome.Tests/LocalChunkCacheTest.cs @@ -131,6 +131,4 @@ public LocalChunkCacheTest() // Assert.Equals(chunk.Index, new Index3(15, 15, 0)); //} } - - } diff --git a/OctoAwesome/OctoAwesome.Tests/SettingsManagerTests.cs b/OctoAwesome/OctoAwesome.Tests/SettingsManagerTests.cs index ad4e8c83..38e3ad90 100644 --- a/OctoAwesome/OctoAwesome.Tests/SettingsManagerTests.cs +++ b/OctoAwesome/OctoAwesome.Tests/SettingsManagerTests.cs @@ -19,37 +19,25 @@ public void ReadWrite() string[] newArray = settings.GetArray("foo"); Assert.True(testArray.SequenceEqual(newArray)); - - int[] testArrayInt = new int[] { 3, 5, 333, 456, 3457 }; settings.Set("fooInt", testArrayInt); int[] newArrayInt = settings.GetArray("fooInt"); Assert.True(testArray.SequenceEqual(newArray)); - - bool[] testArrayBool = new bool[] { true, false }; settings.Set("fooBool", testArrayBool); bool[] newArrayBool = settings.GetArray("fooBool"); Assert.True(testArray.SequenceEqual(newArray)); - - String inputString = "randomStringWith§$%&/()=Charakters"; settings.Set("inputString", inputString); - - Assert.Equals(inputString, settings.Get("inputString")); - - int inputInt = new Random().Next(); settings.Set("inputInt", inputInt); Assert.Equals(inputInt, settings.Get("inputInt")); - - bool inputBool = true; settings.Set("inputBool", inputBool); diff --git a/OctoAwesome/OctoAwesome.Tests/StandaloneTypeContainerTests.cs b/OctoAwesome/OctoAwesome.Tests/StandaloneTypeContainerTests.cs index 4229abc8..172e0ea5 100644 --- a/OctoAwesome/OctoAwesome.Tests/StandaloneTypeContainerTests.cs +++ b/OctoAwesome/OctoAwesome.Tests/StandaloneTypeContainerTests.cs @@ -18,18 +18,18 @@ public void InstanceTest() var typecontainer = new StandaloneTypeContainer(); typecontainer.Register(); typecontainer.Register(); - typecontainer.Register(typeof(ITestInterface), typeof(TestClass), InstanceBehaviour.Instance); + typecontainer.Register(typeof(ITestInterface), typeof(TestClass), InstanceBehavior.Instance); - var result = typecontainer.TryResolve(typeof(TestClass), out var instanceA); + var result = typecontainer.TryGet(typeof(TestClass), out var instanceA); Assert.True(result); - result = typecontainer.TryResolve(typeof(TestClass), out var instanceB); + result = typecontainer.TryGet(typeof(TestClass), out var instanceB); Assert.True(result); - result = typecontainer.TryResolve(typeof(ITestInterface), out var instanceC); + result = typecontainer.TryGet(typeof(ITestInterface), out var instanceC); Assert.True(result); - result = typecontainer.TryResolve(typeof(ITestInterface), out var instanceD); + result = typecontainer.TryGet(typeof(ITestInterface), out var instanceD); Assert.True(result); Assert.True(instanceA is TestClass); @@ -42,7 +42,7 @@ public void InstanceTest() Assert.AreNotSame(instanceA, instanceB); Assert.AreNotSame(instanceA, instanceD); - Assert.False(typecontainer.TryResolve(typeof(SecondTestClass), out instanceA)); + Assert.False(typecontainer.TryGet(typeof(SecondTestClass), out instanceA)); Assert.Null(instanceA); } diff --git a/OctoAwesome/OctoAwesome/Awaiter.cs b/OctoAwesome/OctoAwesome/Awaiter.cs index 105bead8..b949b094 100644 --- a/OctoAwesome/OctoAwesome/Awaiter.cs +++ b/OctoAwesome/OctoAwesome/Awaiter.cs @@ -2,50 +2,48 @@ using OctoAwesome.Serialization; using OctoAwesome.Threading; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Tasks; namespace OctoAwesome { + public class Awaiter : IPoolElement, IDisposable { - public ISerializable Serializable { get; set; } - public bool Timeouted { get; private set; } + + public ISerializable? Result { get; set; } + public bool TimedOut { get; private set; } private readonly ManualResetEventSlim manualReset; private readonly LockSemaphore semaphore; private bool alreadyDeserialized; private IPool pool; private bool isPooled; - public Awaiter() { manualReset = new ManualResetEventSlim(false); semaphore = new LockSemaphore(1, 1); } - public ISerializable WaitOn() + public ISerializable? WaitOn() { if (!alreadyDeserialized) - Timeouted = !manualReset.Wait(10000); + TimedOut = !manualReset.Wait(10000); - return Serializable; + return Result; } - public void WaitOnAndRelease() + public ISerializable? WaitOnAndRelease() { - WaitOn(); + var res = WaitOn(); Release(); + return res; } - public void SetResult(ISerializable serializable) + public void SetResult(ISerializable result) { using (semaphore.Wait()) { - Serializable = serializable; + Result = result; manualReset.Set(); alreadyDeserialized = true; } @@ -57,39 +55,36 @@ public bool TrySetResult(byte[] bytes) { using (semaphore.Wait()) { - if (Timeouted) + if (TimedOut) return false; - if (Serializable == null) - throw new ArgumentNullException(nameof(Serializable)); + if (Result == null) + throw new ArgumentNullException(nameof(Result)); using (var stream = new MemoryStream(bytes)) using (var reader = new BinaryReader(stream)) { - Serializable.Deserialize(reader); + Result.Deserialize(reader); } manualReset.Set(); return alreadyDeserialized = true; } } - catch (Exception ex) + catch (Exception) { - ; return false; } } - public void Init(IPool pool) { this.pool = pool; - Timeouted = false; + TimedOut = false; isPooled = false; alreadyDeserialized = false; - Serializable = null; + Result = null; manualReset.Reset(); } - public void Release() { using (semaphore.Wait()) @@ -99,10 +94,9 @@ public void Release() isPooled = true; - pool.Push(this); + pool.Return(this); } } - public void Dispose() { manualReset.Dispose(); diff --git a/OctoAwesome/OctoAwesome/Block.cs b/OctoAwesome/OctoAwesome/Block.cs index f5568043..3fa85c29 100644 --- a/OctoAwesome/OctoAwesome/Block.cs +++ b/OctoAwesome/OctoAwesome/Block.cs @@ -3,19 +3,11 @@ namespace OctoAwesome { - /// - /// Helferklasse für die Kollisionserkennung mit Blöcken. - /// + public static class Block { - /// - /// Kollisionsmethode, in der die Selektion der Blöcke vom Spieler aus geprüft wird - /// - /// Kollisionsboxen des Blocks - /// Die Position, wo sich die BoundingBox befindet - /// Der Selektionsstrahl, der vom Spieler ausgeht - /// Welche Achse von der Kollision betroffen ist - /// Die Entfernung zwischen der Kollision und der Kollisionsbox der Entität + + public static float? Intersect(ReadOnlySpan collisionBoxes, Index3 boxPosition, Ray ray, out Axis? collisionAxis) { Vector3 min = new Vector3(1, 1, 1); @@ -83,15 +75,6 @@ public static class Block return null; } - /// - /// Prüft, ob die Kollisionsbox einer Entität mit den Kollisionsboxen eines Blocks kollidieren - /// - /// Kollisionsboxen des Blocks - /// Die Position, wo sich der Block befindet - /// Die Kollisionsbox einer Entität - /// Die befegungsrichtung der Entität - /// Welche Achse von der Kollision betroffen ist - /// Die Entfernung zwischen der Kollision und der Kollisionsbox der Entität public static float? Intersect(ReadOnlySpan collisionBoxes, Index3 boxPosition, BoundingBox player, Vector3 move, out Axis? collisionAxis) { Vector3 playerCorner = new Vector3( diff --git a/OctoAwesome/OctoAwesome/BlockInfo.cs b/OctoAwesome/OctoAwesome/BlockInfo.cs index ff211b6a..fa6e0503 100644 --- a/OctoAwesome/OctoAwesome/BlockInfo.cs +++ b/OctoAwesome/OctoAwesome/BlockInfo.cs @@ -1,19 +1,15 @@ -using OctoAwesome.Serialization; -using System; +using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { + public readonly struct BlockInfo : IEquatable { - public static BlockInfo Empty = default; + public static BlockInfo Empty = default; public bool IsEmpty => this == default; - public Index3 Position { get; } public ushort Block { get; } public int Meta { get; } @@ -24,19 +20,17 @@ public BlockInfo(Index3 position, ushort block, int meta = 0) Block = block; Meta = meta; } + public BlockInfo(int x, int y, int z, ushort block, int meta = 0) : this(new Index3(x, y, z), block, meta) { } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is BlockInfo info && Equals(info); - public bool Equals(BlockInfo other) => EqualityComparer.Default.Equals(Position, other.Position) && Block == other.Block && Meta == other.Meta; - public override int GetHashCode() { var hashCode = -1504387948; @@ -45,7 +39,6 @@ public override int GetHashCode() hashCode = hashCode * -1521134295 + Meta.GetHashCode(); return hashCode; } - public static void Serialize(BinaryWriter writer, BlockInfo info) { writer.Write(info.Position.X); @@ -54,7 +47,6 @@ public static void Serialize(BinaryWriter writer, BlockInfo info) writer.Write(info.Block); writer.Write(info.Meta); } - public static BlockInfo Deserialize(BinaryReader reader) => new BlockInfo( reader.ReadInt32(), @@ -65,31 +57,25 @@ public static BlockInfo Deserialize(BinaryReader reader) public static bool operator ==(BlockInfo left, BlockInfo right) => left.Equals(right); + public static bool operator !=(BlockInfo left, BlockInfo right) => !(left == right); #region BlockInfo <=> Tuple Operators public static implicit operator BlockInfo((int x, int y, int z, ushort block, int meta) blockTuple) => new BlockInfo(blockTuple.x, blockTuple.y, blockTuple.z, blockTuple.block, blockTuple.meta); - public static implicit operator (int x, int y, int z, ushort block, int meta)(BlockInfo blockInfo) => (blockInfo.Position.X, blockInfo.Position.Y, blockInfo.Position.Z, blockInfo.Block, blockInfo.Meta); - public static implicit operator BlockInfo((int x, int y, int z, ushort block) blockTuple) => new BlockInfo(blockTuple.x, blockTuple.y, blockTuple.z, blockTuple.block); - public static implicit operator (int x, int y, int z, ushort block)(BlockInfo blockInfo) => (blockInfo.Position.X, blockInfo.Position.Y, blockInfo.Position.Z, blockInfo.Block); - public static implicit operator BlockInfo((Index3 position, ushort block, int meta) blockTuple) => new BlockInfo(blockTuple.position, blockTuple.block, blockTuple.meta); - public static implicit operator (Index3 position, ushort block, int meta)(BlockInfo blockInfo) => (blockInfo.Position, blockInfo.Block, blockInfo.Meta); - public static implicit operator BlockInfo((Index3 position, ushort block) blockTuple) => new BlockInfo(blockTuple.position, blockTuple.block); - public static implicit operator (Index3 position, ushort block)(BlockInfo blockInfo) => (blockInfo.Position, blockInfo.Block); #endregion diff --git a/OctoAwesome/OctoAwesome/Caching/Cache.cs b/OctoAwesome/OctoAwesome/Caching/Cache.cs index 7fb5d939..59974b43 100644 --- a/OctoAwesome/OctoAwesome/Caching/Cache.cs +++ b/OctoAwesome/OctoAwesome/Caching/Cache.cs @@ -1,15 +1,21 @@ using OctoAwesome.Threading; using System; using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace OctoAwesome.Caching { + public abstract class Cache { + public abstract Type TypeOfTValue { get; } + public abstract Type TypeOfTKey { get; } - public bool IsStarted { get; internal set; } + + public bool IsStarted { get; private set; } public abstract TValue Get(TKey key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists); @@ -25,20 +31,22 @@ internal virtual void Stop() internal abstract void CollectGarbage(); } - - public abstract class Cache : Cache + public abstract class Cache : Cache + where TKey : notnull { + public override Type TypeOfTValue { get; } = typeof(TValue); public override Type TypeOfTKey { get; } = typeof(TKey); - protected TimeSpan ClearTime { get; set; } = TimeSpan.FromMinutes(15); protected readonly CountedScopeSemaphore lockSemaphore = new(); - protected readonly Dictionary valueCache = new(); + protected virtual TValue GetBy(TKey key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists) { - CacheItem cacheItem; + Debug.Assert(IsStarted, IsStarted + " == true"); + + CacheItem? cacheItem; bool result; using (var @lock = lockSemaphore.EnterCountScope()) { @@ -46,20 +54,20 @@ protected virtual TValue GetBy(TKey key, LoadingMode loadingMode = LoadingMode.L } if (result - && cacheItem.LastAccessTime.Add(ClearTime) < DateTime.Now) + && cacheItem!.LastAccessTime.Add(ClearTime) < DateTime.Now) { cacheItem.LastAccessTime = DateTime.Now; } if (result) - return cacheItem.Value; + return cacheItem!.Value; if (loadingMode == LoadingMode.LoadIfNotExists) { var loadedValue = Load(key); cacheItem = new(loadedValue); - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); valueCache[key] = cacheItem; } else if (loadingMode == LoadingMode.OnlyCached) @@ -73,12 +81,11 @@ protected virtual TValue GetBy(TKey key, LoadingMode loadingMode = LoadingMode.L return cacheItem.Value; } - protected abstract TValue Load(TKey key); protected CacheItem AddOrUpdate(TKey key, TValue value) { - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); return valueCache[key] = new(value); } @@ -87,7 +94,7 @@ internal override void CollectGarbage() { for (int i = valueCache.Count - 1; i >= 0; i--) { - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); var element = valueCache.ElementAt(i); if (element.Value.LastAccessTime.Add(ClearTime) < DateTime.Now) @@ -95,44 +102,36 @@ internal override void CollectGarbage() } } - internal virtual bool Remove(TKey key, out TValue value) + internal virtual bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) { - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); var returnValue = valueCache .Remove(key, out var cacheItem); - if (returnValue) - { - value = cacheItem!.Value; - } - else - { - value = default; - } + value = returnValue ? cacheItem!.Value : default; return returnValue; } - public override TV Get(TK key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists) { - return GenericCaster + return GenericCaster .Cast( - GetBy(GenericCaster.Cast(key), loadingMode) + GetBy(GenericCaster.Cast(key), loadingMode) ); } - protected class CacheItem { internal DateTime LastAccessTime { get; set; } internal TValue Value { get; set; } public CacheItem(TValue value) + : this(DateTime.Now, value) { - LastAccessTime = DateTime.Now; - Value = value; } + + public CacheItem(DateTime lastAccessTime, TValue value) { LastAccessTime = lastAccessTime; diff --git a/OctoAwesome/OctoAwesome/Caching/CacheService.cs b/OctoAwesome/OctoAwesome/Caching/CacheService.cs index 34b3facf..69f7fc4d 100644 --- a/OctoAwesome/OctoAwesome/Caching/CacheService.cs +++ b/OctoAwesome/OctoAwesome/Caching/CacheService.cs @@ -8,6 +8,7 @@ namespace OctoAwesome.Caching { + public class CacheService : IDisposable { private readonly Dictionary caches; @@ -16,7 +17,6 @@ public class CacheService : IDisposable private CancellationTokenSource cancellationTokenSource; private Task garbageCollectionTask; - public CacheService(IPlanet planet, IResourceManager resourceManager, IUpdateHub updateHub) { caches = new Dictionary(); @@ -36,6 +36,7 @@ public CacheService(IPlanet planet, IResourceManager resourceManager, IUpdateHub caches.Add(typeof(FunctionalBlock), new ComponentContainerCache(resourceManager)); } + public void Start() { if(cancellationTokenSource is not null) @@ -59,7 +60,6 @@ public void Start() garbageCollectionTask.Start(); } - public void Stop() { cancellationTokenSource.Cancel(); @@ -73,7 +73,6 @@ public void Stop() item.Stop(); } } - public void Dispose() { Stop(); @@ -89,16 +88,14 @@ public void Dispose() caches.Clear(); } - public TValue Get(TKey key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists) + public TValue? Get(TKey key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists) { if(caches.TryGetValue(typeof(TValue), out var cache)) { return cache.Get(key, loadingMode); } - else - { - return default; - } + + return default; } private async Task GarbageCollection(CancellationToken cancellationToken) @@ -111,7 +108,7 @@ private async Task GarbageCollection(CancellationToken cancellationToken) item.CollectGarbage(); } - await Task.Delay(30000); + await Task.Delay(30000, cancellationToken); } } } diff --git a/OctoAwesome/OctoAwesome/Caching/ChunkColumnCache.cs b/OctoAwesome/OctoAwesome/Caching/ChunkColumnCache.cs index 57c8c5b4..7b708833 100644 --- a/OctoAwesome/OctoAwesome/Caching/ChunkColumnCache.cs +++ b/OctoAwesome/OctoAwesome/Caching/ChunkColumnCache.cs @@ -1,15 +1,13 @@ -using OctoAwesome.EntityComponents; -using System.Collections.Generic; -using System; +using System; using System.Linq; namespace OctoAwesome.Caching { + public class ChunkColumnCache : Cache { private readonly IResourceManager resourceManager; private readonly IPlanet planet; - public ChunkColumnCache(IResourceManager resourceManager, IPlanet planet) { this.resourceManager = resourceManager; @@ -17,11 +15,11 @@ public ChunkColumnCache(IResourceManager resourceManager, IPlanet planet) } //TODO Implement Reference Count and return to pool - sealed internal override void CollectGarbage() + internal sealed override void CollectGarbage() { for (int i = valueCache.Count - 1; i >= 0; i--) { - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); var element = valueCache.ElementAt(i); if (element.Value.LastAccessTime.Add(ClearTime) < DateTime.Now) @@ -31,7 +29,6 @@ sealed internal override void CollectGarbage() } } - protected override IChunkColumn Load(Index2 key) => resourceManager.LoadChunkColumn(planet, key); @@ -42,12 +39,11 @@ private IChunkColumn GetBy(Index3 chunkColumnIndex, LoadingMode loadingMode) return GetBy(new Index2(chunkColumnIndex), loadingMode); } - public override TV Get(TK key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists) => key switch { - Index2 chunkColumnIndex => GenericCaster.Cast(GetBy(chunkColumnIndex, loadingMode)), - Index3 chunkColumnIndex => GenericCaster.Cast(GetBy(chunkColumnIndex, loadingMode)), + Index2 chunkColumnIndex => GenericCaster.Cast(GetBy(chunkColumnIndex, loadingMode)), + Index3 chunkColumnIndex => GenericCaster.Cast(GetBy(chunkColumnIndex, loadingMode)), _ => throw new NotSupportedException() }; diff --git a/OctoAwesome/OctoAwesome/Caching/ComponentContainerCache.cs b/OctoAwesome/OctoAwesome/Caching/ComponentContainerCache.cs index 33e920c1..2121be22 100644 --- a/OctoAwesome/OctoAwesome/Caching/ComponentContainerCache.cs +++ b/OctoAwesome/OctoAwesome/Caching/ComponentContainerCache.cs @@ -3,6 +3,7 @@ namespace OctoAwesome.Caching { + public class ComponentContainerCache : Cache where TContainer : ComponentContainer where TComponent : IComponent @@ -13,7 +14,6 @@ public ComponentContainerCache(IResourceManager resourceManager) { this.resourceManager = resourceManager; } - protected override TContainer Load(Guid key) => resourceManager.LoadComponentContainer(key); } diff --git a/OctoAwesome/OctoAwesome/Caching/GenericCaster.cs b/OctoAwesome/OctoAwesome/Caching/GenericCaster.cs index 750f5349..4984706a 100644 --- a/OctoAwesome/OctoAwesome/Caching/GenericCaster.cs +++ b/OctoAwesome/OctoAwesome/Caching/GenericCaster.cs @@ -3,8 +3,10 @@ namespace OctoAwesome.Caching { - public static class GenericCaster + + public static class GenericCaster { + public static Func Cast { get; } static GenericCaster() { diff --git a/OctoAwesome/OctoAwesome/Caching/LoadingMode.cs b/OctoAwesome/OctoAwesome/Caching/LoadingMode.cs index 217e5829..ebe3698d 100644 --- a/OctoAwesome/OctoAwesome/Caching/LoadingMode.cs +++ b/OctoAwesome/OctoAwesome/Caching/LoadingMode.cs @@ -1,8 +1,11 @@ namespace OctoAwesome.Caching { + public enum LoadingMode { + LoadIfNotExists, + OnlyCached } } diff --git a/OctoAwesome/OctoAwesome/Caching/PositionComponentCache.cs b/OctoAwesome/OctoAwesome/Caching/PositionComponentCache.cs index 24ac1285..d1b8af17 100644 --- a/OctoAwesome/OctoAwesome/Caching/PositionComponentCache.cs +++ b/OctoAwesome/OctoAwesome/Caching/PositionComponentCache.cs @@ -1,9 +1,11 @@ using OctoAwesome.EntityComponents; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace OctoAwesome.Caching { + public class PositionComponentCache : Cache { private readonly IResourceManager resourceManager; @@ -26,16 +28,16 @@ var positionComponents foreach (var (id, component) in positionComponents) { var cacheItem = AddOrUpdate(id, component); - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); positionComponentByCoor.Add(component.Position, cacheItem); } base.Start(); } - internal override bool Remove(Guid key, out PositionComponent positionComponent) + internal override bool Remove(Guid key, [MaybeNullWhen(false)] out PositionComponent positionComponent) { - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); var returnValue = base.Remove(key, out positionComponent); @@ -50,22 +52,19 @@ internal override bool Remove(Guid key, out PositionComponent positionComponent) return returnValue; } } - protected override PositionComponent Load(Guid key) => resourceManager.GetComponent(key); - protected PositionComponent GetBy(Coordinate position) { - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); var cacheItem = positionComponentByCoor[position]; cacheItem.LastAccessTime = DateTime.Now; return cacheItem.Value; } - - protected List GetBy(Index3 position) + protected List GetBy(Index3 chunkIndex) { - using var @lock = lockSemaphore.EnterExclusivScope(); + using var @lock = lockSemaphore.EnterExclusiveScope(); var list = new List(); @@ -74,11 +73,9 @@ protected List GetBy(Index3 position) var key = component.Key; var normalizedChunkIndex = key.ChunkIndex; normalizedChunkIndex.NormalizeXY(component.Value.Value.Planet.Size); - - - if (key.Planet == position.Z - && normalizedChunkIndex.X == position.X - && normalizedChunkIndex.Y == position.Y) + if (key.Planet == chunkIndex.Z + && normalizedChunkIndex.X == chunkIndex.X + && normalizedChunkIndex.Y == chunkIndex.Y) { list.Add(component.Value.Value); component.Value.LastAccessTime = DateTime.Now; @@ -87,23 +84,19 @@ protected List GetBy(Index3 position) return list; } - + /// - /// + /// Tries to return the Component of the given Type or null /// - /// - /// - /// - /// Is ignored, because this cache load everything on startup and therefore is always cached - /// - /// - public override TV Get(TK key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists) + /// Component Type + /// True if the component was found, false otherwise + public override TValue Get(TKey key, LoadingMode loadingMode = LoadingMode.LoadIfNotExists) => key switch { - Guid guid => GenericCaster.Cast(GetBy(guid, loadingMode)), - Coordinate coordinate => GenericCaster.Cast(GetBy(coordinate)), - Index3 chunkColumnIndex => GenericCaster>.Cast(GetBy(chunkColumnIndex)), - //(IPlanet, Index2) index => GenericCaster>.Cast(GetBy(index)), + Guid guid => GenericCaster.Cast(GetBy(guid, loadingMode)), + Coordinate coordinate => GenericCaster.Cast(GetBy(coordinate)), + Index3 chunkColumnIndex => GenericCaster, TValue>.Cast(GetBy(chunkColumnIndex)), + //(IPlanet, Index2) index => GenericCaster>.Cast(GetBy(index)), _ => throw new NotSupportedException() }; } diff --git a/OctoAwesome/OctoAwesome/Chunk.cs b/OctoAwesome/OctoAwesome/Chunk.cs index 43ba74b2..75039050 100644 --- a/OctoAwesome/OctoAwesome/Chunk.cs +++ b/OctoAwesome/OctoAwesome/Chunk.cs @@ -4,76 +4,28 @@ namespace OctoAwesome { - /// - /// Repräsentiert einen Karten-Abschnitt innerhalb des Planeten. - /// + public sealed class Chunk : IChunk { - /// - /// Zweierpotenz der Chunkgrösse. Ausserdem gibt es die Anzahl Bits an, - /// die die X-Koordinate im Array verwendet. - /// + public const int LimitX = 4; - /// - /// Zweierpotenz der Chunkgrösse. Ausserdem gibt es die Anzahl Bits an, - /// die die Y-Koordinate im Array verwendet. - /// + public const int LimitY = 4; - /// - /// Zweierpotenz der Chunkgrösse. Ausserdem gibt es die Anzahl Bits an, - /// die die Z-Koordinate im Array verwendet. - /// + public const int LimitZ = 4; - /// - /// Größe eines Chunks in Blocks in X-Richtung. - /// public const int CHUNKSIZE_X = 1 << LimitX; - /// - /// Größe eines Chunks in Blocks in Y-Richtung. - /// public const int CHUNKSIZE_Y = 1 << LimitY; - /// - /// Größe eines Chunks in Blocks in Z-Richtung. - /// public const int CHUNKSIZE_Z = 1 << LimitZ; - - /// - /// Grösse eines Chunk als - /// public static readonly Index3 CHUNKSIZE = new Index3(CHUNKSIZE_X, CHUNKSIZE_Y, CHUNKSIZE_Z); private IChunkColumn chunkColumn; - - /// - /// Array, das alle Blöcke eines Chunks enthält. Jeder eintrag entspricht einer Block-ID. - /// Der Index ist derselbe wie bei . - /// - public ushort[] Blocks { get; private set; } - - /// - /// Array, das die Metadaten zu den Blöcken eines Chunks enthält. - /// Der Index ist derselbe wie bei . - /// - public int[] MetaData { get; private set; } - - /// - /// Chunk Index innerhalb des Planeten. - /// + public ushort[] Blocks { get; } + public int[] MetaData { get; } public Index3 Index { get; private set; } - - /// - /// Referenz auf den Planeten. - /// public IPlanet Planet { get; private set; } public int Version { get; set; } - - /// - /// Erzeugt eine neue Instanz der Klasse Chunk - /// - /// Position des Chunks - /// Index des Planeten public Chunk(Index3 pos, IPlanet planet) { Blocks = new ushort[CHUNKSIZE_X * CHUNKSIZE_Y * CHUNKSIZE_Z]; @@ -82,47 +34,18 @@ public Chunk(Index3 pos, IPlanet planet) Index = pos; Planet = planet; } - - /// - /// Liefet den Block an der angegebenen Koordinate zurück. - /// - /// Koordinate des Blocks innerhalb des Chunkgs - /// Die Block-ID an der angegebenen Koordinate public ushort GetBlock(Index3 index) { return GetBlock(index.X, index.Y, index.Z); } - - /// - /// Liefet den Block an der angegebenen Koordinate zurück. - /// - /// X-Anteil der Koordinate des Blocks - /// Y-Anteil der Koordinate des Blocks - /// Z-Anteil der Koordinate des Blocks - /// Block-ID der angegebenen Koordinate public ushort GetBlock(int x, int y, int z) { return Blocks[GetFlatIndex(x, y, z)]; } - - /// - /// Überschreibt den Block an der angegebenen Koordinate. - /// - /// Koordinate des Blocks innerhalb des Chunks - /// Die neue Block-ID. - /// (Optional) Metainformationen für den Block public void SetBlock(Index3 index, ushort block, int meta = 0) { SetBlock(index.X, index.Y, index.Z, block); } - /// - /// Überschreibt den Block an der angegebenen Koordinate. - /// - /// X-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Y-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Z-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Die neue Block-ID - /// (Optional) Die Metadaten des Blocks public void SetBlock(int x, int y, int z, ushort block, int meta = 0) => SetBlock(GetFlatIndex(x, y, z), new BlockInfo(x, y, z, block, meta)); public void SetBlock(int flatIndex, BlockInfo blockInfo) @@ -133,7 +56,6 @@ public void SetBlock(int flatIndex, BlockInfo blockInfo) Version++; BlockChanged(blockInfo); } - public void SetBlocks(bool issueNotification, params BlockInfo[] blockInfos) { for (int i = 0; i < blockInfos.Length; i++) @@ -150,68 +72,32 @@ public void SetBlocks(bool issueNotification, params BlockInfo[] blockInfos) BlocksChanged(blockInfos); } } - public void FlagDirty() { Changed?.Invoke(this); } - - /// - /// Gibt die Metadaten des Blocks an der angegebenen Koordinate zurück. - /// - /// X-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Y-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Z-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Die Metadaten des angegebenen Blocks public int GetBlockMeta(int x, int y, int z) { return MetaData[GetFlatIndex(x, y, z)]; } - - /// - /// Ändert die Metadaten des Blockes an der angegebenen Koordinate. - /// - /// X-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Y-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Z-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Die neuen Metadaten public void SetBlockMeta(int x, int y, int z, int meta) { MetaData[GetFlatIndex(x, y, z)] = meta; Changed?.Invoke(this); } - - /// - /// Liefert alle Ressourcen im Block an der angegebenen Koordinate zurück. - /// - /// X-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Y-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Z-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Ein Array aller Ressourcen des Blocks public ushort[] GetBlockResources(int x, int y, int z) { return Array.Empty(); } - - /// - /// Ändert die Ressourcen des Blocks an der angegebenen Koordinate - /// - /// X-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Y-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Z-Anteil der Koordinate des Blocks innerhalb des Chunks - /// Ein -Array, das alle Ressourcen enthält public void SetBlockResources(int x, int y, int z, ushort[] resources) { Changed?.Invoke(this); } - public void SetColumn(IChunkColumn chunkColumn) => this.chunkColumn = chunkColumn; - public void OnUpdate(SerializableNotification notification) => chunkColumn?.OnUpdate(notification); - public void Update(SerializableNotification notification) { if (notification is BlockChangedNotification blockChanged) @@ -236,7 +122,7 @@ public void Update(SerializableNotification notification) private void BlockChanged(BlockInfo blockInfo) { - var notification = TypeContainer.Get>().Get(); + var notification = TypeContainer.Get>().Rent(); notification.BlockInfo = blockInfo; notification.ChunkPos = Index; notification.Planet = Planet.Id; @@ -247,7 +133,7 @@ private void BlockChanged(BlockInfo blockInfo) } private void BlocksChanged(params BlockInfo[] blockInfos) { - var notification = TypeContainer.Get>().Get(); + var notification = TypeContainer.Get>().Rent(); notification.BlockInfos = blockInfos; notification.ChunkPos = Index; notification.Planet = Planet.Id; @@ -256,29 +142,14 @@ private void BlocksChanged(params BlockInfo[] blockInfos) notification.Release(); } + public event Action? Changed; - public event Action Changed; - - /// - /// Liefert den Index des Blocks im abgeflachten Block-Array der angegebenen 3D-Koordinate zurück. Sollte die Koordinate ausserhalb - /// der Chunkgrösse liegen, wird dies gewrapt. - /// - /// X-Anteil der Koordinate - /// Y-Anteil der Koordinate - /// Z-Anteil der Koordinate - /// Index innerhalb des flachen Arrays public static int GetFlatIndex(int x, int y, int z) { return ((z & (CHUNKSIZE_Z - 1)) << (LimitX + LimitY)) | ((y & (CHUNKSIZE_Y - 1)) << LimitX) | (x & (CHUNKSIZE_X - 1)); } - /// - /// Liefert den Index des Blocks im abgeflachten Block-Array der angegebenen 3D-Koordinate zurück. Sollte die Koordinate ausserhalb - /// der Chunkgrösse liegen, wird dies gewrapt. - /// - /// Die aktuelle Blockposition - /// Index innerhalb des flachen Arrays public static int GetFlatIndex(Index3 position) { return ((position.Z & (CHUNKSIZE_Z - 1)) << (LimitX + LimitY)) @@ -286,7 +157,7 @@ public static int GetFlatIndex(Index3 position) | (position.X & (CHUNKSIZE_X - 1)); } - public void Init(Index3 position, IPlanet planet) + internal void Init(Index3 position, IPlanet planet) { Index = position; Planet = planet; @@ -297,12 +168,10 @@ public void Init(Index3 position, IPlanet planet) for (int i = 0; i < MetaData.Length; i++) MetaData[i] = 0; } - public void Init(IPool pool) { throw new NotSupportedException(); } - public void Release() { Index = default; diff --git a/OctoAwesome/OctoAwesome/ChunkColumn.cs b/OctoAwesome/OctoAwesome/ChunkColumn.cs index 9a10d1a5..563e7464 100644 --- a/OctoAwesome/OctoAwesome/ChunkColumn.cs +++ b/OctoAwesome/OctoAwesome/ChunkColumn.cs @@ -5,6 +5,7 @@ using OctoAwesome.Threading; using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; @@ -16,15 +17,9 @@ namespace OctoAwesome public class ChunkColumn : IChunkColumn { private readonly IGlobalChunkCache globalChunkCache; - - /// - /// Auflistung aller sich in dieser Column befindenden Entitäten. - /// private readonly IEntityList entities; - private readonly LockSemaphore entitieSemaphore; + private readonly LockSemaphore entitySemaphore; private static ChunkPool chunkPool; - - public IDefinitionManager DefinitionManager { get; } public int ChangeCounter { get; set; } @@ -53,7 +48,7 @@ public ChunkColumn(IPlanet planet) { Heights = new int[Chunk.CHUNKSIZE_X, Chunk.CHUNKSIZE_Y]; entities = new EntityList(this); - entitieSemaphore = new LockSemaphore(1, 1); + entitySemaphore = new LockSemaphore(1, 1); DefinitionManager = TypeContainer.Get(); Planet = planet; globalChunkCache = planet.GlobalChunkCache; @@ -96,7 +91,7 @@ private int GetTopBlockHeight(int x, int y) /// /// Höhen innerhalb der Chunk-Säule (oberste Blöcke) /// - public int[,] Heights { get; private set; } + public int[,] Heights { get; } /// /// Die Chunks der Säule. @@ -205,7 +200,6 @@ public void SetBlock(int x, int y, int z, ushort block, int meta = 0) z %= Chunk.CHUNKSIZE_Z; Chunks[index].SetBlock(x, y, z, block, meta); } - public void SetBlocks(bool issueNotification, params BlockInfo[] blockInfos) { foreach (var item in blockInfos.GroupBy(x => x.Position.Z / Chunk.CHUNKSIZE_Z)) @@ -258,7 +252,8 @@ public void Serialize(BinaryWriter writer) { if (chunk.Blocks[i] != 0) { - var definition = (IBlockDefinition)DefinitionManager.GetBlockDefinitionByIndex(chunk.Blocks[i]); + var definition = DefinitionManager.GetBlockDefinitionByIndex(chunk.Blocks[i]); + Debug.Assert(definition != null, nameof(definition) + " != null"); if (!definitions.Contains(definition)) definitions.Add(definition); } @@ -279,7 +274,7 @@ public void Serialize(BinaryWriter writer) for (var x = 0; x < Chunk.CHUNKSIZE_X; x++) writer.Write((ushort)Heights[x, y]); - // Schreibe Phase 2 (Block Definitionen) + // Serialization Phase 2 (Block definition) if (longIndex) writer.Write((ushort)definitions.Count); else @@ -306,21 +301,22 @@ public void Serialize(BinaryWriter writer) else { // Definition Index - var definition = (IBlockDefinition)DefinitionManager.GetBlockDefinitionByIndex(chunk.Blocks[i]); + var definition = DefinitionManager.GetBlockDefinitionByIndex(chunk.Blocks[i]); + Debug.Assert(definition != null, nameof(definition) + " != null"); if (longIndex) writer.Write((ushort)(definitions.IndexOf(definition) + 1)); else writer.Write((byte)(definitions.IndexOf(definition) + 1)); - // Meta Data + // Metadata if (definition.HasMetaData) writer.Write(chunk.MetaData[i]); } } } var resManager = TypeContainer.Get(); - using (var lockObj = entitieSemaphore.Wait()) + using (var lockObj = entitySemaphore.Wait()) { foreach (var entity in entities) resManager.SaveComponentContainer(entity); @@ -338,8 +334,8 @@ public void Deserialize(BinaryReader reader) { var longIndex = reader.ReadByte() > 0; - // Phase 1 (Column Meta: Heightmap, populated, chunkcount) - Chunks = new Chunk[reader.ReadByte()]; // Chunk Count + // Phase 1 (Column Meta: Heightmap, populated, chunk count) + Chunks = new IChunk[reader.ReadByte()]; // Chunk Count Populated = reader.ReadBoolean(); // Populated @@ -352,14 +348,11 @@ public void Deserialize(BinaryReader reader) for (var y = 0; y < Chunk.CHUNKSIZE_Y; y++) // Heightmap for (var x = 0; x < Chunk.CHUNKSIZE_X; x++) Heights[x, y] = reader.ReadUInt16(); - - + // Phase 2 (Block Definitionen) int typecount = longIndex ? reader.ReadUInt16() : reader.ReadByte(); var types = new List(); Span map = stackalloc ushort[typecount]; - - for (var i = 0; i < typecount; i++) { var typeName = reader.ReadString(); @@ -373,7 +366,7 @@ public void Deserialize(BinaryReader reader) // Phase 3 (Chunk Infos) for (var c = 0; c < Chunks.Length; c++) { - IChunk chunk = Chunks[c] = chunkPool.Get(new Index3(Index, c), Planet); + IChunk chunk = Chunks[c] = chunkPool.Rent(new Index3(Index, c), Planet); chunk.Version = reader.ReadInt32(); chunk.Changed += OnChunkChanged; chunk.SetColumn(this); @@ -396,12 +389,10 @@ public void Deserialize(BinaryReader reader) } } } - public void OnUpdate(SerializableNotification notification) { globalChunkCache.OnUpdate(notification); } - public void Update(SerializableNotification notification) { if (notification is IChunkNotification chunkNotification) @@ -411,10 +402,9 @@ public void Update(SerializableNotification notification) .Update(notification); } } - public void ForEachEntity(Action action) { - using (entitieSemaphore.Wait()) + using (entitySemaphore.Wait()) { foreach (var entity in entities) { @@ -422,25 +412,21 @@ public void ForEachEntity(Action action) } } } - public void Add(Entity entity) { - using (entitieSemaphore.Wait()) + using (entitySemaphore.Wait()) entities.Add(entity); } - public void Remove(Entity entity) { - using (entitieSemaphore.Wait()) + using (entitySemaphore.Wait()) entities.Remove(entity); } - public IEnumerable FailChunkEntity() { - using (entitieSemaphore.Wait()) + using (entitySemaphore.Wait()) return entities.FailChunkEntity().ToList(); } - public void FlagDirty() { if (Chunks is null) diff --git a/OctoAwesome/OctoAwesome/ClientType.cs b/OctoAwesome/OctoAwesome/ClientType.cs index b129d98d..32c0ef38 100644 --- a/OctoAwesome/OctoAwesome/ClientType.cs +++ b/OctoAwesome/OctoAwesome/ClientType.cs @@ -1,14 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome +namespace OctoAwesome { + public enum ClientType { + DesktopClient, + GameServer } } diff --git a/OctoAwesome/OctoAwesome/CollisionPlane.cs b/OctoAwesome/OctoAwesome/CollisionPlane.cs index c19f2c4c..46872c1f 100644 --- a/OctoAwesome/OctoAwesome/CollisionPlane.cs +++ b/OctoAwesome/OctoAwesome/CollisionPlane.cs @@ -1,5 +1,4 @@ using engenious; -using System; using System.Collections.Generic; namespace OctoAwesome @@ -47,57 +46,55 @@ public CollisionPlane(Vector3 pos1,Vector3 pos2, Vector3 normal) /// Position des Blockes /// Bewegungsvector /// Liste aller beteiligten Flächen - public static IEnumerable GetBlockCollisionPlanes(Index3 pos, Vector3 movevector) + public static IEnumerable GetBlockCollisionPlanes(Index3 pos, Vector3 moveVector) { //Ebene X - if (movevector.X > 0) + if (moveVector.X > 0) { yield return new CollisionPlane( new Vector3(pos.X, pos.Y, pos.Z), new Vector3(pos.X, pos.Y + 1f, pos.Z + 1f), - new Vector3(-1, 0, 0)); + new Vector3(-1, 0)); } - else if (movevector.X < 0) + else if (moveVector.X < 0) { yield return new CollisionPlane( new Vector3(pos.X + 1f, pos.Y, pos.Z), new Vector3(pos.X + 1f, pos.Y + 1f, pos.Z + 1f), - new Vector3(1, 0, 0)); + new Vector3(1, 0)); } //Ebene Y - if (movevector.Y > 0) + if (moveVector.Y > 0) { yield return new CollisionPlane( new Vector3(pos.X, pos.Y, pos.Z), new Vector3(pos.X + 1f, pos.Y, pos.Z + 1f), - new Vector3(0, -1, 0)); + new Vector3(0, -1)); } - else if (movevector.Y < 0) + else if (moveVector.Y < 0) { yield return new CollisionPlane( new Vector3(pos.X , pos.Y + 1f, pos.Z), new Vector3(pos.X + 1f, pos.Y + 1f, pos.Z + 1f), - new Vector3(0, 1, 0)); + new Vector3(0, 1)); } //Ebene Z - if (movevector.Z > 0) + if (moveVector.Z > 0) { yield return new CollisionPlane( new Vector3(pos.X, pos.Y , pos.Z ), new Vector3(pos.X + 1f, pos.Y + 1f , pos.Z ), new Vector3(0,0, -1)); } - else if (movevector.Z < 0) + else if (moveVector.Z < 0) { yield return new CollisionPlane( new Vector3(pos.X , pos.Y , pos.Z + 1f), new Vector3(pos.X + 1f, pos.Y +1f, pos.Z + 1f), new Vector3(0, 0, 1)); } - - } /// @@ -110,25 +107,25 @@ public static IEnumerable GetBlockCollisionPlanes(Index3 pos, Ve /// Gibt an ob die geschwindigkeit invertiert werden soll /// public static IEnumerable GetEntityCollisionPlanes(float radius, float height, Vector3 velocity, - Coordinate coordinate, bool invertvelocity = true) + Coordinate coordinate, bool invertVelocity = true) { var pos = coordinate.BlockPosition; - Vector3 vel = invertvelocity ? new Vector3(-velocity.X, -velocity.Y, - velocity.Z) : velocity; + Vector3 vel = invertVelocity ? new Vector3(-velocity.X, -velocity.Y, - velocity.Z) : velocity; //Ebene X - if (vel.X > 0) + if (vel.X > 0) { yield return new CollisionPlane( new Vector3(pos.X - radius, pos.Y - radius, pos.Z), new Vector3(pos.X - radius, pos.Y + radius, pos.Z + height), - new Vector3(-1, 0, 0)); + new Vector3(-1, 0)); } else if (vel.X < 0) { yield return new CollisionPlane( new Vector3(pos.X + radius, pos.Y - radius, pos.Z), new Vector3(pos.X + radius, pos.Y + radius, pos.Z + height), - new Vector3(1, 0, 0)); + new Vector3(1, 0)); } //Ebene Y @@ -137,14 +134,14 @@ public static IEnumerable GetEntityCollisionPlanes(float radius, yield return new CollisionPlane( new Vector3(pos.X - radius, pos.Y - radius, pos.Z ), new Vector3(pos.X + radius, pos.Y - radius, pos.Z + height), - new Vector3(0, -1, 0)); + new Vector3(0, -1)); } else if (vel.Y < 0) { yield return new CollisionPlane( new Vector3(pos.X - radius, pos.Y + radius, pos.Z ), new Vector3(pos.X + radius, pos.Y + radius, pos.Z + height), - new Vector3(0, 1, 0)); + new Vector3(0, 1)); } //Ebene Z @@ -202,8 +199,6 @@ public static bool Intersect(CollisionPlane p1, CollisionPlane p2) (p2.edgepos2.Z < p1.edgepos2.Z && p2.edgepos2.Z > p1.edgepos1.Z) || (p1.edgepos1.Z > p2.edgepos1.Z && p1.edgepos1.Z < p2.edgepos2.Z) || (p1.edgepos2.Z < p2.edgepos2.Z && p1.edgepos2.Z > p2.edgepos1.Z); - - result = rx && rz; } else if (vec.Z < 0) @@ -233,14 +228,12 @@ public static bool Intersect(CollisionPlane p1, CollisionPlane p2) public static Vector3 GetDistance(CollisionPlane p1, CollisionPlane p2) { var alpha = p1.normal * p2.normal; + var dVector = new Vector3(); + dVector.X = alpha.X != 0 ? 1 : 0; + dVector.Y = alpha.Y != 0 ? 1 : 0; + dVector.Z = alpha.Z != 0 ? 1 : 0; - - var dvector = new Vector3(); - dvector.X = alpha.X != 0 ? 1 : 0; - dvector.Y = alpha.Y != 0 ? 1 : 0; - dvector.Z = alpha.Z != 0 ? 1 : 0; - - var distance = (p1.pos - p2.pos) * dvector; + var distance = (p1.pos - p2.pos) * dVector; return distance; } @@ -262,8 +255,6 @@ public static bool CheckDistance(Vector3 d1, Vector3 d2) var rx = d1.X > 0 ? diff.X < 0 : diff.X > 0; var ry = d1.Y > 0 ? diff.Y < 0 : diff.Y > 0; var rz = d1.Z > 0 ? diff.Z < 0 : diff.Z > 0; - - return rx || ry || rz; } diff --git a/OctoAwesome/OctoAwesome/ComponentContainer.cs b/OctoAwesome/OctoAwesome/ComponentContainer.cs index 213d4573..e2925e77 100644 --- a/OctoAwesome/OctoAwesome/ComponentContainer.cs +++ b/OctoAwesome/OctoAwesome/ComponentContainer.cs @@ -6,13 +6,11 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { - public abstract class ComponentContainer: ISerializable, IIdentification, IContainsComponents, INotificationSubject + + public abstract class ComponentContainer : ISerializable, IIdentification, IComponentContainer, INotificationSubject { /// /// Id @@ -22,7 +20,7 @@ public abstract class ComponentContainer: ISerializable, IIdentification, IConta /// /// Reference to the active Simulation. /// - public Simulation Simulation { get; internal set; } + public Simulation? Simulation { get; internal set; } /// /// Contains only Components with notification interface implementation. @@ -32,56 +30,49 @@ public abstract class ComponentContainer: ISerializable, IIdentification, IConta /// /// Entity die regelmäßig eine Updateevent bekommt /// - public ComponentContainer() + protected ComponentContainer() { notificationComponents = new(); Id = Guid.Empty; } - public virtual void RegisterDefault() { } - public override int GetHashCode() => Id.GetHashCode(); - - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is Entity entity) return entity.Id == Id; - return base.Equals(obj); + return ReferenceEquals(this, obj); } - public virtual void OnNotification(SerializableNotification notification) { } - public virtual void Push(SerializableNotification notification) { foreach (var component in notificationComponents) component?.OnNotification(notification); } - public abstract void Serialize(BinaryWriter writer); public abstract void Deserialize(BinaryReader reader); public abstract bool ContainsComponent(); - public abstract T GetComponent(); + public abstract T? GetComponent(); } - public abstract class ComponentContainer : ComponentContainer where TComponent : IComponent { /// /// Contains all Components. /// - public ComponentList Components { get; private set; } - + public ComponentList Components { get; } + /// /// Entity die regelmäßig eine Updateevent bekommt /// - public ComponentContainer() : base() + protected ComponentContainer() { Components = new(ValidateAddComponent, ValidateRemoveComponent, OnAddComponent, OnRemoveComponent); } @@ -113,22 +104,20 @@ protected virtual void OnAddComponent(TComponent component) if (component is INotificationSubject nofiticationComponent) notificationComponents.Add(nofiticationComponent); } - protected virtual void ValidateAddComponent(TComponent component) { if (Simulation is not null) throw new NotSupportedException("Can't add components during simulation"); } - protected virtual void ValidateRemoveComponent(TComponent component) { if (Simulation is not null) throw new NotSupportedException("Can't remove components during simulation"); } - public void Initialize(IResourceManager mananger) + public void Initialize(IResourceManager manager) { - OnInitialize(mananger); + OnInitialize(manager); } protected virtual void OnInitialize(IResourceManager manager) @@ -171,10 +160,9 @@ public override void Deserialize(BinaryReader reader) Id = new Guid(reader.ReadBytes(16)); Components.Deserialize(reader); } - public override bool ContainsComponent() => Components.ContainsComponent(); - public override T GetComponent() + public override T? GetComponent() where T : default => Components.GetComponent(); } } diff --git a/OctoAwesome/OctoAwesome/Components/Comparer.cs b/OctoAwesome/OctoAwesome/Components/Comparer.cs deleted file mode 100644 index bdbb4873..00000000 --- a/OctoAwesome/OctoAwesome/Components/Comparer.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; - -namespace OctoAwesome.Components -{ - public struct Comparer : IEquatable>, IEquatable - { - public TOriginal Value { get; set; } - - private readonly Func compareFunc; - - public Comparer(TOriginal value, Func compareFunc) - { - Value = value; - this.compareFunc = compareFunc; - } - - public override bool Equals(object obj) - => (obj is Comparer comparer && Equals(comparer)) - || (obj is TSelected rigth && Equals(rigth)) - || obj is TOriginal left && Equals(left); - - public bool Equals(Comparer other) - => Equals(other.Value); - - public bool Equals(TOriginal other) - => Equals(Value, other); - - public bool Equals(TSelected other) - => compareFunc(Value, other); - - public override int GetHashCode() - => Value.GetHashCode(); - - public static bool operator ==(Comparer left, Comparer right) - => left.Equals(right); - public static bool operator !=(Comparer left, Comparer right) - => !(left == right); - - public static bool operator ==(TOriginal left, Comparer right) - => right.Equals(left); - public static bool operator !=(TOriginal left, Comparer right) - => !(left == right); - - public static bool operator ==(Comparer left, TOriginal right) - => left.Equals(right); - public static bool operator !=(Comparer left, TOriginal right) - => !(left == right); - - public static bool operator ==(TSelected left, Comparer right) - => right.Equals(left); - public static bool operator !=(TSelected left, Comparer right) - => !(left == right); - - public static bool operator ==(Comparer left, TSelected right) - => left.Equals(right); - public static bool operator !=(Comparer left, TSelected right) - => !(left == right); - - public static implicit operator TOriginal(Comparer comparer) - => comparer.Value; - - public static implicit operator Comparer((TOriginal value, Func comparer) tuple) - => new Comparer(tuple.value, tuple.comparer); - - public static implicit operator (TOriginal value, Func comparer)(Comparer comparer) - => (comparer.Value, comparer.compareFunc); - } -} - diff --git a/OctoAwesome/OctoAwesome/Components/Component.cs b/OctoAwesome/OctoAwesome/Components/Component.cs index 2850182a..72621e1a 100644 --- a/OctoAwesome/OctoAwesome/Components/Component.cs +++ b/OctoAwesome/OctoAwesome/Components/Component.cs @@ -1,5 +1,4 @@ using OctoAwesome.Components; -using OctoAwesome.Serialization; using System.IO; using System.Runtime.CompilerServices; @@ -10,10 +9,10 @@ namespace OctoAwesome /// public abstract class Component : IComponent { + public bool Enabled { get; set; } public bool Sendable { get; set; } - - public Component() + protected Component() { Enabled = true; Sendable = false; @@ -37,12 +36,11 @@ public virtual void Deserialize(BinaryReader reader) Enabled = reader.ReadBoolean(); } - protected virtual void OnPropertyChanged(T value, string callerName) + protected virtual void OnPropertyChanged(T value, string propertyName) { } - - protected void SetValue(ref T field, T value, [CallerMemberName]string callerName = "") + protected void SetValue(ref T field, T value, [CallerMemberName] string propertyName = "") { if (field != null) { @@ -52,7 +50,7 @@ protected void SetValue(ref T field, T value, [CallerMemberName]string caller field = value; - OnPropertyChanged(field, callerName); + OnPropertyChanged(field, propertyName); } } } diff --git a/OctoAwesome/OctoAwesome/Components/ComponentList.cs b/OctoAwesome/OctoAwesome/Components/ComponentList.cs index f27d5823..8761f5c3 100644 --- a/OctoAwesome/OctoAwesome/Components/ComponentList.cs +++ b/OctoAwesome/OctoAwesome/Components/ComponentList.cs @@ -1,9 +1,9 @@ using OctoAwesome.Components; using OctoAwesome.Serialization; -using OpenTK.Graphics.OpenGL; using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using OctoAwesome.Caching; @@ -23,21 +23,10 @@ public class ComponentList : IEnumerable where T : IComponent, ISerializab private readonly Dictionary components = new Dictionary(); - public T this[Type type] - { - get - { - if (components.TryGetValue(type, out T result)) - return result; - - return default; - } - } - + public T? this[Type type] => components.TryGetValue(type, out var result) ? result : default; public ComponentList() { } - public ComponentList(Action insertValidator, Action removeValidator, Action onInserter, Action onRemover) { this.insertValidator = insertValidator; @@ -45,7 +34,6 @@ public ComponentList(Action insertValidator, Action removeValidator, Actio this.onInserter = onInserter; this.onRemover = onRemover; } - public IEnumerator GetEnumerator() => components.Values.GetEnumerator(); @@ -108,24 +96,23 @@ public bool ContainsComponent() /// True if the component was found, false otherwise public bool TryGetComponent(out V component) where V : T { - var contains = components.TryGetValue(typeof(V), out T result); + var contains = components.TryGetValue(typeof(V), out var result); component = default; if (!contains) return contains; - component = GenericCaster.Cast(result); + component = GenericCaster.Cast(result!); return contains; } - /// /// Returns the Component of the given Type or null /// /// Component Type /// Component - public V GetComponent() + public V? GetComponent() { - if (components.TryGetValue(typeof(V), out T result)) + if (components.TryGetValue(typeof(V), out var result)) return (V)(object)result; return default; @@ -138,7 +125,7 @@ public V GetComponent() /// public bool RemoveComponent() where V : T { - if (!components.TryGetValue(typeof(V), out T component)) + if (!components.TryGetValue(typeof(V), out var component)) return false; removeValidator?.Invoke(component); @@ -179,9 +166,7 @@ public virtual void Deserialize(BinaryReader reader) var type = Type.GetType(name); - T component; - - if (!components.TryGetValue(type, out component)) + if (!components.TryGetValue(type, out var component)) { component = (T)TypeContainer.GetUnregistered(type); //components.Add(type, component); diff --git a/OctoAwesome/OctoAwesome/Components/IComponent.cs b/OctoAwesome/OctoAwesome/Components/IComponent.cs index f05a6b0f..255ecde8 100644 --- a/OctoAwesome/OctoAwesome/Components/IComponent.cs +++ b/OctoAwesome/OctoAwesome/Components/IComponent.cs @@ -1,14 +1,11 @@ using OctoAwesome.Serialization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Components { + public interface IComponent : ISerializable { + bool Sendable { get; set; } bool Enabled { get; set; } } diff --git a/OctoAwesome/OctoAwesome/Components/IComponentContainer.cs b/OctoAwesome/OctoAwesome/Components/IComponentContainer.cs new file mode 100644 index 00000000..192664f9 --- /dev/null +++ b/OctoAwesome/OctoAwesome/Components/IComponentContainer.cs @@ -0,0 +1,9 @@ +namespace OctoAwesome.Components +{ + public interface IComponentContainer + { + bool ContainsComponent(); + + T? GetComponent(); + } +} diff --git a/OctoAwesome/OctoAwesome/Components/IContainsComponents.cs b/OctoAwesome/OctoAwesome/Components/IContainsComponents.cs deleted file mode 100644 index 0ad57e5c..00000000 --- a/OctoAwesome/OctoAwesome/Components/IContainsComponents.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Components -{ - public interface IContainsComponents - { - bool ContainsComponent(); - - T GetComponent(); - } -} diff --git a/OctoAwesome/OctoAwesome/Components/IEntityComponent.cs b/OctoAwesome/OctoAwesome/Components/IEntityComponent.cs index 62b6710f..6d0281a8 100644 --- a/OctoAwesome/OctoAwesome/Components/IEntityComponent.cs +++ b/OctoAwesome/OctoAwesome/Components/IEntityComponent.cs @@ -1,12 +1,6 @@ -using OctoAwesome.Notifications; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Components +namespace OctoAwesome.Components { + public interface IEntityComponent : IComponent { } diff --git a/OctoAwesome/OctoAwesome/Components/IEntityNotificationComponent.cs b/OctoAwesome/OctoAwesome/Components/IEntityNotificationComponent.cs index 892ce52c..d586938c 100644 --- a/OctoAwesome/OctoAwesome/Components/IEntityNotificationComponent.cs +++ b/OctoAwesome/OctoAwesome/Components/IEntityNotificationComponent.cs @@ -1,12 +1,8 @@ using OctoAwesome.Notifications; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Components { + public interface IEntityNotificationComponent : IEntityComponent, INotificationSubject { } diff --git a/OctoAwesome/OctoAwesome/Components/IFunctionalBlockComponent.cs b/OctoAwesome/OctoAwesome/Components/IFunctionalBlockComponent.cs index 4ea8be30..9bef5483 100644 --- a/OctoAwesome/OctoAwesome/Components/IFunctionalBlockComponent.cs +++ b/OctoAwesome/OctoAwesome/Components/IFunctionalBlockComponent.cs @@ -1,11 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Components +namespace OctoAwesome.Components { + public interface IFunctionalBlockComponent : IComponent { } diff --git a/OctoAwesome/OctoAwesome/Components/IHoldComponent.cs b/OctoAwesome/OctoAwesome/Components/IHoldComponent.cs index 120d14cf..79b05802 100644 --- a/OctoAwesome/OctoAwesome/Components/IHoldComponent.cs +++ b/OctoAwesome/OctoAwesome/Components/IHoldComponent.cs @@ -1,14 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Components +namespace OctoAwesome.Components { - public interface IHoldComponent + public interface IHoldComponent { void Add(T value); + void Remove(T value); } } diff --git a/OctoAwesome/OctoAwesome/Components/SimulationComponent.cs b/OctoAwesome/OctoAwesome/Components/SimulationComponent.cs index 8bbdf340..2a7e105c 100644 --- a/OctoAwesome/OctoAwesome/Components/SimulationComponent.cs +++ b/OctoAwesome/OctoAwesome/Components/SimulationComponent.cs @@ -1,10 +1,5 @@ using engenious; -using OctoAwesome.EntityComponents; using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Components { @@ -90,68 +85,63 @@ public void Remove(T value) /// Ergebnis protected abstract void OnRemove(T value); } - /// /// Basisklasse für Simulationskomponenten /// - public abstract class SimulationComponent : SimulationComponent, IHoldComponent - where T : IContainsComponents - where S : SimulationComponentRecord - where C1 : Component + public abstract class SimulationComponent : SimulationComponent, IHoldComponent + where TContainer : IComponentContainer + where TCachedContainer : SimulationComponentRecord + where TComponent : Component { - - protected readonly List values = new(); - + protected readonly List values = new(); + /// /// Adds a new value of to this Component /// /// an instance of to add - public void Add(T value) + public void Add(TContainer value) { if (Match(value)) { values.Add(OnAdd(value)); } } - - + /// /// Is called during to convert from to /// /// instance of that is passed to /// Converted as - protected virtual S OnAdd(T value) - => (S)new SimulationComponentRecord(value, value.GetComponent()); - + protected virtual TCachedContainer OnAdd(TContainer value) + => (TCachedContainer)new SimulationComponentRecord(value, value.GetComponent()); + /// /// Removes an instance of that is previouse added with /// /// an instance of to Remove - public void Remove(T value) + public void Remove(TContainer value) { OnRemove(value); values.RemoveAll(c => Compare(c, value)); } - /// /// Is called during to convert from to /// /// instance of that is passed to /// Converted as - protected virtual void OnRemove(T value) { } + protected virtual void OnRemove(TContainer value) { } - protected virtual bool Compare(S left, T right) + protected virtual bool Compare(TCachedContainer left, TContainer right) => Equals(left.Value, right); - /// /// Führt ein Vergleich durch, ob diese Entity in die Komponente eingefügt werden kann /// /// Vergleichsentity /// Ergebnis des Vergleiches - protected virtual bool Match(T value) - => value.ContainsComponent(); - + protected virtual bool Match(TContainer value) + => value.ContainsComponent(); + /// /// Updatemethode der Entity /// @@ -161,32 +151,30 @@ public override void Update(GameTime gameTime) foreach (var value in values) UpdateValue(gameTime, value); } - /// /// Internes Event, für das Updaten der Simulationskomponente /// /// Spielzeit /// Entity die geupdatet werden muss - protected abstract void UpdateValue(GameTime gameTime, S value); + protected abstract void UpdateValue(GameTime gameTime, TCachedContainer value); } /// /// Basisklasse für Simulationskomponenten /// - public abstract class SimulationComponent : SimulationComponent, IHoldComponent - where T : IContainsComponents - where S : SimulationComponentRecord - where C1 : Component - where C2 : Component + public abstract class SimulationComponent : SimulationComponent, IHoldComponent + where TContainer : IComponentContainer + where TCachedContainer : SimulationComponentRecord + where TComponent1 : Component + where TComponent2 : Component { - protected readonly List values = new(); - + protected readonly List values = new(); /// /// Adds a new value of to this Component /// /// an instance of to add - public void Add(T value) + public void Add(TContainer value) { if (Match(value)) { @@ -199,14 +187,14 @@ public void Add(T value) /// /// instance of that is passed to /// Converted as - protected virtual S OnAdd(T value) - => (S)new SimulationComponentRecord(value, value.GetComponent(), value.GetComponent()); - + protected virtual TCachedContainer OnAdd(TContainer value) + => (TCachedContainer)new SimulationComponentRecord(value, value.GetComponent(), value.GetComponent()); + /// /// Removes an instance of that is previouse added with /// /// an instance of to Remove - public void Remove(T value) + public void Remove(TContainer value) { OnRemove(value); values.RemoveAll(c => Compare(c, value)); @@ -217,9 +205,9 @@ public void Remove(T value) /// /// instance of that is passed to /// Converted as - protected virtual void OnRemove(T value) { } + protected virtual void OnRemove(TContainer value) { } - protected virtual bool Compare(S left, T right) + protected virtual bool Compare(TCachedContainer left, TContainer right) => Equals(left.Value, right); /// @@ -227,9 +215,9 @@ protected virtual bool Compare(S left, T right) /// /// Vergleichsentity /// Ergebnis des Vergleiches - protected virtual bool Match(T value) - => value.ContainsComponent() - && value.ContainsComponent(); + protected virtual bool Match(TContainer value) + => value.ContainsComponent() + && value.ContainsComponent(); /// /// Updatemethode der Entity @@ -247,28 +235,27 @@ public override void Update(GameTime gameTime) /// /// Spielzeit /// Entity die geupdatet werden muss - protected abstract void UpdateValue(GameTime gameTime, S value); + protected abstract void UpdateValue(GameTime gameTime, TCachedContainer value); } /// /// Basisklasse für Simulationskomponenten /// - public abstract class SimulationComponent : SimulationComponent, IHoldComponent - where T : IContainsComponents - where S : SimulationComponentRecord - where C1 : Component - where C2 : Component - where C3 : Component + public abstract class SimulationComponent : SimulationComponent, IHoldComponent + where TContainer : IComponentContainer + where TCachedContainer : SimulationComponentRecord + where TComponent1 : Component + where TComponent2 : Component + where TComponent3 : Component { - - protected readonly List values = new(); - + protected readonly List values = new(); + /// /// Adds a new value of to this Component /// /// an instance of to add - public void Add(T value) + public void Add(TContainer value) { if (Match(value)) { @@ -282,14 +269,14 @@ public void Add(T value) /// /// instance of that is passed to /// Converted as - protected virtual S OnAdd(T value) - => (S)new SimulationComponentRecord(value, value.GetComponent(), value.GetComponent(), value.GetComponent()); - + protected virtual TCachedContainer OnAdd(TContainer value) + => (TCachedContainer)new SimulationComponentRecord(value, value.GetComponent(), value.GetComponent(), value.GetComponent()); + /// /// Removes an instance of that is previouse added with /// /// an instance of to Remove - public void Remove(T value) + public void Remove(TContainer value) { OnRemove(value); values.RemoveAll(c => Compare(c, value)); @@ -300,10 +287,8 @@ public void Remove(T value) /// /// instance of that is passed to /// Converted as - protected virtual void OnRemove(T value) { } - - - protected virtual bool Compare(S left, T right) + protected virtual void OnRemove(TContainer value) { } + protected virtual bool Compare(TCachedContainer left, TContainer right) => Equals(left.Value, right); /// @@ -311,10 +296,10 @@ protected virtual bool Compare(S left, T right) /// /// Vergleichsentity /// Ergebnis des Vergleiches - protected virtual bool Match(T value) - => value.ContainsComponent() - && value.ContainsComponent() - && value.ContainsComponent(); + protected virtual bool Match(TContainer value) + => value.ContainsComponent() + && value.ContainsComponent() + && value.ContainsComponent(); /// /// Updatemethode der Entity @@ -332,12 +317,11 @@ public override void Update(GameTime gameTime) /// /// Spielzeit /// Entity die geupdatet werden muss - protected abstract void UpdateValue(GameTime gameTime, S value); + protected abstract void UpdateValue(GameTime gameTime, TCachedContainer value); } - - public record SimulationComponentRecord(T Value, C1 Component); - public record SimulationComponentRecord(T Value, C1 Component1, C2 Component2); - public record SimulationComponentRecord(T Value, C1 Component1, C2 Component2, C3 Component3); + public record SimulationComponentRecord(TContainer Value, TComponent Component); + public record SimulationComponentRecord(TContainer Value, TComponent1 Component1, TComponent2 Component2); + public record SimulationComponentRecord(TContainer Value, TComponent1 Component1, TComponent2 Component2, TComponent3 Component3); } diff --git a/OctoAwesome/OctoAwesome/Coordinate.cs b/OctoAwesome/OctoAwesome/Coordinate.cs index 69c599fd..57c2386c 100644 --- a/OctoAwesome/OctoAwesome/Coordinate.cs +++ b/OctoAwesome/OctoAwesome/Coordinate.cs @@ -44,11 +44,9 @@ public Coordinate(int planet, Index3 block, Vector3 position) [XmlIgnore] public Index3 ChunkIndex { - get - { - return new Index3(block.X >> Chunk.LimitX, block.Y >> Chunk.LimitY, + get => + new Index3(block.X >> Chunk.LimitX, block.Y >> Chunk.LimitY, block.Z >> Chunk.LimitZ); - } set { Index3 localBlockIndex = LocalBlockIndex; @@ -99,13 +97,11 @@ public Index3 LocalBlockIndex [XmlIgnore] public Vector3 GlobalPosition { - get - { - return new Vector3( + get => + new Vector3( block.X + position.X, block.Y + position.Y, block.Z + position.Z); - } set { block = Index3.Zero; @@ -145,7 +141,7 @@ public Vector3 LocalPosition /// public Vector3 BlockPosition { - get { return position; } + get => position; set { position = value; @@ -206,25 +202,23 @@ public void NormalizeChunkIndexXY(Index3 limit) /// Stellt die Coordinate-Instanz als string dar. /// /// - public override string ToString() => $@"({ Planet }/{(block.X + position.X).ToString("0.000000")}/{(block.Y + position.Y).ToString("0.000000")}/{(block.Z + position.Z).ToString("0.000000")})"; + public override string ToString() => $@"({ Planet }/{(block.X + position.X):0.000000}/{(block.Y + position.Y):0.000000}/{(block.Z + position.Z):0.000000})"; /// /// Compare this object with an other object /// /// a other object /// true if both objects are equal - public override bool Equals(object obj) + public override bool Equals(object? obj) { - if(obj is Coordinate coordinate) - return base.Equals(obj) || - ( Planet == coordinate.Planet && - position == coordinate.position && - block == coordinate.block - ); + if (obj is Coordinate coordinate) + return (Planet == coordinate.Planet && + position == coordinate.position && + block == coordinate.block + ); return base.Equals(obj); } - public override int GetHashCode() => base.GetHashCode(); } } diff --git a/OctoAwesome/OctoAwesome/Definitions/BlockDefinition.cs b/OctoAwesome/OctoAwesome/Definitions/BlockDefinition.cs index 1aac6501..866676df 100644 --- a/OctoAwesome/OctoAwesome/Definitions/BlockDefinition.cs +++ b/OctoAwesome/OctoAwesome/Definitions/BlockDefinition.cs @@ -1,6 +1,4 @@ -using System.Drawing; -using engenious; -using System.Collections.Generic; +using engenious; using OctoAwesome.Information; using OctoAwesome.Services; using System; @@ -12,6 +10,7 @@ namespace OctoAwesome.Definitions /// public abstract class BlockDefinition : IBlockDefinition { + public virtual uint SolidWall => 0x3f; /// @@ -33,7 +32,6 @@ public abstract class BlockDefinition : IBlockDefinition /// Gibt das Volumen für eine Einheit an. /// public virtual int VolumePerUnit => 125; - public virtual int VolumePerHit => 25; /// @@ -45,7 +43,6 @@ public abstract class BlockDefinition : IBlockDefinition /// Zeigt, ob der Block-Typ Metadaten besitzt /// public virtual bool HasMetaData => false; - public virtual TimeSpan TimeToVolumeReset { get; } = TimeSpan.FromSeconds(10); /// @@ -78,11 +75,8 @@ public virtual BlockHitInformation Hit(BlockVolumeState blockVolume, IItem item) /// Ein Array von Kollisionsboxen public virtual BoundingBox[] GetCollisionBoxes(ILocalChunkCache manager, int x, int y, int z) => defaultCollisionBoxes; - public virtual int GetTextureIndex(Wall wall, ILocalChunkCache manager, int x, int y, int z) => 0; - public virtual int GetTextureRotation(Wall wall, ILocalChunkCache manager, int x, int y, int z) => 0; - public bool IsSolidWall(Wall wall) => (SolidWall & (1 << (int)wall)) != 0; } diff --git a/OctoAwesome/OctoAwesome/Definitions/IBlockDefinition.cs b/OctoAwesome/OctoAwesome/Definitions/IBlockDefinition.cs index 4d6404a8..1f915d27 100644 --- a/OctoAwesome/OctoAwesome/Definitions/IBlockDefinition.cs +++ b/OctoAwesome/OctoAwesome/Definitions/IBlockDefinition.cs @@ -62,7 +62,8 @@ public interface IBlockDefinition : IInventoryable, IDefinition uint SolidWall { get; } TimeSpan TimeToVolumeReset { get; } IMaterialDefinition Material { get; } - bool IsSolidWall(Wall wall); + + int VolumePerHit { get; } } } diff --git a/OctoAwesome/OctoAwesome/Definitions/IDefinitionManager.cs b/OctoAwesome/OctoAwesome/Definitions/IDefinitionManager.cs index b91cf3e7..46a8f12d 100644 --- a/OctoAwesome/OctoAwesome/Definitions/IDefinitionManager.cs +++ b/OctoAwesome/OctoAwesome/Definitions/IDefinitionManager.cs @@ -31,8 +31,9 @@ public interface IDefinitionManager /// /// Index der BlockDefinition /// BlockDefinition - IBlockDefinition GetBlockDefinitionByIndex(ushort index); - T GetDefinitionByTypeName(string typeName) where T : IDefinition; + IBlockDefinition? GetBlockDefinitionByIndex(ushort index); + + T? GetDefinitionByTypeName(string typeName) where T : IDefinition; /// /// Liefert den Index der angegebenen BlockDefinition. diff --git a/OctoAwesome/OctoAwesome/Definitions/IFluidMaterialDefinition.cs b/OctoAwesome/OctoAwesome/Definitions/IFluidMaterialDefinition.cs index 8d88177d..5c2ebcf3 100644 --- a/OctoAwesome/OctoAwesome/Definitions/IFluidMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome/Definitions/IFluidMaterialDefinition.cs @@ -1,11 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Definitions +namespace OctoAwesome.Definitions { + public interface IFluidMaterialDefinition : IMaterialDefinition { /// diff --git a/OctoAwesome/OctoAwesome/Definitions/IGasMaterialDefinition.cs b/OctoAwesome/OctoAwesome/Definitions/IGasMaterialDefinition.cs index c47a724e..96f7844f 100644 --- a/OctoAwesome/OctoAwesome/Definitions/IGasMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome/Definitions/IGasMaterialDefinition.cs @@ -1,11 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Definitions +namespace OctoAwesome.Definitions { + public interface IGasMaterialDefinition : IMaterialDefinition { } diff --git a/OctoAwesome/OctoAwesome/Definitions/IItem.cs b/OctoAwesome/OctoAwesome/Definitions/IItem.cs index e8cdf82e..453f47dd 100644 --- a/OctoAwesome/OctoAwesome/Definitions/IItem.cs +++ b/OctoAwesome/OctoAwesome/Definitions/IItem.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace OctoAwesome.Definitions +namespace OctoAwesome.Definitions { /// /// Interface, das ein Item darstellt diff --git a/OctoAwesome/OctoAwesome/Definitions/IItemDefinition.cs b/OctoAwesome/OctoAwesome/Definitions/IItemDefinition.cs index 63255f7e..e4272f37 100644 --- a/OctoAwesome/OctoAwesome/Definitions/IItemDefinition.cs +++ b/OctoAwesome/OctoAwesome/Definitions/IItemDefinition.cs @@ -1,6 +1,4 @@ using OctoAwesome.Definitions.Items; -using OctoAwesome.Information; -using System; namespace OctoAwesome.Definitions { @@ -9,6 +7,7 @@ namespace OctoAwesome.Definitions /// public interface IItemDefinition : IDefinition { + bool CanMineMaterial(IMaterialDefinition material); Item Create(IMaterialDefinition material); } diff --git a/OctoAwesome/OctoAwesome/Definitions/ISolidMaterialDefinition.cs b/OctoAwesome/OctoAwesome/Definitions/ISolidMaterialDefinition.cs index 24d16ace..a2c91109 100644 --- a/OctoAwesome/OctoAwesome/Definitions/ISolidMaterialDefinition.cs +++ b/OctoAwesome/OctoAwesome/Definitions/ISolidMaterialDefinition.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Definitions +namespace OctoAwesome.Definitions { public interface ISolidMaterialDefinition : IMaterialDefinition { diff --git a/OctoAwesome/OctoAwesome/Definitions/Items/Hand.cs b/OctoAwesome/OctoAwesome/Definitions/Items/Hand.cs index 325a7643..fbe28b4d 100644 --- a/OctoAwesome/OctoAwesome/Definitions/Items/Hand.cs +++ b/OctoAwesome/OctoAwesome/Definitions/Items/Hand.cs @@ -1,18 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Definitions.Items +namespace OctoAwesome.Definitions.Items { + public class Hand : Item { public Hand(HandDefinition handDefinition) : base(handDefinition, null) { } - public override int Hit(IMaterialDefinition material, BlockInfo blockInfo, decimal volumeRemaining, int volumePerHit) { if(material is ISolidMaterialDefinition solidMaterial) diff --git a/OctoAwesome/OctoAwesome/Definitions/Items/HandDefinition.cs b/OctoAwesome/OctoAwesome/Definitions/Items/HandDefinition.cs index d83e29c6..610178a2 100644 --- a/OctoAwesome/OctoAwesome/Definitions/Items/HandDefinition.cs +++ b/OctoAwesome/OctoAwesome/Definitions/Items/HandDefinition.cs @@ -1,39 +1,19 @@ -using OctoAwesome.Information; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Definitions.Items +namespace OctoAwesome.Definitions.Items { + public class HandDefinition : IItemDefinition { - public int VolumePerUnit { get; } - - public int StackLimit { get; } - - public string Name { get; } - - public string Icon { get; } + public string Name => nameof(Hand); + public string Icon => ""; private readonly Hand hand; - public HandDefinition() { - VolumePerUnit = 0; - StackLimit = 0; - Name = nameof(Hand); - Icon = ""; hand = new Hand(this); } - public bool CanMineMaterial(IMaterialDefinition material) => true; - public Item Create(IMaterialDefinition material) => hand; - - public void Hit(IItem item, IBlockDefinition blockDefinition, BlockHitInformation blockHit) { } } } diff --git a/OctoAwesome/OctoAwesome/Definitions/Items/Item.cs b/OctoAwesome/OctoAwesome/Definitions/Items/Item.cs index 4883a2fd..23098d45 100644 --- a/OctoAwesome/OctoAwesome/Definitions/Items/Item.cs +++ b/OctoAwesome/OctoAwesome/Definitions/Items/Item.cs @@ -1,7 +1,6 @@ using engenious; using OctoAwesome.Serialization; using System; -using System.Collections.Generic; using System.IO; namespace OctoAwesome.Definitions.Items @@ -20,13 +19,9 @@ public abstract class Item : IItem, IInventoryable, ISerializable /// Die Koordinate, an der das Item in der Welt herumliegt, falls es nicht im Inventar ist /// public Coordinate? Position { get; set; } - - public IItemDefinition Definition { get; protected set; } - - public IMaterialDefinition Material { get; protected set; } - + public IItemDefinition Definition { get; private set; } + public IMaterialDefinition Material { get; private set; } public virtual int VolumePerUnit => 1; - public virtual int StackLimit => 1; private readonly IDefinitionManager definitionManager; @@ -42,7 +37,6 @@ public Item(IItemDefinition definition, IMaterialDefinition material) definitionManager = TypeContainer.Get(); } - public virtual int Hit(IMaterialDefinition material, BlockInfo blockInfo, decimal volumeRemaining, int volumePerHit) { //TODO Condition Berechnung @@ -62,7 +56,6 @@ public virtual int Hit(IMaterialDefinition material, BlockInfo blockInfo, decima //(Hardness Effectivity + Fracture Effectivity) / 2 return ((Material.Hardness - material.Hardness) * 3 + 100) * volumePerHit / 100; } - public virtual void Serialize(BinaryWriter writer) { writer.Write(Definition.GetType().FullName!); @@ -126,7 +119,8 @@ public static Item Deserialize(BinaryReader reader, Type itemType, IDefinitionMa var definition = manager.GetDefinitionByTypeName(reader.ReadString()); var material = manager.GetDefinitionByTypeName(reader.ReadString()); - var item = Activator.CreateInstance(itemType, new object[] {definition, material } ) as Item; + if (Activator.CreateInstance(itemType, definition, material) is not Item item) + throw new ArgumentException($"Type of {itemType.Name} is not of type Item."); item.InternalDeserialize(reader); return item; diff --git a/OctoAwesome/OctoAwesome/Entity.cs b/OctoAwesome/OctoAwesome/Entity.cs index cc9e8ff1..11de1dfb 100644 --- a/OctoAwesome/OctoAwesome/Entity.cs +++ b/OctoAwesome/OctoAwesome/Entity.cs @@ -1,10 +1,4 @@ -using engenious; -using OctoAwesome.Components; -using OctoAwesome.EntityComponents; -using OctoAwesome.Notifications; -using OctoAwesome.Serialization; -using System; -using System.IO; +using OctoAwesome.Components; namespace OctoAwesome { diff --git a/OctoAwesome/OctoAwesome/EntityComponents/AnimationComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/AnimationComponent.cs index c1243aaf..0eabe2da 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/AnimationComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/AnimationComponent.cs @@ -4,25 +4,21 @@ using OctoAwesome.Components; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public class AnimationComponent : Component, IEntityComponent, IFunctionalBlockComponent { + public float CurrentTime { get; set; } public float MaxTime { get; set; } public float AnimationSpeed { get; set; } - public AnimationComponent() { Sendable = true; } - public override void Serialize(BinaryWriter writer) { writer.Write(CurrentTime); @@ -30,7 +26,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(AnimationSpeed); base.Serialize(writer); } - public override void Deserialize(BinaryReader reader) { CurrentTime = reader.ReadSingle(); @@ -47,7 +42,6 @@ private float NextSmallerValue(float value) return BitConverter.Int32BitsToSingle(BitConverter.SingleToInt32Bits(value) - 1); return -float.Epsilon; } - public void Update(GameTime gameTime, Model model) { if (model.CurrentAnimation is null) diff --git a/OctoAwesome/OctoAwesome/EntityComponents/BodyComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/BodyComponent.cs index 9ea44f7c..179971e4 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/BodyComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/BodyComponent.cs @@ -1,15 +1,12 @@ using OctoAwesome.Components; -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public sealed class BodyComponent : Component, IEntityComponent, IFunctionalBlockComponent { + public float Mass { get; set; } /// @@ -21,14 +18,12 @@ public sealed class BodyComponent : Component, IEntityComponent, IFunctionalBloc /// Die Körperhöhe des Spielers in Blocks /// public float Height { get; set; } - public BodyComponent() { Mass = 1; //1kg Radius = 1; Height = 1; } - public override void Serialize(BinaryWriter writer) { base.Serialize(writer); @@ -37,7 +32,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(Radius); writer.Write(Height); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); diff --git a/OctoAwesome/OctoAwesome/EntityComponents/BoxCollisionComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/BoxCollisionComponent.cs index 4a5b51cf..19413465 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/BoxCollisionComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/BoxCollisionComponent.cs @@ -1,20 +1,16 @@ using engenious; using OctoAwesome.Components; using System; -using System.Collections.Generic; -using System.Drawing.Text; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public sealed class BoxCollisionComponent : CollisionComponent, IFunctionalBlockComponent { + public ReadOnlySpan BoundingBoxes => new(boundingBoxes); private readonly BoundingBox[] boundingBoxes; - public BoxCollisionComponent() { diff --git a/OctoAwesome/OctoAwesome/EntityComponents/CollisionComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/CollisionComponent.cs index 37fa31b9..653dc86c 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/CollisionComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/CollisionComponent.cs @@ -1,13 +1,8 @@ using OctoAwesome.Components; -using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public abstract class CollisionComponent : Component, IEntityComponent { } diff --git a/OctoAwesome/OctoAwesome/EntityComponents/ControllableComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/ControllableComponent.cs index 1172e954..d0cf7e35 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/ControllableComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/ControllableComponent.cs @@ -1,29 +1,21 @@ using engenious; using OctoAwesome.Components; using OctoAwesome.SumTypes; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public class ControllableComponent : Component, IEntityComponent { + public bool JumpInput { get; set; } public Vector2 MoveInput { get; set; } - public bool JumpActive { get; set; } public int JumpTime { get; set; } - public Selection Selection { get; set; } + public Selection? Selection { get; set; } public Index3? InteractBlock { get; set; } public Index3? ApplyBlock { get; set; } public OrientationFlags ApplySide { get; set; } - - public ControllableComponent() - { - } } } diff --git a/OctoAwesome/OctoAwesome/EntityComponents/HeadComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/HeadComponent.cs index ddc72650..354e22a3 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/HeadComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/HeadComponent.cs @@ -1,9 +1,4 @@ using engenious; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.IO; using OctoAwesome.Components; @@ -23,18 +18,16 @@ public sealed class HeadComponent : Component, IEntityComponent /// Tilt /// public float Tilt { get; set; } - + /// /// Angle /// public float Angle { get; set; } - public HeadComponent() { } - public override void Serialize(BinaryWriter writer) { base.Serialize(writer); @@ -46,7 +39,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(Tilt); writer.Write(Angle); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); @@ -55,8 +47,6 @@ public override void Deserialize(BinaryReader reader) var y = reader.ReadSingle(); var z = reader.ReadSingle(); Offset = new Vector3(x, y, z); - - Tilt = reader.ReadSingle(); Angle = reader.ReadSingle(); } diff --git a/OctoAwesome/OctoAwesome/EntityComponents/InstanceComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/InstanceComponent.cs index 5dad544f..d20be662 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/InstanceComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/InstanceComponent.cs @@ -1,5 +1,4 @@ -using OctoAwesome.Components; -using OctoAwesome.Notifications; +using OctoAwesome.Notifications; using OctoAwesome.Serialization; using System; using System.IO; @@ -10,24 +9,25 @@ namespace OctoAwesome.EntityComponents /// Base Class for all Entity Components. /// public abstract class InstanceComponent : Component, INotificationSubject - where T: ComponentContainer + where T : ComponentContainer { /// /// Reference to the Entity. /// public T Instance { get; private set; } - public Guid InstanceId { get; set; } public ulong InstanceTypeId { get; private set; } - public InstanceComponent() { } public void SetInstance(T instance) { - if (instance is not null && Instance?.Id == instance.Id) + if (instance is null) + throw new ArgumentNullException(nameof(instance)); + + if (Instance?.Id == instance.Id) return; var type = instance.GetType(); @@ -41,14 +41,12 @@ public void SetInstance(T instance) Instance = instance; OnSetInstance(); } - public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(InstanceId.ToByteArray()); writer.Write(InstanceTypeId); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); @@ -56,7 +54,6 @@ public override void Deserialize(BinaryReader reader) InstanceId = new Guid(reader.ReadBytes(16)); InstanceTypeId = reader.ReadUInt64(); } - protected virtual void OnSetInstance() { diff --git a/OctoAwesome/OctoAwesome/EntityComponents/InventoryComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/InventoryComponent.cs index 2149fd7e..d9c521e0 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/InventoryComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/InventoryComponent.cs @@ -6,27 +6,23 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public class InventoryComponent : Component, IEntityComponent, IFunctionalBlockComponent { /// /// Das Inventar der Entity /// - public List Inventory { get; set; } + public List Inventory { get; } private readonly IDefinitionManager definitionManager; - public InventoryComponent() { Inventory = new List(); definitionManager = TypeContainer.Get(); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); @@ -65,8 +61,6 @@ public override void Deserialize(BinaryReader reader) serializable.Deserialize(reader); } } - - if (instance is IInventoryable inventoryObject) { inventoryItem = inventoryObject; @@ -76,16 +70,14 @@ public override void Deserialize(BinaryReader reader) if (inventoryItem == default) continue; - var slot = new InventorySlot() + var slot = new InventorySlot(inventoryItem) { Amount = amount, - Item = inventoryItem, }; Inventory.Add(slot); } } - public override void Serialize(BinaryWriter writer) { base.Serialize(writer); @@ -95,7 +87,7 @@ public override void Serialize(BinaryWriter writer) if (slot.Item is Item item) { writer.Write(slot.Item.GetType().AssemblyQualifiedName!); - Item.Serialize(writer, item); + item.Serialize(writer); } else if (slot.Item is ISerializable serializable) { @@ -123,9 +115,8 @@ public void AddUnit(int quantity, IInventoryable item) // Wenn noch kein Slot da ist oder der vorhandene voll, dann neuen Slot if (slot == null) { - slot = new InventorySlot() + slot = new InventorySlot(item) { - Item = item, Amount = quantity, }; Inventory.Add(slot); @@ -156,7 +147,6 @@ public bool RemoveUnit(InventorySlot slot) } return false; } - public bool RemoveSlot(InventorySlot inventorySlot) { return Inventory.Remove(inventorySlot); @@ -170,9 +160,8 @@ public void AddSlot(InventorySlot inventorySlot) // Wenn noch kein Slot da ist oder der vorhandene voll, dann neuen Slot if (slot == null) { - slot = new InventorySlot() + slot = new InventorySlot(inventorySlot.Item) { - Item = inventorySlot.Item, Amount = inventorySlot.Amount, }; Inventory.Add(slot); diff --git a/OctoAwesome/OctoAwesome/EntityComponents/LocalChunkCacheComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/LocalChunkCacheComponent.cs index cadf6a30..7b4674bd 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/LocalChunkCacheComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/LocalChunkCacheComponent.cs @@ -1,20 +1,16 @@ using OctoAwesome.Components; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public sealed class LocalChunkCacheComponent : Component, IEntityComponent { - public ILocalChunkCache LocalChunkCache { get; set; } - + public ILocalChunkCache? LocalChunkCache { get; set; } public LocalChunkCacheComponent() { } - public LocalChunkCacheComponent(IGlobalChunkCache globalChunkCache, int dimensions,int range) + + public LocalChunkCacheComponent(IGlobalChunkCache globalChunkCache, int dimensions, int range) { LocalChunkCache = new LocalChunkCache(globalChunkCache, dimensions, range); } diff --git a/OctoAwesome/OctoAwesome/EntityComponents/PositionComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/PositionComponent.cs index 5cf0b855..c7a4c7c2 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/PositionComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/PositionComponent.cs @@ -2,18 +2,14 @@ using OctoAwesome.Components; using OctoAwesome.Notifications; using OctoAwesome.Pooling; -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public sealed class PositionComponent : InstanceComponent, IEntityComponent, IFunctionalBlockComponent { + public Coordinate Position { get => position; @@ -31,27 +27,21 @@ public Coordinate Position planet = TryGetPlanet(value.Planet); } } - public float Direction { get; set; } - public IPlanet Planet - { - get => planet ??= TryGetPlanet(position.Planet); - private set => planet = value; - } + + public IPlanet Planet => planet ??= TryGetPlanet(position.Planet); private Coordinate position; private bool posUpdate; - private IPlanet planet; + private IPlanet? planet; private readonly IResourceManager resourceManager; private readonly IPool propertyChangedNotificationPool; - public PositionComponent() { Sendable = true; resourceManager = TypeContainer.Get(); propertyChangedNotificationPool = TypeContainer.Get>(); } - public override void Serialize(BinaryWriter writer) { base.Serialize(writer); @@ -64,7 +54,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(Position.BlockPosition.Y); writer.Write(Position.BlockPosition.Z); } - public override void Deserialize(BinaryReader reader) { base.Deserialize(reader); @@ -88,17 +77,16 @@ private IPlanet TryGetPlanet(int planetId) return resourceManager.GetPlanet(planetId); } - - protected override void OnPropertyChanged(T value, string callerName) + protected override void OnPropertyChanged(T value, string propertyName) { - base.OnPropertyChanged(value, callerName); + base.OnPropertyChanged(value, propertyName); - if (callerName == nameof(Position) && posUpdate) + if (propertyName == nameof(Position) && posUpdate) { - var updateNotification = propertyChangedNotificationPool.Get(); + var updateNotification = propertyChangedNotificationPool.Rent(); updateNotification.Issuer = nameof(PositionComponent); - updateNotification.Property = callerName; + updateNotification.Property = propertyName; using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) @@ -110,7 +98,6 @@ protected override void OnPropertyChanged(T value, string callerName) Push(updateNotification); } } - public override void OnNotification(SerializableNotification notification) { base.OnNotification(notification); diff --git a/OctoAwesome/OctoAwesome/EntityComponents/RenderComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/RenderComponent.cs index 0523a672..8dd032bc 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/RenderComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/RenderComponent.cs @@ -1,26 +1,24 @@ using OctoAwesome.Components; -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { + public class RenderComponent : Component, IEntityComponent, IFunctionalBlockComponent { + public string Name { get; set; } public string ModelName { get; set; } + + public string TextureName { get; set; } + public float BaseZRotation { get; set; } - public RenderComponent() { Sendable = true; } - public override void Serialize(BinaryWriter writer) { writer.Write(Name); @@ -29,7 +27,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(BaseZRotation); base.Serialize(writer); } - public override void Deserialize(BinaryReader reader) { Name = reader.ReadString(); diff --git a/OctoAwesome/OctoAwesome/EntityComponents/ToolBarComponent.cs b/OctoAwesome/OctoAwesome/EntityComponents/ToolBarComponent.cs index c3e7504a..ad3fd007 100644 --- a/OctoAwesome/OctoAwesome/EntityComponents/ToolBarComponent.cs +++ b/OctoAwesome/OctoAwesome/EntityComponents/ToolBarComponent.cs @@ -1,11 +1,6 @@ using OctoAwesome.Components; using OctoAwesome.Definitions.Items; using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.EntityComponents { @@ -22,24 +17,19 @@ public class ToolBarComponent : Component, IEntityComponent /// /// Auflistung der Werkzeuge die der Spieler in seiner Toolbar hat. /// - public InventorySlot[] Tools { get; set; } + public InventorySlot?[] Tools { get; } /// /// Derzeit aktives Werkzeug des Spielers /// public InventorySlot ActiveTool => Tools[activeIndex] ?? HandSlot; - public InventorySlot HandSlot { get; } - public int ActiveIndex { get => activeIndex; set => activeIndex = (value + TOOLCOUNT) % TOOLCOUNT; } - - public event Action OnChanged; - - + public event Action? OnChanged; private int activeIndex; @@ -48,7 +38,7 @@ public int ActiveIndex /// public ToolBarComponent() { - HandSlot = new InventorySlot { Item = new Hand(new HandDefinition()) }; + HandSlot = new InventorySlot(new Hand(new HandDefinition())); Tools = new InventorySlot[TOOLCOUNT]; ActiveIndex = 0; } diff --git a/OctoAwesome/OctoAwesome/EntityList.cs b/OctoAwesome/OctoAwesome/EntityList.cs index 9ebb3f82..4754a445 100644 --- a/OctoAwesome/OctoAwesome/EntityList.cs +++ b/OctoAwesome/OctoAwesome/EntityList.cs @@ -1,17 +1,14 @@ using OctoAwesome.EntityComponents; -using System; using System.Collections; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { + public class EntityList : IEntityList { - private List entities; - private IChunkColumn column; + private readonly List entities; + private readonly IChunkColumn column; private readonly IResourceManager resourceManager; public EntityList(IChunkColumn column) @@ -20,31 +17,22 @@ public EntityList(IChunkColumn column) this.column = column; resourceManager = TypeContainer.Get(); } - public int Count => entities.Count; - public bool IsReadOnly => false; - public void Add(Entity item) { entities.Add(item); } - public void Clear() => entities.Clear(); - public bool Contains(Entity item) => entities.Contains(item); - public void CopyTo(Entity[] array, int arrayIndex) => entities.CopyTo(array, arrayIndex); - public IEnumerator GetEnumerator() => entities.GetEnumerator(); - public bool Remove(Entity item) { return entities.Remove(item); } IEnumerator IEnumerable.GetEnumerator() => entities.GetEnumerator(); - public IEnumerable FailChunkEntity() { foreach (var entity in entities) @@ -58,7 +46,7 @@ public IEnumerable FailChunkEntity() yield return new FailEntityChunkArgs() { Entity = entity, - CurrentChunk = new Index2(column.Index), + CurrentChunk = column.Index, CurrentPlanet = column.Planet, TargetChunk = new Index2(position.Position.ChunkIndex), TargetPlanet = resourceManager.GetPlanet(position.Position.Planet), diff --git a/OctoAwesome/OctoAwesome/Expressions/ArrayOfList.cs b/OctoAwesome/OctoAwesome/Expressions/ArrayOfList.cs deleted file mode 100644 index 7c1e0c80..00000000 --- a/OctoAwesome/OctoAwesome/Expressions/ArrayOfList.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Expressions -{ - public static class ArrayOfList - { - public readonly static Func, T[]> GetArray; - static ArrayOfList() - { - ParameterExpression input = Expression.Parameter(typeof(List), "list"); - //ParameterExpression result = Expression.Parameter(typeof(T[]), "list"); - - var body = Expression.Field(input, "_items"); - - GetArray = Expression.Lambda, T[]>>(body, input).Compile(); - } - } -} diff --git a/OctoAwesome/OctoAwesome/Extension.cs b/OctoAwesome/OctoAwesome/Extension.cs index 1e1a96b9..23bbfb18 100644 --- a/OctoAwesome/OctoAwesome/Extension.cs +++ b/OctoAwesome/OctoAwesome/Extension.cs @@ -1,10 +1,5 @@ using engenious; using OctoAwesome.EntityComponents; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { @@ -12,10 +7,9 @@ namespace OctoAwesome public sealed class Extension : IExtension { - public string Description => "OctoAwesome"; + public string Description => "OctoAwesome"; public string Name => "OctoAwesome"; - public void Register(IExtensionLoader extensionLoader, ITypeContainer typeContainer) { extensionLoader.RegisterEntityExtender((player) => @@ -27,7 +21,6 @@ public void Register(IExtensionLoader extensionLoader, ITypeContainer typeContai p.Components.AddComponent(new ToolBarComponent()); }); } - public void Register(ITypeContainer typeContainer) { } } } diff --git a/OctoAwesome/OctoAwesome/FailEntityChunkArgs.cs b/OctoAwesome/OctoAwesome/FailEntityChunkArgs.cs index 4731fdd0..edae96e8 100644 --- a/OctoAwesome/OctoAwesome/FailEntityChunkArgs.cs +++ b/OctoAwesome/OctoAwesome/FailEntityChunkArgs.cs @@ -1,13 +1,13 @@ namespace OctoAwesome { + public class FailEntityChunkArgs { + public Index2 CurrentChunk { get; set; } public IPlanet CurrentPlanet { get; set; } - public Index2 TargetChunk { get; set; } public IPlanet TargetPlanet { get; set; } - public Entity Entity { get; set; } } } diff --git a/OctoAwesome/OctoAwesome/FunctionalBlock.cs b/OctoAwesome/OctoAwesome/FunctionalBlock.cs index 552ed96a..d89177af 100644 --- a/OctoAwesome/OctoAwesome/FunctionalBlock.cs +++ b/OctoAwesome/OctoAwesome/FunctionalBlock.cs @@ -1,25 +1,16 @@ using engenious; using OctoAwesome.Components; -using OctoAwesome.EntityComponents; -using OctoAwesome.Notifications; -using OctoAwesome.Serialization; -using OpenTK.Audio.OpenAL; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { + public abstract class FunctionalBlock : ComponentContainer { + public void Interact(GameTime gameTime, Entity entity) { OnInteract(gameTime, entity); } - protected abstract void OnInteract(GameTime gameTime, Entity entity); } } diff --git a/OctoAwesome/OctoAwesome/GlobalChunkCache.cs b/OctoAwesome/OctoAwesome/GlobalChunkCache.cs index 322364cd..b491de10 100644 --- a/OctoAwesome/OctoAwesome/GlobalChunkCache.cs +++ b/OctoAwesome/OctoAwesome/GlobalChunkCache.cs @@ -1,23 +1,15 @@ using OctoAwesome.Caching; -using OctoAwesome.Components; using OctoAwesome.EntityComponents; using OctoAwesome.Logging; using OctoAwesome.Notifications; using OctoAwesome.Pooling; using OctoAwesome.Rx; -using OctoAwesome.Serialization; using OctoAwesome.Threading; using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Threading; -using System.Threading.Tasks; namespace OctoAwesome { @@ -35,7 +27,7 @@ public sealed class GlobalChunkCache : IGlobalChunkCache, IDisposable private readonly CancellationTokenSource tokenSource; private readonly IResourceManager resourceManager; private readonly SerializationIdTypeProvider typeProvider; - + /// /// Objekt, das für die Locks benutzt wird /// @@ -43,7 +35,6 @@ public sealed class GlobalChunkCache : IGlobalChunkCache, IDisposable private readonly LockSemaphore updateSemaphore = new LockSemaphore(1, 1); // TODO: Früher oder später nach draußen auslagern - private readonly Task cleanupTask; private readonly ILogger logger; private readonly ChunkPool chunkPool; private readonly IDisposable chunkSubscription; @@ -72,7 +63,6 @@ public int LoadedChunkColumns /// Anzahl der noch nicht gespeicherten ChunkColumns. /// public int DirtyChunkColumn => 0; - public IPlanet Planet { get; } private readonly CacheService cacheService; @@ -92,8 +82,6 @@ public GlobalChunkCache(IPlanet planet, IResourceManager resourceManager, IUpdat networkRelay = new Relay(); chunkRelay = new Relay(); simulationRelay = new Relay(); - - tokenSource = new CancellationTokenSource(); logger = (TypeContainer.GetOrNull() ?? NullLogger.Default).As(typeof(GlobalChunkCache)); @@ -167,18 +155,15 @@ var functionalBlock return column; } - /// /// Liefert den Chunk, sofern geladen. /// /// Die Id des Planeten /// Die Position des zurückzugebenden Chunks /// Chunk Instanz oder null, falls nicht geladen - public IChunkColumn Peek(Index2 position) + public IChunkColumn? Peek(Index2 position) => cacheService.Get(position, LoadingMode.OnlyCached); - - /// /// Gibt einen abonnierten Chunk wieder frei. /// @@ -203,8 +188,6 @@ public void Release(Index2 position) } } - - public void BeforeSimulationUpdate(Simulation simulation) { lock (updateSemaphore) @@ -217,8 +200,6 @@ public void BeforeSimulationUpdate(Simulation simulation) //chunk.ChunkColumn.ForEachEntity(simulation.Remove); } } - - public void OnNext(Notification value) { switch (value) @@ -233,7 +214,6 @@ public void OnNext(Notification value) break; } } - public void OnUpdate(SerializableNotification notification) { networkRelay.OnNext(notification); @@ -241,7 +221,6 @@ public void OnUpdate(SerializableNotification notification) if (notification is IChunkNotification) chunkRelay.OnNext(notification); } - public void Update(SerializableNotification notification) { if (notification is IChunkNotification chunk) @@ -252,7 +231,6 @@ public void Update(SerializableNotification notification) column?.Update(notification); } } - public void Dispose() { semaphore.Dispose(); @@ -267,7 +245,6 @@ public void Dispose() cacheService.Dispose(); } - public void AfterSimulationUpdate(Simulation simulation) { } @@ -289,8 +266,6 @@ public void AfterSimulationUpdate(Simulation simulation) // /// Die Zahl der Subscriber, die das Item Abboniert hat. // /// // public int References { get; set; } - - // /// // /// Der Chunk, auf den das referenziert // /// diff --git a/OctoAwesome/OctoAwesome/IChunk.cs b/OctoAwesome/OctoAwesome/IChunk.cs index ac913096..4729bcae 100644 --- a/OctoAwesome/OctoAwesome/IChunk.cs +++ b/OctoAwesome/OctoAwesome/IChunk.cs @@ -1,6 +1,6 @@ using OctoAwesome.Pooling; - using System; +using OctoAwesome.Notifications; namespace OctoAwesome { @@ -30,7 +30,6 @@ public interface IChunk : IPoolElement /// Der Index ist derselbe wie bei . /// int[] MetaData { get; } - int Version { get; set; } /// @@ -66,7 +65,6 @@ public interface IChunk : IPoolElement /// (Optional) Die Metadaten des Blocks /// Die neue Block-ID void SetBlock(int x, int y, int z, ushort block, int meta = 0); - void SetBlock(int flatIndex, BlockInfo blockInfo); /// @@ -106,11 +104,11 @@ public interface IChunk : IPoolElement void SetBlockResources(int x, int y, int z, ushort[] resources); void SetColumn(IChunkColumn chunkColumn); - void Update(Notifications.SerializableNotification notification); - void OnUpdate(Notifications.SerializableNotification notification); + void Update(SerializableNotification notification); + void OnUpdate(SerializableNotification notification); void SetBlocks(bool issueNotification, params BlockInfo[] blockInfos); - event Action Changed; + event Action? Changed; void FlagDirty(); } } diff --git a/OctoAwesome/OctoAwesome/IChunkColumn.cs b/OctoAwesome/OctoAwesome/IChunkColumn.cs index b2ea8802..9a6b75c0 100644 --- a/OctoAwesome/OctoAwesome/IChunkColumn.cs +++ b/OctoAwesome/OctoAwesome/IChunkColumn.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System; -using System.IO; using OctoAwesome.Serialization; namespace OctoAwesome @@ -104,13 +103,19 @@ public interface IChunkColumn : ISerializable /// Z-Anteil der Koordinate des Blocks innerhalb des Chunks /// Ein -Array, das alle Ressourcen enthält void SetBlockResources(int x, int y, int z, ushort[] resources); + void OnUpdate(Notifications.SerializableNotification notification); + void Update(Notifications.SerializableNotification notification); + void ForEachEntity(Action action); IEnumerable FailChunkEntity(); + void Remove(Entity entity); + void Add(Entity entity); void SetBlocks(bool issueNotification, params BlockInfo[] blockInfos); + void FlagDirty(); } } diff --git a/OctoAwesome/OctoAwesome/IEntityList.cs b/OctoAwesome/OctoAwesome/IEntityList.cs index ffdc5cea..23b80cb3 100644 --- a/OctoAwesome/OctoAwesome/IEntityList.cs +++ b/OctoAwesome/OctoAwesome/IEntityList.cs @@ -1,13 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; namespace OctoAwesome { + public interface IEntityList : ICollection { + IEnumerable FailChunkEntity(); } } diff --git a/OctoAwesome/OctoAwesome/IExtension.cs b/OctoAwesome/OctoAwesome/IExtension.cs index 058c6943..501370dc 100644 --- a/OctoAwesome/OctoAwesome/IExtension.cs +++ b/OctoAwesome/OctoAwesome/IExtension.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome +namespace OctoAwesome { /// /// Interface for all Mod Plugin Extensions. @@ -26,6 +20,7 @@ public interface IExtension /// /// ExtensionsLoader void Register(IExtensionLoader extensionLoader, ITypeContainer typeContainer); + void Register(ITypeContainer typeContainer); } } diff --git a/OctoAwesome/OctoAwesome/IExtensionLoader.cs b/OctoAwesome/OctoAwesome/IExtensionLoader.cs index dfc0e9c8..d876ac25 100644 --- a/OctoAwesome/OctoAwesome/IExtensionLoader.cs +++ b/OctoAwesome/OctoAwesome/IExtensionLoader.cs @@ -31,11 +31,12 @@ public interface IExtensionLoader /// Definition Instance void RegisterDefinition(Type definition); + /// /// Removes an existing Definition Type. /// /// Definition Type - void RemoveDefinition() where T : IDefinition; + void RemoveDefinition() where T : IDefinition; // TODO: naming Unregister? /// /// Registers a Type with the required SerializationId attribute. @@ -80,7 +81,6 @@ public interface IExtensionLoader void RemoveMapGenerator(T item) where T : IMapGenerator; void RegisterMapPopulator(IMapPopulator populator); - void RemoveMapPopulator(T item) where T : IMapPopulator; } } diff --git a/OctoAwesome/OctoAwesome/IExtensionResolver.cs b/OctoAwesome/OctoAwesome/IExtensionResolver.cs index d1d4ac0b..ee3fec0c 100644 --- a/OctoAwesome/OctoAwesome/IExtensionResolver.cs +++ b/OctoAwesome/OctoAwesome/IExtensionResolver.cs @@ -31,12 +31,12 @@ public interface IExtensionResolver /// Return a List of MapGenerators /// /// List of Generators - IEnumerable GetMapGenerator(); + IEnumerable GetMapGenerators(); /// /// Return a List of Populators /// /// List of Populators - IEnumerable GetMapPopulator(); + IEnumerable GetMapPopulators(); } } diff --git a/OctoAwesome/OctoAwesome/IFluidInventory.cs b/OctoAwesome/OctoAwesome/IFluidInventory.cs index 1849acf4..f7d1fdff 100644 --- a/OctoAwesome/OctoAwesome/IFluidInventory.cs +++ b/OctoAwesome/OctoAwesome/IFluidInventory.cs @@ -1,17 +1,13 @@ using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { + public interface IFluidInventory { int MaxQuantity { get; } int Quantity { get; } - IBlockDefinition FluidBlock { get; } + IBlockDefinition? FluidBlock { get; } void AddFluid(int quantity, IBlockDefinition fluid); } diff --git a/OctoAwesome/OctoAwesome/IGlobalChunkCache.cs b/OctoAwesome/OctoAwesome/IGlobalChunkCache.cs index c565da72..9481faa0 100644 --- a/OctoAwesome/OctoAwesome/IGlobalChunkCache.cs +++ b/OctoAwesome/OctoAwesome/IGlobalChunkCache.cs @@ -1,5 +1,4 @@ using OctoAwesome.Notifications; -using System; namespace OctoAwesome { @@ -28,14 +27,13 @@ public interface IGlobalChunkCache /// Den neu abonnierten Chunk IChunkColumn Subscribe(Index2 position); - /// /// Liefert den Chunk, sofern geladen. /// /// Die Id des Planeten /// Die Position des zurückzugebenden Chunks /// Chunk Instanz oder null, falls nicht geladen - IChunkColumn Peek(Index2 position); + IChunkColumn? Peek(Index2 position); /// /// Gibt einen abonnierten Chunk wieder frei. @@ -44,9 +42,11 @@ public interface IGlobalChunkCache void Release(Index2 position); void BeforeSimulationUpdate(Simulation simulation); + void AfterSimulationUpdate(Simulation simulation); void OnUpdate(SerializableNotification notification); + void Update(SerializableNotification notification); } } diff --git a/OctoAwesome/OctoAwesome/IInventoryable.cs b/OctoAwesome/OctoAwesome/IInventoryable.cs index e15e3b4a..7705ad02 100644 --- a/OctoAwesome/OctoAwesome/IInventoryable.cs +++ b/OctoAwesome/OctoAwesome/IInventoryable.cs @@ -1,11 +1,4 @@ -using OctoAwesome.Definitions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome +namespace OctoAwesome { /// /// Basis-Interface für alle im Inventar-Verwaltbaren Definitionen. diff --git a/OctoAwesome/OctoAwesome/ILocalChunkCache.cs b/OctoAwesome/OctoAwesome/ILocalChunkCache.cs index d09f1032..b90de52a 100644 --- a/OctoAwesome/OctoAwesome/ILocalChunkCache.cs +++ b/OctoAwesome/OctoAwesome/ILocalChunkCache.cs @@ -13,7 +13,7 @@ public interface ILocalChunkCache /// Der Planet, auf dem sich der Chunk befindet /// Die Koordinaten an der sich der Chunk befindet /// Routine die Aufgerufen werden soll, falls das setzen erfolgreich war oder nicht - bool SetCenter(Index2 index, Action successCallback = null); + bool SetCenter(Index2 index, Action? successCallback = null); /// /// Aktueller Planet auf dem sich der Cache bezieht. @@ -25,7 +25,7 @@ public interface ILocalChunkCache /// /// Chunk Index /// Instanz des Chunks - IChunk GetChunk(Index3 index); + IChunk? GetChunk(Index3 index); /// /// Liefert den Chunk an der angegebenen Chunk-Koordinate zurück. @@ -34,7 +34,7 @@ public interface ILocalChunkCache /// Y Koordinate /// Z Koordinate /// Instanz des Chunks - IChunk GetChunk(int x, int y, int z); + IChunk? GetChunk(int x, int y, int z); /// /// Leert den Cache und gibt sie beim GlobalChunkCache wieder frei diff --git a/OctoAwesome/OctoAwesome/IMapGenerator.cs b/OctoAwesome/OctoAwesome/IMapGenerator.cs index 5441688a..734a0c6a 100644 --- a/OctoAwesome/OctoAwesome/IMapGenerator.cs +++ b/OctoAwesome/OctoAwesome/IMapGenerator.cs @@ -1,6 +1,5 @@ using OctoAwesome.Definitions; using System; -using System.Collections.Generic; using System.IO; namespace OctoAwesome diff --git a/OctoAwesome/OctoAwesome/IPersistenceManager.cs b/OctoAwesome/OctoAwesome/IPersistenceManager.cs index 7cf9537a..b53608a3 100644 --- a/OctoAwesome/OctoAwesome/IPersistenceManager.cs +++ b/OctoAwesome/OctoAwesome/IPersistenceManager.cs @@ -1,9 +1,7 @@ using OctoAwesome.Components; -using OctoAwesome.EntityComponents; using OctoAwesome.Serialization; using System; using System.Collections.Generic; -using System.Threading.Tasks; namespace OctoAwesome { @@ -16,14 +14,14 @@ public interface IPersistenceManager /// Gibt alle Universen zurück, die geladen werden können. /// /// Die Liste der Universen. - Awaiter Load(out SerializableCollection universes); + Awaiter? Load(out SerializableCollection universes); /// /// Lädt das Universum mit der angegebenen Guid. /// /// Die Guid des Universums. /// Das geladene Universum. - Awaiter Load(out IUniverse universe, Guid universeGuid); + Awaiter? Load(out IUniverse universe, Guid universeGuid); /// /// Speichert das Universum. @@ -43,7 +41,7 @@ public interface IPersistenceManager /// Guid des Universums /// Index des Planeten /// - Awaiter Load(out IPlanet planet, Guid universeGuid, int planetId); + Awaiter? Load(out IPlanet planet, Guid universeGuid, int planetId); /// /// Speichert einen Planeten. @@ -59,7 +57,7 @@ public interface IPersistenceManager /// Index des Planeten. /// Zu serialisierende ChunkColumn. /// Die neu geladene ChunkColumn. - Awaiter Load(out IChunkColumn column, Guid universeGuid, IPlanet planet, Index2 columnIndex); + Awaiter? Load(out IChunkColumn? column, Guid universeGuid, IPlanet planet, Index2 columnIndex); /// /// Speichert eine . @@ -75,7 +73,7 @@ public interface IPersistenceManager /// Die Guid des Universums. /// Der Name des Spielers. /// - Awaiter Load(out Player player, Guid universeGuid, string playername); + Awaiter? Load(out Player player, Guid universeGuid, string playerName); /// /// Speichert einen Player @@ -83,18 +81,18 @@ public interface IPersistenceManager /// Die Guid des Universums. /// Der Player. void SavePlayer(Guid universeGuid, Player player); - IEnumerable LoadEntitiesWithComponent(Guid universeGuid) where T : IEntityComponent; void Save(TContainer container, Guid universe) where TContainer : ComponentContainer where TComponent : IComponent; - - Awaiter Load(out Entity entity, Guid universeGuid, Guid entityId); - IEnumerable GetEntityIdsFromComponent(Guid universeGuid) where T : IEntityComponent; + + Awaiter? Load(out Entity entity, Guid universeGuid, Guid entityId); + IEnumerable<(Guid Id, T Component)> GetEntityComponents(Guid universeGuid, Guid[] entityIds) where T : IEntityComponent, new(); IEnumerable GetEntityIds(Guid universeGuid); + IEnumerable<(Guid Id, T Component)> GetAllComponents(Guid universeGuid) where T : IComponent, new(); T GetComponent(Guid universeGuid, Guid id) where T : IComponent, new(); - Awaiter Load(out TContainer componentContainer, Guid universeGuid, Guid id) + Awaiter? Load(out TContainer componentContainer, Guid universeGuid, Guid id) where TContainer : ComponentContainer where TComponent : IComponent; } diff --git a/OctoAwesome/OctoAwesome/IPlanet.cs b/OctoAwesome/OctoAwesome/IPlanet.cs index 8b67a0ae..804d565b 100644 --- a/OctoAwesome/OctoAwesome/IPlanet.cs +++ b/OctoAwesome/OctoAwesome/IPlanet.cs @@ -1,7 +1,5 @@ -using OctoAwesome.Notifications; -using OctoAwesome.Serialization; +using OctoAwesome.Serialization; using System; -using System.IO; namespace OctoAwesome { @@ -44,7 +42,6 @@ public interface IPlanet : ISerializable, IDisposable /// Der Generator des Planeten /// IMapGenerator Generator { get; set; } - IGlobalChunkCache GlobalChunkCache { get; } } } diff --git a/OctoAwesome/OctoAwesome/IResourceManager.cs b/OctoAwesome/OctoAwesome/IResourceManager.cs index 48d31b85..8cc5d293 100644 --- a/OctoAwesome/OctoAwesome/IResourceManager.cs +++ b/OctoAwesome/OctoAwesome/IResourceManager.cs @@ -1,10 +1,8 @@ using OctoAwesome.Components; using OctoAwesome.Definitions; -using OctoAwesome.EntityComponents; using OctoAwesome.Notifications; using System; using System.Collections.Concurrent; -using System.Collections.Generic; namespace OctoAwesome { @@ -13,18 +11,19 @@ namespace OctoAwesome /// public interface IResourceManager { + IDefinitionManager DefinitionManager { get; } /// /// Erzuegt ein neues Universum. /// /// Name des neuen Universums. - /// Weltgenerator-Seed fr das neue Universum. + /// Weltgenerator-Seed f�r das neue Universum. /// Die Guid des neuen Universums. Guid NewUniverse(string name, int seed); /// - /// Ldt das Universum fr die angegebene GUID. + /// L�dt das Universum f�r die angegebene GUID. /// /// Die Guid des Universums. bool TryLoadUniverse(Guid universeId); @@ -32,31 +31,31 @@ public interface IResourceManager /// /// Das aktuell geladene Universum. /// - IUniverse CurrentUniverse { get; } + IUniverse? CurrentUniverse { get; } /// - /// Entldt das aktuelle Universum. + /// Entl�dt das aktuelle Universum. /// void UnloadUniverse(); /// - /// Gibt alle Universen zurck, die geladen werden knnen. + /// Gibt alle Universen zur�ck, die geladen werden k�nnen. /// /// Die Liste der Universen. IUniverse[] ListUniverses(); /// - /// Lscht ein Universum. + /// L�scht ein Universum. /// /// Die Guid des Universums. void DeleteUniverse(Guid id); /// - /// Ldt einen Player. + /// L�dt einen Player. /// /// Der Name des Players. /// - Player LoadPlayer(string playername); + Player LoadPlayer(string playerName); /// /// Speichert einen Player. @@ -65,22 +64,13 @@ public interface IResourceManager void SavePlayer(Player player); /// - /// Entldt das aktuelle Universum - /// - /// Das gewnschte Universum, falls es existiert - IUniverse GetUniverse(); - - /// - /// Gibt den Planeten mit der angegebenen ID zurck + /// Gibt den Planeten mit der angegebenen ID zur�ck /// - /// Die Planteten-ID des gewnschten Planeten - /// Der gewnschte Planet, falls er existiert + /// Die Planteten-ID des gew�nschten Planeten + /// Der gew�nschte Planet, falls er existiert IPlanet GetPlanet(int planetId); - ConcurrentDictionary Planets { get; } - IUpdateHub UpdateHub { get; } - Player CurrentPlayer { get; } void SaveComponentContainer(TContainer componentContainer) @@ -90,20 +80,12 @@ void SaveComponentContainer(TContainer componentContaine void SaveChunkColumn(IChunkColumn value); IChunkColumn LoadChunkColumn(IPlanet planet, Index2 index); - - Entity LoadEntity(Guid entityId); - - IEnumerable LoadEntitiesWithComponent() where T : IEntityComponent; - - IEnumerable GetEntityIdsFromComponent() where T : IEntityComponent; - - (Guid Id, T Component)[] GetEntityComponents(Guid[] entityIds) where T : IEntityComponent, new(); - + Entity? LoadEntity(Guid entityId); (Guid Id, T Component)[] GetAllComponents() where T : IComponent, new(); T GetComponent(Guid id) where T : IComponent, new(); - TContainer LoadComponentContainer(Guid id) + TContainer? LoadComponentContainer(Guid id) where TContainer : ComponentContainer where TComponent : IComponent; } diff --git a/OctoAwesome/OctoAwesome/ISettings.cs b/OctoAwesome/OctoAwesome/ISettings.cs index 45c9cb1f..43456dc7 100644 --- a/OctoAwesome/OctoAwesome/ISettings.cs +++ b/OctoAwesome/OctoAwesome/ISettings.cs @@ -11,7 +11,7 @@ public interface ISettings /// Der Schlüssel der Einstellung. /// Der Wert der Einstellung. T Get(string key); - + /// /// Gibt den Wert einer Einstellung zurück. /// diff --git a/OctoAwesome/OctoAwesome/ITypeContainer.cs b/OctoAwesome/OctoAwesome/ITypeContainer.cs index 2bad2207..0c1187b1 100644 --- a/OctoAwesome/OctoAwesome/ITypeContainer.cs +++ b/OctoAwesome/OctoAwesome/ITypeContainer.cs @@ -1,22 +1,24 @@ -using OctoAwesome.Logging; -using System; +using System; +using System.Diagnostics.CodeAnalysis; namespace OctoAwesome { + public interface ITypeContainer : IDisposable { - object CreateObject(Type type); - T CreateObject() where T : class; - void Register(Type registrar, Type type, InstanceBehaviour instanceBehaviour); - void Register(InstanceBehaviour instanceBehaviour = InstanceBehaviour.Instance) where T : class; - void Register(InstanceBehaviour instanceBehaviour = InstanceBehaviour.Instance) where T : class; - void Register(Type registrar, Type type, object singelton); - void Register(T singelton) where T : class; - void Register(object singelton) where T : class; + object? CreateObject(Type type); + T? CreateObject() where T : class; + + void Register(Type registrar, Type type, InstanceBehavior instanceBehavior); + void Register(InstanceBehavior instanceBehavior = InstanceBehavior.Instance) where T : class; + void Register(InstanceBehavior instanceBehavior = InstanceBehavior.Instance) where T : class; + void Register(Type registrar, Type type, object singleton); + void Register(T singleton) where T : class; + void Register(object singleton) where T : class; - bool TryResolve(Type type, out object instance); - bool TryResolve(out T instance) where T : class; + bool TryGet(Type type, [MaybeNullWhen(false)] out object instance); + bool TryGet([MaybeNullWhen(false)] out T instance) where T : class; object Get(Type type); T Get() where T : class; @@ -24,7 +26,7 @@ public interface ITypeContainer : IDisposable object GetUnregistered(Type type); T GetUnregistered() where T : class; - object GetOrNull(Type type); - T GetOrNull() where T : class; + object? GetOrNull(Type type); + T? GetOrNull() where T : class; } } \ No newline at end of file diff --git a/OctoAwesome/OctoAwesome/IUniverse.cs b/OctoAwesome/OctoAwesome/IUniverse.cs index d9e22570..84b05351 100644 --- a/OctoAwesome/OctoAwesome/IUniverse.cs +++ b/OctoAwesome/OctoAwesome/IUniverse.cs @@ -1,6 +1,5 @@ using OctoAwesome.Serialization; using System; -using System.IO; namespace OctoAwesome { diff --git a/OctoAwesome/OctoAwesome/Index2.cs b/OctoAwesome/OctoAwesome/Index2.cs index 2245b86a..e87ffac8 100644 --- a/OctoAwesome/OctoAwesome/Index2.cs +++ b/OctoAwesome/OctoAwesome/Index2.cs @@ -30,12 +30,6 @@ public Index2(int x, int y) Y = y; } - /// - /// Initialisierung - /// - /// Initialwerte - public Index2(Index2 value) : this(value.X, value.Y) { } - /// /// Initialisierung /// @@ -47,8 +41,8 @@ public Index2(Index3 value) : this(value.X, value.Y) { } /// /// Maximalwert für X public void NormalizeX(int size) - => X = NormalizeAxis(X, size); - + => X = Index2.NormalizeAxis(X, size); + /// /// Normalisiert die X-Achse auf die angegebene Größe. /// @@ -68,7 +62,7 @@ public void NormalizeX(Index3 size) /// /// Maximalwert für Y public void NormalizeY(int size) - => Y = NormalizeAxis(Y, size); + => Y = Index2.NormalizeAxis(Y, size); /// /// Normalisiert die Y-Achse auf die angegebene Größe. @@ -89,10 +83,10 @@ public void NormalizeY(Index3 size) /// /// Größe in X-Richtung /// Größe in Y-Richtung - public void NormalizeXY(int x, int y) + public void NormalizeXY(int sizeX, int sizeY) { - NormalizeX(x); - NormalizeY(y); + NormalizeX(sizeX); + NormalizeY(sizeY); } /// @@ -119,7 +113,7 @@ public static Index2 NormalizeXY(Index2 index, Index3 size) index.NormalizeXY(size); return index; } - + /// /// Ermittelt die kürzeste Entfernung zum Ziel auf einer normalisierten X-Achse. /// @@ -128,7 +122,7 @@ public static Index2 NormalizeXY(Index2 index, Index3 size) /// Entfernung public int ShortestDistanceX(int x, int size) => ShortestDistanceOnAxis(X, x, size); - + /// /// Ermittelt die kürzeste Entfernung zum Ziel auf einer normalisierten Y-Achse. /// @@ -251,13 +245,13 @@ public static int NormalizeAxis(int value, int size) /// Zielwert /// Normalisierungsgröße /// - public static int ShortestDistanceOnAxis(int origin, int destination, int size) + public static int ShortestDistanceOnAxis(int source, int destination, int size) { - origin = NormalizeAxis(origin, size); + source = NormalizeAxis(source, size); destination = NormalizeAxis(destination, size); int half = size / 2; - int distance = destination - origin; + int distance = destination - source; if (distance > half) distance -= size; @@ -279,7 +273,7 @@ public override string ToString() /// /// /// - public override bool Equals(object obj) + public override bool Equals(object? obj) =>obj is Index2 other && Equals(other); @@ -289,7 +283,6 @@ public override bool Equals(object obj) /// public override int GetHashCode() => (X << 16) + Y; - public bool Equals(Index2 other) => other.X == X && other.Y == Y; diff --git a/OctoAwesome/OctoAwesome/Index3.cs b/OctoAwesome/OctoAwesome/Index3.cs index 58a2f008..ab4e4a51 100644 --- a/OctoAwesome/OctoAwesome/Index3.cs +++ b/OctoAwesome/OctoAwesome/Index3.cs @@ -35,7 +35,7 @@ public Index3(int x, int y, int z) Y = y; Z = z; } - + /// /// Gets the X and Y components /// @@ -48,19 +48,13 @@ public Index3(int x, int y, int z) /// Z-Anteil public Index3(Index2 index, int z) : this(index.X, index.Y, z) { } - /// - /// Initialisierung - /// - /// 3D-Basis - public Index3(Index3 index) : this(index.X, index.Y, index.Z) { } - /// /// Normalisiert die X-Achse auf die angegebene Größe. /// /// Maximalwert für X public void NormalizeX(int size) => X = Index2.NormalizeAxis(X, size); - + /// /// Normalisiert die X-Achse auf die angegebene Größe. /// @@ -115,10 +109,10 @@ public void NormalizeZ(Index3 size) /// /// X-Anteil /// Y-Anteil - public void NormalizeXY(int x, int y) + public void NormalizeXY(int sizeX, int sizeY) { - NormalizeX(x); - NormalizeY(y); + NormalizeX(sizeX); + NormalizeY(sizeY); } /// @@ -141,11 +135,11 @@ public void NormalizeXY(Index3 size) /// X-Anteil /// Y-Anteil /// Z-Anteil - public void NormalizeXYZ(int x, int y, int z) + public void NormalizeXYZ(int sizeX, int sizeY, int sizeZ) { - NormalizeX(x); - NormalizeY(y); - NormalizeZ(z); + NormalizeX(sizeX); + NormalizeY(sizeY); + NormalizeZ(sizeZ); } /// @@ -153,8 +147,8 @@ public void NormalizeXYZ(int x, int y, int z) /// /// 2D-Size /// Z-Anteil - public void NormalizeXYZ(Index2 size, int z) - => NormalizeXYZ(size.X, size.Y, z); + public void NormalizeXYZ(Index2 size, int sizeZ) + => NormalizeXYZ(size.X, size.Y, sizeZ); /// /// Normalisiert die X-, Y- und Z-Achse auf die angegebene Größe. @@ -162,7 +156,7 @@ public void NormalizeXYZ(Index2 size, int z) /// Maximalwert für X, Y und Z public void NormalizeXYZ(Index3 size) => NormalizeXYZ(size.X, size.Y, size.Z); - + /// /// Ermittelt die kürzeste Entfernung zum Ziel auf einer normalisierten X-Achse. /// @@ -171,7 +165,7 @@ public void NormalizeXYZ(Index3 size) /// Entfernung public int ShortestDistanceX(int x, int size) => Index2.ShortestDistanceOnAxis(X, x, size); - + /// /// Ermittelt die kürzeste Entfernung zum Ziel auf einer normalisierten Y-Achse. /// @@ -180,7 +174,7 @@ public int ShortestDistanceX(int x, int size) /// Entfernung public int ShortestDistanceY(int y, int size) => Index2.ShortestDistanceOnAxis(Y, y, size); - + /// /// Ermittelt die kürzeste Entfernung zum Ziel auf einer normalisierten Z-Achse. /// @@ -269,7 +263,7 @@ public int LengthSquared() /// public static Index3 operator +(Index3 i1, Index2 i2) => new Index3(i1.X + i2.X, i1.Y + i2.Y, i1.Z); - + /// /// Subtrahiert zwei Indices3 /// @@ -278,7 +272,7 @@ public int LengthSquared() /// public static Index3 operator -(Index3 i1, Index3 i2) => new Index3(i1.X - i2.X, i1.Y - i2.Y, i1.Z - i2.Z); - + /// /// Subtrahiert einen Index2 von einem Index3 /// @@ -350,9 +344,8 @@ public int LengthSquared() /// /// /// - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is Index3 other && Equals(other); - public bool Equals(Index3 other) => other.X == X && other.Y == Y && other.Z == Z; diff --git a/OctoAwesome/OctoAwesome/Information/BlockHitInformation.cs b/OctoAwesome/OctoAwesome/Information/BlockHitInformation.cs index 39867b77..a90485a0 100644 --- a/OctoAwesome/OctoAwesome/Information/BlockHitInformation.cs +++ b/OctoAwesome/OctoAwesome/Information/BlockHitInformation.cs @@ -1,19 +1,15 @@ using OctoAwesome.Definitions; using System; -using System.Collections; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Information { + public readonly struct BlockHitInformation : IEquatable { - public static BlockHitInformation Empty = default; + public static BlockHitInformation Empty = default; public bool IsEmpty => !IsHitValid && Quantity == 0 && definitions == null; - public bool IsHitValid { get; } public int Quantity { get; } public IReadOnlyList<(int Quantity, IDefinition Definition)> Definitions @@ -27,14 +23,12 @@ public BlockHitInformation(bool isHitValid, int quantity, (int Quantity, IDefini Quantity = quantity; this.definitions = definitions; } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is BlockHitInformation information && Equals(information); public bool Equals(BlockHitInformation other) => IsHitValid == other.IsHitValid && Quantity == other.Quantity && EqualityComparer<(int Quantity, IDefinition Definition)[]>.Default.Equals(definitions, other.definitions); - public override int GetHashCode() { var hashCode = -1198439795; @@ -46,6 +40,7 @@ public override int GetHashCode() public static bool operator ==(BlockHitInformation left, BlockHitInformation right) => left.Equals(right); + public static bool operator !=(BlockHitInformation left, BlockHitInformation right) => !(left == right); } diff --git a/OctoAwesome/OctoAwesome/InstanceBehaviour.cs b/OctoAwesome/OctoAwesome/InstanceBehavior.cs similarity index 69% rename from OctoAwesome/OctoAwesome/InstanceBehaviour.cs rename to OctoAwesome/OctoAwesome/InstanceBehavior.cs index 533c4f9f..1af7c2e7 100644 --- a/OctoAwesome/OctoAwesome/InstanceBehaviour.cs +++ b/OctoAwesome/OctoAwesome/InstanceBehavior.cs @@ -1,6 +1,6 @@ namespace OctoAwesome { - public enum InstanceBehaviour + public enum InstanceBehavior { Instance, Singleton diff --git a/OctoAwesome/OctoAwesome/InventorySlot.cs b/OctoAwesome/OctoAwesome/InventorySlot.cs index f367d767..83852f50 100644 --- a/OctoAwesome/OctoAwesome/InventorySlot.cs +++ b/OctoAwesome/OctoAwesome/InventorySlot.cs @@ -12,12 +12,13 @@ public class InventorySlot /// public IInventoryable Item { - get => item; set + get => item; + private init { if (value is IDefinition definition) Definition = definition; - else if (value is IItem item) - Definition = item.Definition; + else if (value is IItem i) + Definition = i.Definition; else Definition = null; @@ -25,13 +26,17 @@ public IInventoryable Item } } - private IInventoryable item; + private readonly IInventoryable item; /// /// Volumen des Elementes in diesem Slot in dm³. /// public decimal Amount { get; set; } + public IDefinition? Definition { get; init; } - public IDefinition Definition { get; set; } + public InventorySlot(IInventoryable item) + { + Item = item; + } } } diff --git a/OctoAwesome/OctoAwesome/LocalBuilder.cs b/OctoAwesome/OctoAwesome/LocalBuilder.cs index 326071c4..06669acb 100644 --- a/OctoAwesome/OctoAwesome/LocalBuilder.cs +++ b/OctoAwesome/OctoAwesome/LocalBuilder.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using System.ComponentModel; -using System.Data.Common; +using System.Diagnostics; using System.Linq; namespace OctoAwesome @@ -46,9 +45,9 @@ public LocalBuilder(int originX, int originY, int originZ, IChunkColumn column00 /// /// /// - public static IChunkColumn GetColumn(IChunkColumn column00, IChunkColumn column10, IChunkColumn column01, IChunkColumn column11, int x, int y) + public static IChunkColumn? GetColumn(IChunkColumn column00, IChunkColumn column10, IChunkColumn column01, IChunkColumn column11, int x, int y) { - IChunkColumn column; + IChunkColumn? column = null; if (x >= Chunk.CHUNKSIZE_X && y >= Chunk.CHUNKSIZE_Y) column = column11; @@ -74,7 +73,9 @@ public static IChunkColumn GetColumn(IChunkColumn column00, IChunkColumn column1 /// public static int GetSurfaceHeight(IChunkColumn column00, IChunkColumn column10, IChunkColumn column01, IChunkColumn column11, int x, int y) { - IChunkColumn curColumn = GetColumn(column00, column10, column01, column11, x, y); + var curColumn = GetColumn(column00, column10, column01, column11, x, y); + if (curColumn == null) + return -1; return curColumn.Heights[x % Chunk.CHUNKSIZE_X, y % Chunk.CHUNKSIZE_Y]; } @@ -91,7 +92,9 @@ public void SetBlock(int x, int y, int z, ushort block, int meta = 0) x += originX; y += originY; z += originZ; - IChunkColumn column = GetColumn(column00, column10, column01, column11, x, y); + var column = GetColumn(column00, column10, column01, column11, x, y); + + Debug.Assert(column != null, nameof(column) + " != null"); var index = z / Chunk.CHUNKSIZE_Z; x %= Chunk.CHUNKSIZE_X; y %= Chunk.CHUNKSIZE_Y; @@ -111,7 +114,9 @@ public void SetBlocks(bool issueNotification, params BlockInfo[] blockInfos) var x = b.Position.X + originX; var y = b.Position.Y + originY; var z = b.Position.Z + originZ; - IChunkColumn column = GetColumn(column00, column10, column01, column11, x, y); + var column = GetColumn(column00, column10, column01, column11, x, y); + + Debug.Assert(column != null, nameof(column) + " != null"); var index = z / Chunk.CHUNKSIZE_Z; x %= Chunk.CHUNKSIZE_X; y %= Chunk.CHUNKSIZE_Y; @@ -164,7 +169,8 @@ public ushort GetBlock(int x, int y, int z) x += originX; y += originY; z += originZ; - IChunkColumn column = GetColumn(column00, column10, column01, column11, x, y); + var column = GetColumn(column00, column10, column01, column11, x, y); + Debug.Assert(column != null, nameof(column) + " != null"); x %= Chunk.CHUNKSIZE_X; y %= Chunk.CHUNKSIZE_Y; return column.GetBlock(x, y, z); diff --git a/OctoAwesome/OctoAwesome/LocalChunkCache.cs b/OctoAwesome/OctoAwesome/LocalChunkCache.cs index 5f6dacc5..1826de0c 100644 --- a/OctoAwesome/OctoAwesome/LocalChunkCache.cs +++ b/OctoAwesome/OctoAwesome/LocalChunkCache.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -21,8 +20,7 @@ public class LocalChunkCache : ILocalChunkCache /// /// Aktueller Planet auf dem sich der Cache bezieht. /// - public IPlanet Planet { get; private set; } - + public IPlanet Planet { get; } public Index2 CenterPosition { get; set; } /// @@ -33,7 +31,7 @@ public class LocalChunkCache : ILocalChunkCache /// /// Die im lokalen Cache gespeicherten Chunks /// - private readonly IChunkColumn[] chunkColumns; + private readonly IChunkColumn?[] chunkColumns; private readonly ILogger logger; /// @@ -53,12 +51,12 @@ public class LocalChunkCache : ILocalChunkCache /// /// Task, der bei einem Wechsel des Zentralen Chunks neue nachlädt falls nötig /// - private Task _loadingTask; + private Task? loadingTask; /// /// Token, das angibt, ob der Chûnk-nachlade-Task abgebrochen werden soll /// - private CancellationTokenSource _cancellationToken; + private CancellationTokenSource? cancellationToken; /// /// Instanziert einen neuen local Chunk Cache. /// @@ -89,7 +87,7 @@ public LocalChunkCache(IGlobalChunkCache globalCache, int dimensions, int range) /// Der Planet, auf dem sich der Chunk befindet /// Die Koordinaten an der sich der Chunk befindet /// Routine die Aufgerufen werden soll, falls das setzen erfolgreich war oder nicht - public bool SetCenter(Index2 index, Action successCallback = null) + public bool SetCenter(Index2 index, Action? successCallback = null) { using (taskSemaphore.Wait()) { @@ -97,18 +95,18 @@ public bool SetCenter(Index2 index, Action successCallback = null) logger.Debug($"Set Center from {callerName}"); CenterPosition = index; - if (_loadingTask != null && !_loadingTask.IsCompleted) + if (loadingTask != null && !loadingTask.IsCompleted) { logger.Debug("Continue with task on index " + index); - _loadingTask = _loadingTask.ContinueWith(_ => InternalSetCenter(_cancellationToken.Token, index, successCallback)); + loadingTask = loadingTask.ContinueWith(_ => InternalSetCenter(cancellationToken!.Token, index, successCallback)); } else { logger.Debug("New task on index " + index); - _cancellationToken?.Cancel(); - _cancellationToken?.Dispose(); - _cancellationToken = new CancellationTokenSource(); - _loadingTask = Task.Run(() => InternalSetCenter(_cancellationToken.Token, index, successCallback)); + cancellationToken?.Cancel(); + cancellationToken?.Dispose(); + cancellationToken = new CancellationTokenSource(); + loadingTask = Task.Run(() => InternalSetCenter(cancellationToken.Token, index, successCallback)); } } return true; @@ -121,7 +119,7 @@ public bool SetCenter(Index2 index, Action successCallback = null) /// Der Planet, auf dem die Chunks aktualisiert werden sollen /// Der ins Zentrum zu setzende Chunk /// Routine die Aufgerufen werden soll, falls das setzen erfolgreich war oder nicht - private void InternalSetCenter(CancellationToken token, Index2 index, Action successCallback) + private void InternalSetCenter(CancellationToken token, Index2 index, Action? successCallback) { if (Planet == null) { @@ -155,9 +153,9 @@ private void InternalSetCenter(CancellationToken token, Index2 index, Action /// Chunk Index /// Instanz des Chunks - public IChunk GetChunk(Index3 index) + public IChunk? GetChunk(Index3 index) => GetChunk(index.X, index.Y, index.Z); /// @@ -229,7 +223,7 @@ public IChunk GetChunk(Index3 index) /// Y Koordinate /// Z Koordinate /// Instanz des Chunks - public IChunk GetChunk(int x, int y, int z) + public IChunk? GetChunk(int x, int y, int z) { if (Planet == null || z < 0 || z >= Planet.Size.Z) return null; @@ -260,7 +254,7 @@ public ushort GetBlock(Index3 index) /// Die Block-ID an der angegebenen Koordinate public BlockInfo GetBlockInfo(Index3 index) { - IChunk chunk = GetChunk(index.X >> Chunk.LimitX, index.Y >> Chunk.LimitY, index.Z >> Chunk.LimitZ); + var chunk = GetChunk(index.X >> Chunk.LimitX, index.Y >> Chunk.LimitY, index.Z >> Chunk.LimitZ); if (chunk != null) { @@ -283,7 +277,7 @@ public BlockInfo GetBlockInfo(Index3 index) /// Die Block-ID an der angegebenen Koordinate public ushort GetBlock(int x, int y, int z) { - IChunk chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); + var chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); if (chunk != null) return chunk.GetBlock(x, y, z); @@ -308,10 +302,9 @@ public void SetBlock(Index3 index, ushort block) /// Die neue Block-ID public void SetBlock(int x, int y, int z, ushort block) { - IChunk chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); + var chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); - if (chunk != null) - chunk.SetBlock(x, y, z, block); + chunk?.SetBlock(x, y, z, block); } /// @@ -323,7 +316,7 @@ public void SetBlock(int x, int y, int z, ushort block) /// Die Metadaten des angegebenen Blocks public int GetBlockMeta(int x, int y, int z) { - IChunk chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); + var chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); if (chunk != null) return chunk.GetBlockMeta(x, y, z); @@ -348,10 +341,9 @@ public int GetBlockMeta(Index3 index) /// Die neuen Metadaten public void SetBlockMeta(int x, int y, int z, int meta) { - IChunk chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); + var chunk = GetChunk(x >> Chunk.LimitX, y >> Chunk.LimitY, z >> Chunk.LimitZ); - if (chunk != null) - chunk.SetBlockMeta(x, y, z, meta); + chunk?.SetBlockMeta(x, y, z, meta); } /// @@ -369,11 +361,10 @@ public void Flush() { for (int i = 0; i < chunkColumns.Length; i++) { - if (chunkColumns[i] == null) + var chunkColumn = chunkColumns[i]; + if (chunkColumn == null) continue; - IChunkColumn chunkColumn = chunkColumns[i]; - globalCache.Release(chunkColumn.Index); chunkColumns[i] = null; } @@ -386,7 +377,7 @@ public void Flush() /// Die Y-Koordinate /// Der Abgeflachte index private int FlatIndex(int x, int y) - => (((y & (mask)) << limit) | ((x & (mask)))); + => ((y & mask) << limit) | (x & mask); /// /// Returns the highest global z block position for the given global block position diff --git a/OctoAwesome/OctoAwesome/Logging/ILogger.cs b/OctoAwesome/OctoAwesome/Logging/ILogger.cs index 278fbbee..791523c3 100644 --- a/OctoAwesome/OctoAwesome/Logging/ILogger.cs +++ b/OctoAwesome/OctoAwesome/Logging/ILogger.cs @@ -2,35 +2,37 @@ namespace OctoAwesome.Logging { + public interface ILogger { void Debug(string message); void Debug(string message, Exception exception); - void Debug(T message); + void Debug(T message); void Error(string message); void Error(string message, Exception exception); - void Error(T message); + void Error(T message); void Fatal(string message); void Fatal(string message, Exception exception); + void Fatal(T message); void Info(string message); void Info(string message, Exception exception); + void Info(T message); void Trace(string message); void Trace(string message, Exception exception); - void Trace(T message); + void Trace(T message); void Warn(string message); void Warn(string message, Exception exception); - void Warn(T message); + void Warn(T message); ILogger As(string loggerName); ILogger As(Type type); - void Flush(); } } \ No newline at end of file diff --git a/OctoAwesome/OctoAwesome/Logging/Logger.cs b/OctoAwesome/OctoAwesome/Logging/Logger.cs index f9e54df6..1bf8e1ac 100644 --- a/OctoAwesome/OctoAwesome/Logging/Logger.cs +++ b/OctoAwesome/OctoAwesome/Logging/Logger.cs @@ -1,15 +1,12 @@ using NLog; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Logging { + public sealed class Logger : ILogger { - private readonly static NLog.ILogger nullLogger; + private static readonly NLog.ILogger nullLogger; static Logger() { @@ -17,62 +14,53 @@ static Logger() } private NLog.ILogger internalLogger; - public Logger() { internalLogger = nullLogger; } - public void Info(string message) => internalLogger.Info(message); public void Info(string message, Exception exception) => internalLogger.Info(exception, message); public void Info(T message) => internalLogger.Info(message); - public void Error(string message) => internalLogger.Error(message); public void Error(string message, Exception exception) => internalLogger.Error(exception, message); public void Error(T message) => internalLogger.Error(message); - public void Warn(string message) => internalLogger.Warn(message); public void Warn(string message, Exception exception) => internalLogger.Warn(exception, message); public void Warn(T message) => internalLogger.Warn(message); - public void Debug(string message) => internalLogger.Debug(message); public void Debug(string message, Exception exception) => internalLogger.Debug(exception, message); public void Debug(T message) => internalLogger.Debug(message); - public void Trace(string message) => internalLogger.Trace(message); public void Trace(string message, Exception exception) => internalLogger.Trace(exception, message); public void Trace(T message) => internalLogger.Trace(message); - public void Fatal(string message) => internalLogger.Fatal(message); public void Fatal(string message, Exception exception) => internalLogger.Fatal(exception, message); public void Fatal(T message) => internalLogger.Fatal(message); - public ILogger As(string loggerName) { - internalLogger = NLog.LogManager.GetLogger(loggerName); + internalLogger = LogManager.GetLogger(loggerName); return this; } public ILogger As(Type type) => As(type.FullName); - public void Flush() { LogManager.Flush(); diff --git a/OctoAwesome/OctoAwesome/Logging/NullLogger.cs b/OctoAwesome/OctoAwesome/Logging/NullLogger.cs index fb435961..e984d71e 100644 --- a/OctoAwesome/OctoAwesome/Logging/NullLogger.cs +++ b/OctoAwesome/OctoAwesome/Logging/NullLogger.cs @@ -1,53 +1,42 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Logging { + public class NullLogger : ILogger { + public static ILogger Default { get; } static NullLogger() { Default = new NullLogger().As(nameof(Default)); } - - public string Name { get; private set; } - + public string Name { get; private init; } public ILogger As(string loggerName) => new NullLogger - { - Name = loggerName - }; + { + Name = loggerName + }; public ILogger As(Type type) => As(type.FullName); - public void Debug(string message) { } public void Debug(string message, Exception exception) { } public void Debug(T message) { } - public void Error(string message) { } public void Error(string message, Exception exception) { } public void Error(T message) { } - public void Fatal(string message) { } public void Fatal(string message, Exception exception) { } public void Fatal(T message) { } - public void Info(string message) { } public void Info(string message, Exception exception) { } public void Info(T message) { } - public void Trace(string message) { } public void Trace(string message, Exception exception) { } public void Trace(T message) { } - public void Warn(string message) { } public void Warn(string message, Exception exception) { } public void Warn(T message) { } - public void Flush() { } } } diff --git a/OctoAwesome/OctoAwesome/Notifications/BlockChangedNotification.cs b/OctoAwesome/OctoAwesome/Notifications/BlockChangedNotification.cs index 7256baaf..cfd8320e 100644 --- a/OctoAwesome/OctoAwesome/Notifications/BlockChangedNotification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/BlockChangedNotification.cs @@ -3,12 +3,13 @@ namespace OctoAwesome.Notifications { + public sealed class BlockChangedNotification : SerializableNotification, IChunkNotification { + public BlockInfo BlockInfo { get; set; } public Index3 ChunkPos { get; internal set; } public int Planet { get; internal set; } - public override void Deserialize(BinaryReader reader) { if (reader.ReadByte() != (byte)BlockNotificationType.BlockChanged)//Read type of the notification @@ -30,7 +31,6 @@ public override void Deserialize(BinaryReader reader) Planet = reader.ReadInt32(); } - public override void Serialize(BinaryWriter writer) { writer.Write((byte)BlockNotificationType.BlockChanged); //indicate that this is a single Block Notification @@ -46,7 +46,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(ChunkPos.Z); writer.Write(Planet); } - protected override void OnRelease() { BlockInfo = default; diff --git a/OctoAwesome/OctoAwesome/Notifications/BlockNotificationType.cs b/OctoAwesome/OctoAwesome/Notifications/BlockNotificationType.cs index ef8198da..55ec1eea 100644 --- a/OctoAwesome/OctoAwesome/Notifications/BlockNotificationType.cs +++ b/OctoAwesome/OctoAwesome/Notifications/BlockNotificationType.cs @@ -1,13 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Notifications +namespace OctoAwesome.Notifications { + public enum BlockNotificationType : byte { + BlockChanged = 1, BlocksChanged = 2 } diff --git a/OctoAwesome/OctoAwesome/Notifications/BlocksChangedNotification.cs b/OctoAwesome/OctoAwesome/Notifications/BlocksChangedNotification.cs index ba82e813..eed3ac2f 100644 --- a/OctoAwesome/OctoAwesome/Notifications/BlocksChangedNotification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/BlocksChangedNotification.cs @@ -1,19 +1,16 @@ -using NLog.Targets.Wrappers; -using System; +using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Notifications { + public sealed class BlocksChangedNotification : SerializableNotification, IChunkNotification { + public ICollection BlockInfos { get; set; } public Index3 ChunkPos { get; internal set; } public int Planet { get; internal set; } - public override void Deserialize(BinaryReader reader) { if (reader.ReadByte() != (byte)BlockNotificationType.BlocksChanged)//Read type of the notification @@ -38,8 +35,9 @@ public override void Deserialize(BinaryReader reader) block: reader.ReadUInt16(), meta: reader.ReadInt32())); } - } + BlockInfos = list; + } public override void Serialize(BinaryWriter writer) { writer.Write((byte)BlockNotificationType.BlocksChanged); //indicate that this is a multi Block Notification @@ -58,7 +56,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(block.Meta); } } - protected override void OnRelease() { BlockInfos = default; diff --git a/OctoAwesome/OctoAwesome/Notifications/DefaultChannels.cs b/OctoAwesome/OctoAwesome/Notifications/DefaultChannels.cs index 0b1da778..2e66ef49 100644 --- a/OctoAwesome/OctoAwesome/Notifications/DefaultChannels.cs +++ b/OctoAwesome/OctoAwesome/Notifications/DefaultChannels.cs @@ -1,7 +1,9 @@ namespace OctoAwesome.Notifications { + public static class DefaultChannels { + public const string None = "none"; public const string Network = "network"; public const string Simulation = "simulation"; diff --git a/OctoAwesome/OctoAwesome/Notifications/EntityNotification.cs b/OctoAwesome/OctoAwesome/Notifications/EntityNotification.cs index 2d6345ce..8de6d480 100644 --- a/OctoAwesome/OctoAwesome/Notifications/EntityNotification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/EntityNotification.cs @@ -1,32 +1,29 @@ using OctoAwesome.Pooling; using OctoAwesome.Serialization; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Notifications { + public sealed class EntityNotification : SerializableNotification { + public ActionType Type { get; set; } public Guid EntityId { get; set; } public Entity Entity { - get => entity; set + get => entity; + set { entity = value; EntityId = value?.Id ?? default; } } - - public PropertyChangedNotification Notification { get; set; } + public PropertyChangedNotification? Notification { get; set; } private Entity entity; private readonly IPool propertyChangedNotificationPool; - public EntityNotification() { propertyChangedNotificationPool = TypeContainer.Get>(); @@ -36,12 +33,9 @@ public EntityNotification(Guid id) : this() { EntityId = id; } - public override void Deserialize(BinaryReader reader) { Type = (ActionType)reader.ReadInt32(); - - if (Type == ActionType.Add) Entity = Serializer.Deserialize(reader.ReadBytes(reader.ReadInt32())); else @@ -52,7 +46,6 @@ public override void Deserialize(BinaryReader reader) Notification = Serializer.DeserializePoolElement( propertyChangedNotificationPool, reader.ReadBytes(reader.ReadInt32())); } - public override void Serialize(BinaryWriter writer) { writer.Write((int)Type); @@ -77,7 +70,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(bytes); } } - protected override void OnRelease() { Notification?.Release(); @@ -88,13 +80,17 @@ protected override void OnRelease() base.OnRelease(); } - public enum ActionType { + None, + Add, + Remove, + Update, + Request } } diff --git a/OctoAwesome/OctoAwesome/Notifications/FunctionalBlockNotification.cs b/OctoAwesome/OctoAwesome/Notifications/FunctionalBlockNotification.cs index 604f0d2e..4fd0b1b5 100644 --- a/OctoAwesome/OctoAwesome/Notifications/FunctionalBlockNotification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/FunctionalBlockNotification.cs @@ -1,16 +1,13 @@ -using OctoAwesome.Pooling; -using OctoAwesome.Serialization; +using OctoAwesome.Serialization; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Notifications { + public sealed class FunctionalBlockNotification : SerializableNotification { + public ActionType Type { get; set; } public Guid BlockId { get; set; } public FunctionalBlock Block @@ -23,7 +20,6 @@ public FunctionalBlock Block } private FunctionalBlock block; - public FunctionalBlockNotification() { } @@ -32,19 +28,15 @@ public FunctionalBlockNotification(Guid id) : this() { BlockId = id; } - public override void Deserialize(BinaryReader reader) { Type = (ActionType)reader.ReadInt32(); - - if (Type == ActionType.Add) { } //Block = Serializer.Deserialize() else BlockId = new Guid(reader.ReadBytes(16)); } - public override void Serialize(BinaryWriter writer) { writer.Write((int)Type); @@ -61,7 +53,6 @@ public override void Serialize(BinaryWriter writer) } } - protected override void OnRelease() { Type = default; @@ -69,13 +60,15 @@ protected override void OnRelease() base.OnRelease(); } - public enum ActionType { + None, Add, Remove, Update, + + Request } } diff --git a/OctoAwesome/OctoAwesome/Notifications/IChunkNotification.cs b/OctoAwesome/OctoAwesome/Notifications/IChunkNotification.cs index 10638959..06e10080 100644 --- a/OctoAwesome/OctoAwesome/Notifications/IChunkNotification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/IChunkNotification.cs @@ -1,13 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Notifications +namespace OctoAwesome.Notifications { + public interface IChunkNotification { + Index3 ChunkPos { get; } int Planet { get; } } diff --git a/OctoAwesome/OctoAwesome/Notifications/INotificationSubject.cs b/OctoAwesome/OctoAwesome/Notifications/INotificationSubject.cs index 4d6487c0..d6a4f58c 100644 --- a/OctoAwesome/OctoAwesome/Notifications/INotificationSubject.cs +++ b/OctoAwesome/OctoAwesome/Notifications/INotificationSubject.cs @@ -1,12 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Notifications +namespace OctoAwesome.Notifications { - public interface INotificationSubject where TNotification : Notification + public interface INotificationSubject where TNotification : Notification { void OnNotification(TNotification notification); diff --git a/OctoAwesome/OctoAwesome/Notifications/IUpdateHub.cs b/OctoAwesome/OctoAwesome/Notifications/IUpdateHub.cs index f8dc862c..4a28d09e 100644 --- a/OctoAwesome/OctoAwesome/Notifications/IUpdateHub.cs +++ b/OctoAwesome/OctoAwesome/Notifications/IUpdateHub.cs @@ -1,13 +1,11 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Notifications { + public interface IUpdateHub { + IDisposable AddSource(IObservable notification, string channel); IObservable ListenOn(string channel); } diff --git a/OctoAwesome/OctoAwesome/Notifications/Notification.cs b/OctoAwesome/OctoAwesome/Notifications/Notification.cs index 30d39042..0f151ade 100644 --- a/OctoAwesome/OctoAwesome/Notifications/Notification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/Notification.cs @@ -1,14 +1,11 @@ using OctoAwesome.Pooling; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Notifications { + public abstract class Notification : IPoolElement { + public uint SenderId { get; set; } private IPool pool; @@ -17,18 +14,16 @@ public virtual bool Match(T filter) { return true; } - public void Init(IPool pool) { this.pool = pool; OnInit(); } - public void Release() { SenderId = 0; OnRelease(); - pool.Push(this); + pool.Return(this); } /// diff --git a/OctoAwesome/OctoAwesome/Notifications/PropertyChangedNotification.cs b/OctoAwesome/OctoAwesome/Notifications/PropertyChangedNotification.cs index b5959fb8..9d29e0dd 100644 --- a/OctoAwesome/OctoAwesome/Notifications/PropertyChangedNotification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/PropertyChangedNotification.cs @@ -1,19 +1,14 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.IO; namespace OctoAwesome.Notifications { + public class PropertyChangedNotification : SerializableNotification { + public string Issuer { get; set; } public string Property { get; set; } - public byte[] Value { get; set; } - public override void Deserialize(BinaryReader reader) { Issuer = reader.ReadString(); @@ -21,7 +16,6 @@ public override void Deserialize(BinaryReader reader) var count = reader.ReadInt32(); Value = reader.ReadBytes(count); } - public override void Serialize(BinaryWriter writer) { writer.Write(Issuer); @@ -29,7 +23,6 @@ public override void Serialize(BinaryWriter writer) writer.Write(Value.Length); writer.Write(Value); } - protected override void OnRelease() { Issuer = default; diff --git a/OctoAwesome/OctoAwesome/Notifications/SerializableNotification.cs b/OctoAwesome/OctoAwesome/Notifications/SerializableNotification.cs index febe0018..64034377 100644 --- a/OctoAwesome/OctoAwesome/Notifications/SerializableNotification.cs +++ b/OctoAwesome/OctoAwesome/Notifications/SerializableNotification.cs @@ -1,18 +1,13 @@ using OctoAwesome.Serialization; -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Notifications { + public abstract class SerializableNotification : Notification, ISerializable { public abstract void Deserialize(BinaryReader reader); - public abstract void Serialize(BinaryWriter writer); } } diff --git a/OctoAwesome/OctoAwesome/Notifications/UpdateHub.cs b/OctoAwesome/OctoAwesome/Notifications/UpdateHub.cs index e1800b5a..90cfb05a 100644 --- a/OctoAwesome/OctoAwesome/Notifications/UpdateHub.cs +++ b/OctoAwesome/OctoAwesome/Notifications/UpdateHub.cs @@ -1,25 +1,22 @@ -using OctoAwesome.Notifications; -using OctoAwesome.Rx; +using OctoAwesome.Rx; using OctoAwesome.Threading; using System; using System.Collections.Generic; namespace OctoAwesome.Notifications { + public class UpdateHub : IDisposable, IUpdateHub { private readonly Dictionary> channels; private readonly LockSemaphore lockSemaphore; - public UpdateHub() { channels = new(); lockSemaphore = new LockSemaphore(1, 1); } - public IObservable ListenOn(string channel) => GetChannelRelay(channel); - public IDisposable AddSource(IObservable notification, string channel) => notification.Subscribe(GetChannelRelay(channel)); @@ -35,7 +32,6 @@ private ConcurrentRelay GetChannelRelay(string channel) return channelRelay; } - public void Dispose() { foreach (var channel in channels) diff --git a/OctoAwesome/OctoAwesome/OctoAwesome.csproj b/OctoAwesome/OctoAwesome/OctoAwesome.csproj index 7047d9da..57b2fb56 100644 --- a/OctoAwesome/OctoAwesome/OctoAwesome.csproj +++ b/OctoAwesome/OctoAwesome/OctoAwesome.csproj @@ -2,7 +2,7 @@ net5.0 - warnings + enable True @@ -10,11 +10,14 @@ + + + - + diff --git a/OctoAwesome/OctoAwesome/OctoMath/Polynomial.cs b/OctoAwesome/OctoAwesome/OctoMath/Polynomial.cs index f41742f7..a8d65ba3 100644 --- a/OctoAwesome/OctoAwesome/OctoMath/Polynomial.cs +++ b/OctoAwesome/OctoAwesome/OctoMath/Polynomial.cs @@ -1,24 +1,25 @@ namespace OctoAwesome.OctoMath { + public class Polynomial { - private readonly float[] coeffecients; - - public Polynomial(params float[] coeffecients) - => this.coeffecients = coeffecients; + private readonly float[] coefficients; + public Polynomial(params float[] coefficients) + => this.coefficients = coefficients; public float Evaluate(float px) { - if (coeffecients.Length == 0) + if (coefficients.Length == 0) { return 0; } - var result = coeffecients[0]; + // c0 + c1 * x + c2 * x^2 + var result = coefficients[0]; float x = px; - for (var i = 1; i < coeffecients.Length; ++i) + for (var i = 1; i < coefficients.Length; ++i) { - result += x * coeffecients[i]; + result += x * coefficients[i]; x *= px; } diff --git a/OctoAwesome/OctoAwesome/Planet.cs b/OctoAwesome/OctoAwesome/Planet.cs index cff0cbf2..dfdd7505 100644 --- a/OctoAwesome/OctoAwesome/Planet.cs +++ b/OctoAwesome/OctoAwesome/Planet.cs @@ -1,7 +1,6 @@ using System; -using System.Collections.Generic; +using System.Diagnostics; using System.IO; -using System.Text; using OctoAwesome.Notifications; namespace OctoAwesome @@ -11,6 +10,7 @@ namespace OctoAwesome /// public class Planet : IPlanet { + protected IClimateMap? climateMap; /// /// ID des Planeten. @@ -25,7 +25,14 @@ public class Planet : IPlanet /// /// Die Klimakarte des Planeten /// - public IClimateMap ClimateMap { get; protected set; } + public IClimateMap ClimateMap + { + get + { + Debug.Assert(climateMap != null, nameof(climateMap) + " != null"); + return climateMap; + } + } /// /// Seed des Zufallsgenerators dieses Planeten. @@ -46,7 +53,6 @@ public class Planet : IPlanet /// Der Generator des Planeten. /// public IMapGenerator Generator { get; set; } - public IGlobalChunkCache GlobalChunkCache { get; } private bool disposed; @@ -110,7 +116,6 @@ public virtual void Deserialize(BinaryReader reader) Universe = new Guid(reader.ReadBytes(16)); //var name = reader.ReadString(); } - public void Dispose() { if (disposed) diff --git a/OctoAwesome/OctoAwesome/PlanetIndex3.cs b/OctoAwesome/OctoAwesome/PlanetIndex3.cs index 8051a19c..74cd73c6 100644 --- a/OctoAwesome/OctoAwesome/PlanetIndex3.cs +++ b/OctoAwesome/OctoAwesome/PlanetIndex3.cs @@ -1,9 +1,11 @@ -namespace OctoAwesome +using System; + +namespace OctoAwesome { /// /// Datenstruktur zur genauen bestimmung eines Chunks und seinen Planeten /// - public struct PlanetIndex3 + public struct PlanetIndex3 : IEquatable { /// /// Die Planeten-ID @@ -58,25 +60,22 @@ public PlanetIndex3(int planet, Index3 chunkIndex) /// /// /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { - if (obj is PlanetIndex3 other) - return other.Planet == Planet && - other.ChunkIndex.X == ChunkIndex.X && - other.ChunkIndex.Y == ChunkIndex.Y && - other.ChunkIndex.Z == ChunkIndex.Z; - - return false; + return obj is PlanetIndex3 other && Equals(other); + } + public bool Equals(PlanetIndex3 other) + { + return Planet == other.Planet && ChunkIndex.Equals(other.ChunkIndex); } /// /// Erzeugt einen möglichst eindeutigen Hashcode des PlanetIndex3s /// /// - public override int GetHashCode() - => (Planet << 24) + - (ChunkIndex.X << 16) + - (ChunkIndex.Y << 8) + - ChunkIndex.Z; + public override int GetHashCode() + { + return HashCode.Combine(Planet, ChunkIndex); + } } } diff --git a/OctoAwesome/OctoAwesome/Player.cs b/OctoAwesome/OctoAwesome/Player.cs index e8c94a83..6781e3b5 100644 --- a/OctoAwesome/OctoAwesome/Player.cs +++ b/OctoAwesome/OctoAwesome/Player.cs @@ -1,10 +1,4 @@ -using System.Collections.Generic; -using System.Xml.Serialization; -using engenious; -using System.IO; -using System.Linq; -using OctoAwesome.EntityComponents; -using OctoAwesome.Notifications; +using OctoAwesome.Notifications; using OctoAwesome.Pooling; using OctoAwesome.Serialization; @@ -26,31 +20,15 @@ public sealed class Player : Entity /// /// Erzeugt eine neue Player-Instanz an der Default-Position. /// - public Player() : base() + public Player() { entityNotificationPool = TypeContainer.Get>(); } - - - /// - /// Serialisiert den Player mit dem angegebenen BinaryWriter. - /// - /// Der BinaryWriter, mit dem geschrieben wird. - public override void Serialize(BinaryWriter writer) - => base.Serialize(writer); // Entity - - /// - /// Deserialisiert den Player aus dem angegebenen BinaryReader. - /// - /// Der BinaryWriter, mit dem gelesen wird. - public override void Deserialize(BinaryReader reader) - => base.Deserialize(reader); // Entity - public override void OnNotification(SerializableNotification notification) { base.OnNotification(notification); - var entityNotification = entityNotificationPool.Get(); + var entityNotification = entityNotificationPool.Rent(); entityNotification.Entity = this; entityNotification.Type = EntityNotification.ActionType.Update; entityNotification.Notification = notification as PropertyChangedNotification; diff --git a/OctoAwesome/OctoAwesome/Pooling/ChunkPool.cs b/OctoAwesome/OctoAwesome/Pooling/ChunkPool.cs index 141311f4..6ab79387 100644 --- a/OctoAwesome/OctoAwesome/Pooling/ChunkPool.cs +++ b/OctoAwesome/OctoAwesome/Pooling/ChunkPool.cs @@ -2,29 +2,25 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Pooling { + public sealed class ChunkPool : IPool { private readonly Stack internalStack; private readonly LockSemaphore semaphoreExtended; - public ChunkPool() { internalStack = new Stack(); semaphoreExtended = new LockSemaphore(1, 1); } - [Obsolete("Can not be used. Use Get(Index3, IPlanet) instead.", true)] - public Chunk Get() + public Chunk Rent() { throw new NotSupportedException($"Use Get(Index3, IPlanet) instead."); } - public Chunk Get(Index3 position, IPlanet planet) + public Chunk Rent(Index3 position, IPlanet planet) { Chunk obj; @@ -39,23 +35,21 @@ public Chunk Get(Index3 position, IPlanet planet) obj.Init(position, planet); return obj; } - - public void Push(Chunk obj) + public void Return(Chunk obj) { using (semaphoreExtended.Wait()) internalStack.Push(obj); } - - public void Push(IPoolElement obj) + public void Return(IPoolElement obj) { if (obj is Chunk chunk) { - Push(chunk); + Return(chunk); } else { - throw new InvalidCastException("Can not push object from type: " + obj.GetType()); + throw new InvalidCastException("Can not push object of type: " + obj.GetType()); } } diff --git a/OctoAwesome/OctoAwesome/Pooling/IPool.cs b/OctoAwesome/OctoAwesome/Pooling/IPool.cs index 6bab83a7..5bfd1115 100644 --- a/OctoAwesome/OctoAwesome/Pooling/IPool.cs +++ b/OctoAwesome/OctoAwesome/Pooling/IPool.cs @@ -1,19 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace OctoAwesome.Pooling +namespace OctoAwesome.Pooling { + public interface IPool { - void Push(IPoolElement obj); + void Return(IPoolElement obj); } public interface IPool : IPool where T : IPoolElement { - T Get(); - void Push(T obj); + T Rent(); + + void Return(T obj); } } diff --git a/OctoAwesome/OctoAwesome/Pooling/IPoolElement.cs b/OctoAwesome/OctoAwesome/Pooling/IPoolElement.cs index 1064caff..b7e53138 100644 --- a/OctoAwesome/OctoAwesome/Pooling/IPoolElement.cs +++ b/OctoAwesome/OctoAwesome/Pooling/IPoolElement.cs @@ -1,5 +1,6 @@ namespace OctoAwesome.Pooling { + public interface IPoolElement { void Init(IPool pool); diff --git a/OctoAwesome/OctoAwesome/Pooling/Pool.cs b/OctoAwesome/OctoAwesome/Pooling/Pool.cs index 479bfcab..89cc2600 100644 --- a/OctoAwesome/OctoAwesome/Pooling/Pool.cs +++ b/OctoAwesome/OctoAwesome/Pooling/Pool.cs @@ -1,10 +1,7 @@ using OctoAwesome.Threading; using System; using System.Collections.Generic; -using System.Linq; using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Pooling { @@ -20,14 +17,12 @@ static Pool() private readonly Stack internalStack; private readonly LockSemaphore semaphoreExtended; - public Pool() { internalStack = new Stack(); semaphoreExtended = new LockSemaphore(1, 1); } - - public T Get() + public T Rent() { T obj; @@ -42,18 +37,16 @@ public T Get() obj.Init(this); return obj; } - - public void Push(T obj) + public void Return(T obj) { using (semaphoreExtended.Wait()) internalStack.Push(obj); } - - public void Push(IPoolElement obj) + public void Return(IPoolElement obj) { if (obj is T t) { - Push(t); + Return(t); } else { diff --git a/OctoAwesome/OctoAwesome/RemoteEntity.cs b/OctoAwesome/OctoAwesome/RemoteEntity.cs index 36f3b50e..9eac0240 100644 --- a/OctoAwesome/OctoAwesome/RemoteEntity.cs +++ b/OctoAwesome/OctoAwesome/RemoteEntity.cs @@ -1,14 +1,11 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.IO; namespace OctoAwesome { + public class RemoteEntity : Entity { + public RemoteEntity() { @@ -23,13 +20,11 @@ public RemoteEntity(Entity originEntity) } Id = originEntity.Id; } - public override void Serialize(BinaryWriter writer) { Components.Serialize(writer); base.Serialize(writer); } - public override void Deserialize(BinaryReader reader) { Components.Deserialize(reader); diff --git a/OctoAwesome/OctoAwesome/Rx/ConcurrentRelay.cs b/OctoAwesome/OctoAwesome/Rx/ConcurrentRelay.cs index c7ec698b..71dbead1 100644 --- a/OctoAwesome/OctoAwesome/Rx/ConcurrentRelay.cs +++ b/OctoAwesome/OctoAwesome/Rx/ConcurrentRelay.cs @@ -1,21 +1,19 @@ using OctoAwesome.Threading; using System; using System.Collections.Generic; -using System.Diagnostics; namespace OctoAwesome.Rx { + public class ConcurrentRelay : IObservable, IObserver, IDisposable { private readonly List subscriptions; private readonly LockSemaphore lockSemaphore; - public ConcurrentRelay() { lockSemaphore = new LockSemaphore(1, 1); subscriptions = new(); } - public void OnCompleted() { using var scope = lockSemaphore.Wait(); @@ -25,7 +23,6 @@ public void OnCompleted() subscriptions[i]?.Observer.OnCompleted(); } } - public void OnError(Exception error) { using var scope = lockSemaphore.Wait(); @@ -35,7 +32,6 @@ public void OnError(Exception error) subscriptions[i]?.Observer.OnError(error); } } - public void OnNext(T value) { using var scope = lockSemaphore.Wait(); @@ -45,7 +41,6 @@ public void OnNext(T value) subscriptions[i]?.Observer.OnNext(value); } } - public IDisposable Subscribe(IObserver observer) { var sub = new RelaySubscription(this, observer); @@ -55,7 +50,6 @@ public IDisposable Subscribe(IObserver observer) return sub; } - public void Dispose() { @@ -70,8 +64,6 @@ private void Unsubscribe(RelaySubscription subscription) subscriptions.Remove(subscription); } - - private class RelaySubscription : IDisposable { public IObserver Observer { get; } diff --git a/OctoAwesome/OctoAwesome/Rx/IObservableExtension.cs b/OctoAwesome/OctoAwesome/Rx/IObservableExtension.cs index 879cddbc..6e831009 100644 --- a/OctoAwesome/OctoAwesome/Rx/IObservableExtension.cs +++ b/OctoAwesome/OctoAwesome/Rx/IObservableExtension.cs @@ -2,23 +2,29 @@ namespace OctoAwesome.Rx { + public static class IObservableExtension { + + public static IDisposable Subscribe(this IObservable observable, Action onNext) => observable.Subscribe(new Observer(onNext)); + + public static IDisposable Subscribe(this IObservable observable, Action onNext, Action onException) => observable.Subscribe(new Observer(onNext, onException)); + public static IDisposable Subscribe(this IObservable observable, Action onNext, Action onException, Action onComplete) => observable.Subscribe(new Observer(onNext, onException, onComplete)); private class Observer : IObserver { - private readonly Action onNext; - private readonly Action onException; - private readonly Action onComplete; + private readonly Action? onNext; + private readonly Action? onException; + private readonly Action? onComplete; - public Observer(Action onNext = null, Action onException = null, Action onComplete = null) + public Observer(Action? onNext = null, Action? onException = null, Action? onComplete = null) { this.onNext = onNext; this.onException = onException; diff --git a/OctoAwesome/OctoAwesome/Rx/Relay.cs b/OctoAwesome/OctoAwesome/Rx/Relay.cs index 9c45d710..4a89fec8 100644 --- a/OctoAwesome/OctoAwesome/Rx/Relay.cs +++ b/OctoAwesome/OctoAwesome/Rx/Relay.cs @@ -6,43 +6,37 @@ namespace OctoAwesome.Rx public class Relay : IObservable, IObserver, IDisposable { private readonly List subscriptions; - public Relay() { subscriptions = new(); } - public void OnCompleted() { for (int i = 0; i < subscriptions.Count; i++) { - subscriptions[i]?.Observer.OnCompleted(); + subscriptions[i].Observer.OnCompleted(); } } - public void OnError(Exception error) { for (int i = 0; i < subscriptions.Count; i++) { - subscriptions[i]?.Observer.OnError(error); + subscriptions[i].Observer.OnError(error); } } - public void OnNext(T value) { for (int i = 0; i < subscriptions.Count; i++) { - subscriptions[i]?.Observer.OnNext(value); + subscriptions[i].Observer.OnNext(value); } } - public IDisposable Subscribe(IObserver observer) { var sub = new RelaySubscription(this, observer); subscriptions.Add(sub); return sub; } - public void Dispose() { foreach (var subscription in subscriptions) @@ -57,8 +51,6 @@ private void Unsubscribe(RelaySubscription subscription) { subscriptions.Remove(subscription); } - - private class RelaySubscription : IDisposable { public IObserver Observer { get; } diff --git a/OctoAwesome/OctoAwesome/Serialization/ChunkColumnDbContext.cs b/OctoAwesome/OctoAwesome/Serialization/ChunkColumnDbContext.cs index e6f67a52..0be7a34c 100644 --- a/OctoAwesome/OctoAwesome/Serialization/ChunkColumnDbContext.cs +++ b/OctoAwesome/OctoAwesome/Serialization/ChunkColumnDbContext.cs @@ -1,30 +1,23 @@ using OctoAwesome.Database; -using System; -using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.IO.Compression; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + public sealed class ChunkColumnDbContext : DatabaseContext { private readonly IPlanet currentPlanet; - public ChunkColumnDbContext(Database database, IPlanet planet) : base(database) => currentPlanet = planet; - public override void AddOrUpdate(IChunkColumn value) { using (Database.Lock(Operation.Write)) Database.AddOrUpdate(new Index2Tag(value.Index), new Value(Serializer.SerializeCompressed(value, 2048))); } - public IChunkColumn Get(Index2 key) + public IChunkColumn? Get(Index2 key) => Get(new Index2Tag(key)); - public override IChunkColumn Get(Index2Tag key) + public override IChunkColumn? Get(Index2Tag key) { if (!Database.ContainsKey(key)) return null; @@ -39,7 +32,6 @@ public override IChunkColumn Get(Index2Tag key) return chunkColumn; } } - public override void Remove(IChunkColumn value) { using (Database.Lock(Operation.Write)) diff --git a/OctoAwesome/OctoAwesome/Serialization/ChunkDiffDbContext.cs b/OctoAwesome/OctoAwesome/Serialization/ChunkDiffDbContext.cs index 60312994..c8908c27 100644 --- a/OctoAwesome/OctoAwesome/Serialization/ChunkDiffDbContext.cs +++ b/OctoAwesome/OctoAwesome/Serialization/ChunkDiffDbContext.cs @@ -1,22 +1,18 @@ using OctoAwesome.Database; using OctoAwesome.Notifications; using OctoAwesome.Pooling; -using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + public sealed class ChunkDiffDbContext : DatabaseContext { private readonly IPool notificationBlockPool; - public ChunkDiffDbContext(Database database, IPool blockPool) : base(database) => notificationBlockPool = blockPool; - public override void AddOrUpdate(BlockChangedNotification value) { using (Database.Lock(Operation.Write)) @@ -31,7 +27,6 @@ public void AddOrUpdate(BlocksChangedNotification value) public IReadOnlyList GetAllKeys() => Database.Keys; - public override void Remove(BlockChangedNotification value) => InternalRemove(new ChunkDiffTag(value.ChunkPos, Chunk.GetFlatIndex(value.BlockInfo.Position))); @@ -43,6 +38,7 @@ public void Remove(params ChunkDiffTag[] tags) foreach (ChunkDiffTag tag in tags) InternalRemove(tag); } + public void Remove(IReadOnlyList tags) { foreach (ChunkDiffTag tag in tags) @@ -74,10 +70,9 @@ private BlockInfo InternalGet(ChunkDiffTag tag) return BlockInfo.Deserialize(reader); } } - public override BlockChangedNotification Get(ChunkDiffTag key) { - BlockChangedNotification notification = notificationBlockPool.Get(); + BlockChangedNotification notification = notificationBlockPool.Rent(); notification.BlockInfo = InternalGet(key); notification.ChunkPos = key.ChunkPositon; return notification; diff --git a/OctoAwesome/OctoAwesome/Serialization/ChunkDiffTag.cs b/OctoAwesome/OctoAwesome/Serialization/ChunkDiffTag.cs index abe359ae..41a1b4e4 100644 --- a/OctoAwesome/OctoAwesome/Serialization/ChunkDiffTag.cs +++ b/OctoAwesome/OctoAwesome/Serialization/ChunkDiffTag.cs @@ -2,25 +2,23 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + public struct ChunkDiffTag : ITag, IEquatable { public int Length => sizeof(int) * 4; - public Index3 ChunkPositon { get; set; } - public int FlatIndex { get; set; } + public Index3 ChunkPositon { get; private set; } + + public int FlatIndex { get; private set; } public ChunkDiffTag(Index3 chunkPosition, int flatIndex) { ChunkPositon = chunkPosition; FlatIndex = flatIndex; } - public void FromBytes(byte[] array, int startIndex) { var x = BitConverter.ToInt32(array, startIndex); @@ -29,7 +27,6 @@ public void FromBytes(byte[] array, int startIndex) FlatIndex = BitConverter.ToInt32(array, startIndex + sizeof(int) * 3); ChunkPositon = new Index3(x, y, z); } - public byte[] GetBytes() { var array = new byte[Length]; @@ -50,16 +47,13 @@ public void WriteBytes(Span span) BitConverter.TryWriteBytes(span[(intSize * 2)..(intSize * 3)], ChunkPositon.Z); BitConverter.TryWriteBytes(span[(intSize * 3)..(intSize * 4)], FlatIndex); } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is ChunkDiffTag tag && Equals(tag); - public bool Equals(ChunkDiffTag other) => Length == other.Length && FlatIndex == other.FlatIndex && EqualityComparer.Default.Equals(ChunkPositon, other.ChunkPositon); - public override int GetHashCode() { int hashCode = 1893591923; diff --git a/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerComponentDbContext.cs b/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerComponentDbContext.cs index bb4bef76..ad73d302 100644 --- a/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerComponentDbContext.cs +++ b/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerComponentDbContext.cs @@ -2,44 +2,38 @@ using OctoAwesome.Database; using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization.Entities { - public sealed class ComponentContainerComponentDbContext where TContainer : IComponent + public sealed class ComponentContainerComponentDbContext where TComponent : IComponent { private readonly IDatabaseProvider databaseProvider; private readonly Guid universeGuid; - public ComponentContainerComponentDbContext(IDatabaseProvider databaseProvider, Guid universe) { this.databaseProvider = databaseProvider; universeGuid = universe; } - public void AddOrUpdate(T value, ComponentContainer entity) where T : IComponent + public void AddOrUpdate(T value, ComponentContainer entity) where T : IComponent { Database> database = databaseProvider.GetDatabase>(universeGuid, false); var tag = new GuidTag(entity.Id); using (database.Lock(Operation.Write)) database.AddOrUpdate(tag, new Value(Serializer.Serialize(value))); } - public T Get(Guid id) where T : IComponent, new() { Database> database = databaseProvider.GetDatabase>(universeGuid, false); var tag = new GuidTag(id); return Serializer.Deserialize(database.GetValue(tag).Content); } - public T Get(ComponentContainer entity) where T : IComponent, new() - => Get(entity.Id); + public T Get(ComponentContainer entity) where T : IComponent, new() + => Get(entity.Id); public IReadOnlyList> GetAllKeys() where T : IComponent => databaseProvider.GetDatabase>(universeGuid, false).Keys; - - public void Remove(ComponentContainer entity) where T : IComponent + public void Remove(ComponentContainer entity) where T : IComponent { Database> database = databaseProvider.GetDatabase>(universeGuid, false); var tag = new GuidTag(entity.Id); diff --git a/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDbContext.cs b/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDbContext.cs index abd35b7f..76320790 100644 --- a/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDbContext.cs +++ b/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDbContext.cs @@ -4,41 +4,38 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization.Entities { + public sealed class ComponentContainerDbContext : IDatabaseContext, TContainer> where TContainer : ComponentContainer where TComponent : IComponent { - private readonly ComponentContainerDefinition.ComponentContainerDefinitionContext entityDefinitionContext; + private readonly ComponentContainerDefinition.ComponentContainerDefinitionContext entityDefinitionContext; private readonly ComponentContainerComponentDbContext componentsDbContext; private readonly MethodInfo getComponentMethod; private readonly MethodInfo removeComponentMethod; public ComponentContainerDbContext(IDatabaseProvider databaseProvider, Guid universe) { - var database = databaseProvider.GetDatabase>>(universeGuid: universe, fixedValueSize: false); - entityDefinitionContext = new ComponentContainerDefinition.ComponentContainerDefinitionContext(database); + var database = databaseProvider.GetDatabase>>(universe, false); + entityDefinitionContext = new ComponentContainerDefinition.ComponentContainerDefinitionContext(database); componentsDbContext = new ComponentContainerComponentDbContext(databaseProvider, universe); getComponentMethod = typeof(ComponentContainerComponentDbContext).GetMethod(nameof(ComponentContainerComponentDbContext.Get), new[] { typeof(TContainer) }); removeComponentMethod = typeof(ComponentContainerComponentDbContext).GetMethod(nameof(ComponentContainerComponentDbContext.Remove)); } - public void AddOrUpdate(TContainer value) { entityDefinitionContext.AddOrUpdate(new ComponentContainerDefinition(value)); - foreach (dynamic component in value.Components) //dynamic so tyepof in get database returns correct type + foreach (dynamic component in value.Components) //dynamic so typeof in get database returns correct type componentsDbContext.AddOrUpdate(component, value); } - public TContainer Get(GuidTag key) { - var definition = entityDefinitionContext.Get(new GuidTag>(key.Tag)); + var definition = entityDefinitionContext.Get(new GuidTag>(key.Id)); var entity = (TContainer)Activator.CreateInstance(definition.Type); entity!.Id = definition.Id; foreach (Type component in definition.Components) @@ -59,20 +56,8 @@ public TContainer Get(GuidTag key) return entity; } - public IEnumerable GetComponentContainerWithComponent() where T : IComponent - { - IEnumerable> entities = componentsDbContext.GetAllKeys().Select(t => new GuidTag(t.Tag)); - - foreach (GuidTag entityId in entities) - yield return Get(entityId); - } - - public IEnumerable> GetComponentContainerIdsFromComponent() where T : IComponent - => componentsDbContext.GetAllKeys().Select(t => new GuidTag(t.Tag)); - public IEnumerable> GetAllKeys() - => entityDefinitionContext.GetAllKeys().Select(e => new GuidTag(e.Tag)); - + => entityDefinitionContext.GetAllKeys().Select(e => new GuidTag(e.Id)); public void Remove(TContainer value) { var definition = entityDefinitionContext.Get(new GuidTag>(value.Id)); diff --git a/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDefinition.cs b/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDefinition.cs index 52fc3e45..27bdde9f 100644 --- a/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDefinition.cs +++ b/OctoAwesome/OctoAwesome/Serialization/Entities/ComponentContainerDefinition.cs @@ -7,18 +7,21 @@ namespace OctoAwesome.Serialization.Entities { - public sealed class ComponentContainerDefinition : ISerializable where TContainer : IComponent + public sealed class ComponentContainerDefinition : ISerializable where TComponent : IComponent { + public Type Type { get; set; } + + public Guid Id { get; set; } public int ComponentsCount { get; set; } public IEnumerable Components { get; set; } - public ComponentContainerDefinition() { } - public ComponentContainerDefinition(ComponentContainer entity) + + public ComponentContainerDefinition(ComponentContainer entity) { Type = entity.GetType(); Id = entity.Id; @@ -26,7 +29,6 @@ public ComponentContainerDefinition(ComponentContainer entity) ComponentsCount = tmpComponents.Count; Components = tmpComponents.Select(c => c.GetType()); } - public void Serialize(BinaryWriter writer) { writer.Write(Type.AssemblyQualifiedName!); @@ -36,7 +38,6 @@ public void Serialize(BinaryWriter writer) foreach (var component in Components) writer.Write(component.AssemblyQualifiedName!); } - public void Deserialize(BinaryReader reader) { Type = Type.GetType(reader.ReadString()); @@ -49,20 +50,17 @@ public void Deserialize(BinaryReader reader) Components = list; } - - public sealed class ComponentContainerDefinitionContext : SerializableDatabaseContext>, ComponentContainerDefinition> where TContainer : IComponent + public sealed class ComponentContainerDefinitionContext : SerializableDatabaseContext>, ComponentContainerDefinition> { - public ComponentContainerDefinitionContext(Database>> database) : base(database) + public ComponentContainerDefinitionContext(Database>> database) : base(database) { } + public override void AddOrUpdate(ComponentContainerDefinition value) + => InternalAddOrUpdate(new GuidTag>(value.Id), value); - public override void AddOrUpdate(ComponentContainerDefinition value) - => InternalAddOrUpdate(new GuidTag>(value.Id), value); - - public IEnumerable>> GetAllKeys() => Database.Keys; - - public override void Remove(ComponentContainerDefinition value) - => InternalRemove(new GuidTag>(value.Id)); + public IEnumerable>> GetAllKeys() => Database.Keys; + public override void Remove(ComponentContainerDefinition value) + => InternalRemove(new GuidTag>(value.Id)); } } } diff --git a/OctoAwesome/OctoAwesome/Serialization/IDatabaseProvider.cs b/OctoAwesome/OctoAwesome/Serialization/IDatabaseProvider.cs index 786d5f1e..20381d7a 100644 --- a/OctoAwesome/OctoAwesome/Serialization/IDatabaseProvider.cs +++ b/OctoAwesome/OctoAwesome/Serialization/IDatabaseProvider.cs @@ -3,10 +3,12 @@ namespace OctoAwesome { + public interface IDatabaseProvider { Database GetDatabase(bool fixedValueSize) where T : ITag, new(); Database GetDatabase(Guid universeGuid, bool fixedValueSize) where T : ITag, new(); + Database GetDatabase(Guid universeGuid, int planetId, bool fixedValueSize) where T : ITag, new(); } } \ No newline at end of file diff --git a/OctoAwesome/OctoAwesome/Serialization/IIdentification.cs b/OctoAwesome/OctoAwesome/Serialization/IIdentification.cs index cee2248a..f1c75a67 100644 --- a/OctoAwesome/OctoAwesome/Serialization/IIdentification.cs +++ b/OctoAwesome/OctoAwesome/Serialization/IIdentification.cs @@ -1,13 +1,11 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + public interface IIdentification { + Guid Id { get; } } } diff --git a/OctoAwesome/OctoAwesome/Serialization/ISerializable.cs b/OctoAwesome/OctoAwesome/Serialization/ISerializable.cs index 7cb9848a..dd409438 100644 --- a/OctoAwesome/OctoAwesome/Serialization/ISerializable.cs +++ b/OctoAwesome/OctoAwesome/Serialization/ISerializable.cs @@ -2,9 +2,11 @@ namespace OctoAwesome.Serialization { + public interface ISerializable { void Serialize(BinaryWriter writer); + void Deserialize(BinaryReader reader); } } \ No newline at end of file diff --git a/OctoAwesome/OctoAwesome/Serialization/ISerializableEnumerable.cs b/OctoAwesome/OctoAwesome/Serialization/ISerializableEnumerable.cs index a1343424..7a2a5846 100644 --- a/OctoAwesome/OctoAwesome/Serialization/ISerializableEnumerable.cs +++ b/OctoAwesome/OctoAwesome/Serialization/ISerializableEnumerable.cs @@ -1,12 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; namespace OctoAwesome.Serialization { - public interface ISerializableEnumerable : IEnumerable, ISerializable where T : ISerializable + public interface ISerializableEnumerable : IEnumerable, ISerializable where T : ISerializable { } } diff --git a/OctoAwesome/OctoAwesome/Serialization/IdDatabaseContext.cs b/OctoAwesome/OctoAwesome/Serialization/IdDatabaseContext.cs index 526a5fba..b1777ce6 100644 --- a/OctoAwesome/OctoAwesome/Serialization/IdDatabaseContext.cs +++ b/OctoAwesome/OctoAwesome/Serialization/IdDatabaseContext.cs @@ -1,7 +1,5 @@ using OctoAwesome.Database; using System; -using System.Collections.Generic; -using System.Text; namespace OctoAwesome.Serialization { @@ -11,13 +9,10 @@ public sealed class IdDatabaseContext : SerializableDatabaseContext> database) : base(database) { } - public override void AddOrUpdate(TObject value) => InternalAddOrUpdate(new GuidTag(value.Id), value); - public TObject Get(Guid key) => Get(new GuidTag(key)); - public override void Remove(TObject value) => InternalRemove(new GuidTag(value.Id)); } diff --git a/OctoAwesome/OctoAwesome/Serialization/Index2Tag.cs b/OctoAwesome/OctoAwesome/Serialization/Index2Tag.cs index fe3f3a99..6b2b3beb 100644 --- a/OctoAwesome/OctoAwesome/Serialization/Index2Tag.cs +++ b/OctoAwesome/OctoAwesome/Serialization/Index2Tag.cs @@ -1,21 +1,19 @@ using OctoAwesome.Database; using System; -using System.Security.Cryptography; namespace OctoAwesome.Serialization { + public struct Index2Tag : ITag, IEquatable { - public int Length => sizeof(int) + sizeof(int); + public int Length => sizeof(int) + sizeof(int); public Index2 Index { get; private set; } public Index2Tag(Index2 index) => Index = index; - public void FromBytes(byte[] array, int startIndex) => Index = new Index2(BitConverter.ToInt32(array, startIndex), BitConverter.ToInt32(array, startIndex + sizeof(int))); - public byte[] GetBytes() { var byteArray = new byte[Length]; @@ -23,13 +21,10 @@ public byte[] GetBytes() BitConverter.TryWriteBytes(byteArray[sizeof(int)..(sizeof(int)*2)], Index.Y); return byteArray; } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is Index2Tag tag && Equals(tag); - public bool Equals(Index2Tag other) => Length == other.Length && Index.Equals(other.Index); - public override int GetHashCode() { int hashCode = 802246856; @@ -37,7 +32,6 @@ public override int GetHashCode() hashCode = hashCode * -1521134295 + Index.GetHashCode(); return hashCode; } - public void WriteBytes(Span span) { BitConverter.TryWriteBytes(span[0..sizeof(int)], Index.X); diff --git a/OctoAwesome/OctoAwesome/Serialization/Index3Tag.cs b/OctoAwesome/OctoAwesome/Serialization/Index3Tag.cs index 57c7c21c..b0d0ee64 100644 --- a/OctoAwesome/OctoAwesome/Serialization/Index3Tag.cs +++ b/OctoAwesome/OctoAwesome/Serialization/Index3Tag.cs @@ -1,40 +1,34 @@ using OctoAwesome.Database; using System; -using System.Security.Cryptography; namespace OctoAwesome.Serialization { + public struct Index3Tag : ITag, IEquatable { - public int Length => sizeof(int) * 3; + public int Length => sizeof(int) * 3; public Index3 Index { get; private set; } public Index3Tag(Index3 index) => Index = index; - public void FromBytes(byte[] array, int startIndex) => Index = new Index3(BitConverter.ToInt32(array, startIndex), BitConverter.ToInt32(array, startIndex + sizeof(int)), BitConverter.ToInt32(array, startIndex + sizeof(int) + sizeof(int))); - public byte[] GetBytes() { var byteArray = new byte[Length]; - const int intSize = sizeof(int); Buffer.BlockCopy(BitConverter.GetBytes(Index.X), 0, byteArray, 0, sizeof(int)); Buffer.BlockCopy(BitConverter.GetBytes(Index.Y), 0, byteArray, sizeof(int), sizeof(int)); Buffer.BlockCopy(BitConverter.GetBytes(Index.Z), 0, byteArray, sizeof(int) + sizeof(int), sizeof(int)); return byteArray; } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is Index3Tag tag && Equals(tag); - public bool Equals(Index3Tag other) => Length == other.Length && Index.Equals(other.Index); - public override int GetHashCode() { int hashCode = 802246856; @@ -42,7 +36,6 @@ public override int GetHashCode() hashCode = hashCode * -1521134295 + Index.GetHashCode(); return hashCode; } - public void WriteBytes(Span span) { BitConverter.TryWriteBytes(span, Index.X); diff --git a/OctoAwesome/OctoAwesome/Serialization/SerializableCollection.cs b/OctoAwesome/OctoAwesome/Serialization/SerializableCollection.cs index d4d7c40b..3e7379c0 100644 --- a/OctoAwesome/OctoAwesome/Serialization/SerializableCollection.cs +++ b/OctoAwesome/OctoAwesome/Serialization/SerializableCollection.cs @@ -1,19 +1,16 @@ -using OctoAwesome.Serialization; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.IO; namespace OctoAwesome.Serialization { - public class SerializableCollection : Collection, ISerializableEnumerable, ISerializable where T : ISerializable + public class SerializableCollection : Collection, ISerializableEnumerable where T : ISerializable { + public void Deserialize(BinaryReader reader) { foreach (var item in this) item.Deserialize(reader); } - public void Serialize(BinaryWriter writer) { foreach (var item in this) diff --git a/OctoAwesome/OctoAwesome/Serialization/SerializableDatabaseContext.cs b/OctoAwesome/OctoAwesome/Serialization/SerializableDatabaseContext.cs index 28a1cdbc..53e20980 100644 --- a/OctoAwesome/OctoAwesome/Serialization/SerializableDatabaseContext.cs +++ b/OctoAwesome/OctoAwesome/Serialization/SerializableDatabaseContext.cs @@ -1,20 +1,15 @@ using OctoAwesome.Database; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + public abstract class SerializableDatabaseContext : DatabaseContext where TTag : ITag, new() where TObject : ISerializable, new() { - public SerializableDatabaseContext(Database database) : base(database) + protected SerializableDatabaseContext(Database database) : base(database) { } - public override TObject Get(TTag key) => Serializer.Deserialize(Database.GetValue(key).Content); @@ -23,7 +18,6 @@ protected void InternalRemove(TTag tag) using (Database.Lock(Operation.Write)) Database.Remove(tag); } - protected void InternalAddOrUpdate(TTag tag, TObject value) { using (Database.Lock(Operation.Write)) diff --git a/OctoAwesome/OctoAwesome/Serialization/SerializationIdAttribute.cs b/OctoAwesome/OctoAwesome/Serialization/SerializationIdAttribute.cs index 9a9c4a9a..f5247859 100644 --- a/OctoAwesome/OctoAwesome/Serialization/SerializationIdAttribute.cs +++ b/OctoAwesome/OctoAwesome/Serialization/SerializationIdAttribute.cs @@ -1,24 +1,21 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] public class SerializationIdAttribute : Attribute { + public uint ModId { get; } - public uint TypeId { get; } + public new uint TypeId { get; } public ulong CombinedId { get; } - public SerializationIdAttribute(uint modId, uint typeId) { ModId = modId; TypeId = typeId; - CombinedId = ((ulong)modId << sizeof(uint)) | typeId; + CombinedId = ((ulong)modId << (sizeof(uint) * 8)) | typeId; } } } diff --git a/OctoAwesome/OctoAwesome/Serialization/Serializer.cs b/OctoAwesome/OctoAwesome/Serialization/Serializer.cs index 70db3070..ac1eba4c 100644 --- a/OctoAwesome/OctoAwesome/Serialization/Serializer.cs +++ b/OctoAwesome/OctoAwesome/Serialization/Serializer.cs @@ -1,17 +1,11 @@ -using NLog.Internal; - -using OctoAwesome.Pooling; - -using System; -using System.Collections.Generic; +using OctoAwesome.Pooling; using System.IO; using System.IO.Compression; -using System.Linq; using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + public static class Serializer { public static byte[] Serialize(T obj) where T : ISerializable @@ -41,7 +35,6 @@ public static byte[] SerializeCompressed(T obj) where T : ISerializable } } } - public static byte[] SerializeCompressed(T obj, int capacity) where T : ISerializable { using (var stream = new MemoryStream(capacity)) @@ -71,14 +64,14 @@ public static byte[] SerializeCompressed(T obj, int capacity) where T : ISeri public static T DeserializePoolElement(byte[] data) where T : ISerializable, IPoolElement, new() { - var obj = TypeContainer.Get>().Get(); + var obj = TypeContainer.Get>().Rent(); InternalDeserialize(ref obj, data); return obj; } public static T DeserializePoolElement(IPool pool, byte[] data) where T : ISerializable, IPoolElement, new() { - var obj = pool.Get(); + var obj = pool.Rent(); InternalDeserialize(ref obj, data); return obj; } diff --git a/OctoAwesome/OctoAwesome/Serialization/TypeExtension.cs b/OctoAwesome/OctoAwesome/Serialization/TypeExtension.cs index d0f5a034..e8e82287 100644 --- a/OctoAwesome/OctoAwesome/Serialization/TypeExtension.cs +++ b/OctoAwesome/OctoAwesome/Serialization/TypeExtension.cs @@ -1,14 +1,12 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Serialization { + public static class TypeExtension { + public static ulong SerializationId(this Type type) { var attr = type.GetCustomAttribute(); diff --git a/OctoAwesome/OctoAwesome/SerializationIdTypeProvider.cs b/OctoAwesome/OctoAwesome/SerializationIdTypeProvider.cs index 15238ea9..532e5062 100644 --- a/OctoAwesome/OctoAwesome/SerializationIdTypeProvider.cs +++ b/OctoAwesome/OctoAwesome/SerializationIdTypeProvider.cs @@ -1,15 +1,14 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; +using OctoAwesome.Serialization; namespace OctoAwesome { + public sealed class SerializationIdTypeProvider { private readonly Dictionary types = new(); - public void Register(ulong serId, Type type) { types.Add(serId, type); @@ -19,22 +18,21 @@ public Type Get(ulong serId) { return types[serId]; } + + private static ulong SerIdFromModTypeId(uint modId, uint typeId) => ((ulong)modId << (sizeof(uint) * 8)) | typeId; public Type Get(uint modId, uint typeId) { - ulong serId = ((ulong)modId << sizeof(uint)) | typeId; - return Get(serId); + return Get(SerIdFromModTypeId(modId, typeId)); } - - public bool TryGet(ulong serId, out Type type) + public bool TryGet(ulong serId, [MaybeNullWhen(false)] out Type type) { return types.TryGetValue(serId, out type); } - public bool TryGet(uint modId, uint typeId, out Type type) + public bool TryGet(uint modId, uint typeId, [MaybeNullWhen(false)] out Type type) { - ulong serId = ((ulong)modId << sizeof(uint)) | typeId; - return TryGet(serId, out type); + return TryGet(SerIdFromModTypeId(modId, typeId), out type); } } } diff --git a/OctoAwesome/OctoAwesome/Services/BlockCollectionService.cs b/OctoAwesome/OctoAwesome/Services/BlockCollectionService.cs index 90fae1b7..c4e04a55 100644 --- a/OctoAwesome/OctoAwesome/Services/BlockCollectionService.cs +++ b/OctoAwesome/OctoAwesome/Services/BlockCollectionService.cs @@ -1,38 +1,32 @@ using OctoAwesome.Definitions; -using OctoAwesome.Definitions.Items; -using OctoAwesome.Information; using OctoAwesome.Pooling; using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Services { + public sealed class BlockCollectionService { private readonly IPool blockCollectionPool; private readonly IDefinitionManager definitionManager; - private readonly Dictionary blockCollectionInformations; - + private readonly Dictionary blockCollectionInformation; public BlockCollectionService(IPool blockCollectionPool, IDefinitionManager definitionManager) { this.blockCollectionPool = blockCollectionPool; this.definitionManager = definitionManager; - blockCollectionInformations = new Dictionary(); + blockCollectionInformation = new Dictionary(); } - public (bool Valid, IReadOnlyList<(int Quantity, IDefinition Definition)> List) Hit(BlockInfo block, IItem item, ILocalChunkCache cache) + public (bool Valid, IReadOnlyList<(int Quantity, IDefinition Definition)>? List) Hit(BlockInfo block, IItem item, ILocalChunkCache cache) { - BlockVolumeState volumeState; - if (!blockCollectionInformations.TryGetValue(block, out volumeState)) + if (!blockCollectionInformation.TryGetValue(block, out var volumeState)) { var definition = definitionManager.GetBlockDefinitionByIndex(block.Block); - volumeState = blockCollectionPool.Get(); + volumeState = blockCollectionPool.Rent(); volumeState.Initialize(block, definition, DateTimeOffset.Now); - blockCollectionInformations.Add(block, volumeState); + blockCollectionInformation.Add(block, volumeState); } volumeState.TryReset(); @@ -47,7 +41,7 @@ public BlockCollectionService(IPool blockCollectionPool, IDefi if (volumeState.VolumeRemaining < 1) { - blockCollectionInformations.Remove(block); + blockCollectionInformation.Remove(block); volumeState.Release(); cache.SetBlock(block.Position, 0); return (true, blockHitInformation.Definitions); diff --git a/OctoAwesome/OctoAwesome/Services/BlockVolumeState.cs b/OctoAwesome/OctoAwesome/Services/BlockVolumeState.cs index f990f0eb..8f3b75fd 100644 --- a/OctoAwesome/OctoAwesome/Services/BlockVolumeState.cs +++ b/OctoAwesome/OctoAwesome/Services/BlockVolumeState.cs @@ -1,18 +1,17 @@ using OctoAwesome.Definitions; using OctoAwesome.Pooling; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.Services { + public sealed class BlockVolumeState : IPoolElement { - public BlockInfo BlockInfo { get; set; } - public IBlockDefinition BlockDefinition { get; set; } + + public BlockInfo BlockInfo { get; private set; } + public IBlockDefinition BlockDefinition { get; private set; } public decimal VolumeRemaining { get; internal set; } + public DateTimeOffset ValidUntil { get; set; } private IPool pool; @@ -24,15 +23,13 @@ public void Initialize(BlockInfo info, IBlockDefinition blockDefinition, DateTim VolumeRemaining = blockDefinition.VolumePerUnit; ValidUntil = validUntil; } - public void Init(IPool pool) { this.pool = pool; } - public void Release() { - pool.Push(this); + pool.Return(this); } internal bool TryReset() diff --git a/OctoAwesome/OctoAwesome/Simulation.cs b/OctoAwesome/OctoAwesome/Simulation.cs index d32b00d2..134a61f5 100644 --- a/OctoAwesome/OctoAwesome/Simulation.cs +++ b/OctoAwesome/OctoAwesome/Simulation.cs @@ -2,9 +2,7 @@ using OctoAwesome.Common; using OctoAwesome.Components; -using OctoAwesome.Database; using OctoAwesome.EntityComponents; -using OctoAwesome.Logging; using OctoAwesome.Notifications; using OctoAwesome.Pooling; using OctoAwesome.Rx; @@ -12,7 +10,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Resources; namespace OctoAwesome { @@ -21,14 +18,14 @@ namespace OctoAwesome /// public sealed class Simulation : IDisposable { - public IResourceManager ResourceManager { get; private set; } + public IResourceManager ResourceManager { get; } public bool IsServerSide { get; set; } /// /// List of all Simulation Components. /// - public ComponentList Components { get; private set; } + public ComponentList Components { get; } /// /// Der aktuelle Status der Simulation. @@ -38,7 +35,7 @@ public sealed class Simulation : IDisposable /// /// Die Guid des aktuell geladenen Universums. /// - public Guid UniverseId { get; private set; } + public Guid UniverseId { get; } /// /// Dienste des Spiels. @@ -49,6 +46,8 @@ public sealed class Simulation : IDisposable /// List of all Entities. /// public IReadOnlyList Entities => entities; + + public IReadOnlyList FunctionalBlocks => functionalBlocks; private readonly IExtensionResolver extensionResolver; @@ -70,8 +69,6 @@ public Simulation(IResourceManager resourceManager, IExtensionResolver extension networkRelay = new Relay(); entityNotificationPool = TypeContainer.Get>(); - - this.extensionResolver = extensionResolver; State = SimulationState.Ready; UniverseId = Guid.Empty; @@ -119,8 +116,6 @@ public Guid NewGame(string name, string rawSeed) { numericSeed = rawSeed.GetHashCode(); } - - Guid guid = ResourceManager.NewUniverse(name, numericSeed); Start(); @@ -156,8 +151,6 @@ private void Start() = ResourceManager .UpdateHub .AddSource(networkRelay, DefaultChannels.Network); - - State = SimulationState.Running; } @@ -203,7 +196,7 @@ public void ExitGame() //TODO: unschön, Dispose Entity's, Reset Extensions entities.ToList().ForEach(entity => Remove(entity)); functionalBlocks.ToList().ForEach(functionalBlock => Remove(functionalBlock)); - //while (entites.Count > 0) + //while (entities.Count > 0) // RemoveEntity(Entities.First()); State = SimulationState.Finished; @@ -220,8 +213,7 @@ public void ExitGame() /// Neue Entity public void Add(Entity entity) { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + Debug.Assert(entity is not null, nameof(entity) + " != null"); if (!(State == SimulationState.Running || State == SimulationState.Paused)) throw new NotSupportedException("Adding Entities only allowed in running or paused state"); @@ -247,12 +239,10 @@ public void Add(Entity entity) holdComponent.Add(entity); } } - public void Add(FunctionalBlock block) { - if (block is null) - throw new ArgumentNullException(nameof(block)); - + Debug.Assert(block is not null, nameof(block) + " != null"); + if (!(State == SimulationState.Running || State == SimulationState.Paused)) throw new NotSupportedException($"Adding {nameof(FunctionalBlock)} only allowed in running or paused state"); @@ -261,8 +251,6 @@ public void Add(FunctionalBlock block) if (functionalBlocks.Contains(block)) return; - - extensionResolver.ExtendEntity(block); block.Initialize(ResourceManager); block.Simulation = this; @@ -285,8 +273,7 @@ public void Add(FunctionalBlock block) /// Entity die entfert werden soll public void Remove(Entity entity) { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + Debug.Assert(entity is not null, nameof(entity) + " != null"); if (entity.Id == Guid.Empty) return; @@ -318,8 +305,7 @@ public void Remove(Entity entity) public void Remove(FunctionalBlock block) { - if (block == null) - throw new ArgumentNullException(nameof(block)); + Debug.Assert(block is not null, nameof(block) + " != null"); if (block.Id == Guid.Empty) return; @@ -378,8 +364,6 @@ public void OnNext(Notification value) break; } } - - public void OnUpdate(SerializableNotification notification) { if (!IsServerSide) @@ -391,7 +375,7 @@ private void EntityUpdate(EntityNotification notification) var entity = entities.FirstOrDefault(e => e.Id == notification.EntityId); if (entity == null) { - var entityNotification = entityNotificationPool.Get(); + var entityNotification = entityNotificationPool.Rent(); entityNotification.EntityId = notification.EntityId; entityNotification.Type = EntityNotification.ActionType.Request; networkRelay.OnNext(entityNotification); @@ -418,14 +402,13 @@ private void RequestEntity(EntityNotification entityNotification) remoteEntity.Components.AddComponent(new RenderComponent() { Name = "Wauzi", ModelName = "dog", TextureName = "texdog", BaseZRotation = -90 }, true); remoteEntity.Components.AddComponent(new PositionComponent() { Position = new Coordinate(0, new Index3(0, 0, 78), new Vector3(0, 0, 0)) }); - var newEntityNotification = entityNotificationPool.Get(); + var newEntityNotification = entityNotificationPool.Rent(); newEntityNotification.Entity = remoteEntity; newEntityNotification.Type = EntityNotification.ActionType.Add; networkRelay.OnNext(newEntityNotification); newEntityNotification.Release(); } - public void Dispose() { networkRelay.Dispose(); diff --git a/OctoAwesome/OctoAwesome/StandaloneTypeContainer.cs b/OctoAwesome/OctoAwesome/StandaloneTypeContainer.cs index 4fd0d264..364ded4a 100644 --- a/OctoAwesome/OctoAwesome/StandaloneTypeContainer.cs +++ b/OctoAwesome/OctoAwesome/StandaloneTypeContainer.cs @@ -1,66 +1,62 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { + public sealed class StandaloneTypeContainer : ITypeContainer { - private readonly Dictionary typeInformationRegister; private readonly Dictionary typeRegister; - public StandaloneTypeContainer() { typeInformationRegister = new Dictionary(); typeRegister = new Dictionary(); } - - public void Register(Type registrar, Type type, InstanceBehaviour instanceBehaviour) + public void Register(Type registrar, Type type, InstanceBehavior instanceBehavior) { if (!typeInformationRegister.ContainsKey(type)) - typeInformationRegister.Add(type, new TypeInformation(this, type, instanceBehaviour)); + typeInformationRegister.Add(type, new TypeInformation(this, type, instanceBehavior)); typeRegister.Add(registrar, type); } - public void Register(InstanceBehaviour instanceBehaviour = InstanceBehaviour.Instance) where T : class - => Register(typeof(T), typeof(T), instanceBehaviour); - public void Register(InstanceBehaviour instanceBehaviour = InstanceBehaviour.Instance) where T : class - => Register(typeof(TRegistrar), typeof(T), instanceBehaviour); - public void Register(Type registrar, Type type, object singelton) + public void Register(InstanceBehavior instanceBehavior = InstanceBehavior.Instance) where T : class + => Register(typeof(T), typeof(T), instanceBehavior); + public void Register(InstanceBehavior instanceBehavior = InstanceBehavior.Instance) where T : class + => Register(typeof(TRegistrar), typeof(T), instanceBehavior); + public void Register(Type registrar, Type type, object singleton) { if (!typeInformationRegister.ContainsKey(type)) - typeInformationRegister.Add(type, new TypeInformation(this, type, InstanceBehaviour.Singleton, singelton)); + typeInformationRegister.Add(type, new TypeInformation(this, type, InstanceBehavior.Singleton, singleton)); typeRegister.Add(registrar, type); } - public void Register(T singelton) where T : class - => Register(typeof(T), typeof(T), singelton); - public void Register(object singelton) where T : class - => Register(typeof(TRegistrar), typeof(T), singelton); - - public bool TryResolve(Type type, out object instance) + public void Register(T singleton) where T : class + => Register(typeof(T), typeof(T), singleton); + public void Register(object singleton) where T : class + => Register(typeof(TRegistrar), typeof(T), singleton); + public bool TryGet(Type type, [MaybeNullWhen(false)] out object instance) { instance = GetOrNull(type); return instance != null; } - public bool TryResolve(out T instance) where T : class + public bool TryGet([MaybeNullWhen(false)] out T instance) where T : class { - var result = TryResolve(typeof(T), out var obj); - instance = (T)obj; + var result = TryGet(typeof(T), out var obj); + if (result) + instance = (T)obj!; + else + instance = null; return result; } - public object Get(Type type) => GetOrNull(type) ?? throw new KeyNotFoundException($"Type {type} was not found in Container"); - public T Get() where T : class => (T)Get(typeof(T)); - - public object GetOrNull(Type type) + public object? GetOrNull(Type type) { if (typeRegister.TryGetValue(type, out var searchType)) { @@ -69,18 +65,15 @@ public object GetOrNull(Type type) } return null; } - public T GetOrNull() where T : class - => (T)GetOrNull(typeof(T)); - + public T? GetOrNull() where T : class + => (T?)GetOrNull(typeof(T)); public object GetUnregistered(Type type) => GetOrNull(type) ?? CreateObject(type) ?? throw new InvalidOperationException($"Can not create unregistered type of {type}"); - public T GetUnregistered() where T : class => (T)GetUnregistered(typeof(T)); - - public object CreateObject(Type type) + public object? CreateObject(Type type) { var tmpList = new List(); @@ -91,7 +84,7 @@ public object CreateObject(Type type) bool next = false; foreach (var parameter in constructor.GetParameters()) { - if (TryResolve(parameter.ParameterType, out object instance)) + if (TryGet(parameter.ParameterType, out var instance)) { tmpList.Add(instance); } @@ -109,7 +102,7 @@ public object CreateObject(Type type) return constructor.Invoke(tmpList.ToArray()); } - if (constructors.Count() < 1) + if (!constructors.Any()) { try { @@ -123,14 +116,13 @@ public object CreateObject(Type type) return null; } - public T CreateObject() where T : class - => (T)CreateObject(typeof(T)); - + public T? CreateObject() where T : class + => (T?)CreateObject(typeof(T)); public void Dispose() { typeRegister.Clear(); typeInformationRegister.Values - .Where(t => t.Behaviour == InstanceBehaviour.Singleton && t.Instance != this) + .Where(t => t.Behavior == InstanceBehavior.Singleton && t.Instance != this) .Select(t => t.Instance as IDisposable) .ToList() .ForEach(i => i?.Dispose()); @@ -140,31 +132,31 @@ public void Dispose() private class TypeInformation { - public InstanceBehaviour Behaviour { get; set; } - public object Instance => CreateObject(); + public InstanceBehavior Behavior { get; set; } + public object? Instance => CreateObject(); private readonly StandaloneTypeContainer typeContainer; private readonly Type type; - private object singeltonInstance; + private object? singletonInstance; public TypeInformation(StandaloneTypeContainer container, - Type type, InstanceBehaviour instanceBehaviour, object instance = null) + Type type, InstanceBehavior instanceBehavior, object? instance = null) { this.type = type; - Behaviour = instanceBehaviour; + Behavior = instanceBehavior; typeContainer = container; - singeltonInstance = instance; + singletonInstance = instance; } - private object CreateObject() + private object? CreateObject() { - if (Behaviour == InstanceBehaviour.Singleton && singeltonInstance != null) - return singeltonInstance; + if (Behavior == InstanceBehavior.Singleton && singletonInstance != null) + return singletonInstance; var obj = typeContainer.CreateObject(type); - if (Behaviour == InstanceBehaviour.Singleton) - singeltonInstance = obj; + if (Behavior == InstanceBehavior.Singleton) + singletonInstance = obj; return obj; } diff --git a/OctoAwesome/OctoAwesome/Startup.cs b/OctoAwesome/OctoAwesome/Startup.cs index f87e11fd..6c43c056 100644 --- a/OctoAwesome/OctoAwesome/Startup.cs +++ b/OctoAwesome/OctoAwesome/Startup.cs @@ -1,44 +1,40 @@ using NLog; using NLog.Config; using NLog.Targets; -using OctoAwesome.Information; using OctoAwesome.Notifications; using OctoAwesome.Pooling; using OctoAwesome.Services; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { + public static class Startup { public static void Register(ITypeContainer typeContainer) { - typeContainer.Register(InstanceBehaviour.Instance); - typeContainer.Register(InstanceBehaviour.Instance); + typeContainer.Register(); + typeContainer.Register(); typeContainer.Register(); typeContainer.Register(); typeContainer.Register(); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register, ChunkPool>(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); - typeContainer.Register, Pool>(InstanceBehaviour.Singleton); - typeContainer.Register(InstanceBehaviour.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register, ChunkPool>(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); + typeContainer.Register, Pool>(InstanceBehavior.Singleton); + typeContainer.Register(InstanceBehavior.Singleton); } public static void ConfigureLogger(ClientType clientType) diff --git a/OctoAwesome/OctoAwesome/SumTypes/Selection.cs b/OctoAwesome/OctoAwesome/SumTypes/Selection.cs index 9d43ee8c..3b6980a3 100644 --- a/OctoAwesome/OctoAwesome/SumTypes/Selection.cs +++ b/OctoAwesome/OctoAwesome/SumTypes/Selection.cs @@ -1,12 +1,8 @@ using dotVariant; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome.SumTypes { + [Variant] public partial class Selection { diff --git a/OctoAwesome/OctoAwesome/Threading/CountedScopeSemaphore.cs b/OctoAwesome/OctoAwesome/Threading/CountedScopeSemaphore.cs index 68708c8f..999cdca2 100644 --- a/OctoAwesome/OctoAwesome/Threading/CountedScopeSemaphore.cs +++ b/OctoAwesome/OctoAwesome/Threading/CountedScopeSemaphore.cs @@ -1,43 +1,41 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; namespace OctoAwesome.Threading { + public class CountedScopeSemaphore : IDisposable { - private readonly ManualResetEventSlim superLock; + private readonly ManualResetEventSlim exclusiveLock; private readonly ManualResetEventSlim mainLock; private readonly object lockObject; private readonly object countLockObject; private int counter; + public CountedScopeSemaphore() { mainLock = new ManualResetEventSlim(true); - superLock = new ManualResetEventSlim(true); + exclusiveLock = new ManualResetEventSlim(true); lockObject = new object(); countLockObject = new object(); } - - public SuperScope EnterExclusivScope() + public ExclusiveScope EnterExclusiveScope() { lock (lockObject) { mainLock.Wait(); - superLock.Wait(); - superLock.Reset(); + exclusiveLock.Wait(); + exclusiveLock.Reset(); } - return new SuperScope(this); + return new ExclusiveScope(this); } - public CountScope EnterCountScope() { lock (lockObject) { - superLock.Wait(); + exclusiveLock.Wait(); lock (countLockObject) { counter++; @@ -45,14 +43,12 @@ public CountScope EnterCountScope() mainLock.Reset(); } } - - + return new CountScope(this); } - public void Dispose() { - superLock.Dispose(); + exclusiveLock.Dispose(); mainLock.Dispose(); } @@ -66,66 +62,57 @@ private void LeaveMainScope() } } - private void LeaveSuperScope() + private void LeaveExclusiveScope() { - superLock.Set(); + exclusiveLock.Set(); } - public readonly struct CountScope : IDisposable, IEquatable { - public static CountScope Empty => new CountScope(null); - private readonly CountedScopeSemaphore internalSemaphore; public CountScope(CountedScopeSemaphore countingSemaphore) { internalSemaphore = countingSemaphore; } - public void Dispose() { - internalSemaphore?.LeaveMainScope(); + internalSemaphore.LeaveMainScope(); } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is CountScope scope && Equals(scope); public bool Equals(CountScope other) => EqualityComparer.Default.Equals(internalSemaphore, other.internalSemaphore); - public override int GetHashCode() => 37286538 + EqualityComparer.Default.GetHashCode(internalSemaphore); public static bool operator ==(CountScope left, CountScope right) => left.Equals(right); + public static bool operator !=(CountScope left, CountScope right) => !(left == right); } - - public readonly struct SuperScope : IDisposable, IEquatable + public readonly struct ExclusiveScope : IDisposable, IEquatable { - public static SuperScope Empty => new SuperScope(null); - private readonly CountedScopeSemaphore internalSemaphore; - public SuperScope(CountedScopeSemaphore semaphore) + public ExclusiveScope(CountedScopeSemaphore semaphore) { internalSemaphore = semaphore; } - public void Dispose() { - internalSemaphore?.LeaveSuperScope(); + internalSemaphore?.LeaveExclusiveScope(); } - - public override bool Equals(object obj) => obj is SuperScope scope && Equals(scope); - public bool Equals(SuperScope other) + public override bool Equals(object? obj) => obj is ExclusiveScope scope && Equals(scope); + public bool Equals(ExclusiveScope other) => EqualityComparer.Default.Equals(internalSemaphore, other.internalSemaphore); public override int GetHashCode() => 37296538 + EqualityComparer.Default.GetHashCode(internalSemaphore); - - public static bool operator ==(SuperScope left, SuperScope right) => left.Equals(right); - public static bool operator !=(SuperScope left, SuperScope right) => !(left == right); + + public static bool operator ==(ExclusiveScope left, ExclusiveScope right) => left.Equals(right); + + public static bool operator !=(ExclusiveScope left, ExclusiveScope right) => !(left == right); } } } diff --git a/OctoAwesome/OctoAwesome/Threading/LockSemaphore.cs b/OctoAwesome/OctoAwesome/Threading/LockSemaphore.cs index 3d4ca5d3..e67f084b 100644 --- a/OctoAwesome/OctoAwesome/Threading/LockSemaphore.cs +++ b/OctoAwesome/OctoAwesome/Threading/LockSemaphore.cs @@ -1,16 +1,16 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; namespace OctoAwesome.Threading { + public sealed class LockSemaphore : IDisposable { private readonly SemaphoreSlim semaphoreSlim; + public LockSemaphore(int initialCount, int maxCount) { semaphoreSlim = new SemaphoreSlim(initialCount, maxCount); @@ -27,7 +27,6 @@ public async Task WaitAsync(CancellationToken token) await semaphoreSlim.WaitAsync(token); return new SemaphoreLock(this); } - public void Dispose() { semaphoreSlim.Dispose(); @@ -37,33 +36,29 @@ private void Release() { semaphoreSlim.Release(); } - public readonly struct SemaphoreLock : IDisposable, IEquatable { - public static SemaphoreLock Empty => new SemaphoreLock(null); - private readonly LockSemaphore internalSemaphore; public SemaphoreLock(LockSemaphore semaphoreExtended) { internalSemaphore = semaphoreExtended; } - public void Dispose() { - internalSemaphore?.Release(); + internalSemaphore.Release(); } - - public override bool Equals(object obj) + public override bool Equals(object? obj) => obj is SemaphoreLock @lock && Equals(@lock); public bool Equals(SemaphoreLock other) => EqualityComparer.Default.Equals(internalSemaphore, other.internalSemaphore); public override int GetHashCode() - => 37286538 + EqualityComparer.Default.GetHashCode(internalSemaphore); + => 37286538 + (internalSemaphore == null ? 0 : EqualityComparer.Default.GetHashCode(internalSemaphore)); public static bool operator ==(SemaphoreLock left, SemaphoreLock right) => left.Equals(right); + public static bool operator !=(SemaphoreLock left, SemaphoreLock right) => !(left == right); } diff --git a/OctoAwesome/OctoAwesome/TypeContainer.cs b/OctoAwesome/OctoAwesome/TypeContainer.cs index 07022cf1..8deba18c 100644 --- a/OctoAwesome/OctoAwesome/TypeContainer.cs +++ b/OctoAwesome/OctoAwesome/TypeContainer.cs @@ -1,12 +1,9 @@ -using OctoAwesome.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System; +using System.Diagnostics.CodeAnalysis; namespace OctoAwesome { + public static class TypeContainer { private static readonly ITypeContainer instance; @@ -14,43 +11,43 @@ public static class TypeContainer static TypeContainer() { instance = new StandaloneTypeContainer(); - instance.Register(instance as StandaloneTypeContainer); + instance.Register((StandaloneTypeContainer)instance); instance.Register(instance); } - - public static object CreateObject(Type type) + public static object? CreateObject(Type type) => instance.CreateObject(type); - public static T CreateObject() where T : class + public static T? CreateObject() where T : class => instance.CreateObject(); - - public static void Register(Type registrar, Type type, InstanceBehaviour instanceBehaviour) - => instance.Register(registrar, type, instanceBehaviour); - public static void Register(InstanceBehaviour instanceBehaviour = InstanceBehaviour.Instance) where T : class - => instance.Register(instanceBehaviour); - public static void Register(InstanceBehaviour instanceBehaviour = InstanceBehaviour.Instance) where T : class - => instance.Register(instanceBehaviour); - public static void Register(Type registrar, Type type, object singelton) - => instance.Register(registrar, type, singelton); - public static void Register(T singelton) where T : class - => instance.Register(singelton); - public static void Register(object singelton) where T : class - => instance.Register(singelton); - - public static bool TryResolve(Type type, out object resolvedInstance) - => instance.TryResolve(type, out resolvedInstance); - public static bool TryResolve(out T resolvedInstance) where T : class - => instance.TryResolve(out resolvedInstance); - + public static void Register(Type registrar, Type type, InstanceBehavior instanceBehavior) + => instance.Register(registrar, type, instanceBehavior); + public static void Register(InstanceBehavior instanceBehavior = InstanceBehavior.Instance) where T : class + + => instance.Register(instanceBehavior); + + public static void Register(InstanceBehavior instanceBehavior = InstanceBehavior.Instance) where T : class + => instance.Register(instanceBehavior); + public static void Register(Type registrar, Type type, object singleton) + => instance.Register(registrar, type, singleton); + + + public static void Register(T singleton) where T : class + => instance.Register(singleton); + public static void Register(object singleton) where T : class + => instance.Register(singleton); + public static bool TryResolve(Type type, [MaybeNullWhen(false)] out object resolvedInstance) + => instance.TryGet(type, out resolvedInstance); + public static bool TryResolve([MaybeNullWhen(false)] out T resolvedInstance) where T : class + => instance.TryGet(out resolvedInstance); public static object Get(Type type) => instance.Get(type); + + public static T Get() where T : class => instance.Get(); - - public static object GetOrNull(Type type) + public static object? GetOrNull(Type type) => instance.GetOrNull(type); - public static T GetOrNull() where T : class + public static T? GetOrNull() where T : class => instance.GetOrNull(); - public static object GetUnregistered(Type type) => instance.GetUnregistered(type); public static T GetUnregistered() where T : class diff --git a/OctoAwesome/OctoAwesome/Universe.cs b/OctoAwesome/OctoAwesome/Universe.cs index a983d9ba..b8e48c45 100644 --- a/OctoAwesome/OctoAwesome/Universe.cs +++ b/OctoAwesome/OctoAwesome/Universe.cs @@ -1,8 +1,5 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; namespace OctoAwesome { diff --git a/OctoAwesome/OctoAwesome/UpdateableEntity.cs b/OctoAwesome/OctoAwesome/UpdateableEntity.cs index 3833e1a6..bcdfc632 100644 --- a/OctoAwesome/OctoAwesome/UpdateableEntity.cs +++ b/OctoAwesome/OctoAwesome/UpdateableEntity.cs @@ -1,9 +1,4 @@ using engenious; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace OctoAwesome { @@ -12,13 +7,6 @@ namespace OctoAwesome /// public abstract class UpdateableEntity : Entity { - /// - /// Entity die regelmäßig eine Updateevent bekommt - /// - public UpdateableEntity() : base() - { - } - /// /// Updatemethode der Entity /// diff --git a/OctoAwesome/OctoAwesome/Wall.cs b/OctoAwesome/OctoAwesome/Wall.cs index 31681a57..decd7c5f 100644 --- a/OctoAwesome/OctoAwesome/Wall.cs +++ b/OctoAwesome/OctoAwesome/Wall.cs @@ -1,7 +1,6 @@ -using System; - -namespace OctoAwesome +namespace OctoAwesome { + public enum Wall { /// @@ -27,6 +26,6 @@ public enum Wall /// /// South -Y /// - Front + Front } } \ No newline at end of file