Răsfoiți Sursa

apply new code formatter

Kolja Strohm 1 an în urmă
părinte
comite
5f6fe46883
94 a modificat fișierele cu 5492 adăugiri și 4926 ștergeri
  1. 21 20
      FactoryCraft/AddEntityUpdate.cpp
  2. 6 7
      FactoryCraft/AddEntityUpdate.h
  3. 44 61
      FactoryCraft/Area.cpp
  4. 16 14
      FactoryCraft/Area.h
  5. 31 26
      FactoryCraft/BasicBlocks.h
  6. 3 4
      FactoryCraft/BiomGenerator.cpp
  7. 15 9
      FactoryCraft/BiomGenerator.h
  8. 128 112
      FactoryCraft/BlockType.cpp
  9. 1 1
      FactoryCraft/BlockType.h
  10. 3 5
      FactoryCraft/CaveGenerator.cpp
  11. 6 6
      FactoryCraft/CaveGenerator.h
  12. 778 662
      FactoryCraft/Chunk.cpp
  13. 56 50
      FactoryCraft/Chunk.h
  14. 10 10
      FactoryCraft/Constants.h
  15. 214 196
      FactoryCraft/CraftingStorage.cpp
  16. 42 25
      FactoryCraft/CraftingStorage.h
  17. 58 53
      FactoryCraft/Dimension.h
  18. 259 185
      FactoryCraft/DimensionGenerator.cpp
  19. 24 22
      FactoryCraft/DimensionGenerator.h
  20. 9 11
      FactoryCraft/DoLaterHandler.cpp
  21. 5 5
      FactoryCraft/DoLaterHandler.h
  22. 6 5
      FactoryCraft/EntityRemovedUpdate.h
  23. 86 80
      FactoryCraft/EntityType.cpp
  24. 15 12
      FactoryCraft/EntityType.h
  25. 9 9
      FactoryCraft/FastNoiseWrapper.cpp
  26. 9 9
      FactoryCraft/FastNoiseWrapper.h
  27. 105 102
      FactoryCraft/Game.h
  28. 84 73
      FactoryCraft/GeneratedStructure.cpp
  29. 21 16
      FactoryCraft/GeneratedStructure.h
  30. 20 12
      FactoryCraft/GenerationTemplate.h
  31. 2 1
      FactoryCraft/GrasslandBiom.cpp
  32. 10 7
      FactoryCraft/GrasslandBiom.h
  33. 707 638
      FactoryCraft/Inventory.cpp
  34. 87 56
      FactoryCraft/Inventory.h
  35. 1 1
      FactoryCraft/Item.cpp
  36. 57 58
      FactoryCraft/ItemEntity.cpp
  37. 12 10
      FactoryCraft/ItemEntity.h
  38. 36 40
      FactoryCraft/ItemFilter.cpp
  39. 31 34
      FactoryCraft/ItemFilter.h
  40. 29 30
      FactoryCraft/ItemModifier.cpp
  41. 10 11
      FactoryCraft/ItemModifier.h
  42. 1 2
      FactoryCraft/ItemSkill.cpp
  43. 74 68
      FactoryCraft/ItemSlot.cpp
  44. 39 31
      FactoryCraft/ItemSlot.h
  45. 33 34
      FactoryCraft/ItemStack.cpp
  46. 15 15
      FactoryCraft/ItemStack.h
  47. 2 1
      FactoryCraft/ItemType.cpp
  48. 79 73
      FactoryCraft/LightSources.cpp
  49. 21 19
      FactoryCraft/ModelInfo.cpp
  50. 7 7
      FactoryCraft/ModelInfo.h
  51. 116 113
      FactoryCraft/MultiblockStructure.cpp
  52. 43 32
      FactoryCraft/MultiblockStructure.h
  53. 66 64
      FactoryCraft/MultiblockTree.cpp
  54. 78 77
      FactoryCraft/NetworkMessage.cpp
  55. 25 24
      FactoryCraft/NetworkMessage.h
  56. 30 32
      FactoryCraft/NoBlock.cpp
  57. 24 20
      FactoryCraft/NoBlock.h
  58. 2 3
      FactoryCraft/Noise.cpp
  59. 12 12
      FactoryCraft/Noise.h
  60. 29 26
      FactoryCraft/NoiseInterpolator.cpp
  61. 12 9
      FactoryCraft/NoiseInterpolator.h
  62. 27 27
      FactoryCraft/OverworldDimension.cpp
  63. 7 7
      FactoryCraft/OverworldDimension.h
  64. 341 312
      FactoryCraft/Player.cpp
  65. 37 30
      FactoryCraft/Player.h
  66. 19 17
      FactoryCraft/PlayerHand.cpp
  67. 18 17
      FactoryCraft/RandNoise.cpp
  68. 6 6
      FactoryCraft/RandNoise.h
  69. 58 54
      FactoryCraft/Recipie.cpp
  70. 29 28
      FactoryCraft/Recipie.h
  71. 25 25
      FactoryCraft/RecipieList.h
  72. 6 6
      FactoryCraft/RecipieLoader.cpp
  73. 15 14
      FactoryCraft/RecipieLoader.h
  74. 293 298
      FactoryCraft/Server.cpp
  75. 47 47
      FactoryCraft/Server.h
  76. 70 67
      FactoryCraft/Start.cpp
  77. 54 56
      FactoryCraft/StaticRegistry.h
  78. 36 36
      FactoryCraft/TickOrganizer.cpp
  79. 9 9
      FactoryCraft/TickOrganizer.h
  80. 65 63
      FactoryCraft/TickQueue.cpp
  81. 17 17
      FactoryCraft/TickQueue.h
  82. 13 13
      FactoryCraft/TickWorker.cpp
  83. 6 6
      FactoryCraft/TickWorker.h
  84. 12 4
      FactoryCraft/TreeSeblingBlock.cpp
  85. 37 26
      FactoryCraft/TreeSeblingBlock.h
  86. 11 6
      FactoryCraft/TreeTemplate.h
  87. 76 63
      FactoryCraft/WorldGenerator.cpp
  88. 16 14
      FactoryCraft/WorldGenerator.h
  89. 109 99
      FactoryCraft/WorldLoader.cpp
  90. 11 12
      FactoryCraft/WorldLoader.h
  91. 21 20
      FactoryCraft/WorldUpdate.cpp
  92. 18 15
      FactoryCraft/WorldUpdate.h
  93. 173 134
      FactoryCraft/WormCaveGenerator.cpp
  94. 36 28
      FactoryCraft/WormCaveGenerator.h

+ 21 - 20
FactoryCraft/AddEntityUpdate.cpp

@@ -1,39 +1,40 @@
 #include "AddEntityUpdate.h"
+
 #include "Dimension.h"
 #include "EntityType.h"
 #include "StaticRegistry.h"
 
-
 AddEntityUpdate::AddEntityUpdate(Entity* entity, int dimension)
-	: WorldUpdate(WorldUpdateTypeEnum::ADD_ENTITY, dimension, entity->getPosition(), entity->getPosition()),
-	entity(entity)
+    : WorldUpdate(WorldUpdateTypeEnum::ADD_ENTITY,
+        dimension,
+        entity->getPosition(),
+        entity->getPosition()),
+      entity(entity)
 {}
 
 AddEntityUpdate::~AddEntityUpdate()
 {
-	entity->release();
+    entity->release();
 }
 
-
 void AddEntityUpdate::onUpdate(Dimension* zDimension)
 {
-	zDimension->addEntity(dynamic_cast<Entity*>(entity->getThis()));
+    zDimension->addEntity(dynamic_cast<Entity*>(entity->getThis()));
 }
 
 void AddEntityUpdate::write(Framework::StreamWriter* zWriter)
 {
-	int id = entity->zType()->getId();
-	zWriter->schreibe((char*)&id, 4);
-	id = entity->getId();
-	zWriter->schreibe((char*)&id, 4);
-	Framework::Vec3<float> pos = entity->getPosition();
-	zWriter->schreibe((char*)&pos.x, 4);
-	zWriter->schreibe((char*)&pos.y, 4);
-	zWriter->schreibe((char*)&pos.z, 4);
-	float maxSpeed = entity->getMaxSpeed();
-	zWriter->schreibe((char*)&maxSpeed, 4);
-	bool special = !entity->hasDefaultModel();
-	zWriter->schreibe((char*)&special, 1);
-	if (special)
-		entity->getSpecialModel().writeTo(zWriter);
+    int id = entity->zType()->getId();
+    zWriter->schreibe((char*)&id, 4);
+    id = entity->getId();
+    zWriter->schreibe((char*)&id, 4);
+    Framework::Vec3<float> pos = entity->getPosition();
+    zWriter->schreibe((char*)&pos.x, 4);
+    zWriter->schreibe((char*)&pos.y, 4);
+    zWriter->schreibe((char*)&pos.z, 4);
+    float maxSpeed = entity->getMaxSpeed();
+    zWriter->schreibe((char*)&maxSpeed, 4);
+    bool special = !entity->hasDefaultModel();
+    zWriter->schreibe((char*)&special, 1);
+    if (special) entity->getSpecialModel().writeTo(zWriter);
 }

+ 6 - 7
FactoryCraft/AddEntityUpdate.h

@@ -1,19 +1,18 @@
 #pragma once
-#include "WorldUpdate.h"
 #include "Entity.h"
-
+#include "WorldUpdate.h"
 
 class AddEntityUpdate : public WorldUpdate
 {
 private:
-	Entity* entity;
+    Entity* entity;
 
 protected:
-	void write(Framework::StreamWriter* zWriter) override;
+    void write(Framework::StreamWriter* zWriter) override;
 
 public:
-	AddEntityUpdate(Entity* entity, int dimension);
-	~AddEntityUpdate();
+    AddEntityUpdate(Entity* entity, int dimension);
+    ~AddEntityUpdate();
 
-	void onUpdate(Dimension* zDimension) override;
+    void onUpdate(Dimension* zDimension) override;
 };

+ 44 - 61
FactoryCraft/Area.cpp

@@ -2,80 +2,63 @@
 
 Direction getOppositeDirection(Direction dir)
 {
-	switch (dir)
-	{
-	case NORTH:
-		return SOUTH;
-	case EAST:
-		return WEST;
-	case SOUTH:
-		return NORTH;
-	case WEST:
-		return EAST;
-	case TOP:
-		return BOTTOM;
-	case BOTTOM:
-		return TOP;
-	default:
-		return NO_DIRECTION;
-	}
+    switch (dir)
+    {
+    case NORTH:
+        return SOUTH;
+    case EAST:
+        return WEST;
+    case SOUTH:
+        return NORTH;
+    case WEST:
+        return EAST;
+    case TOP:
+        return BOTTOM;
+    case BOTTOM:
+        return TOP;
+    default:
+        return NO_DIRECTION;
+    }
 }
 
-Directions getDirections(Framework::Vec3<float> currentPos, Framework::Vec3<float> otherPos)
+Directions getDirections(
+    Framework::Vec3<float> currentPos, Framework::Vec3<float> otherPos)
 {
-	Directions result = NO_DIRECTION;
-	if (currentPos.x < otherPos.x)
-		result |= EAST;
-	if (currentPos.x > otherPos.x)
-		result |= WEST;
-	if (currentPos.y < otherPos.y)
-		result |= SOUTH;
-	if (currentPos.y > otherPos.y)
-		result |= NORTH;
-	if (currentPos.z < otherPos.z)
-		result |= TOP;
-	if (currentPos.z > otherPos.z)
-		result |= BOTTOM;
-	return result;
+    Directions result = NO_DIRECTION;
+    if (currentPos.x < otherPos.x) result |= EAST;
+    if (currentPos.x > otherPos.x) result |= WEST;
+    if (currentPos.y < otherPos.y) result |= SOUTH;
+    if (currentPos.y > otherPos.y) result |= NORTH;
+    if (currentPos.z < otherPos.z) result |= TOP;
+    if (currentPos.z > otherPos.z) result |= BOTTOM;
+    return result;
 }
 
 Framework::Vec3<int> getDirection(Directions dir)
 {
-	Framework::Vec3<int> result(0, 0, 0);
-	if ((dir | NORTH) == dir)
-		--result.y;
-	if ((dir | EAST) == dir)
-		++result.x;
-	if ((dir | SOUTH) == dir)
-		++result.y;
-	if ((dir | WEST) == dir)
-		--result.x;
-	if ((dir | TOP) == dir)
-		++result.z;
-	if ((dir | BOTTOM) == dir)
-		--result.z;
-	return result;
+    Framework::Vec3<int> result(0, 0, 0);
+    if ((dir | NORTH) == dir) --result.y;
+    if ((dir | EAST) == dir) ++result.x;
+    if ((dir | SOUTH) == dir) ++result.y;
+    if ((dir | WEST) == dir) --result.x;
+    if ((dir | TOP) == dir) ++result.z;
+    if ((dir | BOTTOM) == dir) --result.z;
+    return result;
 }
 
 int getDirectionIndex(Direction dir)
 {
-	if (dir == NORTH)
-		return 0;
-	if (dir == EAST)
-		return 1;
-	if (dir == SOUTH)
-		return 2;
-	if (dir == WEST)
-		return 3;
-	if (dir == TOP)
-		return 4;
-	if (dir == BOTTOM)
-		return 5;
-	assert(false);
-	return -1;
+    if (dir == NORTH) return 0;
+    if (dir == EAST) return 1;
+    if (dir == SOUTH) return 2;
+    if (dir == WEST) return 3;
+    if (dir == TOP) return 4;
+    if (dir == BOTTOM) return 5;
+    assert(false);
+    return -1;
 }
 
 Direction getDirectionFromIndex(int index)
 {
-	return (Direction)(1 << index);
+    return (Direction)(1 << index);
 }

+ 16 - 14
FactoryCraft/Area.h

@@ -4,30 +4,32 @@
 
 struct Area
 {
-	int startX;
-	int startY;
-	int endX;
-	int endY;
-	int dimensionId;
+    int startX;
+    int startY;
+    int endX;
+    int endY;
+    int dimensionId;
 };
 
 enum Direction
 {
-	NO_DIRECTION = 0,
-	NORTH = 1,
-	EAST = 2,
-	SOUTH = 4,
-	WEST = 8,
-	TOP = 16,
-	BOTTOM = 32,
-	INSIDE = 64
+    NO_DIRECTION = 0,
+    NORTH = 1,
+    EAST = 2,
+    SOUTH = 4,
+    WEST = 8,
+    TOP = 16,
+    BOTTOM = 32,
+    INSIDE = 64
 };
+
 typedef int Directions;
 
 #define ANY_DIRECTION NORTH | EAST | SOUTH | WEST | TOP | BOTTOM
 
 Direction getOppositeDirection(Direction dir);
-Directions getDirections(Framework::Vec3<float> currentPos, Framework::Vec3<float> otherPos);
+Directions getDirections(
+    Framework::Vec3<float> currentPos, Framework::Vec3<float> otherPos);
 Framework::Vec3<int> getDirection(Directions dir);
 int getDirectionIndex(Direction dir);
 Direction getDirectionFromIndex(int index);

+ 31 - 26
FactoryCraft/BasicBlocks.h

@@ -11,51 +11,56 @@ class BasicBlockType;
 class BasicBlock : public Block
 {
 public:
-	BasicBlock(int typeId, ItemType* zTool, Framework::Vec3<int> pos);
-	virtual bool onTick(TickQueue* zQueue, int numTicks, bool& blocked) override;
-	virtual void onPostTick() override;
+    BasicBlock(int typeId, ItemType* zTool, Framework::Vec3<int> pos);
+    virtual bool onTick(
+        TickQueue* zQueue, int numTicks, bool& blocked) override;
+    virtual void onPostTick() override;
 
-	friend BasicBlockType;
+    friend BasicBlockType;
 };
 
 struct SpawnConfig
 {
-	int min;
-	int max;
-	double chance;
-	int itemType;
+    int min;
+    int max;
+    double chance;
+    int itemType;
 };
 
 class AdditionalItemSpawningBlock : public BasicBlock
 {
 private:
-	Framework::Array< SpawnConfig> spawns;
+    Framework::Array<SpawnConfig> spawns;
 
 public:
-	AdditionalItemSpawningBlock(int typeId, ItemType* zTool, Framework::Vec3<int> pos);
-	void addSpawn(SpawnConfig config);
-	virtual void onDestroy() override;
+    AdditionalItemSpawningBlock(
+        int typeId, ItemType* zTool, Framework::Vec3<int> pos);
+    void addSpawn(SpawnConfig config);
+    virtual void onDestroy() override;
 };
 
 class BasicBlockType : public BlockType
 {
 private:
-	int itemType;
-	bool transparent;
-	bool passable;
-	float hardness;
-	ItemType* zTool;
-	float speedModifier;
-	bool interactable;
-	std::function<Block* (Framework::Vec3<int>)> creatBlockCustom;
+    int itemType;
+    bool transparent;
+    bool passable;
+    float hardness;
+    ItemType* zTool;
+    float speedModifier;
+    bool interactable;
+    std::function<Block*(Framework::Vec3<int>)> creatBlockCustom;
 
 protected:
-	virtual void createSuperBlock(Block* zBlock, Item* zItem) const override;
+    virtual void createSuperBlock(Block* zBlock, Item* zItem) const override;
 
 public:
-	BasicBlockType(int typeId, int itemTypeId, ModelInfo model);
-	BasicBlockType(int typeId, int itemTypeId, ModelInfo model, std::function<Block* (Framework::Vec3<int>)> creatBlockCustom);
-	virtual Block* createBlock(Framework::Vec3<int> position) const override;
-	virtual Item* createItem() const override;
-	BasicBlockType* setHardness(float hardness);
+    BasicBlockType(int typeId, int itemTypeId, ModelInfo model);
+    BasicBlockType(int typeId,
+        int itemTypeId,
+        ModelInfo model,
+        std::function<Block*(Framework::Vec3<int>)> creatBlockCustom);
+    virtual Block* createBlock(Framework::Vec3<int> position) const override;
+    virtual Item* createItem() const override;
+    BasicBlockType* setHardness(float hardness);
 };

+ 3 - 4
FactoryCraft/BiomGenerator.cpp

@@ -1,16 +1,15 @@
 #include "BiomGenerator.h"
 
-
 BiomGenerator::BiomGenerator()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {}
 
 void BiomGenerator::addTemplateGenerator(GenerationTemplate* gTemplate)
 {
-	templates.add(gTemplate);
+    templates.add(gTemplate);
 }
 
 const Framework::RCArray<GenerationTemplate>& BiomGenerator::getTemplates()
 {
-	return templates;
+    return templates;
 }

+ 15 - 9
FactoryCraft/BiomGenerator.h

@@ -1,7 +1,7 @@
 #pragma once
 
+#include <Either.h>
 #include <ReferenceCounter.h>
-#include <Either.h> 
 
 #include "GenerationTemplate.h"
 
@@ -11,16 +11,22 @@ class Noise;
 class BiomGenerator : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::RCArray<GenerationTemplate> templates;
+    Framework::RCArray<GenerationTemplate> templates;
 
 protected:
-	void addTemplateGenerator(GenerationTemplate* gTemplate);
+    void addTemplateGenerator(GenerationTemplate* gTemplate);
 
 public:
-	BiomGenerator();
-	virtual Framework::Either<Block*, int> generateSurfaceBlock(int x, int y, int z) = 0;
-	virtual Framework::Either<Block*, int> generateBelowSurfaceBlock(int x, int y, int z) = 0;
-	virtual Framework::Either<Block*, int> generateCaveBlock(int x, int y, int z) = 0;
-	virtual Noise* zHeightMapNoise(int seed) = 0;
-	const Framework::RCArray<GenerationTemplate>& getTemplates();
+    BiomGenerator();
+    virtual Framework::Either<Block*, int> generateSurfaceBlock(
+        int x, int y, int z)
+        = 0;
+    virtual Framework::Either<Block*, int> generateBelowSurfaceBlock(
+        int x, int y, int z)
+        = 0;
+    virtual Framework::Either<Block*, int> generateCaveBlock(
+        int x, int y, int z)
+        = 0;
+    virtual Noise* zHeightMapNoise(int seed) = 0;
+    const Framework::RCArray<GenerationTemplate>& getTemplates();
 };

+ 128 - 112
FactoryCraft/BlockType.cpp

@@ -1,179 +1,195 @@
 #include "BlockType.h"
-#include "ItemType.h"
+
 #include "BasicBlocks.h"
 #include "Block.h"
-#include "MultiblockStructure.h"
 #include "Game.h"
+#include "ItemType.h"
+#include "MultiblockStructure.h"
 
 using namespace Framework;
 
-BlockType::BlockType(int id, Block* defaultBlock,
-	ModelInfo model, bool needsClientInstance, int initialMaxHP, bool lightSource)
-	: ReferenceCounter(),
-	id(id),
-	model(model),
-	initialMaxHP(initialMaxHP),
-	needsClientInstance(needsClientInstance),
-	lightSource(lightSource),
-	defaultBlock(defaultBlock)
+BlockType::BlockType(int id,
+    Block* defaultBlock,
+    ModelInfo model,
+    bool needsClientInstance,
+    int initialMaxHP,
+    bool lightSource)
+    : ReferenceCounter(),
+      id(id),
+      model(model),
+      initialMaxHP(initialMaxHP),
+      needsClientInstance(needsClientInstance),
+      lightSource(lightSource),
+      defaultBlock(defaultBlock)
 {
-	StaticRegistry<BlockType>::INSTANCE.registerT(this, id);
+    StaticRegistry<BlockType>::INSTANCE.registerT(this, id);
 }
 
 BlockType::~BlockType()
 {
-	if (defaultBlock)
-		defaultBlock->release();
-}
-
-void BlockType::loadSuperBlock(Block* zBlock, Framework::StreamReader* zReader, int dimensionId) const
-{
-	zBlock->loadInventory(zReader);
-	zReader->lese((char*)&zBlock->transparent, 1);
-	zReader->lese((char*)&zBlock->passable, 1);
-	zReader->lese((char*)&zBlock->hp, 4);
-	zReader->lese((char*)&zBlock->maxHP, 4);
-	zReader->lese((char*)&zBlock->hardness, 4);
-	zReader->lese((char*)&zBlock->speedModifier, 4);
-	int effectiveToolId;
-	zReader->lese((char*)&effectiveToolId, 4);
-	if (effectiveToolId >= 0)
-		zBlock->zTool = StaticRegistry<ItemType>::INSTANCE.zElement(effectiveToolId);
-	else
-		zBlock->zTool = 0;
-	zReader->lese((char*)&zBlock->interactable, 1);
-	int strCount;
-	zReader->lese((char*)&strCount, 4);
-	for (int i = 0; i < strCount; i++)
-	{
-		__int64 id;
-		zReader->lese((char*)&id, 8);
-		MultiblockStructure* str = Game::INSTANCE->zDimension(dimensionId)->zStructureById(id);
-		zBlock->structures.add(dynamic_cast<MultiblockStructure*>(str->getThis()));
-	}
-}
-
-void BlockType::saveSuperBlock(Block* zBlock, Framework::StreamWriter* zWriter) const
-{
-	zBlock->saveInventory(zWriter);
-	zWriter->schreibe((char*)&zBlock->transparent, 1);
-	zWriter->schreibe((char*)&zBlock->passable, 1);
-	zWriter->schreibe((char*)&zBlock->hp, 4);
-	zWriter->schreibe((char*)&zBlock->maxHP, 4);
-	zWriter->schreibe((char*)&zBlock->hardness, 4);
-	zWriter->schreibe((char*)&zBlock->speedModifier, 4);
-	int effectiveToolId = zBlock->zTool ? zBlock->zTool->getId() : -1;
-	zWriter->schreibe((char*)&effectiveToolId, 4);
-	zWriter->schreibe((char*)&zBlock->interactable, 1);
-	int strCount = zBlock->structures.getEintragAnzahl();
-	zWriter->schreibe((char*)&strCount, 4);
-	for (MultiblockStructure* structure : zBlock->structures)
-	{
-		__int64 id = structure->getStructureId();
-		zWriter->schreibe((char*)&id, 8);
-	}
+    if (defaultBlock) defaultBlock->release();
+}
+
+void BlockType::loadSuperBlock(
+    Block* zBlock, Framework::StreamReader* zReader, int dimensionId) const
+{
+    zBlock->loadInventory(zReader);
+    zReader->lese((char*)&zBlock->transparent, 1);
+    zReader->lese((char*)&zBlock->passable, 1);
+    zReader->lese((char*)&zBlock->hp, 4);
+    zReader->lese((char*)&zBlock->maxHP, 4);
+    zReader->lese((char*)&zBlock->hardness, 4);
+    zReader->lese((char*)&zBlock->speedModifier, 4);
+    int effectiveToolId;
+    zReader->lese((char*)&effectiveToolId, 4);
+    if (effectiveToolId >= 0)
+        zBlock->zTool
+            = StaticRegistry<ItemType>::INSTANCE.zElement(effectiveToolId);
+    else
+        zBlock->zTool = 0;
+    zReader->lese((char*)&zBlock->interactable, 1);
+    int strCount;
+    zReader->lese((char*)&strCount, 4);
+    for (int i = 0; i < strCount; i++)
+    {
+        __int64 id;
+        zReader->lese((char*)&id, 8);
+        MultiblockStructure* str
+            = Game::INSTANCE->zDimension(dimensionId)->zStructureById(id);
+        zBlock->structures.add(
+            dynamic_cast<MultiblockStructure*>(str->getThis()));
+    }
+}
+
+void BlockType::saveSuperBlock(
+    Block* zBlock, Framework::StreamWriter* zWriter) const
+{
+    zBlock->saveInventory(zWriter);
+    zWriter->schreibe((char*)&zBlock->transparent, 1);
+    zWriter->schreibe((char*)&zBlock->passable, 1);
+    zWriter->schreibe((char*)&zBlock->hp, 4);
+    zWriter->schreibe((char*)&zBlock->maxHP, 4);
+    zWriter->schreibe((char*)&zBlock->hardness, 4);
+    zWriter->schreibe((char*)&zBlock->speedModifier, 4);
+    int effectiveToolId = zBlock->zTool ? zBlock->zTool->getId() : -1;
+    zWriter->schreibe((char*)&effectiveToolId, 4);
+    zWriter->schreibe((char*)&zBlock->interactable, 1);
+    int strCount = zBlock->structures.getEintragAnzahl();
+    zWriter->schreibe((char*)&strCount, 4);
+    for (MultiblockStructure* structure : zBlock->structures)
+    {
+        __int64 id = structure->getStructureId();
+        zWriter->schreibe((char*)&id, 8);
+    }
 }
 
 void BlockType::createSuperBlock(Block* zBlock, Item* zItem) const
 {
-	if (zItem)
-	{
-		BasicBlockItem* item = dynamic_cast<BasicBlockItem*>(zItem);
-		if (!item)
-		{
-			throw "BlockType::createSuperBlock was called with an item witch was not an instance of BasicBlockItem";
-		}
-		zBlock->transparent = item->transparent;
-		zBlock->passable = item->passable;
-		zBlock->hardness = item->hardness;
-		zBlock->speedModifier = item->speedModifier;
-		zBlock->zTool = item->toolId >= 0 ? StaticRegistry<ItemType>::INSTANCE.zElement(item->toolId) : 0;
-		zBlock->interactable = item->interactable;
-	}
+    if (zItem)
+    {
+        BasicBlockItem* item = dynamic_cast<BasicBlockItem*>(zItem);
+        if (!item)
+        {
+            throw "BlockType::createSuperBlock was called with an item witch "
+                  "was not an instance of BasicBlockItem";
+        }
+        zBlock->transparent = item->transparent;
+        zBlock->passable = item->passable;
+        zBlock->hardness = item->hardness;
+        zBlock->speedModifier = item->speedModifier;
+        zBlock->zTool
+            = item->toolId >= 0
+                ? StaticRegistry<ItemType>::INSTANCE.zElement(item->toolId)
+                : 0;
+        zBlock->interactable = item->interactable;
+    }
 }
 
 void BlockType::createSuperItem(Block* zBlock, Item* zItem) const
 {
-	BasicBlockItem* item = dynamic_cast<BasicBlockItem*>(zItem);
-	if (!item)
-	{
-		throw "BlockType::createSuperItem was called with an item witch was not an instance of BasicBlockItem";
-	}
-	item->transparent = zBlock->transparent;
-	item->passable = zBlock->passable;
-	item->hardness = zBlock->hardness;
-	item->speedModifier = zBlock->speedModifier;
-	item->toolId = zBlock->zTool ? zBlock->zTool->getId() : -1;
-	item->interactable = zBlock->interactable;
+    BasicBlockItem* item = dynamic_cast<BasicBlockItem*>(zItem);
+    if (!item)
+    {
+        throw "BlockType::createSuperItem was called with an item witch was "
+              "not an instance of BasicBlockItem";
+    }
+    item->transparent = zBlock->transparent;
+    item->passable = zBlock->passable;
+    item->hardness = zBlock->hardness;
+    item->speedModifier = zBlock->speedModifier;
+    item->toolId = zBlock->zTool ? zBlock->zTool->getId() : -1;
+    item->interactable = zBlock->interactable;
 }
 
-Block* BlockType::loadBlock(Framework::Vec3<int> position, Framework::StreamReader* zReader, int dimensionId) const
+Block* BlockType::loadBlock(Framework::Vec3<int> position,
+    Framework::StreamReader* zReader,
+    int dimensionId) const
 {
-	Block* result = createBlock(position);
-	loadSuperBlock(result, zReader, dimensionId);
-	return result;
+    Block* result = createBlock(position);
+    loadSuperBlock(result, zReader, dimensionId);
+    return result;
 }
 
 void BlockType::saveBlock(Block* zBlock, Framework::StreamWriter* zWriter) const
 {
-	saveSuperBlock(zBlock, zWriter);
+    saveSuperBlock(zBlock, zWriter);
 }
 
 Item* BlockType::getItemFromBlock(Block* zBlock) const
 {
-	Item* result = createItem();
-	createSuperItem(zBlock, result);
-	return result;
+    Item* result = createItem();
+    createSuperItem(zBlock, result);
+    return result;
 }
 
-Block* BlockType::createBlockAt(Framework::Vec3<int> position, Item* zUsedItem) const
+Block* BlockType::createBlockAt(
+    Framework::Vec3<int> position, Item* zUsedItem) const
 {
-	Block* result = createBlock(position);
-	createSuperBlock(result, zUsedItem);
-	return result;
+    Block* result = createBlock(position);
+    createSuperBlock(result, zUsedItem);
+    return result;
 }
 
 bool BlockType::doesNeedClientInstance() const
 {
-	return needsClientInstance;
+    return needsClientInstance;
 }
 
 const ModelInfo& BlockType::getModel() const
 {
-	return model;
+    return model;
 }
 
 int BlockType::getId() const
 {
-	return id;
+    return id;
 }
 
 const Block* BlockType::zDefault() const
 {
-	return defaultBlock;
+    return defaultBlock;
 }
 
 int BlockType::getInitialMaxHP() const
 {
-	return initialMaxHP;
+    return initialMaxHP;
 }
 
 bool BlockType::isLightSource() const
 {
-	return lightSource;
+    return lightSource;
 }
 
-
 const Block* getDefaultBlock(Either<Block*, int> b)
 {
-	if (b.isA())
-		return b;
-	else
-		return StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault();
+    if (b.isA())
+        return b;
+    else
+        return StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault();
 }
 
 BlockType* BlockType::initializeDefault()
 {
-	defaultBlock = createBlockAt({ 0, 0, 0 }, 0);
-	return this;
+    defaultBlock = createBlockAt({0, 0, 0}, 0);
+    return this;
 }

+ 1 - 1
FactoryCraft/BlockType.h

@@ -37,7 +37,7 @@ public:
     static const int SEBLING_WOOD_PINE = 20;
     static const int TORCH = 21;
 
-	static const int MAX_VALUE = 21;
+    static const int MAX_VALUE = 21;
 };
 
 class BlockType : public virtual Framework::ReferenceCounter

+ 3 - 5
FactoryCraft/CaveGenerator.cpp

@@ -2,17 +2,15 @@
 
 using namespace Framework;
 
-
 CaveChunkGenerator::CaveChunkGenerator()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {}
 
-
 CaveGenerator::CaveGenerator()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {}
 
 void CaveGenerator::initialize(int seed)
 {
-	this->seed = seed;
+    this->seed = seed;
 }

+ 6 - 6
FactoryCraft/CaveGenerator.h

@@ -5,17 +5,17 @@
 class CaveChunkGenerator : public virtual Framework::ReferenceCounter
 {
 public:
-	CaveChunkGenerator();
-	virtual bool isInCave(int x, int y, int z) = 0;
+    CaveChunkGenerator();
+    virtual bool isInCave(int x, int y, int z) = 0;
 };
 
 class CaveGenerator : public virtual Framework::ReferenceCounter
 {
 protected:
-	int seed;
+    int seed;
 
 public:
-	CaveGenerator();
-	virtual void initialize(int seed);
-	virtual CaveChunkGenerator* getGeneratorForChunk(int x, int y) = 0;
+    CaveGenerator();
+    virtual void initialize(int seed);
+    virtual CaveChunkGenerator* getGeneratorForChunk(int x, int y) = 0;
 };

+ 778 - 662
FactoryCraft/Chunk.cpp

@@ -1,786 +1,902 @@
-#include <InMemoryBuffer.h>
+#include "Chunk.h"
+
 #include <AsynchronCall.h>
+#include <InMemoryBuffer.h>
 
-#include "Chunk.h"
 #include "Constants.h"
 #include "Game.h"
 #include "NoBlock.h"
 
-
 Chunk::Chunk(Framework::Punkt location, int dimensionId)
-	: ReferenceCounter(),
-	dimensionId(dimensionId),
-	location(location),
-	added(0),
-	currentlyLoading(1)
-{
-	blocks = new Block * [CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT];
-	blockIds = new unsigned short[CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT];
-	lightData = new unsigned char[CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * 6];
-	memset(blocks, 0, CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * sizeof(Block*));
-	memset(blockIds, 0, CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * sizeof(unsigned short));
-	memset(lightData, 0, CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * 6);
-	zNeighbours[0] = 0;
-	zNeighbours[1] = 0;
-	zNeighbours[2] = 0;
-	zNeighbours[3] = 0;
-}
-
-Chunk::Chunk(Framework::Punkt location, int dimensionId, Framework::StreamReader* zReader)
-	: Chunk(location, dimensionId)
-{
-	load(zReader);
+    : ReferenceCounter(),
+      dimensionId(dimensionId),
+      location(location),
+      added(0),
+      currentlyLoading(1)
+{
+    blocks = new Block*[CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT];
+    blockIds = new unsigned short[CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT];
+    lightData = new unsigned char[CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * 6];
+    memset(blocks, 0, CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * sizeof(Block*));
+    memset(blockIds,
+        0,
+        CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * sizeof(unsigned short));
+    memset(lightData, 0, CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * 6);
+    zNeighbours[0] = 0;
+    zNeighbours[1] = 0;
+    zNeighbours[2] = 0;
+    zNeighbours[3] = 0;
+}
+
+Chunk::Chunk(Framework::Punkt location,
+    int dimensionId,
+    Framework::StreamReader* zReader)
+    : Chunk(location, dimensionId)
+{
+    load(zReader);
 }
 
 Chunk::~Chunk()
 {
-	for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
-	{
-		if (blocks[i])
-			blocks[i]->release();
-	}
-	delete[] blocks;
-	delete[] blockIds;
-	delete[] lightData;
+    for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
+    {
+        if (blocks[i]) blocks[i]->release();
+    }
+    delete[] blocks;
+    delete[] blockIds;
+    delete[] lightData;
 }
 
 void Chunk::addLightSource(int index)
 {
-	for (int i : lightSources)
-	{
-		if (i == index)
-			return;
-	}
-	lightSources.add(index);
+    for (int i : lightSources)
+    {
+        if (i == index) return;
+    }
+    lightSources.add(index);
 }
 
 void Chunk::removeLightSource(int index)
 {
-	for (auto i = lightSources.begin(); i; i++)
-	{
-		if (i.val() == index)
-		{
-			i.remove();
-			return;
-		}
-	}
+    for (auto i = lightSources.begin(); i; i++)
+    {
+        if (i.val() == index)
+        {
+            i.remove();
+            return;
+        }
+    }
 }
 
 void Chunk::sendLightToClient(Framework::StreamWriter* zWriter)
 {
-	for (int z = 0; z < WORLD_HEIGHT; z++)
-	{
-		for (int x = 0; x < CHUNK_SIZE; x++)
-		{
-			for (int y = 0; y < CHUNK_SIZE; y++)
-			{
-				bool needSend = 0;
-				for (int i = 0; i < 6; i++)
-				{
-					Vec3<int> pos = Vec3<int>(x, y, z) + getDirection(getDirectionFromIndex(i));
-					if (pos.z >= 0 && pos.z < WORLD_HEIGHT)
-					{
-						if (pos.x >= 0 && pos.x < CHUNK_SIZE && pos.y >= 0 && pos.y < CHUNK_SIZE)
-						{
-							int bi = (pos.x * CHUNK_SIZE + pos.y) * WORLD_HEIGHT + pos.z;
-							int type = blockIds[bi];
+    for (int z = 0; z < WORLD_HEIGHT; z++)
+    {
+        for (int x = 0; x < CHUNK_SIZE; x++)
+        {
+            for (int y = 0; y < CHUNK_SIZE; y++)
+            {
+                bool needSend = 0;
+                for (int i = 0; i < 6; i++)
+                {
+                    Vec3<int> pos = Vec3<int>(x, y, z)
+                                  + getDirection(getDirectionFromIndex(i));
+                    if (pos.z >= 0 && pos.z < WORLD_HEIGHT)
+                    {
+                        if (pos.x >= 0 && pos.x < CHUNK_SIZE && pos.y >= 0
+                            && pos.y < CHUNK_SIZE)
+                        {
+                            int bi = (pos.x * CHUNK_SIZE + pos.y) * WORLD_HEIGHT
+                                   + pos.z;
+                            int type = blockIds[bi];
                             needSend |= type != BlockTypeEnum::NO_BLOCK
                                      && type != BlockTypeEnum::AIR;
-						}
-						else
-						{
-							if (i < 4 && zNeighbours[i])
-							{
-								Vec3<int> offset = getDirection(getDirectionFromIndex(i)) * 16;
-								int bi = ((pos.x - offset.x) * CHUNK_SIZE + (pos.y - offset.y)) * WORLD_HEIGHT + (pos.z - offset.z);
-								int type = zNeighbours[i]->blockIds[bi];
+                        }
+                        else
+                        {
+                            if (i < 4 && zNeighbours[i])
+                            {
+                                Vec3<int> offset
+                                    = getDirection(getDirectionFromIndex(i))
+                                    * 16;
+                                int bi = ((pos.x - offset.x) * CHUNK_SIZE
+                                             + (pos.y - offset.y))
+                                           * WORLD_HEIGHT
+                                       + (pos.z - offset.z);
+                                int type = zNeighbours[i]->blockIds[bi];
                                 needSend |= type != BlockTypeEnum::NO_BLOCK
                                          && type != BlockTypeEnum::AIR;
-							}
-						}
-						if (needSend)
-							break;
-					}
-				}
-				if (needSend)
-				{
-					int index = (x * CHUNK_SIZE + y) * WORLD_HEIGHT + z;
-					zWriter->schreibe((char*)&index, 4);
-					zWriter->schreibe((char*)(lightData + index * 6), 6);
-				}
-			}
-		}
-	}
-	int end = -1;
-	zWriter->schreibe((char*)&end, 4);
-}
-
-Framework::Either<Block*, int> Chunk::zBlockNeighbor(Framework::Vec3<int> location)
-{
-	if (location.x >= 0 && location.x < CHUNK_SIZE && location.y >= 0 && location.y < CHUNK_SIZE && location.z >= 0 && location.z < WORLD_HEIGHT)
-	{
-		int index = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
-		if (blocks[index])
-			return blocks[index];
-		else
-			return (int)blockIds[index];
-	}
-	if (added && location.z >= 0 && location.z < WORLD_HEIGHT)
-		return Game::INSTANCE->zBlockAt({ location.x + this->location.x - CHUNK_SIZE / 2, location.y + this->location.y - CHUNK_SIZE / 2, location.z }, dimensionId);
-	return 0;
+                            }
+                        }
+                        if (needSend) break;
+                    }
+                }
+                if (needSend)
+                {
+                    int index = (x * CHUNK_SIZE + y) * WORLD_HEIGHT + z;
+                    zWriter->schreibe((char*)&index, 4);
+                    zWriter->schreibe((char*)(lightData + index * 6), 6);
+                }
+            }
+        }
+    }
+    int end = -1;
+    zWriter->schreibe((char*)&end, 4);
+}
+
+Framework::Either<Block*, int> Chunk::zBlockNeighbor(
+    Framework::Vec3<int> location)
+{
+    if (location.x >= 0 && location.x < CHUNK_SIZE && location.y >= 0
+        && location.y < CHUNK_SIZE && location.z >= 0
+        && location.z < WORLD_HEIGHT)
+    {
+        int index = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT
+                  + location.z;
+        if (blocks[index])
+            return blocks[index];
+        else
+            return (int)blockIds[index];
+    }
+    if (added && location.z >= 0 && location.z < WORLD_HEIGHT)
+        return Game::INSTANCE->zBlockAt(
+            {location.x + this->location.x - CHUNK_SIZE / 2,
+                location.y + this->location.y - CHUNK_SIZE / 2,
+                location.z},
+            dimensionId);
+    return 0;
 }
 
 void Chunk::notifyObservers(NetworkMessage* msg)
 {
-	Array<int> remove;
-	int index = 0;
-	for (int id : observers)
-	{
-		Entity* zE = Game::INSTANCE->zEntity(id);
-		if (!zE)
-			remove.add(index, 0);
-		else
-			Game::INSTANCE->sendMessage(dynamic_cast<NetworkMessage*>(msg->getThis()), zE);
-		index++;
-	}
-	for (int i : remove)
-		observers.remove(i);
-	msg->release();
+    Array<int> remove;
+    int index = 0;
+    for (int id : observers)
+    {
+        Entity* zE = Game::INSTANCE->zEntity(id);
+        if (!zE)
+            remove.add(index, 0);
+        else
+            Game::INSTANCE->sendMessage(
+                dynamic_cast<NetworkMessage*>(msg->getThis()), zE);
+        index++;
+    }
+    for (int i : remove)
+        observers.remove(i);
+    msg->release();
 }
 
 void Chunk::addObserver(Entity* zEntity, DoLaterHandler& laterHandler)
 {
-	for (int id : observers)
-	{
-		if (id == zEntity->getId())
-			return;
-	}
-	int id = zEntity->getId();
-	observers.add(id);
-	laterHandler.addTodo([this, id]()
-		{
-			InMemoryBuffer buffer;
-			buffer.schreibe("\4", 1);
-			buffer.schreibe((char*)&location.x, 4);
-			buffer.schreibe((char*)&location.y, 4);
-			sendToClient(&buffer);
-			sendLightToClient(&buffer);
-			NetworkMessage* msg = new NetworkMessage();
-			msg->addressDimension();
-			std::cout << "chunk size: " << buffer.getSize() << "b\n";
-			char* message = new char[buffer.getSize()];
-			buffer.lese(message, (int)buffer.getSize());
-			msg->setMessage(message, (int)buffer.getSize());
-			msg->setUseBackground();
-			Entity* e = Game::INSTANCE->zEntity(id);
-			if (e)
-			{
-				Game::INSTANCE->sendMessage(msg, e);
-			}
-			else
-				msg->release();
-		});
+    for (int id : observers)
+    {
+        if (id == zEntity->getId()) return;
+    }
+    int id = zEntity->getId();
+    observers.add(id);
+    laterHandler.addTodo([this, id]() {
+        InMemoryBuffer buffer;
+        buffer.schreibe("\4", 1);
+        buffer.schreibe((char*)&location.x, 4);
+        buffer.schreibe((char*)&location.y, 4);
+        sendToClient(&buffer);
+        sendLightToClient(&buffer);
+        NetworkMessage* msg = new NetworkMessage();
+        msg->addressDimension();
+        std::cout << "chunk size: " << buffer.getSize() << "b\n";
+        char* message = new char[buffer.getSize()];
+        buffer.lese(message, (int)buffer.getSize());
+        msg->setMessage(message, (int)buffer.getSize());
+        msg->setUseBackground();
+        Entity* e = Game::INSTANCE->zEntity(id);
+        if (e)
+        {
+            Game::INSTANCE->sendMessage(msg, e);
+        }
+        else
+            msg->release();
+    });
 }
 
 void Chunk::removeObserver(Entity* zEntity)
 {
-	int index = 0;
-	for (int id : observers)
-	{
-		if (id == zEntity->getId())
-		{
-			observers.remove(index);
-			return;
-		}
-		index++;
-	}
-}
-
-void Chunk::api(Framework::StreamReader* zRequest, Entity* zSource, DoLaterHandler& laterHandler)
-{
-	// TODO: answer api messages
-	char type;
-	zRequest->lese(&type, 1);
-	switch (type)
-	{
-	case 0:
-		// register observer
-		addObserver(zSource, laterHandler);
-		break;
-	case 1:
-		// unsubscribe
-		removeObserver(zSource);
-		break;
-	}
+    int index = 0;
+    for (int id : observers)
+    {
+        if (id == zEntity->getId())
+        {
+            observers.remove(index);
+            return;
+        }
+        index++;
+    }
+}
+
+void Chunk::api(Framework::StreamReader* zRequest,
+    Entity* zSource,
+    DoLaterHandler& laterHandler)
+{
+    // TODO: answer api messages
+    char type;
+    zRequest->lese(&type, 1);
+    switch (type)
+    {
+    case 0:
+        // register observer
+        addObserver(zSource, laterHandler);
+        break;
+    case 1:
+        // unsubscribe
+        removeObserver(zSource);
+        break;
+    }
 }
 
 void Chunk::initializeLightning()
 {
-	unsigned char dayLight[6] = { 255, 255, 255, 0, 0, 0 };
-	unsigned char noLight[6] = { 0, 0, 0, 0, 0, 0 };
-	while (true)
-	{
-		bool changes = false;
-		for (int z = WORLD_HEIGHT - 1; z >= 0; z--)
-		{
-			for (int x = 0; x < CHUNK_SIZE; x++)
-			{
-				for (int y = 0; y < CHUNK_SIZE; y++)
-				{
-					int index = (x * CHUNK_SIZE + y) * WORLD_HEIGHT + z;
-					unsigned char* light = getLightData(Vec3<int>(x, y, z));
-					unsigned char newLight[6] = { 0, 0, 0, 0, 0, 0 };
-					for (int i = 0; i < 6; i++)
-					{
-						unsigned char* neighborLeight;
-						Vec3<int> neighborPos = Vec3<int>(x, y, z) + getDirection(getDirectionFromIndex(i));
-						if (neighborPos.z < 0 || neighborPos.x < 0 || neighborPos.y < 0 || neighborPos.x >= CHUNK_SIZE || neighborPos.y >= CHUNK_SIZE)
-						{
-							neighborLeight = noLight;
-						}
-						else if (neighborPos.z >= WORLD_HEIGHT)
-						{
-							neighborLeight = dayLight;
-						}
-						else
-						{
-							neighborLeight = getLightData(neighborPos);
-						}
-						for (int j = 0; j < 3; j++)
-							newLight[j] = (unsigned char)MAX(newLight[j], i == getDirectionIndex(TOP) ? neighborLeight[j] : (unsigned char)((float)neighborLeight[j] * 0.8f));
-						for (int j = 3; j < 6; j++)
-							newLight[j] = (unsigned char)MAX(newLight[j], (unsigned char)((float)neighborLeight[j] * 0.85f));
-					}
-					const Block* current = blocks[index] ? blocks[index] : StaticRegistry<BlockType>::INSTANCE.zElement(blockIds[index])->zDefault();
-					// add own light emission
-					for (int j = 3; j < 6; j++)
-						newLight[j] = (unsigned char)MAX(newLight[j], current->getLightEmisionColor()[j - 3]);
-					current->filterPassingLight(newLight);
-					current->filterPassingLight(newLight + 3);
-					for (int i = 0; i < 6; i++)
-					{
-						if (newLight[i] != light[i])
-						{
-							changes = 1;
-							memcpy(light, newLight, 6);
-							break;
-						}
-					}
-
-				}
-			}
-		}
-		if (!changes)
-			break;
-	}
-}
-
-Framework::Either<Block*, int> Chunk::zBlockAt(Framework::Vec3<int> location) const
-{
-	int index = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
-	assert(index < CHUNK_SIZE* CHUNK_SIZE* WORLD_HEIGHT);
-	if (blocks[index])
-		return blocks[index];
-	else
-		return (int)blockIds[index];
+    unsigned char dayLight[6] = {255, 255, 255, 0, 0, 0};
+    unsigned char noLight[6] = {0, 0, 0, 0, 0, 0};
+    while (true)
+    {
+        bool changes = false;
+        for (int z = WORLD_HEIGHT - 1; z >= 0; z--)
+        {
+            for (int x = 0; x < CHUNK_SIZE; x++)
+            {
+                for (int y = 0; y < CHUNK_SIZE; y++)
+                {
+                    int index = (x * CHUNK_SIZE + y) * WORLD_HEIGHT + z;
+                    unsigned char* light = getLightData(Vec3<int>(x, y, z));
+                    unsigned char newLight[6] = {0, 0, 0, 0, 0, 0};
+                    for (int i = 0; i < 6; i++)
+                    {
+                        unsigned char* neighborLeight;
+                        Vec3<int> neighborPos
+                            = Vec3<int>(x, y, z)
+                            + getDirection(getDirectionFromIndex(i));
+                        if (neighborPos.z < 0 || neighborPos.x < 0
+                            || neighborPos.y < 0 || neighborPos.x >= CHUNK_SIZE
+                            || neighborPos.y >= CHUNK_SIZE)
+                        {
+                            neighborLeight = noLight;
+                        }
+                        else if (neighborPos.z >= WORLD_HEIGHT)
+                        {
+                            neighborLeight = dayLight;
+                        }
+                        else
+                        {
+                            neighborLeight = getLightData(neighborPos);
+                        }
+                        for (int j = 0; j < 3; j++)
+                            newLight[j] = (unsigned char)MAX(newLight[j],
+                                i == getDirectionIndex(TOP)
+                                    ? neighborLeight[j]
+                                    : (unsigned char)((float)neighborLeight[j]
+                                                      * 0.8f));
+                        for (int j = 3; j < 6; j++)
+                            newLight[j] = (unsigned char)MAX(newLight[j],
+                                (unsigned char)((float)neighborLeight[j]
+                                                * 0.85f));
+                    }
+                    const Block* current
+                        = blocks[index] ? blocks[index]
+                                        : StaticRegistry<BlockType>::INSTANCE
+                                              .zElement(blockIds[index])
+                                              ->zDefault();
+                    // add own light emission
+                    for (int j = 3; j < 6; j++)
+                        newLight[j] = (unsigned char)MAX(newLight[j],
+                            current->getLightEmisionColor()[j - 3]);
+                    current->filterPassingLight(newLight);
+                    current->filterPassingLight(newLight + 3);
+                    for (int i = 0; i < 6; i++)
+                    {
+                        if (newLight[i] != light[i])
+                        {
+                            changes = 1;
+                            memcpy(light, newLight, 6);
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        if (!changes) break;
+    }
+}
+
+Framework::Either<Block*, int> Chunk::zBlockAt(
+    Framework::Vec3<int> location) const
+{
+    int index
+        = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
+    assert(index < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT);
+    if (blocks[index])
+        return blocks[index];
+    else
+        return (int)blockIds[index];
 }
 
 const Block* Chunk::zBlockConst(Framework::Vec3<int> location) const
 {
-	auto b = zBlockAt(location);
-	if (b.isA())
-		return b;
-	if (b.getB())
-		return StaticRegistry<BlockType>::INSTANCE.zElement(b.getB())->zDefault();
-	return 0;
+    auto b = zBlockAt(location);
+    if (b.isA()) return b;
+    if (b.getB())
+        return StaticRegistry<BlockType>::INSTANCE.zElement(b.getB())
+            ->zDefault();
+    return 0;
 }
 
 void Chunk::instantiateBlock(Framework::Vec3<int> location)
 {
-	auto b = zBlockAt(location);
-	if (b.isA())
-		return;
-	if (!b.getB())
-		generateBlock(location);
-	b = zBlockAt(location);
-	if (b.isB())
-		putBlockAt(location, StaticRegistry<BlockType>::INSTANCE.zElement(b.getB())->createBlockAt({ location.x + this->location.x - CHUNK_SIZE / 2, location.y + this->location.y - CHUNK_SIZE / 2, location.z }, 0));
+    auto b = zBlockAt(location);
+    if (b.isA()) return;
+    if (!b.getB()) generateBlock(location);
+    b = zBlockAt(location);
+    if (b.isB())
+        putBlockAt(location,
+            StaticRegistry<BlockType>::INSTANCE.zElement(b.getB())
+                ->createBlockAt(
+                    {location.x + this->location.x - CHUNK_SIZE / 2,
+                        location.y + this->location.y - CHUNK_SIZE / 2,
+                        location.z},
+                    0));
 }
 
 void Chunk::generateBlock(Framework::Vec3<int> location)
 {
-	int index = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
-	if (blockIds[index])
-		return;
-	auto generated = Game::INSTANCE->zGenerator()->generateSingleBlock({ location.x + this->location.x - CHUNK_SIZE / 2, location.y + this->location.y - CHUNK_SIZE / 2, location.z }, dimensionId);
-	if (generated.isA())
-		putBlockAt(location, generated);
-	else
-		putBlockTypeAt(location, generated);
+    int index
+        = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
+    if (blockIds[index]) return;
+    auto generated = Game::INSTANCE->zGenerator()->generateSingleBlock(
+        {location.x + this->location.x - CHUNK_SIZE / 2,
+            location.y + this->location.y - CHUNK_SIZE / 2,
+            location.z},
+        dimensionId);
+    if (generated.isA())
+        putBlockAt(location, generated);
+    else
+        putBlockTypeAt(location, generated);
 }
 
 void Chunk::putBlockAt(Framework::Vec3<int> location, Block* block)
 {
-	int index = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
-	assert(index < CHUNK_SIZE* CHUNK_SIZE* WORLD_HEIGHT&& index >= 0);
-	Block* old = blocks[index];
-	bool change = 0;
-	bool wasLightSource = old ? old->zBlockType()->isLightSource() : StaticRegistry<BlockType>::INSTANCE.zElement(blockIds[index])->isLightSource();
-	bool isLightSource = 0;
-	if (block)
-	{
-		change = blockIds[index] != (unsigned short)block->zBlockType()->getId();
-		blockIds[index] = (unsigned short)block->zBlockType()->getId();
-		isLightSource = block->zBlockType()->isLightSource();
-	}
-	else
-	{
-		change = old != 0;
-	}
-	blocks[index] = block;
-	for (int i = 0; i < 6; i++)
-	{
-		Direction d = getDirectionFromIndex(i);
-		Either<Block*, int> neighbor = zBlockNeighbor(location + getDirection(d));
-		if (neighbor.isA())
-			((Block*)neighbor)->setNeighbour(getOppositeDirection(d), block);
-		if (block)
-			block->setNeighbour(d, neighbor);
-	}
-	if (old)
-		old->release();
-	if (change)
-	{
-		if (isLightSource != wasLightSource)
-		{
-			if (isLightSource)
-				addLightSource(index);
-			else
-				removeLightSource(index);
-		}
-		if (added)
-		{
-			char* msg = new char[9];
-			msg[0] = 0; // set block
-			*(int*)(msg + 1) = index;
-            *(int*)(msg + 5)
-                = block ? block->zBlockType()->getId() : BlockTypeEnum::NO_BLOCK;
-			NetworkMessage* message = new NetworkMessage();
-			message->addressChunck(this);
-			message->setMessage(msg, 9);
-			notifyObservers(message);
-			for (int i = 0; i < 6; i++)
-			{
-				Direction d = getDirectionFromIndex(i);
-				Framework::Vec3<int> loc = location + getDirection(d);
-				if (loc.x >= 0 && loc.x < CHUNK_SIZE && loc.y >= 0 && loc.y < CHUNK_SIZE && loc.z >= 0 && loc.z < WORLD_HEIGHT)
-				{
-					NetworkMessage* msg = new NetworkMessage();
-					msg->addressChunck(this);
-					char* message = new char[11];
-					message[0] = 1;
-					int index = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z) * 6;
-					*(int*)(message + 1) = index / 6;
-					memcpy(message + 5, lightData + index, 6);
-					msg->setMessage(message, 11);
-					notifyObservers(msg);
-				}
-				else if (loc.z >= 0 && loc.z < WORLD_HEIGHT && i < 4 && zNeighbours[i])
-				{
-					NetworkMessage* msg = new NetworkMessage();
-					msg->addressChunck(zNeighbours[i]);
-					char* message = new char[11];
-					message[0] = 1;
-					loc -= getDirection(d) * CHUNK_SIZE;
-					int index = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z) * 6;
-					*(int*)(message + 1) = index / 6;
-					memcpy(message + 5, zNeighbours[i]->getLightData(loc), 6);
-					msg->setMessage(message, 11);
-					notifyObservers(msg);
-				}
-			}
-			Game::INSTANCE->updateLightningWithoutWait(getDimensionId(), Vec3<int>(location.x + this->location.x - CHUNK_SIZE / 2, location.y + this->location.y - CHUNK_SIZE / 2, location.z));
-		}
-	}
+    int index
+        = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
+    assert(index < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT && index >= 0);
+    Block* old = blocks[index];
+    bool change = 0;
+    bool wasLightSource
+        = old ? old->zBlockType()->isLightSource()
+              : StaticRegistry<BlockType>::INSTANCE.zElement(blockIds[index])
+                    ->isLightSource();
+    bool isLightSource = 0;
+    if (block)
+    {
+        change
+            = blockIds[index] != (unsigned short)block->zBlockType()->getId();
+        blockIds[index] = (unsigned short)block->zBlockType()->getId();
+        isLightSource = block->zBlockType()->isLightSource();
+    }
+    else
+    {
+        change = old != 0;
+    }
+    blocks[index] = block;
+    for (int i = 0; i < 6; i++)
+    {
+        Direction d = getDirectionFromIndex(i);
+        Either<Block*, int> neighbor
+            = zBlockNeighbor(location + getDirection(d));
+        if (neighbor.isA())
+            ((Block*)neighbor)->setNeighbour(getOppositeDirection(d), block);
+        if (block) block->setNeighbour(d, neighbor);
+    }
+    if (old) old->release();
+    if (change)
+    {
+        if (isLightSource != wasLightSource)
+        {
+            if (isLightSource)
+                addLightSource(index);
+            else
+                removeLightSource(index);
+        }
+        if (added)
+        {
+            char* msg = new char[9];
+            msg[0] = 0; // set block
+            *(int*)(msg + 1) = index;
+            *(int*)(msg + 5) = block ? block->zBlockType()->getId()
+                                     : BlockTypeEnum::NO_BLOCK;
+            NetworkMessage* message = new NetworkMessage();
+            message->addressChunck(this);
+            message->setMessage(msg, 9);
+            notifyObservers(message);
+            for (int i = 0; i < 6; i++)
+            {
+                Direction d = getDirectionFromIndex(i);
+                Framework::Vec3<int> loc = location + getDirection(d);
+                if (loc.x >= 0 && loc.x < CHUNK_SIZE && loc.y >= 0
+                    && loc.y < CHUNK_SIZE && loc.z >= 0 && loc.z < WORLD_HEIGHT)
+                {
+                    NetworkMessage* msg = new NetworkMessage();
+                    msg->addressChunck(this);
+                    char* message = new char[11];
+                    message[0] = 1;
+                    int index
+                        = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z)
+                        * 6;
+                    *(int*)(message + 1) = index / 6;
+                    memcpy(message + 5, lightData + index, 6);
+                    msg->setMessage(message, 11);
+                    notifyObservers(msg);
+                }
+                else if (loc.z >= 0 && loc.z < WORLD_HEIGHT && i < 4
+                         && zNeighbours[i])
+                {
+                    NetworkMessage* msg = new NetworkMessage();
+                    msg->addressChunck(zNeighbours[i]);
+                    char* message = new char[11];
+                    message[0] = 1;
+                    loc -= getDirection(d) * CHUNK_SIZE;
+                    int index
+                        = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z)
+                        * 6;
+                    *(int*)(message + 1) = index / 6;
+                    memcpy(message + 5, zNeighbours[i]->getLightData(loc), 6);
+                    msg->setMessage(message, 11);
+                    notifyObservers(msg);
+                }
+            }
+            Game::INSTANCE->updateLightningWithoutWait(getDimensionId(),
+                Vec3<int>(location.x + this->location.x - CHUNK_SIZE / 2,
+                    location.y + this->location.y - CHUNK_SIZE / 2,
+                    location.z));
+        }
+    }
 }
 
 void Chunk::putBlockTypeAt(Framework::Vec3<int> location, int type)
 {
-	int index = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
-	assert(index < CHUNK_SIZE* CHUNK_SIZE* WORLD_HEIGHT);
-	bool wasLightSource = StaticRegistry<BlockType>::INSTANCE.zElement(blockIds[index])->isLightSource();
-	bool isLightSource = StaticRegistry<BlockType>::INSTANCE.zElement(type)->isLightSource();
-	if (blockIds[index] != (unsigned short)type)
-	{
-		blockIds[index] = (unsigned short)type;
-		for (int i = 0; i < 6; i++)
-		{
-			Direction d = getDirectionFromIndex(i);
-			Either<Block*, int> neighbor = zBlockNeighbor(location + getDirection(d));
-			if (neighbor.isA())
-				((Block*)neighbor)->setNeighbourType(getOppositeDirection(d), type);
-		}
-		if (isLightSource != wasLightSource)
-		{
-			if (isLightSource)
-				addLightSource(index);
-			else
-				removeLightSource(index);
-		}
-		if (added)
-		{
-			char* msg = new char[9];
-			msg[0] = 0; // set block
-			*(int*)(msg + 1) = index;
-			*(int*)(msg + 5) = type;
-			NetworkMessage* message = new NetworkMessage();
-			message->addressChunck(this);
-			message->setMessage(msg, 9);
-			notifyObservers(message);
-			for (int i = 0; i < 6; i++)
-			{
-				Direction d = getDirectionFromIndex(i);
-				Framework::Vec3<int> loc = location + getDirection(d);
-				if (loc.x >= 0 && loc.x < CHUNK_SIZE && loc.y >= 0 && loc.y < CHUNK_SIZE && loc.z >= 0 && loc.z < WORLD_HEIGHT)
-				{
-					NetworkMessage* msg = new NetworkMessage();
-					msg->addressChunck(this);
-					char* message = new char[11];
-					message[0] = 1;
-					int index = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z) * 6;
-					*(int*)(message + 1) = index / 6;
-					memcpy(message + 5, lightData + index, 6);
-					msg->setMessage(message, 11);
-					notifyObservers(msg);
-				}
-				else if (loc.z >= 0 && loc.z < WORLD_HEIGHT && i < 4 && zNeighbours[i])
-				{
-					NetworkMessage* msg = new NetworkMessage();
-					msg->addressChunck(zNeighbours[i]);
-					char* message = new char[11];
-					message[0] = 1;
-					loc -= getDirection(d) * CHUNK_SIZE;
-					int index = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z) * 6;
-					*(int*)(message + 1) = index / 6;
-					memcpy(message + 5, zNeighbours[i]->getLightData(loc), 6);
-					msg->setMessage(message, 11);
-					notifyObservers(msg);
-				}
-			}
-			Game::INSTANCE->updateLightningWithoutWait(getDimensionId(), Vec3<int>(location.x + this->location.x - CHUNK_SIZE / 2, location.y + this->location.y - CHUNK_SIZE / 2, location.z));
-		}
-	}
+    int index
+        = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
+    assert(index < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT);
+    bool wasLightSource
+        = StaticRegistry<BlockType>::INSTANCE.zElement(blockIds[index])
+              ->isLightSource();
+    bool isLightSource
+        = StaticRegistry<BlockType>::INSTANCE.zElement(type)->isLightSource();
+    if (blockIds[index] != (unsigned short)type)
+    {
+        blockIds[index] = (unsigned short)type;
+        for (int i = 0; i < 6; i++)
+        {
+            Direction d = getDirectionFromIndex(i);
+            Either<Block*, int> neighbor
+                = zBlockNeighbor(location + getDirection(d));
+            if (neighbor.isA())
+                ((Block*)neighbor)
+                    ->setNeighbourType(getOppositeDirection(d), type);
+        }
+        if (isLightSource != wasLightSource)
+        {
+            if (isLightSource)
+                addLightSource(index);
+            else
+                removeLightSource(index);
+        }
+        if (added)
+        {
+            char* msg = new char[9];
+            msg[0] = 0; // set block
+            *(int*)(msg + 1) = index;
+            *(int*)(msg + 5) = type;
+            NetworkMessage* message = new NetworkMessage();
+            message->addressChunck(this);
+            message->setMessage(msg, 9);
+            notifyObservers(message);
+            for (int i = 0; i < 6; i++)
+            {
+                Direction d = getDirectionFromIndex(i);
+                Framework::Vec3<int> loc = location + getDirection(d);
+                if (loc.x >= 0 && loc.x < CHUNK_SIZE && loc.y >= 0
+                    && loc.y < CHUNK_SIZE && loc.z >= 0 && loc.z < WORLD_HEIGHT)
+                {
+                    NetworkMessage* msg = new NetworkMessage();
+                    msg->addressChunck(this);
+                    char* message = new char[11];
+                    message[0] = 1;
+                    int index
+                        = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z)
+                        * 6;
+                    *(int*)(message + 1) = index / 6;
+                    memcpy(message + 5, lightData + index, 6);
+                    msg->setMessage(message, 11);
+                    notifyObservers(msg);
+                }
+                else if (loc.z >= 0 && loc.z < WORLD_HEIGHT && i < 4
+                         && zNeighbours[i])
+                {
+                    NetworkMessage* msg = new NetworkMessage();
+                    msg->addressChunck(zNeighbours[i]);
+                    char* message = new char[11];
+                    message[0] = 1;
+                    loc -= getDirection(d) * CHUNK_SIZE;
+                    int index
+                        = ((loc.x * CHUNK_SIZE + loc.y) * WORLD_HEIGHT + loc.z)
+                        * 6;
+                    *(int*)(message + 1) = index / 6;
+                    memcpy(message + 5, zNeighbours[i]->getLightData(loc), 6);
+                    msg->setMessage(message, 11);
+                    notifyObservers(msg);
+                }
+            }
+            Game::INSTANCE->updateLightningWithoutWait(getDimensionId(),
+                Vec3<int>(location.x + this->location.x - CHUNK_SIZE / 2,
+                    location.y + this->location.y - CHUNK_SIZE / 2,
+                    location.z));
+        }
+    }
 }
 
 void Chunk::setNeighbor(Direction dir, Chunk* zChunk)
 {
-	zNeighbours[getDirectionIndex(dir)] = zChunk;
-	for (int i = 0; i < CHUNK_SIZE; i++)
-	{
-		for (int z = 0; z < WORLD_HEIGHT; z++)
-		{
-			if (dir == NORTH)
-			{
-				int index = i * CHUNK_SIZE * WORLD_HEIGHT + z;
-				if (blocks[index])
-				{
-					int j = (i * CHUNK_SIZE + CHUNK_SIZE - 1) * WORLD_HEIGHT + z;
-					if (zChunk && zChunk->blocks[j])
-						blocks[index]->setNeighbour(NORTH, zChunk->blocks[j]);
-					else
-					{
-						blocks[index]->setNeighbour(NORTH, 0);
-						blocks[index]->setNeighbourType(NORTH, zChunk ? zChunk->blockIds[j] : 0);
-					}
-				}
-			}
-			else if (dir == EAST)
-			{
-				int index = ((CHUNK_SIZE - 1) * CHUNK_SIZE + i) * WORLD_HEIGHT + z;
-				if (blocks[index])
-				{
-					int j = i * WORLD_HEIGHT + z;
-					if (zChunk && zChunk->blocks[j])
-						blocks[index]->setNeighbour(EAST, zChunk->blocks[j]);
-					else
-					{
-						blocks[index]->setNeighbour(EAST, 0);
-						blocks[index]->setNeighbourType(EAST, zChunk ? zChunk->blockIds[j] : 0);
-					}
-				}
-			}
-			else if (dir == SOUTH)
-			{
-				int index = (i * CHUNK_SIZE + CHUNK_SIZE - 1) * WORLD_HEIGHT + z;
-				if (blocks[index])
-				{
-					int j = i * CHUNK_SIZE * WORLD_HEIGHT + z;
-					if (zChunk && zChunk->blocks[j])
-						blocks[index]->setNeighbour(SOUTH, zChunk->blocks[j]);
-					else
-					{
-						blocks[index]->setNeighbour(SOUTH, 0);
-						blocks[index]->setNeighbourType(SOUTH, zChunk ? zChunk->blockIds[j] : 0);
-					}
-				}
-			}
-			else if (dir == WEST)
-			{
-				int index = i * WORLD_HEIGHT + z;
-				if (blocks[index])
-				{
-					int j = ((CHUNK_SIZE - 1) * CHUNK_SIZE + i) * WORLD_HEIGHT + z;
-					if (zChunk && zChunk->blocks[j])
-						blocks[index]->setNeighbour(WEST, zChunk->blocks[j]);
-					else
-					{
-						blocks[index]->setNeighbour(WEST, 0);
-						blocks[index]->setNeighbourType(WEST, zChunk ? zChunk->blockIds[j] : 0);
-					}
-				}
-			}
-		}
-	}
+    zNeighbours[getDirectionIndex(dir)] = zChunk;
+    for (int i = 0; i < CHUNK_SIZE; i++)
+    {
+        for (int z = 0; z < WORLD_HEIGHT; z++)
+        {
+            if (dir == NORTH)
+            {
+                int index = i * CHUNK_SIZE * WORLD_HEIGHT + z;
+                if (blocks[index])
+                {
+                    int j
+                        = (i * CHUNK_SIZE + CHUNK_SIZE - 1) * WORLD_HEIGHT + z;
+                    if (zChunk && zChunk->blocks[j])
+                        blocks[index]->setNeighbour(NORTH, zChunk->blocks[j]);
+                    else
+                    {
+                        blocks[index]->setNeighbour(NORTH, 0);
+                        blocks[index]->setNeighbourType(
+                            NORTH, zChunk ? zChunk->blockIds[j] : 0);
+                    }
+                }
+            }
+            else if (dir == EAST)
+            {
+                int index
+                    = ((CHUNK_SIZE - 1) * CHUNK_SIZE + i) * WORLD_HEIGHT + z;
+                if (blocks[index])
+                {
+                    int j = i * WORLD_HEIGHT + z;
+                    if (zChunk && zChunk->blocks[j])
+                        blocks[index]->setNeighbour(EAST, zChunk->blocks[j]);
+                    else
+                    {
+                        blocks[index]->setNeighbour(EAST, 0);
+                        blocks[index]->setNeighbourType(
+                            EAST, zChunk ? zChunk->blockIds[j] : 0);
+                    }
+                }
+            }
+            else if (dir == SOUTH)
+            {
+                int index
+                    = (i * CHUNK_SIZE + CHUNK_SIZE - 1) * WORLD_HEIGHT + z;
+                if (blocks[index])
+                {
+                    int j = i * CHUNK_SIZE * WORLD_HEIGHT + z;
+                    if (zChunk && zChunk->blocks[j])
+                        blocks[index]->setNeighbour(SOUTH, zChunk->blocks[j]);
+                    else
+                    {
+                        blocks[index]->setNeighbour(SOUTH, 0);
+                        blocks[index]->setNeighbourType(
+                            SOUTH, zChunk ? zChunk->blockIds[j] : 0);
+                    }
+                }
+            }
+            else if (dir == WEST)
+            {
+                int index = i * WORLD_HEIGHT + z;
+                if (blocks[index])
+                {
+                    int j = ((CHUNK_SIZE - 1) * CHUNK_SIZE + i) * WORLD_HEIGHT
+                          + z;
+                    if (zChunk && zChunk->blocks[j])
+                        blocks[index]->setNeighbour(WEST, zChunk->blocks[j]);
+                    else
+                    {
+                        blocks[index]->setNeighbour(WEST, 0);
+                        blocks[index]->setNeighbourType(
+                            WEST, zChunk ? zChunk->blockIds[j] : 0);
+                    }
+                }
+            }
+        }
+    }
 }
 
 void Chunk::load(Framework::StreamReader* zReader)
 {
-	for (int index = 0; index < WORLD_HEIGHT * CHUNK_SIZE * CHUNK_SIZE; index++)
-	{
-		unsigned short blockType;
-		zReader->lese((char*)&blockType, 2);
-		if (blockType)
-		{
-			Framework::Vec3<int> pos = Framework::Vec3<int>((index / WORLD_HEIGHT) / CHUNK_SIZE, (index / WORLD_HEIGHT) % CHUNK_SIZE, index % WORLD_HEIGHT);
-			bool d;
-			zReader->lese((char*)&d, 1);
-			if (d)
-			{
-				putBlockAt(pos, StaticRegistry<BlockType>::INSTANCE.zElement(blockType)->loadBlock(Framework::Vec3<int>(pos.x + location.x - CHUNK_SIZE / 2, pos.y + location.y - CHUNK_SIZE / 2, pos.z), zReader, dimensionId));
-			}
-			else
-			{
-				putBlockTypeAt(pos, blockType);
-			}
-		}
-	}
-	initializeLightning();
+    for (int index = 0; index < WORLD_HEIGHT * CHUNK_SIZE * CHUNK_SIZE; index++)
+    {
+        unsigned short blockType;
+        zReader->lese((char*)&blockType, 2);
+        if (blockType)
+        {
+            Framework::Vec3<int> pos
+                = Framework::Vec3<int>((index / WORLD_HEIGHT) / CHUNK_SIZE,
+                    (index / WORLD_HEIGHT) % CHUNK_SIZE,
+                    index % WORLD_HEIGHT);
+            bool d;
+            zReader->lese((char*)&d, 1);
+            if (d)
+            {
+                putBlockAt(pos,
+                    StaticRegistry<BlockType>::INSTANCE.zElement(blockType)
+                        ->loadBlock(Framework::Vec3<int>(
+                                        pos.x + location.x - CHUNK_SIZE / 2,
+                                        pos.y + location.y - CHUNK_SIZE / 2,
+                                        pos.z),
+                            zReader,
+                            dimensionId));
+            }
+            else
+            {
+                putBlockTypeAt(pos, blockType);
+            }
+        }
+    }
+    initializeLightning();
 }
 
 void Chunk::save(Framework::StreamWriter* zWriter)
 {
-	for (int index = 0; index < WORLD_HEIGHT * CHUNK_SIZE * CHUNK_SIZE; index++)
-	{
-		unsigned short blockType = blocks[index] ? (unsigned short)blocks[index]->zBlockType()->getId() : blockIds[index];
-		zWriter->schreibe((char*)&blockType, 2);
-		if (blockType)
-		{
-			if (blocks[index])
-			{
-				bool d = 1;
-				zWriter->schreibe((char*)&d, 1);
-				StaticRegistry<BlockType>::INSTANCE.zElement(blockType)->saveBlock(blocks[index], zWriter);
-			}
-			else
-			{
-				bool d = 0;
-				zWriter->schreibe((char*)&d, 1);
-			}
-		}
-	}
+    for (int index = 0; index < WORLD_HEIGHT * CHUNK_SIZE * CHUNK_SIZE; index++)
+    {
+        unsigned short blockType
+            = blocks[index]
+                ? (unsigned short)blocks[index]->zBlockType()->getId()
+                : blockIds[index];
+        zWriter->schreibe((char*)&blockType, 2);
+        if (blockType)
+        {
+            if (blocks[index])
+            {
+                bool d = 1;
+                zWriter->schreibe((char*)&d, 1);
+                StaticRegistry<BlockType>::INSTANCE.zElement(blockType)
+                    ->saveBlock(blocks[index], zWriter);
+            }
+            else
+            {
+                bool d = 0;
+                zWriter->schreibe((char*)&d, 1);
+            }
+        }
+    }
 }
 
 void Chunk::sendToClient(Framework::StreamWriter* zWriter)
 {
-	for (int x = 0; x < CHUNK_SIZE; x++)
-	{
-		for (int y = 0; y < CHUNK_SIZE; y++)
-		{
-			for (int z = 0; z < WORLD_HEIGHT; z++)
-			{
-				int index = (x * CHUNK_SIZE + y) * WORLD_HEIGHT + z;
-				unsigned short blockType = blocks[index] ? (unsigned short)blocks[index]->zBlockType()->getId() : blockIds[index];
-				if (blockType)
-				{
-					bool visible = 0;
-					if (!visible)
-					{
-						if (!blocks[index])
-						{
-							if (CONST_BLOCK(0, blockIds[index])->isTransparent() || CONST_BLOCK(0, blockIds[index])->isPassable())
-								visible = 1;
-							else
-							{
-								for (int d = 0; d < 6 && !visible; d++)
-								{
-									auto n = zBlockNeighbor(getDirection((Directions)getDirectionFromIndex(d)) + Framework::Vec3<int>(x, y, z));
-									if (n.isA() && (((Block*)n)->isPassable() || ((Block*)n)->isTransparent()))
-										visible = 1;
-									if (n.isB() && (CONST_BLOCK(0, n)->isTransparent() || CONST_BLOCK(0, n)->isPassable()))
-										visible = 1;
-								}
-							}
-						}
-						else
-							visible = blocks[index]->isVisible();
-					}
-					if (visible && (blocks[index] || blockType != BlockTypeEnum::AIR))
-					{
-						zWriter->schreibe((char*)&blockType, 2);
-						zWriter->schreibe((char*)&index, 4);
-					}
-				}
-			}
-		}
-	}
-	unsigned short end = 0;
-	zWriter->schreibe((char*)&end, 2);
+    for (int x = 0; x < CHUNK_SIZE; x++)
+    {
+        for (int y = 0; y < CHUNK_SIZE; y++)
+        {
+            for (int z = 0; z < WORLD_HEIGHT; z++)
+            {
+                int index = (x * CHUNK_SIZE + y) * WORLD_HEIGHT + z;
+                unsigned short blockType
+                    = blocks[index]
+                        ? (unsigned short)blocks[index]->zBlockType()->getId()
+                        : blockIds[index];
+                if (blockType)
+                {
+                    bool visible = 0;
+                    if (!visible)
+                    {
+                        if (!blocks[index])
+                        {
+                            if (CONST_BLOCK(0, blockIds[index])->isTransparent()
+                                || CONST_BLOCK(0, blockIds[index])
+                                       ->isPassable())
+                                visible = 1;
+                            else
+                            {
+                                for (int d = 0; d < 6 && !visible; d++)
+                                {
+                                    auto n = zBlockNeighbor(
+                                        getDirection((
+                                            Directions)getDirectionFromIndex(d))
+                                        + Framework::Vec3<int>(x, y, z));
+                                    if (n.isA()
+                                        && (((Block*)n)->isPassable()
+                                            || ((Block*)n)->isTransparent()))
+                                        visible = 1;
+                                    if (n.isB()
+                                        && (CONST_BLOCK(0, n)->isTransparent()
+                                            || CONST_BLOCK(0, n)->isPassable()))
+                                        visible = 1;
+                                }
+                            }
+                        }
+                        else
+                            visible = blocks[index]->isVisible();
+                    }
+                    if (visible
+                        && (blocks[index] || blockType != BlockTypeEnum::AIR))
+                    {
+                        zWriter->schreibe((char*)&blockType, 2);
+                        zWriter->schreibe((char*)&index, 4);
+                    }
+                }
+            }
+        }
+    }
+    unsigned short end = 0;
+    zWriter->schreibe((char*)&end, 2);
 }
 
 void Chunk::removeUnusedBlocks()
 {
-	for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
-	{
-		if (!blocks[i] && blockIds[i])
-		{
-			int x = (i / WORLD_HEIGHT) / CHUNK_SIZE;
-			int y = (i / WORLD_HEIGHT) % CHUNK_SIZE;
-			int z = i % WORLD_HEIGHT;
-			bool visible = 0;
-			if (CONST_BLOCK(0, blockIds[i])->isTransparent() || CONST_BLOCK(0, blockIds[i])->isPassable())
-				visible = 1;
-			else
-			{
-				for (int d = 0; d < 6 && !visible; d++)
-				{
-					auto n = zBlockNeighbor(getDirection((Directions)getDirectionFromIndex(d)) + Framework::Vec3<int>(x, y, z));
-					if (n.isA() && (((Block*)n)->isPassable() || ((Block*)n)->isTransparent()))
-						visible = 1;
-					if (n.isB() && (CONST_BLOCK(0, n)->isTransparent() || CONST_BLOCK(0, n)->isPassable()))
-						visible = 1;
-				}
-			}
-			if (!visible)
-			{
-				putBlockAt({ x,y,z }, 0);
-				putBlockTypeAt({ x, y, z }, BlockTypeEnum::NO_BLOCK);
-			}
-		}
-	}
-	int count = 0;
-	for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
-	{
-		if (blockIds[i] && blockIds[i] != BlockTypeEnum::AIR)
-			count++;
-	}
-	std::cout << "chunk " << location.x << ", " << location.y << " was generated with " << count << " blocks.\n";
+    for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
+    {
+        if (!blocks[i] && blockIds[i])
+        {
+            int x = (i / WORLD_HEIGHT) / CHUNK_SIZE;
+            int y = (i / WORLD_HEIGHT) % CHUNK_SIZE;
+            int z = i % WORLD_HEIGHT;
+            bool visible = 0;
+            if (CONST_BLOCK(0, blockIds[i])->isTransparent()
+                || CONST_BLOCK(0, blockIds[i])->isPassable())
+                visible = 1;
+            else
+            {
+                for (int d = 0; d < 6 && !visible; d++)
+                {
+                    auto n = zBlockNeighbor(
+                        getDirection((Directions)getDirectionFromIndex(d))
+                        + Framework::Vec3<int>(x, y, z));
+                    if (n.isA()
+                        && (((Block*)n)->isPassable()
+                            || ((Block*)n)->isTransparent()))
+                        visible = 1;
+                    if (n.isB()
+                        && (CONST_BLOCK(0, n)->isTransparent()
+                            || CONST_BLOCK(0, n)->isPassable()))
+                        visible = 1;
+                }
+            }
+            if (!visible)
+            {
+                putBlockAt({x, y, z}, 0);
+                putBlockTypeAt({x, y, z}, BlockTypeEnum::NO_BLOCK);
+            }
+        }
+    }
+    int count = 0;
+    for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
+    {
+        if (blockIds[i] && blockIds[i] != BlockTypeEnum::AIR) count++;
+    }
+    std::cout << "chunk " << location.x << ", " << location.y
+              << " was generated with " << count << " blocks.\n";
 }
 
 int Chunk::getDimensionId() const
 {
-	return dimensionId;
+    return dimensionId;
 }
 
 void Chunk::onLoaded()
 {
-	for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
-	{
-		if (blocks[i])
-			blocks[i]->onLoaded();
-	}
-	currentlyLoading = 0;
+    for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
+    {
+        if (blocks[i]) blocks[i]->onLoaded();
+    }
+    currentlyLoading = 0;
 }
 
 void Chunk::onUnloaded()
 {
-	for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
-	{
-		if (blocks[i])
-			blocks[i]->onUnloaded();
-	}
+    for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
+    {
+        if (blocks[i]) blocks[i]->onUnloaded();
+    }
 }
 
 Framework::Punkt Chunk::getCenter() const
 {
-	return location;
+    return location;
 }
 
 Framework::Vec3<int> Chunk::getMin() const
 {
-	return { location.x - CHUNK_SIZE / 2, location.y - CHUNK_SIZE / 2, 0 };
+    return {location.x - CHUNK_SIZE / 2, location.y - CHUNK_SIZE / 2, 0};
 }
 
 Framework::Vec3<int> Chunk::getMax() const
 {
-	return { location.x + CHUNK_SIZE / 2, location.y + CHUNK_SIZE / 2, WORLD_HEIGHT };
+    return {
+        location.x + CHUNK_SIZE / 2, location.y + CHUNK_SIZE / 2, WORLD_HEIGHT};
 }
 
 void Chunk::prepareRemove()
 {
-	added = 0;
-	for (int i = 0; i < 4; i++)
-	{
-		if (zNeighbours[i])
-		{
-			zNeighbours[i]->setNeighbor(getOppositeDirection(getDirectionFromIndex(i)), 0);
-			zNeighbours[i] = 0;
-		}
-	}
+    added = 0;
+    for (int i = 0; i < 4; i++)
+    {
+        if (zNeighbours[i])
+        {
+            zNeighbours[i]->setNeighbor(
+                getOppositeDirection(getDirectionFromIndex(i)), 0);
+            zNeighbours[i] = 0;
+        }
+    }
 }
 
 void Chunk::setAdded()
 {
-	added = 1;
+    added = 1;
 }
 
 bool Chunk::hasObservers() const
 {
-	return observers.getEintragAnzahl() > 0 || currentlyLoading;
+    return observers.getEintragAnzahl() > 0 || currentlyLoading;
 }
 
 unsigned char* Chunk::getLightData(Framework::Vec3<int> location) const
 {
-	int index = ((location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z) * 6;
-	assert(index < CHUNK_SIZE* CHUNK_SIZE* WORLD_HEIGHT);
-	return lightData + index;
-}
-
-void Chunk::setLightData(Framework::Vec3<int> location, unsigned char* data, bool foreground)
-{
-	int index = ((location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z) * 6;
-	memcpy(lightData + index, data, 6);
-	// check if neighbor is a visible block and send update to clients
-	bool needSend = 0;
-	for (int i = 0; i < 6; i++)
-	{
-		Vec3<int> pos = location + getDirection(getDirectionFromIndex(i));
-		if (pos.z >= 0 && pos.z < WORLD_HEIGHT)
-		{
-			if (pos.x >= 0 && pos.x < CHUNK_SIZE && pos.y >= 0 && pos.y < CHUNK_SIZE)
-			{
-				int bi = (pos.x * CHUNK_SIZE + pos.y) * WORLD_HEIGHT + pos.z;
-				int type = blockIds[bi];
-				needSend |= type != BlockTypeEnum::NO_BLOCK && type != BlockTypeEnum::AIR;
-				if (needSend)
-					break;
-			}
-			else
-			{
-				needSend = 1; // TODO: check if the block is visible
-			}
-		}
-	}
-	if (needSend)
-	{
-		NetworkMessage* msg = new NetworkMessage();
-		msg->addressChunck(this);
-		char* message = new char[11];
-		message[0] = 1;
-		*(int*)(message + 1) = index / 6;
-		memcpy(message + 5, data, 6);
-		msg->setMessage(message, 11);
-		if (!foreground)
-			msg->setUseBackground();
-		notifyObservers(msg);
-	}
+    int index
+        = ((location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z)
+        * 6;
+    assert(index < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT);
+    return lightData + index;
+}
+
+void Chunk::setLightData(
+    Framework::Vec3<int> location, unsigned char* data, bool foreground)
+{
+    int index
+        = ((location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z)
+        * 6;
+    memcpy(lightData + index, data, 6);
+    // check if neighbor is a visible block and send update to clients
+    bool needSend = 0;
+    for (int i = 0; i < 6; i++)
+    {
+        Vec3<int> pos = location + getDirection(getDirectionFromIndex(i));
+        if (pos.z >= 0 && pos.z < WORLD_HEIGHT)
+        {
+            if (pos.x >= 0 && pos.x < CHUNK_SIZE && pos.y >= 0
+                && pos.y < CHUNK_SIZE)
+            {
+                int bi = (pos.x * CHUNK_SIZE + pos.y) * WORLD_HEIGHT + pos.z;
+                int type = blockIds[bi];
+                needSend |= type != BlockTypeEnum::NO_BLOCK
+                         && type != BlockTypeEnum::AIR;
+                if (needSend) break;
+            }
+            else
+            {
+                needSend = 1; // TODO: check if the block is visible
+            }
+        }
+    }
+    if (needSend)
+    {
+        NetworkMessage* msg = new NetworkMessage();
+        msg->addressChunck(this);
+        char* message = new char[11];
+        message[0] = 1;
+        *(int*)(message + 1) = index / 6;
+        memcpy(message + 5, data, 6);
+        msg->setMessage(message, 11);
+        if (!foreground) msg->setUseBackground();
+        notifyObservers(msg);
+    }
 }

+ 56 - 50
FactoryCraft/Chunk.h

@@ -1,66 +1,72 @@
 #pragma once
 
-#include "Block.h"
-#include "DoLaterHandler.h"
-
-#include <Vec3.h>
 #include <Array.h>
 #include <Datei.h>
-#include <Punkt.h>
 #include <Either.h>
+#include <Punkt.h>
+#include <Vec3.h>
 
+#include "Block.h"
+#include "DoLaterHandler.h"
 
 class Chunk : public virtual Framework::ReferenceCounter
 {
 private:
-	int dimensionId;
-	Framework::Punkt location;
-	Block** blocks;
-	Chunk* zNeighbours[4];
-	unsigned short* blockIds;
-	Framework::Either<Block*, int> zBlockNeighbor(Framework::Vec3<int> location);
-	bool added;
-	Framework::Critical cs;
-	Framework::Array<int> observers;
-	Framework::Array<int> lightSources;
-	unsigned char* lightData;
-	bool currentlyLoading;
+    int dimensionId;
+    Framework::Punkt location;
+    Block** blocks;
+    Chunk* zNeighbours[4];
+    unsigned short* blockIds;
+    Framework::Either<Block*, int> zBlockNeighbor(
+        Framework::Vec3<int> location);
+    bool added;
+    Framework::Critical cs;
+    Framework::Array<int> observers;
+    Framework::Array<int> lightSources;
+    unsigned char* lightData;
+    bool currentlyLoading;
 
-	void addLightSource(int index);
-	void removeLightSource(int index);
-	void sendLightToClient(Framework::StreamWriter* zWriter);
+    void addLightSource(int index);
+    void removeLightSource(int index);
+    void sendLightToClient(Framework::StreamWriter* zWriter);
 
 public:
-	Chunk(Framework::Punkt location, int dimensionId);
-	Chunk(Framework::Punkt location, int dimensionId, Framework::StreamReader* zReader);
-	~Chunk();
+    Chunk(Framework::Punkt location, int dimensionId);
+    Chunk(Framework::Punkt location,
+        int dimensionId,
+        Framework::StreamReader* zReader);
+    ~Chunk();
 
-	void notifyObservers(NetworkMessage* msg);
-	void addObserver(Entity* zEntity, DoLaterHandler& laterHandler);
-	void removeObserver(Entity* zEntity);
-	void api(Framework::StreamReader* zRequest, Entity* zSource, DoLaterHandler& laterHandler);
-	void initializeLightning();
+    void notifyObservers(NetworkMessage* msg);
+    void addObserver(Entity* zEntity, DoLaterHandler& laterHandler);
+    void removeObserver(Entity* zEntity);
+    void api(Framework::StreamReader* zRequest,
+        Entity* zSource,
+        DoLaterHandler& laterHandler);
+    void initializeLightning();
 
-	Framework::Either<Block*, int> zBlockAt(Framework::Vec3<int> cLocation) const;
-	const Block* zBlockConst(Framework::Vec3<int> location) const;
-	void instantiateBlock(Framework::Vec3<int> location);
-	void generateBlock(Framework::Vec3<int> location);
-	void putBlockAt(Framework::Vec3<int> location, Block* block);
-	void putBlockTypeAt(Framework::Vec3<int> location, int type);
-	void setNeighbor(Direction dir, Chunk* zChunk);
-	void load(Framework::StreamReader* zReader);
-	void save(Framework::StreamWriter* zWriter);
-	void sendToClient(Framework::StreamWriter* zWriter);
-	void removeUnusedBlocks();
-	int getDimensionId() const;
-	void onLoaded();
-	void onUnloaded();
-	Framework::Punkt getCenter() const;
-	Framework::Vec3<int> getMin() const;
-	Framework::Vec3<int> getMax() const;
-	void prepareRemove();
-	void setAdded();
-	bool hasObservers() const;
-	unsigned char* getLightData(Framework::Vec3<int> location) const;
-	void setLightData(Framework::Vec3<int> location, unsigned char* data, bool foreground);
+    Framework::Either<Block*, int> zBlockAt(
+        Framework::Vec3<int> cLocation) const;
+    const Block* zBlockConst(Framework::Vec3<int> location) const;
+    void instantiateBlock(Framework::Vec3<int> location);
+    void generateBlock(Framework::Vec3<int> location);
+    void putBlockAt(Framework::Vec3<int> location, Block* block);
+    void putBlockTypeAt(Framework::Vec3<int> location, int type);
+    void setNeighbor(Direction dir, Chunk* zChunk);
+    void load(Framework::StreamReader* zReader);
+    void save(Framework::StreamWriter* zWriter);
+    void sendToClient(Framework::StreamWriter* zWriter);
+    void removeUnusedBlocks();
+    int getDimensionId() const;
+    void onLoaded();
+    void onUnloaded();
+    Framework::Punkt getCenter() const;
+    Framework::Vec3<int> getMin() const;
+    Framework::Vec3<int> getMax() const;
+    void prepareRemove();
+    void setAdded();
+    bool hasObservers() const;
+    unsigned char* getLightData(Framework::Vec3<int> location) const;
+    void setLightData(
+        Framework::Vec3<int> location, unsigned char* data, bool foreground);
 };

+ 10 - 10
FactoryCraft/Constants.h

@@ -1,14 +1,14 @@
 #pragma once
 
 // needs to be an even number
-#define CHUNK_SIZE 16
-#define WORLD_HEIGHT 500
+#define CHUNK_SIZE               16
+#define WORLD_HEIGHT             500
 #define BIOM_GENERATION_Z_OFFSET 100
-#define AIR_LEVEL_Z_OFFSET 99
-#define MIN_AIR_LEVEL 100
-#define MAX_AIR_LEVEL 400
-#define NUM_TICK_WORKERS 4
-#define ITEM_CACHE_SIZE 256
-#define DEFAULT_VIEW_DISTANCE 5
-#define MAX_SURFACE_HEIGHT 50
-#define VARIABLE_SURFACE_PART 0.5f 
+#define AIR_LEVEL_Z_OFFSET       99
+#define MIN_AIR_LEVEL            100
+#define MAX_AIR_LEVEL            400
+#define NUM_TICK_WORKERS         4
+#define ITEM_CACHE_SIZE          256
+#define DEFAULT_VIEW_DISTANCE    5
+#define MAX_SURFACE_HEIGHT       50
+#define VARIABLE_SURFACE_PART    0.5f

+ 214 - 196
FactoryCraft/CraftingStorage.cpp

@@ -1,230 +1,248 @@
+#include "CraftingStorage.h"
+
 #include <InMemoryBuffer.h>
 
-#include "CraftingStorage.h"
 #include "Game.h"
 #include "Inventory.h"
 #include "Item.h"
 
-
-BasicShapedCrafter::BasicShapedCrafter(int width, int height, Inventory* zInventory, Framework::Text recipieList)
-	: zInventory(zInventory),
-	currentRecipie(0),
-	recipieList(recipieList),
-	width(width),
-	height(height)
+BasicShapedCrafter::BasicShapedCrafter(
+    int width, int height, Inventory* zInventory, Framework::Text recipieList)
+    : zInventory(zInventory),
+      currentRecipie(0),
+      recipieList(recipieList),
+      width(width),
+      height(height)
 {
-	for (int i = 0; i < width * height; i++)
-	{
-		ItemSlot* slot = new ItemSlot("CraftingGrid", 1, std::numeric_limits<int>::max(), std::numeric_limits<int>::max(), INSIDE, INSIDE, 0);
-		zInventory->addSlot(slot);
-		craftingInput.add(slot);
-	}
-	std::function<void(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)> onChange = [this, recipieList](ItemSlot* zSlot, Direction dir, const Item* zItem, int count)
-	{
-		if (!zSlot->getName().istGleich("CraftingGrid"))
-			return;
-		calculateOutputPreview();
-	};
-	zInventory->registerAfterPullStackCall(onChange);
-	zInventory->registerAfterPushStackCall(onChange);
-	zInventory->registerObserverAddedCall([this](Entity* zSource, Framework::Text id)
-		{
-			ShapedRecipie* old = currentRecipie;
-			calculateOutputPreview();
-			if (old == currentRecipie)
-			{
-				NetworkMessage* message = new NetworkMessage();
-				getOutputPreview(message);
-				message->addressGui(id);
-				Game::INSTANCE->sendMessage(message, zSource);
-			}
-		});
+    for (int i = 0; i < width * height; i++)
+    {
+        ItemSlot* slot = new ItemSlot("CraftingGrid",
+            1,
+            std::numeric_limits<int>::max(),
+            std::numeric_limits<int>::max(),
+            INSIDE,
+            INSIDE,
+            0);
+        zInventory->addSlot(slot);
+        craftingInput.add(slot);
+    }
+    std::function<void(
+        ItemSlot * zSlot, Direction dir, const Item* zItem, int count)>
+        onChange
+        = [this, recipieList](
+              ItemSlot* zSlot, Direction dir, const Item* zItem, int count) {
+              if (!zSlot->getName().istGleich("CraftingGrid")) return;
+              calculateOutputPreview();
+          };
+    zInventory->registerAfterPullStackCall(onChange);
+    zInventory->registerAfterPushStackCall(onChange);
+    zInventory->registerObserverAddedCall(
+        [this](Entity* zSource, Framework::Text id) {
+            ShapedRecipie* old = currentRecipie;
+            calculateOutputPreview();
+            if (old == currentRecipie)
+            {
+                NetworkMessage* message = new NetworkMessage();
+                getOutputPreview(message);
+                message->addressGui(id);
+                Game::INSTANCE->sendMessage(message, zSource);
+            }
+        });
 }
 
 void BasicShapedCrafter::getOutputPreview(NetworkMessage* zMessage)
 {
-	if (currentRecipie)
-	{
-		Framework::Array<ItemInfo> output = currentRecipie->getOutput(this);
-		Framework::InMemoryBuffer buffer;
-		int count = 0;
-		for (ItemInfo slot : output)
-		{
-			count++;
-			int itemCount = slot.count;
-			buffer.schreibe((char*)&itemCount, 4);
-			if (itemCount > 0)
-			{
-				float f = slot.hp;
-				buffer.schreibe((char*)&f, 4);
-				f = slot.maxHp;
-				buffer.schreibe((char*)&f, 4);
-				f = slot.durability;
-				buffer.schreibe((char*)&f, 4);
-				f = slot.maxDurability;
-				buffer.schreibe((char*)&f, 4);
-				int id = slot.type;
-				buffer.schreibe((char*)&id, 4);
-			}
-		}
-		char* msg = new char[5 + buffer.getSize()];
-		msg[0] = 100; // set crafting result
-		*(int*)(msg + 1) = count;
-		buffer.lese(msg + 5, (int)buffer.getSize());
-		zMessage->setMessage(msg, 5 + (int)buffer.getSize());
-	}
-	else
-	{
-		char* msg = new char[5];
-		msg[0] = 100; // set crafting result
-		*(int*)(msg + 1) = 0;
-		zMessage->setMessage(msg, 5);
-	}
+    if (currentRecipie)
+    {
+        Framework::Array<ItemInfo> output = currentRecipie->getOutput(this);
+        Framework::InMemoryBuffer buffer;
+        int count = 0;
+        for (ItemInfo slot : output)
+        {
+            count++;
+            int itemCount = slot.count;
+            buffer.schreibe((char*)&itemCount, 4);
+            if (itemCount > 0)
+            {
+                float f = slot.hp;
+                buffer.schreibe((char*)&f, 4);
+                f = slot.maxHp;
+                buffer.schreibe((char*)&f, 4);
+                f = slot.durability;
+                buffer.schreibe((char*)&f, 4);
+                f = slot.maxDurability;
+                buffer.schreibe((char*)&f, 4);
+                int id = slot.type;
+                buffer.schreibe((char*)&id, 4);
+            }
+        }
+        char* msg = new char[5 + buffer.getSize()];
+        msg[0] = 100; // set crafting result
+        *(int*)(msg + 1) = count;
+        buffer.lese(msg + 5, (int)buffer.getSize());
+        zMessage->setMessage(msg, 5 + (int)buffer.getSize());
+    }
+    else
+    {
+        char* msg = new char[5];
+        msg[0] = 100; // set crafting result
+        *(int*)(msg + 1) = 0;
+        zMessage->setMessage(msg, 5);
+    }
 }
 
-bool BasicShapedCrafter::isAllAvailable(Framework::RCArray<ItemFilter>& filters, int width, int height)
+bool BasicShapedCrafter::isAllAvailable(
+    Framework::RCArray<ItemFilter>& filters, int width, int height)
 {
-	for (int x = 0; x <= this->width - width; x++)
-	{
-		for (int y = 0; y <= this->height - height; y++)
-		{
-			bool wrong = 0;
-			for (int w = 0; w < width; w++)
-			{
-				for (int h = 0; h < height; h++)
-				{
-					ItemFilter* f = filters.z(h * width + w);
-					ItemSlot* s = craftingInput.get((h + y) * this->width + (x + w));
-					const Item* item = 0;
-					if (s && s->zStack())
-						item = s->zStack()->zItem();
-					wrong |= (item && !f) || (!item && f);
-					wrong |= item && f && !f->matchItem(item);
-					if (wrong)
-						break;
-				}
-				if (wrong)
-					break;
-			}
-			if (!wrong)
-			{
-				int i = 0;
-				for (ItemSlot* slot : craftingInput)
-				{
-					int w = i % this->width;
-					int h = i / this->width;
-					if ((w < x || w >= x + width || h < y || h >= y + height) && slot->zStack())
-						return 0; // more items then needed are in crafting grid
-					i++;
-				}
-				return 1;
-			}
-		}
-	}
-	return 0;
+    for (int x = 0; x <= this->width - width; x++)
+    {
+        for (int y = 0; y <= this->height - height; y++)
+        {
+            bool wrong = 0;
+            for (int w = 0; w < width; w++)
+            {
+                for (int h = 0; h < height; h++)
+                {
+                    ItemFilter* f = filters.z(h * width + w);
+                    ItemSlot* s
+                        = craftingInput.get((h + y) * this->width + (x + w));
+                    const Item* item = 0;
+                    if (s && s->zStack()) item = s->zStack()->zItem();
+                    wrong |= (item && !f) || (!item && f);
+                    wrong |= item && f && !f->matchItem(item);
+                    if (wrong) break;
+                }
+                if (wrong) break;
+            }
+            if (!wrong)
+            {
+                int i = 0;
+                for (ItemSlot* slot : craftingInput)
+                {
+                    int w = i % this->width;
+                    int h = i / this->width;
+                    if ((w < x || w >= x + width || h < y || h >= y + height)
+                        && slot->zStack())
+                        return 0; // more items then needed are in crafting grid
+                    i++;
+                }
+                return 1;
+            }
+        }
+    }
+    return 0;
 }
 
 bool BasicShapedCrafter::hasFreeSpace(const Item* zItem, int amount)
 {
-	ItemStack* stack = new ItemStack(zItem->zItemType()->cloneItem(zItem), amount);
-	int addable = zInventory->numberOfAddableItems(stack, NO_DIRECTION);
-	stack->release();
-	return addable >= amount;
+    ItemStack* stack
+        = new ItemStack(zItem->zItemType()->cloneItem(zItem), amount);
+    int addable = zInventory->numberOfAddableItems(stack, NO_DIRECTION);
+    stack->release();
+    return addable >= amount;
 }
 
-bool BasicShapedCrafter::consume(Framework::RCArray<ItemFilter>& filters, Framework::RCArray<ItemModifier>& modfiers, int width, int height)
+bool BasicShapedCrafter::consume(Framework::RCArray<ItemFilter>& filters,
+    Framework::RCArray<ItemModifier>& modfiers,
+    int width,
+    int height)
 {
-	int beginX = this->width;
-	int beginY = this->height;
-	SourceSlotBlacklistFilter otherSlots;
-	for (int i = 0; i < craftingInput.getEintragAnzahl(); i++)
-	{
-		if (!craftingInput.get(i)->isEmpty())
-		{
-			int x = i % this->width;
-			int y = i / this->width;
-			beginX = MIN(beginX, x);
-			beginY = MIN(beginY, y);
-		}
-		otherSlots.addBlackListSlotId(craftingInput.get(i)->getId());
-	}
-	for (int x = 0; x < width; x++)
-	{
-		for (int y = 0; y < height; y++)
-		{
-			ItemSlot* target = craftingInput.get((y + beginY) * this->width + x + beginX);
-			ItemStack* stack = zInventory->takeItemsOut(target, 1, INSIDE);
-			if (stack)
-			{
-				if (stack->getSize() > 0 && stack->zItem())
-				{
-					ItemModifier* m = modfiers.z(y * width + x);
-					if (m)
-						m->applyOn((Item*)stack->zItem());
-				}
-				if (stack->zItem()->getHp() == 0)
-					stack->release();
-				else if (stack->zItem()->getDurability() == 0)
-				{
-					Item* broken = stack->zItem()->zItemType()->breakItem(stack->zItem());
-					stack->release();
-					if (broken)
-					{
-						ItemStack* brokenStack = new ItemStack(broken, 1);
-						zInventory->unsaveAddItem(brokenStack, INSIDE);
-						// TODO: if brokenStack is not empty spawn an item entity
-						brokenStack->release();
-					}
-				}
-				else
-				{
-					// TODO: transfer all items from target to other slots or drop them
-					zInventory->addItems(target, stack, INSIDE);
-					// TODO: if stack is not empty spawn an item entity
-				}
-			}
-			ItemFilter* f = filters.z(y * width + x);
-			if (f)
-			{
-				if (target->isEmpty())
-				{
-					Framework::Array< ItemSlot*> tmp;
-					tmp.add(target);
-					CombinedItemFilter combinedFilter(dynamic_cast<ItemFilter*>(f->getThis()), dynamic_cast<ItemFilter*>(otherSlots.getThis()), [](bool a, bool b)
-						{
-							return a && b;
-						});
-					zInventory->localTransaction(0, &tmp, &combinedFilter, 1, NO_DIRECTION, INSIDE);
-				}
-			}
-		}
-	}
-	return 1;
+    int beginX = this->width;
+    int beginY = this->height;
+    SourceSlotBlacklistFilter otherSlots;
+    for (int i = 0; i < craftingInput.getEintragAnzahl(); i++)
+    {
+        if (!craftingInput.get(i)->isEmpty())
+        {
+            int x = i % this->width;
+            int y = i / this->width;
+            beginX = MIN(beginX, x);
+            beginY = MIN(beginY, y);
+        }
+        otherSlots.addBlackListSlotId(craftingInput.get(i)->getId());
+    }
+    for (int x = 0; x < width; x++)
+    {
+        for (int y = 0; y < height; y++)
+        {
+            ItemSlot* target
+                = craftingInput.get((y + beginY) * this->width + x + beginX);
+            ItemStack* stack = zInventory->takeItemsOut(target, 1, INSIDE);
+            if (stack)
+            {
+                if (stack->getSize() > 0 && stack->zItem())
+                {
+                    ItemModifier* m = modfiers.z(y * width + x);
+                    if (m) m->applyOn((Item*)stack->zItem());
+                }
+                if (stack->zItem()->getHp() == 0)
+                    stack->release();
+                else if (stack->zItem()->getDurability() == 0)
+                {
+                    Item* broken = stack->zItem()->zItemType()->breakItem(
+                        stack->zItem());
+                    stack->release();
+                    if (broken)
+                    {
+                        ItemStack* brokenStack = new ItemStack(broken, 1);
+                        zInventory->unsaveAddItem(brokenStack, INSIDE);
+                        // TODO: if brokenStack is not empty spawn an item
+                        // entity
+                        brokenStack->release();
+                    }
+                }
+                else
+                {
+                    // TODO: transfer all items from target to other slots or
+                    // drop them
+                    zInventory->addItems(target, stack, INSIDE);
+                    // TODO: if stack is not empty spawn an item entity
+                }
+            }
+            ItemFilter* f = filters.z(y * width + x);
+            if (f)
+            {
+                if (target->isEmpty())
+                {
+                    Framework::Array<ItemSlot*> tmp;
+                    tmp.add(target);
+                    CombinedItemFilter combinedFilter(
+                        dynamic_cast<ItemFilter*>(f->getThis()),
+                        dynamic_cast<ItemFilter*>(otherSlots.getThis()),
+                        [](bool a, bool b) { return a && b; });
+                    zInventory->localTransaction(
+                        0, &tmp, &combinedFilter, 1, NO_DIRECTION, INSIDE);
+                }
+            }
+        }
+    }
+    return 1;
 }
 
 void BasicShapedCrafter::addCraftingResult(ItemStack* stack)
 {
-	zInventory->unsaveAddItem(stack, NO_DIRECTION);
+    zInventory->unsaveAddItem(stack, NO_DIRECTION);
 }
 
 void BasicShapedCrafter::applyCurrentRecipie()
 {
-	if (currentRecipie && currentRecipie->testApplicability(this))
-		currentRecipie->apply(this);
+    if (currentRecipie && currentRecipie->testApplicability(this))
+        currentRecipie->apply(this);
 }
 
 void BasicShapedCrafter::calculateOutputPreview()
 {
-	ShapedRecipieList* recipies = Game::INSTANCE->getRecipies().zShapedRecipieList(recipieList);
-	if (recipies)
-	{
-		ShapedRecipie* recipie = recipies->zFirstRecipie(this);
-		if (recipie != currentRecipie)
-		{
-			currentRecipie = recipie;
-			NetworkMessage* message = new NetworkMessage();
-			getOutputPreview(message);
-			zInventory->notyObservers(message);
-		}
-	}
+    ShapedRecipieList* recipies
+        = Game::INSTANCE->getRecipies().zShapedRecipieList(recipieList);
+    if (recipies)
+    {
+        ShapedRecipie* recipie = recipies->zFirstRecipie(this);
+        if (recipie != currentRecipie)
+        {
+            currentRecipie = recipie;
+            NetworkMessage* message = new NetworkMessage();
+            getOutputPreview(message);
+            zInventory->notyObservers(message);
+        }
+    }
 }

+ 42 - 25
FactoryCraft/CraftingStorage.h

@@ -1,49 +1,66 @@
 #pragma once
 #include <Array.h>
 
-#include "ItemStack.h"
+#include "Inventory.h"
 #include "ItemFilter.h"
 #include "ItemSlot.h"
-#include "Inventory.h"
+#include "ItemStack.h"
 #include "Recipie.h"
 
-
 class CraftingStorage
 {
 public:
-	virtual bool isAllAvailable(Framework::RCArray<ItemFilter>& filters, Framework::Array<int>& inputAmount) = 0;
-	virtual bool hasFreeSpace(const Item* zItem, int amount) = 0;
-	virtual bool consume(Framework::RCArray<ItemFilter>& filters, Framework::Array<int>& inputAmount) = 0;
-	virtual void addCraftingResult(ItemStack* stack) = 0;
+    virtual bool isAllAvailable(Framework::RCArray<ItemFilter>& filters,
+        Framework::Array<int>& inputAmount)
+        = 0;
+    virtual bool hasFreeSpace(const Item* zItem, int amount) = 0;
+    virtual bool consume(Framework::RCArray<ItemFilter>& filters,
+        Framework::Array<int>& inputAmount)
+        = 0;
+    virtual void addCraftingResult(ItemStack* stack) = 0;
 };
 
 class ShapedCraftingStorage
 {
 public:
-	virtual bool isAllAvailable(Framework::RCArray<ItemFilter>& filters, int width, int height) = 0;
-	virtual bool hasFreeSpace(const Item* zItem, int amount) = 0;
-	virtual bool consume(Framework::RCArray<ItemFilter>& filters, Framework::RCArray<ItemModifier>& modifiers, int width, int height) = 0;
-	virtual void addCraftingResult(ItemStack* stack) = 0;
+    virtual bool isAllAvailable(
+        Framework::RCArray<ItemFilter>& filters, int width, int height)
+        = 0;
+    virtual bool hasFreeSpace(const Item* zItem, int amount) = 0;
+    virtual bool consume(Framework::RCArray<ItemFilter>& filters,
+        Framework::RCArray<ItemModifier>& modifiers,
+        int width,
+        int height)
+        = 0;
+    virtual void addCraftingResult(ItemStack* stack) = 0;
 };
 
 class BasicShapedCrafter : public ShapedCraftingStorage
 {
 private:
-	Framework::Array<ItemSlot*> craftingInput;
-	Inventory* zInventory;
-	ShapedRecipie* currentRecipie;
-	Framework::Text recipieList;
-	int width;
-	int height;
+    Framework::Array<ItemSlot*> craftingInput;
+    Inventory* zInventory;
+    ShapedRecipie* currentRecipie;
+    Framework::Text recipieList;
+    int width;
+    int height;
 
-	void getOutputPreview(NetworkMessage* zMsg);
+    void getOutputPreview(NetworkMessage* zMsg);
 
 public:
-	BasicShapedCrafter(int width, int height, Inventory* zInventory, Framework::Text recipieList);
-	virtual bool isAllAvailable(Framework::RCArray<ItemFilter>& filters, int width, int height) override;
-	virtual bool hasFreeSpace(const Item* zItem, int amount) override;
-	virtual bool consume(Framework::RCArray<ItemFilter>& filters, Framework::RCArray<ItemModifier>& modifiers, int width, int height) override;
-	virtual void addCraftingResult(ItemStack* stack) override;
-	void applyCurrentRecipie();
-	void calculateOutputPreview();
+    BasicShapedCrafter(int width,
+        int height,
+        Inventory* zInventory,
+        Framework::Text recipieList);
+    virtual bool isAllAvailable(Framework::RCArray<ItemFilter>& filters,
+        int width,
+        int height) override;
+    virtual bool hasFreeSpace(const Item* zItem, int amount) override;
+    virtual bool consume(Framework::RCArray<ItemFilter>& filters,
+        Framework::RCArray<ItemModifier>& modifiers,
+        int width,
+        int height) override;
+    virtual void addCraftingResult(ItemStack* stack) override;
+    void applyCurrentRecipie();
+    void calculateOutputPreview();
 };

+ 58 - 53
FactoryCraft/Dimension.h

@@ -1,74 +1,79 @@
 #pragma once
 
-#include <Punkt.h>
 #include <InMemoryBuffer.h>
+#include <Punkt.h>
 #include <Thread.h>
 
 #include "Chunk.h"
-#include "NetworkMessage.h"
 #include "MultiblockStructure.h"
+#include "NetworkMessage.h"
 
 struct RequestQueue
 {
-	Framework::InMemoryBuffer* request;
-	Framework::Punkt chunkCenter;
-	int sourceId;
+    Framework::InMemoryBuffer* request;
+    Framework::Punkt chunkCenter;
+    int sourceId;
 };
 
 class Dimension : public Framework::Thread
 {
 private:
-	__int64 nextStructureId;
-	int dimensionId;
-	float gravity;
-	Framework::Trie<Chunk>* chunks;
-	Framework::Array<Chunk*> chunkList;
-	Framework::Critical chunkCs;
-	Framework::RCArray<Entity>* entities;
-	Framework::Array<RequestQueue> waitingRequests;
-	Framework::Critical cs;
-	void getAddrOf(Framework::Punkt cPos, char* addr) const;
-	void getAddrOfWorld(Framework::Punkt wPos, char* addr) const;
-	Framework::Array<Framework::Vec3<int>> lightUpdateQueue;
-	Framework::Array<Framework::Vec3<int>> priorizedLightUpdateQueue;
-	Framework::Critical lightCs;
-	Framework::Critical prioLightCs;
-	Framework::Critical structurCs;
-	Framework::RCArray<Chunk> removedChunks;
-	Framework::Critical removedChunksCs;
-	Framework::RCArray<MultiblockStructure> structures;
+    __int64 nextStructureId;
+    int dimensionId;
+    float gravity;
+    Framework::Trie<Chunk>* chunks;
+    Framework::Array<Chunk*> chunkList;
+    Framework::Critical chunkCs;
+    Framework::RCArray<Entity>* entities;
+    Framework::Array<RequestQueue> waitingRequests;
+    Framework::Critical cs;
+    void getAddrOf(Framework::Punkt cPos, char* addr) const;
+    void getAddrOfWorld(Framework::Punkt wPos, char* addr) const;
+    Framework::Array<Framework::Vec3<int>> lightUpdateQueue;
+    Framework::Array<Framework::Vec3<int>> priorizedLightUpdateQueue;
+    Framework::Critical lightCs;
+    Framework::Critical prioLightCs;
+    Framework::Critical structurCs;
+    Framework::RCArray<Chunk> removedChunks;
+    Framework::Critical removedChunksCs;
+    Framework::RCArray<MultiblockStructure> structures;
 
 public:
-	Dimension(int id);
-	~Dimension();
+    Dimension(int id);
+    ~Dimension();
 
-	void api(Framework::InMemoryBuffer* zRequest, NetworkMessage* zResponse, Entity* zSource);
-	void tickEntities();
+    void api(Framework::InMemoryBuffer* zRequest,
+        NetworkMessage* zResponse,
+        Entity* zSource);
+    void tickEntities();
 
-	void thread() override;
+    void thread() override;
 
-	Framework::Either<Block*, int> zBlock(Framework::Vec3<int> location);
-	Block* zRealBlockInstance(Framework::Vec3<int> location);
-	const Block* zBlockOrDefault(Framework::Vec3<int> location);
-	void placeBlock(Framework::Vec3<int> location, Framework::Either<Block*, int> block);
-	void addEntity(Entity* entity);
-	void setChunk(Chunk* chunk, Framework::Punkt center);
-	void save(Framework::Text worldDir) const;
-	int getDimensionId() const;
-	bool hasChunck(int x, int y);
-	bool reviveChunk(int x, int y);
-	Chunk* zChunk(Framework::Punkt wPos) const;
-	float getGravity() const;
-	void removeOldChunks();
-	Entity* zEntity(int id);
-	Entity* zNearestEntity(Framework::Vec3<float> pos, std::function<bool(Entity*)> filter);
-	void removeEntity(int id);
-	void removeSubscriptions(Entity* zEntity);
-	void updateLightning(Framework::Vec3<int> location);
-	void updateLightningWithoutWait(Framework::Vec3<int> location);
-	void updateLightAtChunkBorders(Framework::Punkt chunkCenter);
-	__int64 getNextStructureId();
-	void addStructure(MultiblockStructure* structure);
-	MultiblockStructure* zStructureByPosition(Framework::Vec3<int> uniquePosition);
-	MultiblockStructure* zStructureById(__int64 id);
+    Framework::Either<Block*, int> zBlock(Framework::Vec3<int> location);
+    Block* zRealBlockInstance(Framework::Vec3<int> location);
+    const Block* zBlockOrDefault(Framework::Vec3<int> location);
+    void placeBlock(
+        Framework::Vec3<int> location, Framework::Either<Block*, int> block);
+    void addEntity(Entity* entity);
+    void setChunk(Chunk* chunk, Framework::Punkt center);
+    void save(Framework::Text worldDir) const;
+    int getDimensionId() const;
+    bool hasChunck(int x, int y);
+    bool reviveChunk(int x, int y);
+    Chunk* zChunk(Framework::Punkt wPos) const;
+    float getGravity() const;
+    void removeOldChunks();
+    Entity* zEntity(int id);
+    Entity* zNearestEntity(
+        Framework::Vec3<float> pos, std::function<bool(Entity*)> filter);
+    void removeEntity(int id);
+    void removeSubscriptions(Entity* zEntity);
+    void updateLightning(Framework::Vec3<int> location);
+    void updateLightningWithoutWait(Framework::Vec3<int> location);
+    void updateLightAtChunkBorders(Framework::Punkt chunkCenter);
+    __int64 getNextStructureId();
+    void addStructure(MultiblockStructure* structure);
+    MultiblockStructure* zStructureByPosition(
+        Framework::Vec3<int> uniquePosition);
+    MultiblockStructure* zStructureById(__int64 id);
 };

+ 259 - 185
FactoryCraft/DimensionGenerator.cpp

@@ -1,221 +1,295 @@
 #include "DimensionGenerator.h"
-#include "Constants.h"
-#include "Noise.h"
-#include "NoBlock.h"
-#include "RandNoise.h"
-#include "Game.h"
 
 #include <iostream>
 
+#include "Constants.h"
+#include "Game.h"
+#include "NoBlock.h"
+#include "Noise.h"
+#include "RandNoise.h"
 
-DimensionGenerator::DimensionGenerator(int dimensionId, CaveGenerator* caveGenerator)
-	: ReferenceCounter(),
-	dimensionId(dimensionId),
-	minTemplateAffectedPosition(0, 0, 0),
-	maxTemplateAffectedPosition(0, 0, 0),
-	caveGenerator(caveGenerator)
+DimensionGenerator::DimensionGenerator(
+    int dimensionId, CaveGenerator* caveGenerator)
+    : ReferenceCounter(),
+      dimensionId(dimensionId),
+      minTemplateAffectedPosition(0, 0, 0),
+      maxTemplateAffectedPosition(0, 0, 0),
+      caveGenerator(caveGenerator)
 {
-	StaticRegistry<DimensionGenerator>::INSTANCE.registerT(this, dimensionId);
+    StaticRegistry<DimensionGenerator>::INSTANCE.registerT(this, dimensionId);
 }
 
-DimensionGenerator::~DimensionGenerator()
-{}
+DimensionGenerator::~DimensionGenerator() {}
 
 void DimensionGenerator::initialize(int seed)
 {
-	this->seed = seed + dimensionId;
-	caveGenerator->initialize(this->seed);
+    this->seed = seed + dimensionId;
+    caveGenerator->initialize(this->seed);
 }
 
 BiomGenerator* DimensionGenerator::zBiomGenerator(int x, int y)
 {
-	double noise = zBiomNoise()->getNoise((double)x, (double)y, 0.0);
-	double border = 0;
-	BiomGenerator* gen = 0;
-	auto genI = biomGenerators.begin();
-	auto distI = biomDistribution.begin();
-	do
-	{
-		border += (double)distI++;
-		gen = genI++;
-	} while (border < noise && (bool)distI && (bool)genI);
-	return gen;
+    double noise = zBiomNoise()->getNoise((double)x, (double)y, 0.0);
+    double border = 0;
+    BiomGenerator* gen = 0;
+    auto genI = biomGenerators.begin();
+    auto distI = biomDistribution.begin();
+    do
+    {
+        border += (double)distI++;
+        gen = genI++;
+    } while (border < noise && (bool)distI && (bool)genI);
+    return gen;
 }
 
-void DimensionGenerator::registerBiom(BiomGenerator* generator, double possibility)
+void DimensionGenerator::registerBiom(
+    BiomGenerator* generator, double possibility)
 {
-	biomGenerators.add(generator);
-	biomDistribution.add(possibility);
-	for (auto t : generator->getTemplates())
-	{
-		minTemplateAffectedPosition.x = MIN(minTemplateAffectedPosition.x, t->getMinAffectedOffset().x);
-		minTemplateAffectedPosition.y = MIN(minTemplateAffectedPosition.y, t->getMinAffectedOffset().y);
-		minTemplateAffectedPosition.z = MIN(minTemplateAffectedPosition.z, t->getMinAffectedOffset().z);
-		maxTemplateAffectedPosition.x = MAX(maxTemplateAffectedPosition.x, t->getMaxAffectedOffset().x);
-		maxTemplateAffectedPosition.y = MAX(maxTemplateAffectedPosition.y, t->getMaxAffectedOffset().y);
-		maxTemplateAffectedPosition.z = MAX(maxTemplateAffectedPosition.z, t->getMaxAffectedOffset().z);
-	}
+    biomGenerators.add(generator);
+    biomDistribution.add(possibility);
+    for (auto t : generator->getTemplates())
+    {
+        minTemplateAffectedPosition.x
+            = MIN(minTemplateAffectedPosition.x, t->getMinAffectedOffset().x);
+        minTemplateAffectedPosition.y
+            = MIN(minTemplateAffectedPosition.y, t->getMinAffectedOffset().y);
+        minTemplateAffectedPosition.z
+            = MIN(minTemplateAffectedPosition.z, t->getMinAffectedOffset().z);
+        maxTemplateAffectedPosition.x
+            = MAX(maxTemplateAffectedPosition.x, t->getMaxAffectedOffset().x);
+        maxTemplateAffectedPosition.y
+            = MAX(maxTemplateAffectedPosition.y, t->getMaxAffectedOffset().y);
+        maxTemplateAffectedPosition.z
+            = MAX(maxTemplateAffectedPosition.z, t->getMaxAffectedOffset().z);
+    }
 }
 
-Framework::RCArray<GeneratedStructure>* DimensionGenerator::getGeneratedStructoresForArea(Framework::Vec3<int> minPos, Framework::Vec3<int> maxPos)
+Framework::RCArray<GeneratedStructure>*
+DimensionGenerator::getGeneratedStructoresForArea(
+    Framework::Vec3<int> minPos, Framework::Vec3<int> maxPos)
 {
-	Framework::RCArray<GeneratedStructure>* result = new Framework::RCArray<GeneratedStructure>();
-
-	int minSearchX = minPos.x - maxTemplateAffectedPosition.x;
-	int minSearchY = minPos.y - maxTemplateAffectedPosition.y;
-	int minSearchZ = MAX(minPos.z - maxTemplateAffectedPosition.z, 0);
-	int maxSearchX = maxPos.x - minTemplateAffectedPosition.x;
-	int maxSearchY = maxPos.y - minTemplateAffectedPosition.y;
-	int maxSearchZ = MIN(maxPos.z - minTemplateAffectedPosition.z, WORLD_HEIGHT - 1);
-
-	Noise* structureNoise = zStructureNoise();
-	for (int x = minSearchX; x <= maxSearchX; x++)
-	{
-		for (int y = minSearchY; y <= maxSearchY; y++)
-		{
-			BiomGenerator* biom = zBiomGenerator(x, y);
-			int height = MIN_AIR_LEVEL + (int)(biom->zHeightMapNoise(seed)->getNoise((double)(x), (double)(y), 0.0) * (MAX_AIR_LEVEL - MIN_AIR_LEVEL));
-			for (int z = minSearchZ; z <= maxSearchZ; z++)
-			{
-				if (z < height)
-				{
-					double rValue = structureNoise->getNoise((double)x, (double)y, (double)z);
-					double probSum = 0;
-					for (auto t : biom->getTemplates())
-					{
-						if (t->isGenerationPossable(Framework::Vec3<int>(x, y, z), height - z))
-						{
-							if (rValue - probSum <= t->getPropability())
-							{
-								result->add(t->generateAt(Framework::Vec3<int>(x, y, z), structureNoise, dimensionId));
-								break;
-							}
-						}
-						probSum += t->getPropability();
-					}
-				}
-			}
-		}
-	}
-
-	return result;
+    Framework::RCArray<GeneratedStructure>* result
+        = new Framework::RCArray<GeneratedStructure>();
+
+    int minSearchX = minPos.x - maxTemplateAffectedPosition.x;
+    int minSearchY = minPos.y - maxTemplateAffectedPosition.y;
+    int minSearchZ = MAX(minPos.z - maxTemplateAffectedPosition.z, 0);
+    int maxSearchX = maxPos.x - minTemplateAffectedPosition.x;
+    int maxSearchY = maxPos.y - minTemplateAffectedPosition.y;
+    int maxSearchZ
+        = MIN(maxPos.z - minTemplateAffectedPosition.z, WORLD_HEIGHT - 1);
+
+    Noise* structureNoise = zStructureNoise();
+    for (int x = minSearchX; x <= maxSearchX; x++)
+    {
+        for (int y = minSearchY; y <= maxSearchY; y++)
+        {
+            BiomGenerator* biom = zBiomGenerator(x, y);
+            int height = MIN_AIR_LEVEL
+                       + (int)(biom->zHeightMapNoise(seed)->getNoise(
+                                   (double)(x), (double)(y), 0.0)
+                               * (MAX_AIR_LEVEL - MIN_AIR_LEVEL));
+            for (int z = minSearchZ; z <= maxSearchZ; z++)
+            {
+                if (z < height)
+                {
+                    double rValue = structureNoise->getNoise(
+                        (double)x, (double)y, (double)z);
+                    double probSum = 0;
+                    for (auto t : biom->getTemplates())
+                    {
+                        if (t->isGenerationPossable(
+                                Framework::Vec3<int>(x, y, z), height - z))
+                        {
+                            if (rValue - probSum <= t->getPropability())
+                            {
+                                result->add(
+                                    t->generateAt(Framework::Vec3<int>(x, y, z),
+                                        structureNoise,
+                                        dimensionId));
+                                break;
+                            }
+                        }
+                        probSum += t->getPropability();
+                    }
+                }
+            }
+        }
+    }
+
+    return result;
 }
 
 Chunk* DimensionGenerator::generateChunk(int centerX, int centerY)
 {
-	Framework::RCArray<GeneratedStructure>* structures = getGeneratedStructoresForArea(Framework::Vec3<int>(centerX - CHUNK_SIZE / 2, centerY - CHUNK_SIZE / 2, 0), Framework::Vec3<int>(centerX + CHUNK_SIZE / 2, centerY + CHUNK_SIZE / 2, WORLD_HEIGHT - 1));
-	std::cout << "generating chunk " << centerX << ", " << centerY << "\n";
-	CaveChunkGenerator* caveGen = caveGenerator->getGeneratorForChunk(centerX, centerY);
-	Chunk* chunk = new Chunk(Framework::Punkt(centerX, centerY), dimensionId);
-	for (int x = -CHUNK_SIZE / 2; x < CHUNK_SIZE / 2; x++)
-	{
-		for (int y = -CHUNK_SIZE / 2; y < CHUNK_SIZE / 2; y++)
-		{
-			BiomGenerator* biom = zBiomGenerator(x + centerX, y + centerY);
-			// TODO: use Noise interpolator for height map between different bioms
-			int height = MIN_AIR_LEVEL + (int)(biom->zHeightMapNoise(seed)->getNoise((double)(x + centerX), (double)(y + centerY), 0.0) * (MAX_AIR_LEVEL - MIN_AIR_LEVEL));
-			int maxSurfaceHeight = (int)(MAX_SURFACE_HEIGHT * (1.f - (float)(height - MIN_AIR_LEVEL) / (float)(MAX_AIR_LEVEL - MIN_AIR_LEVEL)));
-			int actualSurfaceHeight = (int)((float)maxSurfaceHeight * (1.f - VARIABLE_SURFACE_PART) + ((float)maxSurfaceHeight * VARIABLE_SURFACE_PART * (float)biom->zHeightMapNoise(seed)->getNoise((double)(x + centerX), (double)(y + centerY), 10.0)));
-			for (int z = 0; z < WORLD_HEIGHT; z++)
-			{
-				Framework::Either<Block*, int> generated = BlockTypeEnum::AIR;
-				bool structureAffected = 0;
-				for (auto structure : *structures)
-				{
-					if (structure->isBlockAffected(Framework::Vec3<int>(x + centerX, y + centerY, z)))
-					{
-						generated = structure->generateBlockAt(Framework::Vec3<int>(x + centerX, y + centerY, z));
-						structureAffected = 1;
-						break;
-					}
-				}
-				if (!structureAffected)
-				{
-					if (caveGen->isInCave(x + centerX, y + centerY, z))
-						generated = biom->generateCaveBlock(x + centerX, y + centerY, z);
-					else if (z < height && z >= height - actualSurfaceHeight)
-						generated = biom->generateSurfaceBlock(x + centerX, y + centerY, z);
-					else if (z < height)
-						generated = biom->generateBelowSurfaceBlock(x + centerX, y + centerY, z);
-				}
-				if (generated.isA())
-					chunk->putBlockAt(Framework::Vec3<int>(x + CHUNK_SIZE / 2, y + CHUNK_SIZE / 2, z), generated);
-				else
-					chunk->putBlockTypeAt(Framework::Vec3<int>(x + CHUNK_SIZE / 2, y + CHUNK_SIZE / 2, z), generated);
-			}
-		}
-	}
-	caveGen->release();
-	structures->release();
-	return chunk;
+    Framework::RCArray<GeneratedStructure>* structures
+        = getGeneratedStructoresForArea(
+            Framework::Vec3<int>(
+                centerX - CHUNK_SIZE / 2, centerY - CHUNK_SIZE / 2, 0),
+            Framework::Vec3<int>(centerX + CHUNK_SIZE / 2,
+                centerY + CHUNK_SIZE / 2,
+                WORLD_HEIGHT - 1));
+    std::cout << "generating chunk " << centerX << ", " << centerY << "\n";
+    CaveChunkGenerator* caveGen
+        = caveGenerator->getGeneratorForChunk(centerX, centerY);
+    Chunk* chunk = new Chunk(Framework::Punkt(centerX, centerY), dimensionId);
+    for (int x = -CHUNK_SIZE / 2; x < CHUNK_SIZE / 2; x++)
+    {
+        for (int y = -CHUNK_SIZE / 2; y < CHUNK_SIZE / 2; y++)
+        {
+            BiomGenerator* biom = zBiomGenerator(x + centerX, y + centerY);
+            // TODO: use Noise interpolator for height map between different
+            // bioms
+            int height
+                = MIN_AIR_LEVEL
+                + (int)(biom->zHeightMapNoise(seed)->getNoise(
+                            (double)(x + centerX), (double)(y + centerY), 0.0)
+                        * (MAX_AIR_LEVEL - MIN_AIR_LEVEL));
+            int maxSurfaceHeight
+                = (int)(MAX_SURFACE_HEIGHT
+                        * (1.f
+                            - (float)(height - MIN_AIR_LEVEL)
+                                  / (float)(MAX_AIR_LEVEL - MIN_AIR_LEVEL)));
+            int actualSurfaceHeight
+                = (int)((float)maxSurfaceHeight * (1.f - VARIABLE_SURFACE_PART)
+                        + ((float)maxSurfaceHeight * VARIABLE_SURFACE_PART
+                            * (float)biom->zHeightMapNoise(seed)->getNoise(
+                                (double)(x + centerX),
+                                (double)(y + centerY),
+                                10.0)));
+            for (int z = 0; z < WORLD_HEIGHT; z++)
+            {
+                Framework::Either<Block*, int> generated = BlockTypeEnum::AIR;
+                bool structureAffected = 0;
+                for (auto structure : *structures)
+                {
+                    if (structure->isBlockAffected(
+                            Framework::Vec3<int>(x + centerX, y + centerY, z)))
+                    {
+                        generated = structure->generateBlockAt(
+                            Framework::Vec3<int>(x + centerX, y + centerY, z));
+                        structureAffected = 1;
+                        break;
+                    }
+                }
+                if (!structureAffected)
+                {
+                    if (caveGen->isInCave(x + centerX, y + centerY, z))
+                        generated = biom->generateCaveBlock(
+                            x + centerX, y + centerY, z);
+                    else if (z < height && z >= height - actualSurfaceHeight)
+                        generated = biom->generateSurfaceBlock(
+                            x + centerX, y + centerY, z);
+                    else if (z < height)
+                        generated = biom->generateBelowSurfaceBlock(
+                            x + centerX, y + centerY, z);
+                }
+                if (generated.isA())
+                    chunk->putBlockAt(
+                        Framework::Vec3<int>(
+                            x + CHUNK_SIZE / 2, y + CHUNK_SIZE / 2, z),
+                        generated);
+                else
+                    chunk->putBlockTypeAt(
+                        Framework::Vec3<int>(
+                            x + CHUNK_SIZE / 2, y + CHUNK_SIZE / 2, z),
+                        generated);
+            }
+        }
+    }
+    caveGen->release();
+    structures->release();
+    return chunk;
 }
 
-Framework::Either<Block*, int> DimensionGenerator::generateBlock(Framework::Vec3<int> location)
+Framework::Either<Block*, int> DimensionGenerator::generateBlock(
+    Framework::Vec3<int> location)
 {
-	Framework::RCArray<GeneratedStructure>* structures = getGeneratedStructoresForArea(location, location);
-	BiomGenerator* biom = zBiomGenerator(location.x, location.y);
-	// TODO: use Noise interpolator for height map between different bioms
-	int height = MIN_AIR_LEVEL + (int)(biom->zHeightMapNoise(seed)->getNoise((double)(location.x), (double)(location.y), 0.0) * (MAX_AIR_LEVEL - MIN_AIR_LEVEL));
-	int maxSurfaceHeight = (int)(MAX_SURFACE_HEIGHT * (1.f - (float)(height - MIN_AIR_LEVEL) / (float)(MAX_AIR_LEVEL - MIN_AIR_LEVEL)));
-	int actualSurfaceHeight = (int)((float)maxSurfaceHeight * (1.f - VARIABLE_SURFACE_PART) + ((float)maxSurfaceHeight * VARIABLE_SURFACE_PART * (float)biom->zHeightMapNoise(seed)->getNoise((double)(location.x), (double)(location.y), 10.0)));
-	for (auto structure : *structures)
-	{
-		if (structure->isBlockAffected(location))
-		{
-			auto generated = structure->generateBlockAt(location);
-			structures->release();
-			return generated;
-		}
-	}
-	structures->release();
-	if (location.z < height && location.z >= height - actualSurfaceHeight)
-		return biom->generateSurfaceBlock(location.x, location.y, location.z);
-	else if (location.z < height)
-		return biom->generateBelowSurfaceBlock(location.x, location.y, location.z);
-	return BlockTypeEnum::AIR;
+    Framework::RCArray<GeneratedStructure>* structures
+        = getGeneratedStructoresForArea(location, location);
+    BiomGenerator* biom = zBiomGenerator(location.x, location.y);
+    // TODO: use Noise interpolator for height map between different bioms
+    int height = MIN_AIR_LEVEL
+               + (int)(biom->zHeightMapNoise(seed)->getNoise(
+                           (double)(location.x), (double)(location.y), 0.0)
+                       * (MAX_AIR_LEVEL - MIN_AIR_LEVEL));
+    int maxSurfaceHeight
+        = (int)(MAX_SURFACE_HEIGHT
+                * (1.f
+                    - (float)(height - MIN_AIR_LEVEL)
+                          / (float)(MAX_AIR_LEVEL - MIN_AIR_LEVEL)));
+    int actualSurfaceHeight
+        = (int)((float)maxSurfaceHeight * (1.f - VARIABLE_SURFACE_PART)
+                + ((float)maxSurfaceHeight * VARIABLE_SURFACE_PART
+                    * (float)biom->zHeightMapNoise(seed)->getNoise(
+                        (double)(location.x), (double)(location.y), 10.0)));
+    for (auto structure : *structures)
+    {
+        if (structure->isBlockAffected(location))
+        {
+            auto generated = structure->generateBlockAt(location);
+            structures->release();
+            return generated;
+        }
+    }
+    structures->release();
+    if (location.z < height && location.z >= height - actualSurfaceHeight)
+        return biom->generateSurfaceBlock(location.x, location.y, location.z);
+    else if (location.z < height)
+        return biom->generateBelowSurfaceBlock(
+            location.x, location.y, location.z);
+    return BlockTypeEnum::AIR;
 }
 
-bool DimensionGenerator::spawnStructure(Framework::Vec3<int> location, std::function<bool(GenerationTemplate* tmpl)> filter)
+bool DimensionGenerator::spawnStructure(Framework::Vec3<int> location,
+    std::function<bool(GenerationTemplate* tmpl)> filter)
 {
-	BiomGenerator* biom = zBiomGenerator(location.x, location.y);
-	for (auto t : biom->getTemplates())
-	{
-		if (filter(t))
-		{
-			RandNoise noise((int)time(0));
-			GeneratedStructure *genStr = t->generateAt(location, &noise, dimensionId);
-			if (genStr)
-			{
-				int minSearchX = location.x + t->getMinAffectedOffset().x;
-				int minSearchY = location.y + t->getMinAffectedOffset().y;
-				int minSearchZ = MAX(location.z + t->getMinAffectedOffset().z, 0);
-				int maxSearchX = location.x + t->getMaxAffectedOffset().x;
-				int maxSearchY = location.y + t->getMaxAffectedOffset().y;
-				int maxSearchZ = MIN(location.z + t->getMaxAffectedOffset().z, WORLD_HEIGHT - 1);
-
-				for (int x = minSearchX; x <= maxSearchX; x++)
-				{
-					for (int y = minSearchY; y <= maxSearchY; y++)
-					{
-						for (int z = minSearchZ; z <= maxSearchZ; z++)
-						{
-							if (genStr->isBlockAffected(Framework::Vec3<int>(x, y, z)))
-							{
-								auto gen = genStr->generateBlockAt(Framework::Vec3<int>(x, y, z));
-								Game::INSTANCE->zDimension(dimensionId)->placeBlock(Framework::Vec3<int>(x, y, z), gen);
-							}
-						}
-					}
-				}
-				genStr->release();
-				return 1;
-			}
-		}
-	}
-	return 0;
+    BiomGenerator* biom = zBiomGenerator(location.x, location.y);
+    for (auto t : biom->getTemplates())
+    {
+        if (filter(t))
+        {
+            RandNoise noise((int)time(0));
+            GeneratedStructure* genStr
+                = t->generateAt(location, &noise, dimensionId);
+            if (genStr)
+            {
+                int minSearchX = location.x + t->getMinAffectedOffset().x;
+                int minSearchY = location.y + t->getMinAffectedOffset().y;
+                int minSearchZ
+                    = MAX(location.z + t->getMinAffectedOffset().z, 0);
+                int maxSearchX = location.x + t->getMaxAffectedOffset().x;
+                int maxSearchY = location.y + t->getMaxAffectedOffset().y;
+                int maxSearchZ = MIN(
+                    location.z + t->getMaxAffectedOffset().z, WORLD_HEIGHT - 1);
+
+                for (int x = minSearchX; x <= maxSearchX; x++)
+                {
+                    for (int y = minSearchY; y <= maxSearchY; y++)
+                    {
+                        for (int z = minSearchZ; z <= maxSearchZ; z++)
+                        {
+                            if (genStr->isBlockAffected(
+                                    Framework::Vec3<int>(x, y, z)))
+                            {
+                                auto gen = genStr->generateBlockAt(
+                                    Framework::Vec3<int>(x, y, z));
+                                Game::INSTANCE->zDimension(dimensionId)
+                                    ->placeBlock(
+                                        Framework::Vec3<int>(x, y, z), gen);
+                            }
+                        }
+                    }
+                }
+                genStr->release();
+                return 1;
+            }
+        }
+    }
+    return 0;
 }
 
 int DimensionGenerator::getDimensionId() const
 {
-	return dimensionId;
+    return dimensionId;
 }

+ 24 - 22
FactoryCraft/DimensionGenerator.h

@@ -1,44 +1,46 @@
 #pragma once
 
 #include <Array.h>
-#include <ReferenceCounter.h>
 #include <Either.h>
+#include <ReferenceCounter.h>
 
 #include "BiomGenerator.h"
-#include "Chunk.h"
 #include "CaveGenerator.h"
+#include "Chunk.h"
 
 class DimensionEnum
 {
 public:
-	static const int OVERWORLD = 0;
+    static const int OVERWORLD = 0;
 };
 
 class DimensionGenerator : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::RCArray<BiomGenerator> biomGenerators;
-	Framework::Array<double> biomDistribution;
-	const int dimensionId;
-	Framework::Vec3<int> minTemplateAffectedPosition;
-	Framework::Vec3<int> maxTemplateAffectedPosition;
-	CaveGenerator* caveGenerator;
+    Framework::RCArray<BiomGenerator> biomGenerators;
+    Framework::Array<double> biomDistribution;
+    const int dimensionId;
+    Framework::Vec3<int> minTemplateAffectedPosition;
+    Framework::Vec3<int> maxTemplateAffectedPosition;
+    CaveGenerator* caveGenerator;
 
-	BiomGenerator* zBiomGenerator(int x, int y);
+    BiomGenerator* zBiomGenerator(int x, int y);
 
 protected:
-	int seed;
-	DimensionGenerator(int dimensionId, CaveGenerator* caveGenerator);
-	~DimensionGenerator();
-	void registerBiom(BiomGenerator* generator, double possibility);
-	Framework::RCArray<GeneratedStructure>* getGeneratedStructoresForArea(Framework::Vec3<int> minPos, Framework::Vec3<int> maxPos);
+    int seed;
+    DimensionGenerator(int dimensionId, CaveGenerator* caveGenerator);
+    ~DimensionGenerator();
+    void registerBiom(BiomGenerator* generator, double possibility);
+    Framework::RCArray<GeneratedStructure>* getGeneratedStructoresForArea(
+        Framework::Vec3<int> minPos, Framework::Vec3<int> maxPos);
 
 public:
-	void initialize(int seed);
-	Chunk* generateChunk(int centerX, int centerY);
-	Framework::Either<Block*, int> generateBlock(Framework::Vec3<int> location);
-	bool spawnStructure(Framework::Vec3<int> location, std::function<bool(GenerationTemplate* tmpl)> filter);
-	int getDimensionId() const;
-	virtual Noise* zBiomNoise() = 0;
-	virtual Noise* zStructureNoise() = 0;
+    void initialize(int seed);
+    Chunk* generateChunk(int centerX, int centerY);
+    Framework::Either<Block*, int> generateBlock(Framework::Vec3<int> location);
+    bool spawnStructure(Framework::Vec3<int> location,
+        std::function<bool(GenerationTemplate* tmpl)> filter);
+    int getDimensionId() const;
+    virtual Noise* zBiomNoise() = 0;
+    virtual Noise* zStructureNoise() = 0;
 };

+ 9 - 11
FactoryCraft/DoLaterHandler.cpp

@@ -1,28 +1,26 @@
 #include "DoLaterHandler.h"
 
-
 DoLaterHandler::DoLaterHandler()
 {
-	action = []() {};
+    action = []() {};
 }
 
 DoLaterHandler::~DoLaterHandler()
 {
-	action();
+    action();
 }
 
 void DoLaterHandler::addTodo(std::function<void()> newAction)
 {
-	std::function<void()> oldAction = action;
-	this->action = [oldAction, newAction]()
-	{
-		oldAction();
-		newAction();
-	};
+    std::function<void()> oldAction = action;
+    this->action = [oldAction, newAction]() {
+        oldAction();
+        newAction();
+    };
 }
 
 void DoLaterHandler::execute()
 {
-	action();
-	action = []() {};
+    action();
+    action = []() {};
 }

+ 5 - 5
FactoryCraft/DoLaterHandler.h

@@ -5,11 +5,11 @@
 class DoLaterHandler
 {
 private:
-	std::function<void()> action;
+    std::function<void()> action;
 
 public:
-	DoLaterHandler();
-	~DoLaterHandler();
-	void addTodo(std::function<void()> action);
-	void execute();
+    DoLaterHandler();
+    ~DoLaterHandler();
+    void addTodo(std::function<void()> action);
+    void execute();
 };

+ 6 - 5
FactoryCraft/EntityRemovedUpdate.h

@@ -5,14 +5,15 @@
 class EntityRemovedUpdate : public WorldUpdate
 {
 private:
-	int entityId;
+    int entityId;
 
 protected:
-	void write(Framework::StreamWriter* zWriter) override;
+    void write(Framework::StreamWriter* zWriter) override;
 
 public:
-	EntityRemovedUpdate(int entityId, int dimensionId, Framework::Vec3<int> pos);
-	~EntityRemovedUpdate();
+    EntityRemovedUpdate(
+        int entityId, int dimensionId, Framework::Vec3<int> pos);
+    ~EntityRemovedUpdate();
 
-	void onUpdate(Dimension* zDimension) override;
+    void onUpdate(Dimension* zDimension) override;
 };

+ 86 - 80
FactoryCraft/EntityType.cpp

@@ -1,112 +1,118 @@
 #include "EntityType.h"
+
 #include "Entity.h"
 #include "Game.h"
 
 EntityType::EntityType(int id, ModelInfo model)
-	: ReferenceCounter(),
-	id(id),
-	model(model)
+    : ReferenceCounter(),
+      id(id),
+      model(model)
 {
-	StaticRegistry<EntityType>::INSTANCE.registerT(this, id);
+    StaticRegistry<EntityType>::INSTANCE.registerT(this, id);
 }
 
-void EntityType::loadSuperEntity(Entity* zEntity, Framework::StreamReader* zReader) const
+void EntityType::loadSuperEntity(
+    Entity* zEntity, Framework::StreamReader* zReader) const
 {
-	zEntity->loadInventory(zReader);
-	zReader->lese((char*)&zEntity->id, 4);
-	zReader->lese((char*)&zEntity->maxHP, 4);
-	zReader->lese((char*)&zEntity->currentHP, 4);
-	zReader->lese((char*)&zEntity->stamina, 4);
-	zReader->lese((char*)&zEntity->maxStamina, 4);
-	zReader->lese((char*)&zEntity->hunger, 4);
-	zReader->lese((char*)&zEntity->maxHunger, 4);
-	zReader->lese((char*)&zEntity->thirst, 4);
-	zReader->lese((char*)&zEntity->maxThirst, 4);
-	zReader->lese((char*)&zEntity->speed.x, 4);
-	zReader->lese((char*)&zEntity->speed.y, 4);
-	zReader->lese((char*)&zEntity->speed.z, 4);
-	zReader->lese((char*)&zEntity->faceDir.x, 4);
-	zReader->lese((char*)&zEntity->faceDir.y, 4);
-	zReader->lese((char*)&zEntity->currentDimensionId, 4);
-	zReader->lese((char*)&zEntity->location.x, 4);
-	zReader->lese((char*)&zEntity->location.y, 4);
-	zReader->lese((char*)&zEntity->location.z, 4);
-	if (zEntity->target)
-		delete zEntity->target;
-	zEntity->target = ActionTarget::load(zReader);
-	// load item skills
-	zEntity->skills.leeren();
-	int skillCount;
-	zReader->lese((char*)&skillCount, 4);
-	for (int i = 0; i < skillCount; i++)
-	{
-		int type;
-		zReader->lese((char*)&type, 4);
-		zEntity->skills.add(StaticRegistry<ItemType>::INSTANCE.zElement(type)->loadItemSkill(zReader));
-	}
+    zEntity->loadInventory(zReader);
+    zReader->lese((char*)&zEntity->id, 4);
+    zReader->lese((char*)&zEntity->maxHP, 4);
+    zReader->lese((char*)&zEntity->currentHP, 4);
+    zReader->lese((char*)&zEntity->stamina, 4);
+    zReader->lese((char*)&zEntity->maxStamina, 4);
+    zReader->lese((char*)&zEntity->hunger, 4);
+    zReader->lese((char*)&zEntity->maxHunger, 4);
+    zReader->lese((char*)&zEntity->thirst, 4);
+    zReader->lese((char*)&zEntity->maxThirst, 4);
+    zReader->lese((char*)&zEntity->speed.x, 4);
+    zReader->lese((char*)&zEntity->speed.y, 4);
+    zReader->lese((char*)&zEntity->speed.z, 4);
+    zReader->lese((char*)&zEntity->faceDir.x, 4);
+    zReader->lese((char*)&zEntity->faceDir.y, 4);
+    zReader->lese((char*)&zEntity->currentDimensionId, 4);
+    zReader->lese((char*)&zEntity->location.x, 4);
+    zReader->lese((char*)&zEntity->location.y, 4);
+    zReader->lese((char*)&zEntity->location.z, 4);
+    if (zEntity->target) delete zEntity->target;
+    zEntity->target = ActionTarget::load(zReader);
+    // load item skills
+    zEntity->skills.leeren();
+    int skillCount;
+    zReader->lese((char*)&skillCount, 4);
+    for (int i = 0; i < skillCount; i++)
+    {
+        int type;
+        zReader->lese((char*)&type, 4);
+        zEntity->skills.add(
+            StaticRegistry<ItemType>::INSTANCE.zElement(type)->loadItemSkill(
+                zReader));
+    }
 }
 
-void EntityType::saveSuperEntity(Entity* zEntity, Framework::StreamWriter* zWriter) const
+void EntityType::saveSuperEntity(
+    Entity* zEntity, Framework::StreamWriter* zWriter) const
 {
-	zEntity->saveInventory(zWriter);
-	zWriter->schreibe((char*)&zEntity->id, 4);
-	zWriter->schreibe((char*)&zEntity->maxHP, 4);
-	zWriter->schreibe((char*)&zEntity->currentHP, 4);
-	zWriter->schreibe((char*)&zEntity->stamina, 4);
-	zWriter->schreibe((char*)&zEntity->maxStamina, 4);
-	zWriter->schreibe((char*)&zEntity->hunger, 4);
-	zWriter->schreibe((char*)&zEntity->maxHunger, 4);
-	zWriter->schreibe((char*)&zEntity->thirst, 4);
-	zWriter->schreibe((char*)&zEntity->maxThirst, 4);
-	zWriter->schreibe((char*)&zEntity->speed.x, 4);
-	zWriter->schreibe((char*)&zEntity->speed.y, 4);
-	zWriter->schreibe((char*)&zEntity->speed.z, 4);
-	zWriter->schreibe((char*)&zEntity->faceDir.x, 4);
-	zWriter->schreibe((char*)&zEntity->faceDir.y, 4);
-	zWriter->schreibe((char*)&zEntity->currentDimensionId, 4);
-	zWriter->schreibe((char*)&zEntity->location.x, 4);
-	zWriter->schreibe((char*)&zEntity->location.y, 4);
-	zWriter->schreibe((char*)&zEntity->location.z, 4);
-	ActionTarget::save(zEntity->target, zWriter);
-	// save item skills
-	int skillCount = zEntity->skills.getEintragAnzahl();
-	zWriter->schreibe((char*)&skillCount, 4);
-	for (ItemSkill* skill : zEntity->skills)
-	{
-		int type = skill->zSkillType()->getId();
-		zWriter->schreibe((char*)&type, 4);
-		skill->zSkillType()->saveItemSkill(skill, zWriter);
-	}
+    zEntity->saveInventory(zWriter);
+    zWriter->schreibe((char*)&zEntity->id, 4);
+    zWriter->schreibe((char*)&zEntity->maxHP, 4);
+    zWriter->schreibe((char*)&zEntity->currentHP, 4);
+    zWriter->schreibe((char*)&zEntity->stamina, 4);
+    zWriter->schreibe((char*)&zEntity->maxStamina, 4);
+    zWriter->schreibe((char*)&zEntity->hunger, 4);
+    zWriter->schreibe((char*)&zEntity->maxHunger, 4);
+    zWriter->schreibe((char*)&zEntity->thirst, 4);
+    zWriter->schreibe((char*)&zEntity->maxThirst, 4);
+    zWriter->schreibe((char*)&zEntity->speed.x, 4);
+    zWriter->schreibe((char*)&zEntity->speed.y, 4);
+    zWriter->schreibe((char*)&zEntity->speed.z, 4);
+    zWriter->schreibe((char*)&zEntity->faceDir.x, 4);
+    zWriter->schreibe((char*)&zEntity->faceDir.y, 4);
+    zWriter->schreibe((char*)&zEntity->currentDimensionId, 4);
+    zWriter->schreibe((char*)&zEntity->location.x, 4);
+    zWriter->schreibe((char*)&zEntity->location.y, 4);
+    zWriter->schreibe((char*)&zEntity->location.z, 4);
+    ActionTarget::save(zEntity->target, zWriter);
+    // save item skills
+    int skillCount = zEntity->skills.getEintragAnzahl();
+    zWriter->schreibe((char*)&skillCount, 4);
+    for (ItemSkill* skill : zEntity->skills)
+    {
+        int type = skill->zSkillType()->getId();
+        zWriter->schreibe((char*)&type, 4);
+        skill->zSkillType()->saveItemSkill(skill, zWriter);
+    }
 }
 
-void EntityType::createSuperEntity(Entity* zEntity) const
-{}
+void EntityType::createSuperEntity(Entity* zEntity) const {}
 
 Entity* EntityType::loadEntity(Framework::StreamReader* zReader) const
 {
-	Entity* entity = createEntity(Framework::Vec3<float>(0, 0, 0), 0, 0);
-	loadSuperEntity(entity, zReader);
-	return entity;
+    Entity* entity = createEntity(Framework::Vec3<float>(0, 0, 0), 0, 0);
+    loadSuperEntity(entity, zReader);
+    return entity;
 }
 
-void EntityType::saveEntity(Entity* zEntity, Framework::StreamWriter* zWriter) const
+void EntityType::saveEntity(
+    Entity* zEntity, Framework::StreamWriter* zWriter) const
 {
-	saveSuperEntity(zEntity, zWriter);
+    saveSuperEntity(zEntity, zWriter);
 }
 
-Entity* EntityType::createEntityAt(Framework::Vec3<float> position, int dimensionId) const
+Entity* EntityType::createEntityAt(
+    Framework::Vec3<float> position, int dimensionId) const
 {
-	Entity* entity = createEntity(position, dimensionId, Game::INSTANCE->getNextEntityId());
-	createSuperEntity(entity);
-	return entity;
+    Entity* entity = createEntity(
+        position, dimensionId, Game::INSTANCE->getNextEntityId());
+    createSuperEntity(entity);
+    return entity;
 }
 
 int EntityType::getId() const
 {
-	return id;
+    return id;
 }
 
 const ModelInfo& EntityType::getModel() const
 {
-	return model;
+    return model;
 }

+ 15 - 12
FactoryCraft/EntityType.h

@@ -2,11 +2,11 @@
 
 #include <Reader.h>
 #include <ReferenceCounter.h>
-#include <Writer.h>
 #include <Vec3.h>
+#include <Writer.h>
 
-#include "StaticRegistry.h"
 #include "ModelInfo.h"
+#include "StaticRegistry.h"
 
 class Entity;
 
@@ -20,25 +20,28 @@ public:
 class EntityType : public virtual Framework::ReferenceCounter
 {
 private:
-	const int id;
-	const ModelInfo model;
+    const int id;
+    const ModelInfo model;
 
 protected:
-	EntityType(int id, ModelInfo model);
+    EntityType(int id, ModelInfo model);
 
-	virtual void loadSuperEntity(Entity* zEntity, Framework::StreamReader* zReader) const;
-	virtual void saveSuperEntity(Entity* zEntity, Framework::StreamWriter* zWriter) const;
-	virtual void createSuperEntity(Entity* zEntity) const;
+    virtual void loadSuperEntity(
+        Entity* zEntity, Framework::StreamReader* zReader) const;
+    virtual void saveSuperEntity(
+        Entity* zEntity, Framework::StreamWriter* zWriter) const;
+    virtual void createSuperEntity(Entity* zEntity) const;
 
 public:
-	virtual Entity* loadEntity(Framework::StreamReader* zReader) const;
-	virtual void saveEntity(Entity* zEntity, Framework::StreamWriter* zWriter) const;
+    virtual Entity* loadEntity(Framework::StreamReader* zReader) const;
+    virtual void saveEntity(
+        Entity* zEntity, Framework::StreamWriter* zWriter) const;
     virtual Entity* createEntityAt(
         Framework::Vec3<float> position, int dimensionId) const;
     virtual Entity* createEntity(Framework::Vec3<float> position,
         int dimensionId,
         int entityId) const = 0;
 
-	int getId() const;
-	const ModelInfo& getModel() const;
+    int getId() const;
+    const ModelInfo& getModel() const;
 };

+ 9 - 9
FactoryCraft/FastNoiseWrapper.cpp

@@ -2,29 +2,29 @@
 
 FastNoiseWrapper::FastNoiseWrapper(FastNoiseLite* noise, int seed)
 {
-	this->noise = noise;
-	this->seed = seed;
-	this->multiplier = 1.f;
+    this->noise = noise;
+    this->seed = seed;
+    this->multiplier = 1.f;
 }
 
 FastNoiseWrapper::~FastNoiseWrapper()
 {
-	delete noise;
+    delete noise;
 }
 
 void FastNoiseWrapper::setMultiplier(float multiplier)
 {
-	assert(multiplier > 0);
-	this->multiplier = multiplier;
+    assert(multiplier > 0);
+    this->multiplier = multiplier;
 }
 
 int FastNoiseWrapper::getSeed() const
 {
-	return seed;
+    return seed;
 }
 
 double FastNoiseWrapper::getNoise(double x, double y, double z)
 {
-	// scale the noise from 0 to 1
-	return (noise->GetNoise(x, y, z) * multiplier + 1) / 2;
+    // scale the noise from 0 to 1
+    return (noise->GetNoise(x, y, z) * multiplier + 1) / 2;
 }

+ 9 - 9
FactoryCraft/FastNoiseWrapper.h

@@ -1,18 +1,18 @@
 #pragma once
-#include "Noise.h"
 #include "FastNoiseLite.h"
+#include "Noise.h"
 
 class FastNoiseWrapper : public Noise
 {
 private:
-	int seed;
-	float multiplier;
-	FastNoiseLite* noise;
+    int seed;
+    float multiplier;
+    FastNoiseLite* noise;
 
 public:
-	FastNoiseWrapper(FastNoiseLite* noise, int seed);
-	~FastNoiseWrapper();
-	void setMultiplier(float multiplier);
-	int getSeed() const;
-	double getNoise(double x, double y, double z);
+    FastNoiseWrapper(FastNoiseLite* noise, int seed);
+    ~FastNoiseWrapper();
+    void setMultiplier(float multiplier);
+    int getSeed() const;
+    double getNoise(double x, double y, double z);
 };

+ 105 - 102
FactoryCraft/Game.h

@@ -1,21 +1,21 @@
 #pragma once
 
-#include <Text.h>
+#include <Critical.h>
+#include <Network.h>
 #include <Punkt.h>
+#include <Text.h>
 #include <Thread.h>
-#include <Network.h>
-#include <Critical.h>
 
+#include "Constants.h"
 #include "Dimension.h"
+#include "InMemoryBuffer.h"
 #include "Player.h"
+#include "RecipieLoader.h"
+#include "Server.h"
+#include "TickOrganizer.h"
 #include "WorldGenerator.h"
-#include "Constants.h"
-#include "WorldUpdate.h"
 #include "WorldLoader.h"
-#include "TickOrganizer.h"
-#include "Server.h"
-#include "InMemoryBuffer.h"
-#include "RecipieLoader.h"
+#include "WorldUpdate.h"
 
 class FCKlient;
 
@@ -24,110 +24,113 @@ char* randomKey(int& len);
 class GameClient : public Framework::Thread
 {
 private:
-	Player* zPlayer;
-	FCKlient* client;
-	Critical background;
-	Critical foreground;
-	Critical other;
-	Framework::Synchronizer updateSync;
-	RCArray<InMemoryBuffer> requests;
-	RCArray<WorldUpdate> updateQueue;
-	RCArray<NetworkMessage> backgroundQueue;
-	RCArray<NetworkMessage> foregroundQueue;
-	Framework::Synchronizer foregroundQueueSync;
-	Framework::Synchronizer backgroundQueueSync;
-	Critical queueCs;
-	Framework::Synchronizer emptyForegroundQueueSync;
-	Framework::Synchronizer emptyBackgroundQueueSync;
-	int viewDistance;
-	bool first;
-	bool online;
-	bool finished;
-	bool backgroundFinished;
-	bool foregroundFinished;
+    Player* zPlayer;
+    FCKlient* client;
+    Critical background;
+    Critical foreground;
+    Critical other;
+    Framework::Synchronizer updateSync;
+    RCArray<InMemoryBuffer> requests;
+    RCArray<WorldUpdate> updateQueue;
+    RCArray<NetworkMessage> backgroundQueue;
+    RCArray<NetworkMessage> foregroundQueue;
+    Framework::Synchronizer foregroundQueueSync;
+    Framework::Synchronizer backgroundQueueSync;
+    Critical queueCs;
+    Framework::Synchronizer emptyForegroundQueueSync;
+    Framework::Synchronizer emptyBackgroundQueueSync;
+    int viewDistance;
+    bool first;
+    bool online;
+    bool finished;
+    bool backgroundFinished;
+    bool foregroundFinished;
 
 public:
-	GameClient(Player* zPlayer, FCKlient* client);
-	~GameClient();
+    GameClient(Player* zPlayer, FCKlient* client);
+    ~GameClient();
 
-	void thread() override;
-	void sendWorldUpdate(WorldUpdate* update);
-	void reply();
-	void logout();
-	void addMessage(StreamReader* reader);
-	bool isOnline() const;
-	void sendResponse(NetworkMessage* response);
-	Player* zEntity() const;
-	void sendTypes();
+    void thread() override;
+    void sendWorldUpdate(WorldUpdate* update);
+    void reply();
+    void logout();
+    void addMessage(StreamReader* reader);
+    bool isOnline() const;
+    void sendResponse(NetworkMessage* response);
+    Player* zEntity() const;
+    void sendTypes();
 
-	class Message
-	{
-	public:
-		inline const static unsigned char TERMINATE = 1;
-		inline const static unsigned char WORLD_UPDATE = 2;
-		inline const static unsigned char API_MESSAGE = 3;
-		inline const static unsigned char POSITION_UPDATE = 4;
-	};
+    class Message
+    {
+    public:
+        inline static const unsigned char TERMINATE = 1;
+        inline static const unsigned char WORLD_UPDATE = 2;
+        inline static const unsigned char API_MESSAGE = 3;
+        inline static const unsigned char POSITION_UPDATE = 4;
+    };
 };
 
 class Game : public virtual Framework::Thread
 {
 private:
-	Framework::Text name;
-	Framework::RCArray<Dimension>* dimensions;
-	Framework::RCArray<WorldUpdate>* updates;
-	Framework::RCArray<GameClient>* clients;
-	Framework::Array<std::function<void()>> actions;
-	Critical actionsCs;
-	TickOrganizer* ticker;
-	Framework::Text path;
-	bool stop;
-	__int64 tickId;
-	Critical cs;
-	int nextEntityId;
-	WorldGenerator* generator;
-	WorldLoader* loader;
-	RecipieLoader recipies;
-	double totalTickTime;
-	int tickCounter;
+    Framework::Text name;
+    Framework::RCArray<Dimension>* dimensions;
+    Framework::RCArray<WorldUpdate>* updates;
+    Framework::RCArray<GameClient>* clients;
+    Framework::Array<std::function<void()>> actions;
+    Critical actionsCs;
+    TickOrganizer* ticker;
+    Framework::Text path;
+    bool stop;
+    __int64 tickId;
+    Critical cs;
+    int nextEntityId;
+    WorldGenerator* generator;
+    WorldLoader* loader;
+    RecipieLoader recipies;
+    double totalTickTime;
+    int tickCounter;
+
+    void thread() override;
 
-	void thread() override;
+    Game(Framework::Text name, Framework::Text worldsDir);
 
-	Game(Framework::Text name, Framework::Text worldsDir);
-	
 public:
-	~Game();
-	void initialize();
-	void api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin);
-	void updateLightning(int dimensionId, Vec3<int> location);
-	void updateLightningWithoutWait(int dimensionId, Vec3<int> location);
-	void broadcastMessage(NetworkMessage* response);
-	void sendMessage(NetworkMessage* response, Entity* zTargetPlayer);
-	bool requestWorldUpdate(WorldUpdate* update);
-	bool checkPlayer(Framework::Text name, Framework::Text secret);
-	bool existsPlayer(Framework::Text name);
-	Framework::Text createPlayer(Framework::Text name);
-	GameClient* addPlayer(FCKlient* client, Framework::Text name);
-	bool doesChunkExist(int x, int y, int dimension);
-	bool isChunkLoaded(int x, int y, int dimension) const;
-	Framework::Either<Block*, int> zBlockAt(Framework::Vec3<int> location, int dimension) const;
-	Block* zRealBlockInstance(Framework::Vec3<int> location, int dimension);
-	Dimension* zDimension(int id) const;
-	static Framework::Punkt getChunkCenter(int x, int y);
-	Area getChunckArea(Punkt center) const;
-	Framework::Text getWorldDirectory() const;
-	void requestArea(Area area);
-	void save() const;
-	void requestStop();
-	void addDimension(Dimension* d);
-	int getNextEntityId();
-	WorldGenerator* zGenerator() const;
-	Entity* zEntity(int id, int dimensionId) const;
-	Entity* zEntity(int id) const;
-	Entity* zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter);
-	const RecipieLoader& getRecipies() const;
-	void doLater(std::function<void()> action);
+    ~Game();
+    void initialize();
+    void api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin);
+    void updateLightning(int dimensionId, Vec3<int> location);
+    void updateLightningWithoutWait(int dimensionId, Vec3<int> location);
+    void broadcastMessage(NetworkMessage* response);
+    void sendMessage(NetworkMessage* response, Entity* zTargetPlayer);
+    bool requestWorldUpdate(WorldUpdate* update);
+    bool checkPlayer(Framework::Text name, Framework::Text secret);
+    bool existsPlayer(Framework::Text name);
+    Framework::Text createPlayer(Framework::Text name);
+    GameClient* addPlayer(FCKlient* client, Framework::Text name);
+    bool doesChunkExist(int x, int y, int dimension);
+    bool isChunkLoaded(int x, int y, int dimension) const;
+    Framework::Either<Block*, int> zBlockAt(
+        Framework::Vec3<int> location, int dimension) const;
+    Block* zRealBlockInstance(Framework::Vec3<int> location, int dimension);
+    Dimension* zDimension(int id) const;
+    static Framework::Punkt getChunkCenter(int x, int y);
+    Area getChunckArea(Punkt center) const;
+    Framework::Text getWorldDirectory() const;
+    void requestArea(Area area);
+    void save() const;
+    void requestStop();
+    void addDimension(Dimension* d);
+    int getNextEntityId();
+    WorldGenerator* zGenerator() const;
+    Entity* zEntity(int id, int dimensionId) const;
+    Entity* zEntity(int id) const;
+    Entity* zNearestEntity(int dimensionId,
+        Framework::Vec3<float> pos,
+        std::function<bool(Entity*)> filter);
+    const RecipieLoader& getRecipies() const;
+    void doLater(std::function<void()> action);
 
-	static Game* INSTANCE;
-	static void initialize(Framework::Text name, Framework::Text worldsDir);
+    static Game* INSTANCE;
+    static void initialize(Framework::Text name, Framework::Text worldsDir);
 };

+ 84 - 73
FactoryCraft/GeneratedStructure.cpp

@@ -1,107 +1,118 @@
 #include "GeneratedStructure.h"
+
 #include "GenerationTemplate.h"
-#include "NoBlock.h"
 #include "MultiblockStructure.h"
+#include "NoBlock.h"
 
 using namespace Framework;
 
-GeneratedStructure::GeneratedStructure(GenerationTemplate* t, Framework::Vec3<int> originPos, Framework::Vec3<int> size, Framework::Vec3<int> minAffectedPos)
-	: ReferenceCounter(),
-	size(size),
-	minAffectedPos(minAffectedPos),
-	originPos(originPos),
-	t(t),
-	multiblock(0)
+GeneratedStructure::GeneratedStructure(GenerationTemplate* t,
+    Framework::Vec3<int> originPos,
+    Framework::Vec3<int> size,
+    Framework::Vec3<int> minAffectedPos)
+    : ReferenceCounter(),
+      size(size),
+      minAffectedPos(minAffectedPos),
+      originPos(originPos),
+      t(t),
+      multiblock(0)
 {
-	blockIds = new int[size.x * size.y * size.z];
-	blocks = new Block * [size.x * size.y * size.z];
-	memset(blockIds, 0, sizeof(int) * size.x * size.y * size.z);
-	memset(blocks, 0, sizeof(Block*) * size.x * size.y * size.z);
+    blockIds = new int[size.x * size.y * size.z];
+    blocks = new Block*[size.x * size.y * size.z];
+    memset(blockIds, 0, sizeof(int) * size.x * size.y * size.z);
+    memset(blocks, 0, sizeof(Block*) * size.x * size.y * size.z);
 }
 
 GeneratedStructure::~GeneratedStructure()
 {
-	for (int i = 0; i < size.x * size.y * size.z; i++)
-	{
-		if (blocks[i])
-			blocks[i]->release();
-	}
-	delete[] blockIds;
-	delete[] blocks;
-	t->release();
-	if (multiblock)
-		multiblock->release();
+    for (int i = 0; i < size.x * size.y * size.z; i++)
+    {
+        if (blocks[i]) blocks[i]->release();
+    }
+    delete[] blockIds;
+    delete[] blocks;
+    t->release();
+    if (multiblock) multiblock->release();
 }
 
-void GeneratedStructure::setBlockAt(Framework::Either<Block*, int> block, Framework::Vec3<int> localPos)
+void GeneratedStructure::setBlockAt(
+    Framework::Either<Block*, int> block, Framework::Vec3<int> localPos)
 {
-	assert(localPos.x >= 0 && localPos.y >= 0 && localPos.z >= 0 && localPos.x < size.x&& localPos.y < size.y&& localPos.z < size.z);
-	int index = ((localPos.x * size.y) + localPos.y) * size.z + localPos.z;
-	if (block.isA())
-		blocks[index] = block;
-	else
-		blockIds[index] = block;
+    assert(localPos.x >= 0 && localPos.y >= 0 && localPos.z >= 0
+           && localPos.x < size.x && localPos.y < size.y
+           && localPos.z < size.z);
+    int index = ((localPos.x * size.y) + localPos.y) * size.z + localPos.z;
+    if (block.isA())
+        blocks[index] = block;
+    else
+        blockIds[index] = block;
 }
 
 bool GeneratedStructure::isBlockAffected(Framework::Vec3<int> location) const
 {
-	Framework::Vec3<int> localPos = location - minAffectedPos;
-	if (localPos.x >= 0 && localPos.y >= 0 && localPos.z >= 0 && localPos.x < size.x && localPos.y < size.y && localPos.z < size.z)
-	{
-		int index = ((localPos.x * size.y) + localPos.y) * size.z + localPos.z;
-		return blocks[index] || blockIds[index];
-	}
-	return 0;
+    Framework::Vec3<int> localPos = location - minAffectedPos;
+    if (localPos.x >= 0 && localPos.y >= 0 && localPos.z >= 0
+        && localPos.x < size.x && localPos.y < size.y && localPos.z < size.z)
+    {
+        int index = ((localPos.x * size.y) + localPos.y) * size.z + localPos.z;
+        return blocks[index] || blockIds[index];
+    }
+    return 0;
 }
 
-Framework::Either<Block*, int> GeneratedStructure::generateBlockAt(Framework::Vec3<int> location) const
+Framework::Either<Block*, int> GeneratedStructure::generateBlockAt(
+    Framework::Vec3<int> location) const
 {
-	Framework::Vec3<int> localPos = location - minAffectedPos;
-	if (localPos.x >= 0 && localPos.y >= 0 && localPos.z >= 0 && localPos.x < size.x && localPos.y < size.y && localPos.z < size.z)
-	{
-		int index = ((localPos.x * size.y) + localPos.y) * size.z + localPos.z;
-		if (multiblock)
-		{
-			multiblock->addMemberPosition(minAffectedPos + localPos);
-			if (blocks[index])
-			{
-				blocks[index]->addToStructure(dynamic_cast<MultiblockStructure*>(multiblock->getThis()));
-				return blocks[index];
-			}
-			if (blockIds[index] && blockIds[index] != BlockTypeEnum::AIR)
-			{
-				Block* result = StaticRegistry<BlockType>::INSTANCE.zElement(blockIds[index])->createBlockAt(minAffectedPos + localPos, 0);
-				if (result)
-				{
-					result->addToStructure(dynamic_cast<MultiblockStructure*>(multiblock->getThis()));
-					return result;
-				}
-			}
-			return blockIds[index];
-		}
-		else
-		{
-			if (blocks[index])
-				return blocks[index];
-			return blockIds[index];
-		}
-	}
-	return 0;
+    Framework::Vec3<int> localPos = location - minAffectedPos;
+    if (localPos.x >= 0 && localPos.y >= 0 && localPos.z >= 0
+        && localPos.x < size.x && localPos.y < size.y && localPos.z < size.z)
+    {
+        int index = ((localPos.x * size.y) + localPos.y) * size.z + localPos.z;
+        if (multiblock)
+        {
+            multiblock->addMemberPosition(minAffectedPos + localPos);
+            if (blocks[index])
+            {
+                blocks[index]->addToStructure(
+                    dynamic_cast<MultiblockStructure*>(multiblock->getThis()));
+                return blocks[index];
+            }
+            if (blockIds[index] && blockIds[index] != BlockTypeEnum::AIR)
+            {
+                Block* result
+                    = StaticRegistry<BlockType>::INSTANCE
+                          .zElement(blockIds[index])
+                          ->createBlockAt(minAffectedPos + localPos, 0);
+                if (result)
+                {
+                    result->addToStructure(dynamic_cast<MultiblockStructure*>(
+                        multiblock->getThis()));
+                    return result;
+                }
+            }
+            return blockIds[index];
+        }
+        else
+        {
+            if (blocks[index]) return blocks[index];
+            return blockIds[index];
+        }
+    }
+    return 0;
 }
 
 void GeneratedStructure::addAllBlocksToStructure(MultiblockStructure* structure)
 {
-	if (multiblock)
-		multiblock->release();
-	multiblock = structure;
+    if (multiblock) multiblock->release();
+    multiblock = structure;
 }
 
 Framework::Vec3<int> GeneratedStructure::getOriginPos() const
 {
-	return originPos;
+    return originPos;
 }
 
 GenerationTemplate* GeneratedStructure::zTemplate() const
 {
-	return t;
+    return t;
 }

+ 21 - 16
FactoryCraft/GeneratedStructure.h

@@ -1,8 +1,8 @@
 #pragma once
 
+#include <Either.h>
 #include <ReferenceCounter.h>
 #include <Vec3.h>
-#include <Either.h>
 
 #include "Block.h"
 
@@ -12,22 +12,27 @@ class MultiblockStructure;
 class GeneratedStructure : public Framework::ReferenceCounter
 {
 private:
-	int* blockIds;
-	Block** blocks;
-	Framework::Vec3<int> size;
-	Framework::Vec3<int> minAffectedPos;
-	Framework::Vec3<int> originPos;
-	GenerationTemplate* t;
-	MultiblockStructure* multiblock;
+    int* blockIds;
+    Block** blocks;
+    Framework::Vec3<int> size;
+    Framework::Vec3<int> minAffectedPos;
+    Framework::Vec3<int> originPos;
+    GenerationTemplate* t;
+    MultiblockStructure* multiblock;
 
 public:
-	GeneratedStructure(GenerationTemplate* t, Framework::Vec3<int> originPos, Framework::Vec3<int> size, Framework::Vec3<int> minAffectedPos);
-	~GeneratedStructure();
-	void setBlockAt(Framework::Either<Block*, int> block, Framework::Vec3<int> localPos);
-	bool isBlockAffected(Framework::Vec3<int> location) const;
-	Framework::Either<Block*, int> generateBlockAt(Framework::Vec3<int> location) const;
-	void addAllBlocksToStructure(MultiblockStructure* structure);
+    GeneratedStructure(GenerationTemplate* t,
+        Framework::Vec3<int> originPos,
+        Framework::Vec3<int> size,
+        Framework::Vec3<int> minAffectedPos);
+    ~GeneratedStructure();
+    void setBlockAt(
+        Framework::Either<Block*, int> block, Framework::Vec3<int> localPos);
+    bool isBlockAffected(Framework::Vec3<int> location) const;
+    Framework::Either<Block*, int> generateBlockAt(
+        Framework::Vec3<int> location) const;
+    void addAllBlocksToStructure(MultiblockStructure* structure);
 
-	Framework::Vec3<int> getOriginPos() const;
-	GenerationTemplate* zTemplate() const;
+    Framework::Vec3<int> getOriginPos() const;
+    GenerationTemplate* zTemplate() const;
 };

+ 20 - 12
FactoryCraft/GenerationTemplate.h

@@ -9,20 +9,28 @@
 class GenerationTemplate : public Framework::ReferenceCounter
 {
 private:
-	float propability;
-	int minSurfaceDist;
-	int maxSurfaceDist;
-	Framework::Vec3<int> minPosOffset;
-	Framework::Vec3<int> maxSize;
+    float propability;
+    int minSurfaceDist;
+    int maxSurfaceDist;
+    Framework::Vec3<int> minPosOffset;
+    Framework::Vec3<int> maxSize;
 
 public:
-	GenerationTemplate(float propability, int minSurfaceDist, int maxSurfaceDist, Framework::Vec3<int> minPosOffset, Framework::Vec3<int> maxSize);
+    GenerationTemplate(float propability,
+        int minSurfaceDist,
+        int maxSurfaceDist,
+        Framework::Vec3<int> minPosOffset,
+        Framework::Vec3<int> maxSize);
 
-	virtual bool canEffect(Framework::Vec3<int> location, Framework::Vec3<int> affectedLocation) const;
-	virtual bool isGenerationPossable(Framework::Vec3<int> location, int distToSurface) const;
-	virtual GeneratedStructure* generateAt(Framework::Vec3<int> location, Noise* zNoise, int dimensionId) = 0;
+    virtual bool canEffect(Framework::Vec3<int> location,
+        Framework::Vec3<int> affectedLocation) const;
+    virtual bool isGenerationPossable(
+        Framework::Vec3<int> location, int distToSurface) const;
+    virtual GeneratedStructure* generateAt(
+        Framework::Vec3<int> location, Noise* zNoise, int dimensionId)
+        = 0;
 
-	float getPropability() const;
-	Framework::Vec3<int> getMinAffectedOffset() const;
-	Framework::Vec3<int> getMaxAffectedOffset() const;
+    float getPropability() const;
+    Framework::Vec3<int> getMinAffectedOffset() const;
+    Framework::Vec3<int> getMaxAffectedOffset() const;
 };

+ 2 - 1
FactoryCraft/GrasslandBiom.cpp

@@ -7,7 +7,8 @@
 #include "NoBlock.h"
 #include "TreeTemplate.h"
 
-GrasslandBiom::GrasslandBiom() : BiomGenerator()
+GrasslandBiom::GrasslandBiom()
+    : BiomGenerator()
 {
     addTemplateGenerator(new TreeTemplate(0.02f,
         BlockTypeEnum::WOOD_BIRCH,

+ 10 - 7
FactoryCraft/GrasslandBiom.h

@@ -5,13 +5,16 @@
 
 class GrasslandBiom : public BiomGenerator
 {
-	Noise* heightNoise;
+    Noise* heightNoise;
 
 public:
-	GrasslandBiom();
-	~GrasslandBiom();
-	Framework::Either<Block*, int> generateSurfaceBlock(int x, int y, int z) override;
-	Framework::Either<Block*, int> generateBelowSurfaceBlock(int x, int y, int z) override;
-	Framework::Either<Block*, int> generateCaveBlock(int x, int y, int z) override;
-	Noise* zHeightMapNoise(int seed) override;
+    GrasslandBiom();
+    ~GrasslandBiom();
+    Framework::Either<Block*, int> generateSurfaceBlock(
+        int x, int y, int z) override;
+    Framework::Either<Block*, int> generateBelowSurfaceBlock(
+        int x, int y, int z) override;
+    Framework::Either<Block*, int> generateCaveBlock(
+        int x, int y, int z) override;
+    Noise* zHeightMapNoise(int seed) override;
 };

+ 707 - 638
FactoryCraft/Inventory.cpp

@@ -1,747 +1,816 @@
+#include "Inventory.h"
+
 #include <InMemoryBuffer.h>
 
-#include "Inventory.h"
-#include "ItemFilter.h"
-#include "Constants.h"
 #include "Area.h"
-#include "NetworkMessage.h"
+#include "Constants.h"
 #include "Entity.h"
 #include "Game.h"
-
+#include "ItemFilter.h"
+#include "NetworkMessage.h"
 
 using namespace Framework;
 
-
-
-InventoryInteraction::InventoryInteraction(Inventory* current, Inventory* other, Direction dir)
-	: current(current),
-	other(other),
-	dir(dir)
+InventoryInteraction::InventoryInteraction(
+    Inventory* current, Inventory* other, Direction dir)
+    : current(current),
+      other(other),
+      dir(dir)
 {
-	lock();
+    lock();
 }
 
-InventoryInteraction::InventoryInteraction(const InventoryInteraction& interaction)
-	: InventoryInteraction(interaction.current, interaction.other, interaction.dir)
+InventoryInteraction::InventoryInteraction(
+    const InventoryInteraction& interaction)
+    : InventoryInteraction(
+        interaction.current, interaction.other, interaction.dir)
 {}
 
 InventoryInteraction::~InventoryInteraction()
 {
-	unlock();
+    unlock();
 }
 
 void InventoryInteraction::lock()
 {
-	if (!current || !other) return;
-	if (current->location.x < other->location.x)
-	{
-		current->cs.lock();
-		other->cs.lock();
-		return;
-	}
-	else if (current->location.x == other->location.x)
-	{
-		if (current->location.y < other->location.y)
-		{
-			current->cs.lock();
-			other->cs.lock();
-			return;
-		}
-		else if (current->location.y == other->location.y)
-		{
-			if (current->location.z < other->location.z)
-			{
-				current->cs.lock();
-				other->cs.lock();
-				return;
-			}
-		}
-	}
-	other->cs.lock();
-	current->cs.lock();
+    if (!current || !other) return;
+    if (current->location.x < other->location.x)
+    {
+        current->cs.lock();
+        other->cs.lock();
+        return;
+    }
+    else if (current->location.x == other->location.x)
+    {
+        if (current->location.y < other->location.y)
+        {
+            current->cs.lock();
+            other->cs.lock();
+            return;
+        }
+        else if (current->location.y == other->location.y)
+        {
+            if (current->location.z < other->location.z)
+            {
+                current->cs.lock();
+                other->cs.lock();
+                return;
+            }
+        }
+    }
+    other->cs.lock();
+    current->cs.lock();
 }
 
 void InventoryInteraction::unlock()
 {
-	if (!current || !other) return;
-	if (current->location.x < other->location.x)
-	{
-		current->cs.unlock();
-		other->cs.unlock();
-		return;
-	}
-	else if (current->location.x == other->location.x)
-	{
-		if (current->location.y < other->location.y)
-		{
-			current->cs.unlock();
-			other->cs.unlock();
-			return;
-		}
-		else if (current->location.y == other->location.y)
-		{
-			if (current->location.z < other->location.z)
-			{
-				current->cs.unlock();
-				other->cs.unlock();
-				return;
-			}
-		}
-	}
-	other->cs.unlock();
-	current->cs.unlock();
-}
-
-void InventoryInteraction::transaction(Inventory* zSource, Inventory* zTarget, ItemFilter* zFilter, Direction sourceView, Direction targetView, int count)
-{
-	for (auto sourceSlot = zSource->pullSlotsOrder->begin(); sourceSlot; )
-	{
-		while (sourceSlot && (sourceSlot->getNumberOfItems() == 0 || (zFilter && !zFilter->matchSourceSlot(sourceSlot))))
-			sourceSlot++;
-		if (!sourceSlot) break;
-		// TODO: use target cache ot get list of slots that already contains the source item
-		bool needNext = 1;
-		for (auto targetSlot = zTarget->pushSlotsOrder->begin(); targetSlot; )
-		{
-			while (targetSlot && (targetSlot->isFull() || (zFilter && !zFilter->matchTargetSlot(targetSlot))))
-				targetSlot++;
-			if (!targetSlot) break;
-			needNext &= !Inventory::unsafeMove(zSource, zTarget, sourceSlot, targetSlot, sourceView, targetView, count);
-			if (count == 0)
-				return;
-			if (sourceSlot->getNumberOfItems() == 0)
-				break;
-		}
-		if (needNext)
-			sourceSlot++;
-	}
-}
-
-
-InventoryInteraction& InventoryInteraction::operator=(const InventoryInteraction& data)
-{
-	if (&data == this) return *this;
-	unlock();
-	current = data.current;
-	other = data.other;
-	dir = data.dir;
-	lock();
-	return *this;
+    if (!current || !other) return;
+    if (current->location.x < other->location.x)
+    {
+        current->cs.unlock();
+        other->cs.unlock();
+        return;
+    }
+    else if (current->location.x == other->location.x)
+    {
+        if (current->location.y < other->location.y)
+        {
+            current->cs.unlock();
+            other->cs.unlock();
+            return;
+        }
+        else if (current->location.y == other->location.y)
+        {
+            if (current->location.z < other->location.z)
+            {
+                current->cs.unlock();
+                other->cs.unlock();
+                return;
+            }
+        }
+    }
+    other->cs.unlock();
+    current->cs.unlock();
+}
+
+void InventoryInteraction::transaction(Inventory* zSource,
+    Inventory* zTarget,
+    ItemFilter* zFilter,
+    Direction sourceView,
+    Direction targetView,
+    int count)
+{
+    for (auto sourceSlot = zSource->pullSlotsOrder->begin(); sourceSlot;)
+    {
+        while (sourceSlot
+               && (sourceSlot->getNumberOfItems() == 0
+                   || (zFilter && !zFilter->matchSourceSlot(sourceSlot))))
+            sourceSlot++;
+        if (!sourceSlot) break;
+        // TODO: use target cache ot get list of slots that already contains the
+        // source item
+        bool needNext = 1;
+        for (auto targetSlot = zTarget->pushSlotsOrder->begin(); targetSlot;)
+        {
+            while (targetSlot
+                   && (targetSlot->isFull()
+                       || (zFilter && !zFilter->matchTargetSlot(targetSlot))))
+                targetSlot++;
+            if (!targetSlot) break;
+            needNext &= !Inventory::unsafeMove(zSource,
+                zTarget,
+                sourceSlot,
+                targetSlot,
+                sourceView,
+                targetView,
+                count);
+            if (count == 0) return;
+            if (sourceSlot->getNumberOfItems() == 0) break;
+        }
+        if (needNext) sourceSlot++;
+    }
+}
+
+InventoryInteraction& InventoryInteraction::operator=(
+    const InventoryInteraction& data)
+{
+    if (&data == this) return *this;
+    unlock();
+    current = data.current;
+    other = data.other;
+    dir = data.dir;
+    lock();
+    return *this;
 }
 
 void InventoryInteraction::endInteraction()
 {
-	unlock();
-	current = 0;
-	other = 0;
+    unlock();
+    current = 0;
+    other = 0;
 }
 
 void InventoryInteraction::pullItems(int count, ItemFilter* zFilter)
 {
-	if (!current || !other) return;
-	transaction(other, current, zFilter, getOppositeDirection(dir), dir, count);
+    if (!current || !other) return;
+    transaction(other, current, zFilter, getOppositeDirection(dir), dir, count);
 }
 
 void InventoryInteraction::pushItems(int count, ItemFilter* zFilter)
 {
-	if (!current || !other) return;
-	transaction(current, other, zFilter, dir, getOppositeDirection(dir), count);
+    if (!current || !other) return;
+    transaction(current, other, zFilter, dir, getOppositeDirection(dir), count);
 }
 
-
 Inventory::Inventory(const Framework::Vec3<float> location, bool hasInventory)
-	: ReferenceCounter(),
-	nextSlotId(1),
-	location(location)
-{
-	if (hasInventory)
-	{
-		pullSlotsOrder = new Framework::RCArray<ItemSlot>();
-		pushSlotsOrder = new Framework::RCArray<ItemSlot>();
-		itemCache = new Framework::HashMap<int, Framework::Array<ItemSlot*>*>(ITEM_CACHE_SIZE, std::_Identity<int>());
-	}
-	else
-	{
-		pullSlotsOrder = 0;
-		pushSlotsOrder = 0;
-		itemCache = 0;
-	}
+    : ReferenceCounter(),
+      nextSlotId(1),
+      location(location)
+{
+    if (hasInventory)
+    {
+        pullSlotsOrder = new Framework::RCArray<ItemSlot>();
+        pushSlotsOrder = new Framework::RCArray<ItemSlot>();
+        itemCache = new Framework::HashMap<int, Framework::Array<ItemSlot*>*>(
+            ITEM_CACHE_SIZE, std::_Identity<int>());
+    }
+    else
+    {
+        pullSlotsOrder = 0;
+        pushSlotsOrder = 0;
+        itemCache = 0;
+    }
 }
 
 Inventory::~Inventory()
 {
-	if (pullSlotsOrder)
-		pullSlotsOrder->release();
-	if (pushSlotsOrder)
-		pushSlotsOrder->release();
-	if (itemCache)
-		itemCache->release();
+    if (pullSlotsOrder) pullSlotsOrder->release();
+    if (pushSlotsOrder) pushSlotsOrder->release();
+    if (itemCache) itemCache->release();
 }
 
 void Inventory::updateCache(ItemSlot* zSlot, int beforeKey)
 {
-	if (!itemCache)
-		return;
-	int key = zSlot->zStack() ? zSlot->zStack()->zItem()->zItemType()->getId() : -1;
-	if (key == beforeKey)
-		return;
-	if (beforeKey >= 0)
-	{
-		auto tmp = itemCache->safeGet(key, 0);
-		if (tmp)
-			tmp->removeValue(zSlot);
-	}
-	if (zSlot->zStack())
-	{
-		auto tmp = itemCache->safeGet(key, 0);
-		if (!tmp)
-		{
-			tmp = new Array<ItemSlot*>();
-			itemCache->put(key, tmp);
-		}
-		tmp->add(zSlot, 0);
-	}
+    if (!itemCache) return;
+    int key
+        = zSlot->zStack() ? zSlot->zStack()->zItem()->zItemType()->getId() : -1;
+    if (key == beforeKey) return;
+    if (beforeKey >= 0)
+    {
+        auto tmp = itemCache->safeGet(key, 0);
+        if (tmp) tmp->removeValue(zSlot);
+    }
+    if (zSlot->zStack())
+    {
+        auto tmp = itemCache->safeGet(key, 0);
+        if (!tmp)
+        {
+            tmp = new Array<ItemSlot*>();
+            itemCache->put(key, tmp);
+        }
+        tmp->add(zSlot, 0);
+    }
 }
 
 void Inventory::addSlot(ItemSlot* slot)
 {
-	cs.lock();
-	((ItemSlotIDSetter*)slot)->setId(nextSlotId++);
-	int pullPrio = slot->getPullPriority();
-	int pushPrio = slot->getPushPriority();
-	int index = 0;
-	for (auto stack : *pullSlotsOrder)
-	{
-		if (stack->getPullPriority() > pullPrio)
-			break;
-		index++;
-	}
-	pullSlotsOrder->add(dynamic_cast<ItemSlot*>(slot->getThis()), index);
-	index = 0;
-	for (auto stack : *pushSlotsOrder)
-	{
-		if (stack->getPushPriority() > pushPrio)
-			break;
-		index++;
-	}
-	pushSlotsOrder->add(slot, index);
-	updateCache(slot, -1);
-	cs.unlock();
+    cs.lock();
+    ((ItemSlotIDSetter*)slot)->setId(nextSlotId++);
+    int pullPrio = slot->getPullPriority();
+    int pushPrio = slot->getPushPriority();
+    int index = 0;
+    for (auto stack : *pullSlotsOrder)
+    {
+        if (stack->getPullPriority() > pullPrio) break;
+        index++;
+    }
+    pullSlotsOrder->add(dynamic_cast<ItemSlot*>(slot->getThis()), index);
+    index = 0;
+    for (auto stack : *pushSlotsOrder)
+    {
+        if (stack->getPushPriority() > pushPrio) break;
+        index++;
+    }
+    pushSlotsOrder->add(slot, index);
+    updateCache(slot, -1);
+    cs.unlock();
 }
 
 bool Inventory::allowPullStack(ItemSlot* zSlot, Direction dir) const
 {
-	return pullSlotsOrder;
-}
-
-bool Inventory::allowPushStack(ItemSlot* zSlot, Direction dir, const Item* zItem, int& count) const
-{
-	return pushSlotsOrder;
-}
-
-void Inventory::afterPullStack(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)
-{
-	NetworkMessage* msg = new NetworkMessage();
-	char* message = new char[9];
-	message[0] = 1; // set count of items
-	*(int*)(message + 1) = zSlot->getId();
-	*(int*)(message + 5) = zSlot->getNumberOfItems();
-	msg->setMessage(message, 9);
-	notyObservers(msg);
-	for (auto call : afterPullStackCalls)
-		call(zSlot, dir, zItem, count);
-}
-
-void Inventory::afterPushStack(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)
-{
-	if (zSlot->getNumberOfItems() > count)
-	{
-		NetworkMessage* msg = new NetworkMessage();
-		char* message = new char[9];
-		message[0] = 1; // set count of items
-		*(int*)(message + 1) = zSlot->getId();
-		*(int*)(message + 5) = zSlot->getNumberOfItems();
-		msg->setMessage(message, 9);
-		notyObservers(msg);
-	}
-	else
-	{
-		NetworkMessage* msg = new NetworkMessage();
-		char* message = new char[29];
-		message[0] = 2; // add new stack
-		*(int*)(message + 1) = zSlot->getId();
-		*(int*)(message + 5) = zSlot->getNumberOfItems();
-		const Item* zItem = zSlot->zStack()->zItem();
-		*(float*)(message + 9) = zItem->getHp();
-		*(float*)(message + 13) = zItem->getMaxHp();
-		*(float*)(message + 17) = zItem->getDurability();
-		*(float*)(message + 21) = zItem->getMaxDurability();
-		*(int*)(message + 25) = zItem->zItemType()->getId();
-		msg->setMessage(message, 29);
-		notyObservers(msg);
-	}
-	for (auto call : afterPushStackCalls)
-		call(zSlot, dir, zItem, count);
+    return pullSlotsOrder;
+}
+
+bool Inventory::allowPushStack(
+    ItemSlot* zSlot, Direction dir, const Item* zItem, int& count) const
+{
+    return pushSlotsOrder;
+}
+
+void Inventory::afterPullStack(
+    ItemSlot* zSlot, Direction dir, const Item* zItem, int count)
+{
+    NetworkMessage* msg = new NetworkMessage();
+    char* message = new char[9];
+    message[0] = 1; // set count of items
+    *(int*)(message + 1) = zSlot->getId();
+    *(int*)(message + 5) = zSlot->getNumberOfItems();
+    msg->setMessage(message, 9);
+    notyObservers(msg);
+    for (auto call : afterPullStackCalls)
+        call(zSlot, dir, zItem, count);
+}
+
+void Inventory::afterPushStack(
+    ItemSlot* zSlot, Direction dir, const Item* zItem, int count)
+{
+    if (zSlot->getNumberOfItems() > count)
+    {
+        NetworkMessage* msg = new NetworkMessage();
+        char* message = new char[9];
+        message[0] = 1; // set count of items
+        *(int*)(message + 1) = zSlot->getId();
+        *(int*)(message + 5) = zSlot->getNumberOfItems();
+        msg->setMessage(message, 9);
+        notyObservers(msg);
+    }
+    else
+    {
+        NetworkMessage* msg = new NetworkMessage();
+        char* message = new char[29];
+        message[0] = 2; // add new stack
+        *(int*)(message + 1) = zSlot->getId();
+        *(int*)(message + 5) = zSlot->getNumberOfItems();
+        const Item* zItem = zSlot->zStack()->zItem();
+        *(float*)(message + 9) = zItem->getHp();
+        *(float*)(message + 13) = zItem->getMaxHp();
+        *(float*)(message + 17) = zItem->getDurability();
+        *(float*)(message + 21) = zItem->getMaxDurability();
+        *(int*)(message + 25) = zItem->zItemType()->getId();
+        msg->setMessage(message, 29);
+        notyObservers(msg);
+    }
+    for (auto call : afterPushStackCalls)
+        call(zSlot, dir, zItem, count);
 }
 
 void Inventory::loadInventory(Framework::StreamReader* zReader)
 {
-	if (itemCache)
-	{
-		for (auto stack : *pushSlotsOrder)
-		{
-			int size = 0;
-			zReader->lese((char*)&size, 4);
-			if (size != 0)
-			{
-				int id = 0;
-				zReader->lese((char*)&id, 4);
-				Item* item = StaticRegistry<ItemType>::INSTANCE.zElement(id)->loadItem(zReader);
-				stack->addItems(new ItemStack(item, size), NO_DIRECTION);
-			}
-		}
-	}
+    if (itemCache)
+    {
+        for (auto stack : *pushSlotsOrder)
+        {
+            int size = 0;
+            zReader->lese((char*)&size, 4);
+            if (size != 0)
+            {
+                int id = 0;
+                zReader->lese((char*)&id, 4);
+                Item* item
+                    = StaticRegistry<ItemType>::INSTANCE.zElement(id)->loadItem(
+                        zReader);
+                stack->addItems(new ItemStack(item, size), NO_DIRECTION);
+            }
+        }
+    }
 }
 
 void Inventory::saveInventory(Framework::StreamWriter* zWriter)
 {
-	if (itemCache)
-	{
-		for (auto slot : *pushSlotsOrder)
-		{
-			const ItemStack* stack = slot->zStack();
-			int value = 0;
-			if (!stack || !stack->zItem())
-			{
-				zWriter->schreibe((char*)&value, 4);
-			}
-			else
-			{
-				value = stack->getSize();
-				zWriter->schreibe((char*)&value, 4);
-				value = stack->zItem()->zItemType()->getId();
-				zWriter->schreibe((char*)&value, 4);
-				stack->zItem()->zItemType()->saveItem(stack->zItem(), zWriter);
-			}
-		}
-	}
+    if (itemCache)
+    {
+        for (auto slot : *pushSlotsOrder)
+        {
+            const ItemStack* stack = slot->zStack();
+            int value = 0;
+            if (!stack || !stack->zItem())
+            {
+                zWriter->schreibe((char*)&value, 4);
+            }
+            else
+            {
+                value = stack->getSize();
+                zWriter->schreibe((char*)&value, 4);
+                value = stack->zItem()->zItemType()->getId();
+                zWriter->schreibe((char*)&value, 4);
+                stack->zItem()->zItemType()->saveItem(stack->zItem(), zWriter);
+            }
+        }
+    }
 }
 
 void Inventory::notyObservers(NetworkMessage* msg)
 {
-	cs.lock();
-	int index = 0;
-	Array<int> toDelete;
-	for (auto observer : observers)
-	{
-		Entity* e = Game::INSTANCE->zEntity(observer.getFirst());
-		if (e)
-		{
-			msg->addressGui(observer.getSecond());
-			Game::INSTANCE->sendMessage(msg->clone(), e);
-		}
-		else
-			toDelete.add(index, 0);
-		index++;
-	}
-	for (int i : toDelete)
-		observers.remove(i);
-	cs.unlock();
-	msg->release();
+    cs.lock();
+    int index = 0;
+    Array<int> toDelete;
+    for (auto observer : observers)
+    {
+        Entity* e = Game::INSTANCE->zEntity(observer.getFirst());
+        if (e)
+        {
+            msg->addressGui(observer.getSecond());
+            Game::INSTANCE->sendMessage(msg->clone(), e);
+        }
+        else
+            toDelete.add(index, 0);
+        index++;
+    }
+    for (int i : toDelete)
+        observers.remove(i);
+    cs.unlock();
+    msg->release();
 }
 
 void Inventory::removeObserver(Entity* zSource, Framework::Text id)
 {
-	cs.lock();
-	int index = 0;
-	for (auto observer : observers)
-	{
-		if (observer.getFirst() == zSource->getId() && observer.getSecond().istGleich(id))
-		{
-			observers.remove(index);
-			break;
-		}
-		index++;
-	}
-	cs.unlock();
+    cs.lock();
+    int index = 0;
+    for (auto observer : observers)
+    {
+        if (observer.getFirst() == zSource->getId()
+            && observer.getSecond().istGleich(id))
+        {
+            observers.remove(index);
+            break;
+        }
+        index++;
+    }
+    cs.unlock();
 }
 
 void Inventory::addObserver(Entity* zSource, Framework::Text id)
 {
-	cs.lock();
-	for (auto observer : observers)
-	{
-		if (observer.getFirst() == zSource->getId() && observer.getSecond().istGleich(id))
-		{
-			cs.unlock();
-			return;
-		}
-	}
-	observers.add(ImmutablePair<int, Text>(zSource->getId(), id));
-	cs.unlock();
-	for (auto call : observerAddedCalls)
-		call(zSource, id);
+    cs.lock();
+    for (auto observer : observers)
+    {
+        if (observer.getFirst() == zSource->getId()
+            && observer.getSecond().istGleich(id))
+        {
+            cs.unlock();
+            return;
+        }
+    }
+    observers.add(ImmutablePair<int, Text>(zSource->getId(), id));
+    cs.unlock();
+    for (auto call : observerAddedCalls)
+        call(zSource, id);
 }
 
 const ItemSlot* Inventory::zSlot(int id) const
 {
-	if (itemCache)
-	{
-		for (auto slot : *pushSlotsOrder)
-		{
-			if (slot->getId() == id)
-				return slot;
-		}
-	}
-	return 0;
-}
-
-void Inventory::localTransaction(Array< ItemSlot* >* zSourceSlots, Array< ItemSlot* >* zTargetSlots, ItemFilter* zFilter, int count, Direction outDir, Direction inDir)
-{
-	if (itemCache)
-	{
-		cs.lock();
-		auto sourceSlot = zSourceSlots ? zSourceSlots->begin() : pullSlotsOrder->begin();
-		while (true)
-		{
-			while (sourceSlot && (sourceSlot->getNumberOfItems() == 0 || (zFilter && !zFilter->matchSourceSlot(sourceSlot))))
-				sourceSlot++;
-			if (!sourceSlot)
-			{
-				cs.unlock();
-				return;
-			}
-			bool needNext = 1;
-			for (auto targetSlot = zTargetSlots->begin(); targetSlot; )
-			{
-				while (targetSlot && (targetSlot->isFull() || (zFilter && !zFilter->matchTargetSlot(targetSlot))))
-					targetSlot++;
-				if (!targetSlot) break;
-				needNext &= !Inventory::unsafeMove(this, this, sourceSlot, targetSlot, outDir, inDir, count);
-				if (count == 0)
-				{
-					cs.unlock();
-					return;
-				}
-				if (sourceSlot->getNumberOfItems() == 0)
-					break;
-			}
-			if (needNext)
-				sourceSlot++;
-		}
-		cs.unlock();
-	}
+    if (itemCache)
+    {
+        for (auto slot : *pushSlotsOrder)
+        {
+            if (slot->getId() == id) return slot;
+        }
+    }
+    return 0;
+}
+
+void Inventory::localTransaction(Array<ItemSlot*>* zSourceSlots,
+    Array<ItemSlot*>* zTargetSlots,
+    ItemFilter* zFilter,
+    int count,
+    Direction outDir,
+    Direction inDir)
+{
+    if (itemCache)
+    {
+        cs.lock();
+        auto sourceSlot
+            = zSourceSlots ? zSourceSlots->begin() : pullSlotsOrder->begin();
+        while (true)
+        {
+            while (sourceSlot
+                   && (sourceSlot->getNumberOfItems() == 0
+                       || (zFilter && !zFilter->matchSourceSlot(sourceSlot))))
+                sourceSlot++;
+            if (!sourceSlot)
+            {
+                cs.unlock();
+                return;
+            }
+            bool needNext = 1;
+            for (auto targetSlot = zTargetSlots->begin(); targetSlot;)
+            {
+                while (
+                    targetSlot
+                    && (targetSlot->isFull()
+                        || (zFilter && !zFilter->matchTargetSlot(targetSlot))))
+                    targetSlot++;
+                if (!targetSlot) break;
+                needNext &= !Inventory::unsafeMove(
+                    this, this, sourceSlot, targetSlot, outDir, inDir, count);
+                if (count == 0)
+                {
+                    cs.unlock();
+                    return;
+                }
+                if (sourceSlot->getNumberOfItems() == 0) break;
+            }
+            if (needNext) sourceSlot++;
+        }
+        cs.unlock();
+    }
 }
 
 void Inventory::addItems(ItemStack* zItems, Direction dir)
 {
-	if (itemCache && zItems && zItems->getSize() > 0)
-	{
-		cs.lock();
-		for (auto targetSlot = pushSlotsOrder->begin(); targetSlot; targetSlot++)
-		{
-			if (!targetSlot->isFull())
-			{
-				if (targetSlot->zStack())
-				{
-					if (targetSlot->zStack()->zItem()->canBeStackedWith(zItems->zItem()))
-					{
-						int number = MIN(targetSlot->numberOfAddableItems(zItems, dir), zItems->getSize());
-						int tmp = number;
-						if (number > 0 && allowPushStack(targetSlot, dir, zItems->zItem(), tmp))
-						{
-							number = MIN(number, tmp);
-							ItemStack* stack = zItems->split(number);
-							if (stack)
-							{
-								targetSlot->addItems(stack, dir);
-								afterPushStack(targetSlot, dir, targetSlot->zStack()->zItem(), number);
-								if (stack->getSize())
-									throw stack;
-								stack->release();
-								if (!zItems->getSize())
-									break;
-							}
-						}
-					}
-				}
-				else
-				{
-					int number = MIN(targetSlot->numberOfAddableItems(zItems, dir), zItems->getSize());
-					int tmp = number;
-					if (number > 0 && allowPushStack(targetSlot, dir, zItems->zItem(), tmp))
-					{
-						number = MIN(number, tmp);
-						ItemStack* stack = zItems->split(number);
-						if (stack)
-						{
-							targetSlot->addItems(stack, dir);
-							updateCache(targetSlot, -1);
-							afterPushStack(targetSlot, dir, targetSlot->zStack()->zItem(), number);
-							if (stack->getSize())
-								throw stack;
-							stack->release();
-							if (!zItems->getSize())
-								break;
-						}
-					}
-				}
-			}
-		}
-		cs.unlock();
-	}
+    if (itemCache && zItems && zItems->getSize() > 0)
+    {
+        cs.lock();
+        for (auto targetSlot = pushSlotsOrder->begin(); targetSlot;
+             targetSlot++)
+        {
+            if (!targetSlot->isFull())
+            {
+                if (targetSlot->zStack())
+                {
+                    if (targetSlot->zStack()->zItem()->canBeStackedWith(
+                            zItems->zItem()))
+                    {
+                        int number
+                            = MIN(targetSlot->numberOfAddableItems(zItems, dir),
+                                zItems->getSize());
+                        int tmp = number;
+                        if (number > 0
+                            && allowPushStack(
+                                targetSlot, dir, zItems->zItem(), tmp))
+                        {
+                            number = MIN(number, tmp);
+                            ItemStack* stack = zItems->split(number);
+                            if (stack)
+                            {
+                                targetSlot->addItems(stack, dir);
+                                afterPushStack(targetSlot,
+                                    dir,
+                                    targetSlot->zStack()->zItem(),
+                                    number);
+                                if (stack->getSize()) throw stack;
+                                stack->release();
+                                if (!zItems->getSize()) break;
+                            }
+                        }
+                    }
+                }
+                else
+                {
+                    int number
+                        = MIN(targetSlot->numberOfAddableItems(zItems, dir),
+                            zItems->getSize());
+                    int tmp = number;
+                    if (number > 0
+                        && allowPushStack(
+                            targetSlot, dir, zItems->zItem(), tmp))
+                    {
+                        number = MIN(number, tmp);
+                        ItemStack* stack = zItems->split(number);
+                        if (stack)
+                        {
+                            targetSlot->addItems(stack, dir);
+                            updateCache(targetSlot, -1);
+                            afterPushStack(targetSlot,
+                                dir,
+                                targetSlot->zStack()->zItem(),
+                                number);
+                            if (stack->getSize()) throw stack;
+                            stack->release();
+                            if (!zItems->getSize()) break;
+                        }
+                    }
+                }
+            }
+        }
+        cs.unlock();
+    }
 }
 
 void Inventory::addItems(ItemSlot* zSlot, ItemStack* zItems, Direction dir)
 {
-	if (zSlot->zStack() && !zSlot->zStack()->zItem()->canBeStackedWith(zItems->zItem()))
-		return;
-	bool needUpdate = !zSlot->zStack();
-	int number = MIN(zSlot->numberOfAddableItems(zItems, dir), zItems->getSize());
-	int tmp = number;
-	if (number > 0 && allowPushStack(zSlot, dir, zItems->zItem(), tmp))
-	{
-		number = MIN(number, tmp);
-		ItemStack* stack = zItems->split(number);
-		if (stack)
-		{
-			zSlot->addItems(stack, dir);
-			if (needUpdate)
-				updateCache(zSlot, -1);
-			afterPushStack(zSlot, dir, zSlot->zStack()->zItem(), number);
-			if (stack->getSize())
-				throw stack;
-			stack->release();
-		}
-	}
+    if (zSlot->zStack()
+        && !zSlot->zStack()->zItem()->canBeStackedWith(zItems->zItem()))
+        return;
+    bool needUpdate = !zSlot->zStack();
+    int number
+        = MIN(zSlot->numberOfAddableItems(zItems, dir), zItems->getSize());
+    int tmp = number;
+    if (number > 0 && allowPushStack(zSlot, dir, zItems->zItem(), tmp))
+    {
+        number = MIN(number, tmp);
+        ItemStack* stack = zItems->split(number);
+        if (stack)
+        {
+            zSlot->addItems(stack, dir);
+            if (needUpdate) updateCache(zSlot, -1);
+            afterPushStack(zSlot, dir, zSlot->zStack()->zItem(), number);
+            if (stack->getSize()) throw stack;
+            stack->release();
+        }
+    }
 }
 
 ItemStack* Inventory::takeItemsOut(ItemSlot* zSlot, int count, Direction dir)
 {
-	if (allowPullStack(zSlot, dir))
-	{
-		ItemStack* stack = zSlot->takeItemsOut(count, dir);
-		if (stack)
-		{
-			updateCache(zSlot, stack->zItem()->zItemType()->getId());
-			if (stack->getSize() > 0)
-				afterPullStack(zSlot, dir, stack->zItem(), stack->getSize());
-		}
-		return stack;
-	}
-	return 0;
+    if (allowPullStack(zSlot, dir))
+    {
+        ItemStack* stack = zSlot->takeItemsOut(count, dir);
+        if (stack)
+        {
+            updateCache(zSlot, stack->zItem()->zItemType()->getId());
+            if (stack->getSize() > 0)
+                afterPullStack(zSlot, dir, stack->zItem(), stack->getSize());
+        }
+        return stack;
+    }
+    return 0;
 }
 
-InventoryInteraction Inventory::interactWith(Inventory* zInventory, Direction dir)
+InventoryInteraction Inventory::interactWith(
+    Inventory* zInventory, Direction dir)
 {
-	return InventoryInteraction(this, zInventory, dir);
+    return InventoryInteraction(this, zInventory, dir);
 }
 
 void Inventory::unsaveAddItem(ItemStack* zStack, Direction dir)
 {
-	addItems(zStack, dir);
+    addItems(zStack, dir);
 }
 
-int Inventory::numberOfAddableItems(const ItemStack* zStack, Direction dir) const
+int Inventory::numberOfAddableItems(
+    const ItemStack* zStack, Direction dir) const
 {
-	int count = 0;
-	for (auto targetSlot = pushSlotsOrder->begin(); targetSlot; targetSlot++)
-	{
-		int maxCount = targetSlot->numberOfAddableItems(zStack, dir);
-		int allowed = maxCount;
-		if (allowPushStack(targetSlot, dir, zStack->zItem(), allowed))
-			count += MIN(maxCount, allowed);
-	}
-	return count;
+    int count = 0;
+    for (auto targetSlot = pushSlotsOrder->begin(); targetSlot; targetSlot++)
+    {
+        int maxCount = targetSlot->numberOfAddableItems(zStack, dir);
+        int allowed = maxCount;
+        if (allowPushStack(targetSlot, dir, zStack->zItem(), allowed))
+            count += MIN(maxCount, allowed);
+    }
+    return count;
 }
 
 Framework::Iterator<ItemSlot*> Inventory::begin()
 {
-	return pullSlotsOrder->begin();
+    return pullSlotsOrder->begin();
 }
 
 Framework::Iterator<ItemSlot*> Inventory::end()
 {
-	return pullSlotsOrder->end();
-}
-
-void Inventory::inventoryApi(Framework::StreamReader* zRequest, NetworkMessage* zResponse, Entity* zSource)
-{
-	char type;
-	zRequest->lese(&type, 1);
-	switch (type)
-	{
-	case 0: // request inventory
-	{
-		char idLen;
-		zRequest->lese(&idLen, 1);
-		char* id = new char[idLen + 1];
-		zRequest->lese(id, idLen);
-		id[(int)idLen] = 0;
-		zResponse->addressGui(id);
-		addObserver(zSource, id);
-		delete[] id;
-		char filterLen;
-		zRequest->lese(&filterLen, 1);
-		char* filter = new char[filterLen + 1];
-		zRequest->lese(filter, filterLen);
-		filter[(int)filterLen] = 0;
-		InMemoryBuffer buffer;
-		int count = 0;
-		for (ItemSlot* slot : *this)
-		{
-			if (slot->getName().istGleich(filter))
-			{
-				count++;
-				int id = slot->getId();
-				buffer.schreibe((char*)&id, 4);
-				int itemCount = slot->getNumberOfItems();
-				buffer.schreibe((char*)&itemCount, 4);
-				if (itemCount > 0)
-				{
-					float f = slot->zStack()->zItem()->getHp();
-					buffer.schreibe((char*)&f, 4);
-					f = slot->zStack()->zItem()->getMaxHp();
-					buffer.schreibe((char*)&f, 4);
-					f = slot->zStack()->zItem()->getDurability();
-					buffer.schreibe((char*)&f, 4);
-					f = slot->zStack()->zItem()->getMaxDurability();
-					buffer.schreibe((char*)&f, 4);
-					int id = slot->zStack()->zItem()->zItemType()->getId();
-					buffer.schreibe((char*)&id, 4);
-				}
-			}
-		}
-		delete[] filter;
-		char* msg = new char[5 + buffer.getSize()];
-		msg[0] = 0;
-		*(int*)(msg + 1) = count;
-		buffer.lese(msg + 5, (int)buffer.getSize());
-		zResponse->setMessage(msg, 5 + (int)buffer.getSize());
-		break;
-	}
-	case 1: // remove Observer
-	{
-		char idLen;
-		zRequest->lese(&idLen, 1);
-		char* id = new char[idLen + 1];
-		zRequest->lese(id, idLen);
-		id[(int)idLen] = 0;
-		removeObserver(zSource, id);
-		delete[] id;
-		break;
-	}
-	case 2: // request item tooltip
-	{
-		char idLen;
-		zRequest->lese(&idLen, 1);
-		char* id = new char[idLen + 1];
-		zRequest->lese(id, idLen);
-		id[(int)idLen] = 0;
-		zResponse->addressGui(id);
-		delete[] id;
-		int slotId;
-		zRequest->lese((char*)&slotId, 4);
-		Text uiml;
-		for (ItemSlot* slot : *pullSlotsOrder)
-		{
-			if (slot->getId() == slotId)
-			{
-				if (slot->zStack() && slot->zStack()->zItem())
-					uiml = slot->zStack()->zItem()->getTooltipUIML();
-			}
-		}
-		short len = (short)uiml.getLength();
-		char* buffer = new char[uiml.getLength() + 7];
-		buffer[0] = 3;
-		*(int*)(buffer + 1) = slotId;
-		*(short*)(buffer + 5) = len;
-		memcpy(buffer + 7, uiml, len);
-		zResponse->setMessage(buffer, len + 7);
-		break;
-	}
-	}
-}
-
-void Inventory::registerAfterPullStackCall(std::function<void(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)> call)
-{
-	afterPullStackCalls.add(call);
-}
-
-void Inventory::registerAfterPushStackCall(std::function<void(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)> call)
-{
-	afterPushStackCalls.add(call);
-}
-
-void Inventory::registerObserverAddedCall(std::function<void(Entity* zSource, Framework::Text id)> call)
-{
-	observerAddedCalls.add(call);
-}
-
-bool Inventory::unsafeMove(Inventory* zSource, Inventory* zTarget, Iterator<ItemSlot*>& sourceSlot, Iterator<ItemSlot*>& targetSlot, Direction outDir, Direction inDir, int& count)
-{
-	if (targetSlot->zStack())
-	{
-		if (sourceSlot->zStack()->zItem()->canBeStackedWith(targetSlot->zStack()->zItem()))
-		{
-			int number = MIN(targetSlot->numberOfAddableItems(sourceSlot->zStack(), outDir), count);
-			int tmp = number;
-			if (number > 0 && zSource->allowPullStack(sourceSlot, outDir) && zTarget->allowPushStack(targetSlot, inDir, sourceSlot->zStack()->zItem(), tmp))
-			{
-				number = MIN(number, tmp);
-				ItemStack* stack = sourceSlot->takeItemsOut(number, outDir);
-				if (stack)
-				{
-					targetSlot->addItems(stack, inDir);
-					zSource->updateCache(sourceSlot, targetSlot->zStack()->zItem()->zItemType()->getId());
-					zSource->afterPullStack(sourceSlot, outDir, targetSlot->zStack()->zItem(), number);
-					zTarget->afterPushStack(targetSlot, inDir, targetSlot->zStack()->zItem(), number);
-					if (stack->getSize())
-						throw stack;
-					stack->release();
-					count -= number;
-					return 1;
-				}
-				else
-					targetSlot++;
-			}
-			else
-				targetSlot++;
-		}
-		else
-			targetSlot++;
-	}
-	else
-	{
-		int number = MIN(targetSlot->numberOfAddableItems(sourceSlot->zStack(), outDir), count);
-		int tmp = number;
-		if (number > 0 && zSource->allowPullStack(sourceSlot, outDir) && zTarget->allowPushStack(targetSlot, inDir, sourceSlot->zStack()->zItem(), tmp))
-		{
-			number = MIN(number, tmp);
-			if (number > 0)
-			{
-				ItemStack* stack = sourceSlot->takeItemsOut(number, outDir);
-				if (stack)
-				{
-					targetSlot->addItems(stack, inDir);
-					zSource->updateCache(sourceSlot, targetSlot->zStack()->zItem()->zItemType()->getId());
-					zTarget->updateCache(targetSlot, -1);
-					zSource->afterPullStack(sourceSlot, outDir, targetSlot->zStack()->zItem(), number);
-					zTarget->afterPushStack(targetSlot, inDir, targetSlot->zStack()->zItem(), number);
-					if (stack->getSize())
-						throw stack;
-					stack->release();
-					count -= number;
-					return 1;
-				}
-				else
-					targetSlot++;
-			}
-			else
-				targetSlot++;
-		}
-		else
-			targetSlot++;
-	}
-	return 0;
+    return pullSlotsOrder->end();
+}
+
+void Inventory::inventoryApi(Framework::StreamReader* zRequest,
+    NetworkMessage* zResponse,
+    Entity* zSource)
+{
+    char type;
+    zRequest->lese(&type, 1);
+    switch (type)
+    {
+    case 0: // request inventory
+        {
+            char idLen;
+            zRequest->lese(&idLen, 1);
+            char* id = new char[idLen + 1];
+            zRequest->lese(id, idLen);
+            id[(int)idLen] = 0;
+            zResponse->addressGui(id);
+            addObserver(zSource, id);
+            delete[] id;
+            char filterLen;
+            zRequest->lese(&filterLen, 1);
+            char* filter = new char[filterLen + 1];
+            zRequest->lese(filter, filterLen);
+            filter[(int)filterLen] = 0;
+            InMemoryBuffer buffer;
+            int count = 0;
+            for (ItemSlot* slot : *this)
+            {
+                if (slot->getName().istGleich(filter))
+                {
+                    count++;
+                    int id = slot->getId();
+                    buffer.schreibe((char*)&id, 4);
+                    int itemCount = slot->getNumberOfItems();
+                    buffer.schreibe((char*)&itemCount, 4);
+                    if (itemCount > 0)
+                    {
+                        float f = slot->zStack()->zItem()->getHp();
+                        buffer.schreibe((char*)&f, 4);
+                        f = slot->zStack()->zItem()->getMaxHp();
+                        buffer.schreibe((char*)&f, 4);
+                        f = slot->zStack()->zItem()->getDurability();
+                        buffer.schreibe((char*)&f, 4);
+                        f = slot->zStack()->zItem()->getMaxDurability();
+                        buffer.schreibe((char*)&f, 4);
+                        int id = slot->zStack()->zItem()->zItemType()->getId();
+                        buffer.schreibe((char*)&id, 4);
+                    }
+                }
+            }
+            delete[] filter;
+            char* msg = new char[5 + buffer.getSize()];
+            msg[0] = 0;
+            *(int*)(msg + 1) = count;
+            buffer.lese(msg + 5, (int)buffer.getSize());
+            zResponse->setMessage(msg, 5 + (int)buffer.getSize());
+            break;
+        }
+    case 1: // remove Observer
+        {
+            char idLen;
+            zRequest->lese(&idLen, 1);
+            char* id = new char[idLen + 1];
+            zRequest->lese(id, idLen);
+            id[(int)idLen] = 0;
+            removeObserver(zSource, id);
+            delete[] id;
+            break;
+        }
+    case 2: // request item tooltip
+        {
+            char idLen;
+            zRequest->lese(&idLen, 1);
+            char* id = new char[idLen + 1];
+            zRequest->lese(id, idLen);
+            id[(int)idLen] = 0;
+            zResponse->addressGui(id);
+            delete[] id;
+            int slotId;
+            zRequest->lese((char*)&slotId, 4);
+            Text uiml;
+            for (ItemSlot* slot : *pullSlotsOrder)
+            {
+                if (slot->getId() == slotId)
+                {
+                    if (slot->zStack() && slot->zStack()->zItem())
+                        uiml = slot->zStack()->zItem()->getTooltipUIML();
+                }
+            }
+            short len = (short)uiml.getLength();
+            char* buffer = new char[uiml.getLength() + 7];
+            buffer[0] = 3;
+            *(int*)(buffer + 1) = slotId;
+            *(short*)(buffer + 5) = len;
+            memcpy(buffer + 7, uiml, len);
+            zResponse->setMessage(buffer, len + 7);
+            break;
+        }
+    }
+}
+
+void Inventory::registerAfterPullStackCall(std::function<void(
+        ItemSlot* zSlot, Direction dir, const Item* zItem, int count)> call)
+{
+    afterPullStackCalls.add(call);
+}
+
+void Inventory::registerAfterPushStackCall(std::function<void(
+        ItemSlot* zSlot, Direction dir, const Item* zItem, int count)> call)
+{
+    afterPushStackCalls.add(call);
+}
+
+void Inventory::registerObserverAddedCall(
+    std::function<void(Entity* zSource, Framework::Text id)> call)
+{
+    observerAddedCalls.add(call);
+}
+
+bool Inventory::unsafeMove(Inventory* zSource,
+    Inventory* zTarget,
+    Iterator<ItemSlot*>& sourceSlot,
+    Iterator<ItemSlot*>& targetSlot,
+    Direction outDir,
+    Direction inDir,
+    int& count)
+{
+    if (targetSlot->zStack())
+    {
+        if (sourceSlot->zStack()->zItem()->canBeStackedWith(
+                targetSlot->zStack()->zItem()))
+        {
+            int number = MIN(
+                targetSlot->numberOfAddableItems(sourceSlot->zStack(), outDir),
+                count);
+            int tmp = number;
+            if (number > 0 && zSource->allowPullStack(sourceSlot, outDir)
+                && zTarget->allowPushStack(
+                    targetSlot, inDir, sourceSlot->zStack()->zItem(), tmp))
+            {
+                number = MIN(number, tmp);
+                ItemStack* stack = sourceSlot->takeItemsOut(number, outDir);
+                if (stack)
+                {
+                    targetSlot->addItems(stack, inDir);
+                    zSource->updateCache(sourceSlot,
+                        targetSlot->zStack()->zItem()->zItemType()->getId());
+                    zSource->afterPullStack(sourceSlot,
+                        outDir,
+                        targetSlot->zStack()->zItem(),
+                        number);
+                    zTarget->afterPushStack(targetSlot,
+                        inDir,
+                        targetSlot->zStack()->zItem(),
+                        number);
+                    if (stack->getSize()) throw stack;
+                    stack->release();
+                    count -= number;
+                    return 1;
+                }
+                else
+                    targetSlot++;
+            }
+            else
+                targetSlot++;
+        }
+        else
+            targetSlot++;
+    }
+    else
+    {
+        int number = MIN(
+            targetSlot->numberOfAddableItems(sourceSlot->zStack(), outDir),
+            count);
+        int tmp = number;
+        if (number > 0 && zSource->allowPullStack(sourceSlot, outDir)
+            && zTarget->allowPushStack(
+                targetSlot, inDir, sourceSlot->zStack()->zItem(), tmp))
+        {
+            number = MIN(number, tmp);
+            if (number > 0)
+            {
+                ItemStack* stack = sourceSlot->takeItemsOut(number, outDir);
+                if (stack)
+                {
+                    targetSlot->addItems(stack, inDir);
+                    zSource->updateCache(sourceSlot,
+                        targetSlot->zStack()->zItem()->zItemType()->getId());
+                    zTarget->updateCache(targetSlot, -1);
+                    zSource->afterPullStack(sourceSlot,
+                        outDir,
+                        targetSlot->zStack()->zItem(),
+                        number);
+                    zTarget->afterPushStack(targetSlot,
+                        inDir,
+                        targetSlot->zStack()->zItem(),
+                        number);
+                    if (stack->getSize()) throw stack;
+                    stack->release();
+                    count -= number;
+                    return 1;
+                }
+                else
+                    targetSlot++;
+            }
+            else
+                targetSlot++;
+        }
+        else
+            targetSlot++;
+    }
+    return 0;
 }

+ 87 - 56
FactoryCraft/Inventory.h

@@ -1,13 +1,13 @@
 #pragma once
 
-#include <Vec3.h>
-#include <ReferenceCounter.h>
-#include <HashMap.h>
 #include <Critical.h>
+#include <HashMap.h>
 #include <ImmutablePair.h>
+#include <ReferenceCounter.h>
+#include <Vec3.h>
 
-#include "ItemSlot.h"
 #include "Area.h"
+#include "ItemSlot.h"
 
 class ItemFilter;
 class Inventory;
@@ -17,72 +17,103 @@ class Entity;
 class InventoryInteraction
 {
 private:
-	Inventory* current;
-	Inventory* other;
-	Direction dir;
-	void lock();
-	void unlock();
-	void transaction(Inventory* zSource, Inventory* zTarget, ItemFilter* zFilter, Direction sourceView, Direction targetView, int count);
+    Inventory* current;
+    Inventory* other;
+    Direction dir;
+    void lock();
+    void unlock();
+    void transaction(Inventory* zSource,
+        Inventory* zTarget,
+        ItemFilter* zFilter,
+        Direction sourceView,
+        Direction targetView,
+        int count);
 
 public:
-	InventoryInteraction(Inventory* zCurrent, Inventory* zOther, Direction dir);
-	InventoryInteraction(const InventoryInteraction& interaction);
-	~InventoryInteraction();
-	InventoryInteraction& operator=(const InventoryInteraction& data);
-	void endInteraction();
-	void pullItems(int count, ItemFilter* zFilter);
-	void pushItems(int count, ItemFilter* zFilter);
+    InventoryInteraction(Inventory* zCurrent, Inventory* zOther, Direction dir);
+    InventoryInteraction(const InventoryInteraction& interaction);
+    ~InventoryInteraction();
+    InventoryInteraction& operator=(const InventoryInteraction& data);
+    void endInteraction();
+    void pullItems(int count, ItemFilter* zFilter);
+    void pushItems(int count, ItemFilter* zFilter);
 };
 
 class Inventory : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::Array<Framework::ImmutablePair<int, Framework::Text>> observers;
-	Framework::RCArray<ItemSlot>* pullSlotsOrder;
-	Framework::RCArray<ItemSlot>* pushSlotsOrder;
-	Framework::HashMap<int, Framework::Array<ItemSlot*>*>* itemCache;
-	Framework::Critical cs;
-	Framework::Array<std::function<void(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)>> afterPullStackCalls;
-	Framework::Array<std::function<void(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)>> afterPushStackCalls;
-	Framework::Array<std::function<void(Entity* zSource, Framework::Text id)>> observerAddedCalls;
-	int nextSlotId;
+    Framework::Array<Framework::ImmutablePair<int, Framework::Text>> observers;
+    Framework::RCArray<ItemSlot>* pullSlotsOrder;
+    Framework::RCArray<ItemSlot>* pushSlotsOrder;
+    Framework::HashMap<int, Framework::Array<ItemSlot*>*>* itemCache;
+    Framework::Critical cs;
+    Framework::Array<std::function<void(
+        ItemSlot* zSlot, Direction dir, const Item* zItem, int count)>>
+        afterPullStackCalls;
+    Framework::Array<std::function<void(
+        ItemSlot* zSlot, Direction dir, const Item* zItem, int count)>>
+        afterPushStackCalls;
+    Framework::Array<std::function<void(Entity* zSource, Framework::Text id)>>
+        observerAddedCalls;
+    int nextSlotId;
 
-	void updateCache(ItemSlot* zSlot, int beforeKey);
+    void updateCache(ItemSlot* zSlot, int beforeKey);
 
 protected:
-	Framework::Vec3<float> location;
+    Framework::Vec3<float> location;
 
-	virtual bool allowPullStack(ItemSlot* zSlot, Direction dir) const;
-	virtual bool allowPushStack(ItemSlot* zSlot, Direction dir, const Item* zItem, int& count) const;
-	virtual void afterPullStack(ItemSlot* zSlot, Direction dir, const Item* zItem, int count);
-	virtual void afterPushStack(ItemSlot* zSlot, Direction dir, const Item* zItem, int count);
-	virtual void loadInventory(Framework::StreamReader* zReader);
-	virtual void saveInventory(Framework::StreamWriter* zWriter);
-	void removeObserver(Entity* zSource, Framework::Text id);
-	void addObserver(Entity* zSource, Framework::Text id);
-	virtual void addItems(ItemStack* zItems, Direction dir);
+    virtual bool allowPullStack(ItemSlot* zSlot, Direction dir) const;
+    virtual bool allowPushStack(
+        ItemSlot* zSlot, Direction dir, const Item* zItem, int& count) const;
+    virtual void afterPullStack(
+        ItemSlot* zSlot, Direction dir, const Item* zItem, int count);
+    virtual void afterPushStack(
+        ItemSlot* zSlot, Direction dir, const Item* zItem, int count);
+    virtual void loadInventory(Framework::StreamReader* zReader);
+    virtual void saveInventory(Framework::StreamWriter* zWriter);
+    void removeObserver(Entity* zSource, Framework::Text id);
+    void addObserver(Entity* zSource, Framework::Text id);
+    virtual void addItems(ItemStack* zItems, Direction dir);
 
 public:
-	Inventory(const Framework::Vec3<float> location, bool hasInventory);
-	virtual ~Inventory();
-	void notyObservers(NetworkMessage* msg);
-	const ItemSlot* zSlot(int id) const;
-	void addSlot(ItemSlot* slot);
-	void localTransaction(Framework::Array< ItemSlot* >* zSourceSlots, Framework::Array<ItemSlot*>* zTargetSlots, ItemFilter* zFilter, int count, Direction outDir, Direction inDir);
-	ItemStack* takeItemsOut(ItemSlot* zSlot, int count, Direction dir);
-	virtual void addItems(ItemSlot* zSlot, ItemStack* zItems, Direction dir);
-	InventoryInteraction interactWith(Inventory* zInventory, Direction dir);
-	void unsaveAddItem(ItemStack* zStack, Direction dir);
-	int numberOfAddableItems(const ItemStack* zStack, Direction dir) const;
-	Framework::Iterator<ItemSlot*> begin();
-	Framework::Iterator<ItemSlot*> end();
-	void inventoryApi(Framework::StreamReader* zRequest, NetworkMessage* zResponse, Entity* zSource);
-	void registerAfterPullStackCall(std::function<void(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)> call);
-	void registerAfterPushStackCall(std::function<void(ItemSlot* zSlot, Direction dir, const Item* zItem, int count)> call);
-	void registerObserverAddedCall(std::function<void(Entity* zSource, Framework::Text id)> call);
+    Inventory(const Framework::Vec3<float> location, bool hasInventory);
+    virtual ~Inventory();
+    void notyObservers(NetworkMessage* msg);
+    const ItemSlot* zSlot(int id) const;
+    void addSlot(ItemSlot* slot);
+    void localTransaction(Framework::Array<ItemSlot*>* zSourceSlots,
+        Framework::Array<ItemSlot*>* zTargetSlots,
+        ItemFilter* zFilter,
+        int count,
+        Direction outDir,
+        Direction inDir);
+    ItemStack* takeItemsOut(ItemSlot* zSlot, int count, Direction dir);
+    virtual void addItems(ItemSlot* zSlot, ItemStack* zItems, Direction dir);
+    InventoryInteraction interactWith(Inventory* zInventory, Direction dir);
+    void unsaveAddItem(ItemStack* zStack, Direction dir);
+    int numberOfAddableItems(const ItemStack* zStack, Direction dir) const;
+    Framework::Iterator<ItemSlot*> begin();
+    Framework::Iterator<ItemSlot*> end();
+    void inventoryApi(Framework::StreamReader* zRequest,
+        NetworkMessage* zResponse,
+        Entity* zSource);
+    void registerAfterPullStackCall(std::function<void(
+            ItemSlot* zSlot, Direction dir, const Item* zItem, int count)>
+            call);
+    void registerAfterPushStackCall(std::function<void(
+            ItemSlot* zSlot, Direction dir, const Item* zItem, int count)>
+            call);
+    void registerObserverAddedCall(
+        std::function<void(Entity* zSource, Framework::Text id)> call);
 
-	friend InventoryInteraction;
+    friend InventoryInteraction;
 
 private:
-	static bool unsafeMove(Inventory* zSource, Inventory* zTarget, Framework::Iterator<ItemSlot*>& sourceSlot, Framework::Iterator<ItemSlot*>& targetSlot, Direction outDir, Direction inDir, int& count);
+    static bool unsafeMove(Inventory* zSource,
+        Inventory* zTarget,
+        Framework::Iterator<ItemSlot*>& sourceSlot,
+        Framework::Iterator<ItemSlot*>& targetSlot,
+        Direction outDir,
+        Direction inDir,
+        int& count);
 };

+ 1 - 1
FactoryCraft/Item.cpp

@@ -33,7 +33,7 @@ const ItemType* Item::zItemType() const
 
 int Item::getTypeId() const
 {
-	return itemTypeId;
+    return itemTypeId;
 }
 
 const BlockType* Item::zPlacedBlockType() const

+ 57 - 58
FactoryCraft/ItemEntity.cpp

@@ -1,100 +1,99 @@
 #include "ItemEntity.h"
-#include "Game.h"
 
+#include "Game.h"
 
-ItemEntity::ItemEntity(Framework::Vec3<float> location, int dimensionId, int entityId)
+ItemEntity::ItemEntity(
+    Framework::Vec3<float> location, int dimensionId, int entityId)
     : Entity(EntityTypeEnum::ITEM, location, dimensionId, entityId)
 {
-	slot = new ItemSlot("Inventory", __INT32_MAX__, 0, 0, 0, ANY_DIRECTION, 0);
-	addSlot(slot);
-	faceOffset = { 0.f, 0.f, 0.f };
-	maxHP = 10;
-	currentHP = 10;
-	stamina = 10;
-	maxStamina = 10;
-	hunger = 10;
-	maxHunger = 10;
-	thirst = 10;
-	maxThirst = 10;
-	targetDistanceLimit = 4;
-	maxMovementSpeed = 1;
+    slot = new ItemSlot("Inventory", __INT32_MAX__, 0, 0, 0, ANY_DIRECTION, 0);
+    addSlot(slot);
+    faceOffset = {0.f, 0.f, 0.f};
+    maxHP = 10;
+    currentHP = 10;
+    stamina = 10;
+    maxStamina = 10;
+    hunger = 10;
+    maxHunger = 10;
+    thirst = 10;
+    maxThirst = 10;
+    targetDistanceLimit = 4;
+    maxMovementSpeed = 1;
 }
 
 void ItemEntity::prepareTick(const Dimension* zDimension)
 {
-	if (slot->zStack() == 0 && !removed)
-		throw "Illegal State exception";
-	if (movements.getEintragAnzahl() <= 1)
-	{
-		Entity* zOther = Game::INSTANCE->zNearestEntity(currentDimensionId, location, [this](Entity* zOther)
-			{
+    if (slot->zStack() == 0 && !removed) throw "Illegal State exception";
+    if (movements.getEintragAnzahl() <= 1)
+    {
+        Entity* zOther = Game::INSTANCE->zNearestEntity(
+            currentDimensionId, location, [this](Entity* zOther) {
                 return zOther != this
                     && zOther->numberOfAddableItems(
                         slot->zStack(), NO_DIRECTION)
                     && (!this->slot->isFull()
                         || zOther->zType()->getId() != EntityTypeEnum::ITEM);
-			});
-		if (zOther)
-		{
-			MovementFrame frame;
-			frame.direction = zOther->getPosition() - getPosition();
-			frame.duration = 0.25;
-			frame.movementFlags = 0x1; // TODO: torn on flight mode
-			frame.targetPosition = getPosition() + frame.direction * (0.5f * maxMovementSpeed);
-			addMovementFrame(frame);
-		}
-	}
-	Entity::prepareTick(zDimension);
+            });
+        if (zOther)
+        {
+            MovementFrame frame;
+            frame.direction = zOther->getPosition() - getPosition();
+            frame.duration = 0.25;
+            frame.movementFlags = 0x1; // TODO: torn on flight mode
+            frame.targetPosition
+                = getPosition() + frame.direction * (0.5f * maxMovementSpeed);
+            addMovementFrame(frame);
+        }
+    }
+    Entity::prepareTick(zDimension);
 }
 
 void ItemEntity::tick(const Dimension* zDimension)
 {
-	Entity* zOther = Game::INSTANCE->zNearestEntity(currentDimensionId, location, [this](Entity* zOther)
-		{
+    Entity* zOther = Game::INSTANCE->zNearestEntity(
+        currentDimensionId, location, [this](Entity* zOther) {
             return zOther != this
                 && zOther->numberOfAddableItems(slot->zStack(), NO_DIRECTION)
                 && (!this->slot->isFull()
                     || zOther->zType()->getId() != EntityTypeEnum::ITEM);
-		});
-	if (zOther)
-	{
-		float d = location.abstand(zOther->getPosition());
-		if (d < 0.5f)
-		{
-			// add items of this entity to the other entity
-			zOther->interactWith(this, NO_DIRECTION).pullItems(slot->getNumberOfItems(), 0);
-			if (slot->getNumberOfItems() == 0)
-				onDeath();
-		}
-	}
-	Entity::tick(zDimension);
+        });
+    if (zOther)
+    {
+        float d = location.abstand(zOther->getPosition());
+        if (d < 0.5f)
+        {
+            // add items of this entity to the other entity
+            zOther->interactWith(this, NO_DIRECTION)
+                .pullItems(slot->getNumberOfItems(), 0);
+            if (slot->getNumberOfItems() == 0) onDeath();
+        }
+    }
+    Entity::tick(zDimension);
 }
 
 void ItemEntity::onFall(float collisionSpeed)
 {
-	if (collisionSpeed >= 50.f)
-		this->currentHP = 0;
+    if (collisionSpeed >= 50.f) this->currentHP = 0;
 }
 
 bool ItemEntity::hasDefaultModel() const
 {
-	return 0;
+    return 0;
 }
 
 ModelInfo ItemEntity::getSpecialModel() const
 {
-	const ItemType* zItemType = 0;
-	if (!slot->isEmpty())
-		zItemType = slot->zStack()->zItem()->zItemType();
-	return !zItemType ? ModelInfo("", "", 0) : zItemType->getModel();
+    const ItemType* zItemType = 0;
+    if (!slot->isEmpty()) zItemType = slot->zStack()->zItem()->zItemType();
+    return !zItemType ? ModelInfo("", "", 0) : zItemType->getModel();
 }
 
-
 ItemEntityType::ItemEntityType()
     : EntityType(EntityTypeEnum::ITEM, ModelInfo("", "", 0))
 {}
 
-Entity* ItemEntityType::createEntity(Framework::Vec3<float> position, int dimensionId, int entityId) const
+Entity* ItemEntityType::createEntity(
+    Framework::Vec3<float> position, int dimensionId, int entityId) const
 {
-	return new ItemEntity(position, dimensionId, entityId);
+    return new ItemEntity(position, dimensionId, entityId);
 }

+ 12 - 10
FactoryCraft/ItemEntity.h

@@ -8,25 +8,27 @@ class ItemEntityType;
 class ItemEntity : public Entity
 {
 private:
-	ItemSlot* slot;
+    ItemSlot* slot;
 
-	ItemEntity(Framework::Vec3<float> location, int dimensionId, int entityId);
+    ItemEntity(Framework::Vec3<float> location, int dimensionId, int entityId);
 
 public:
-	void prepareTick(const Dimension* zDimension) override;
-	void tick(const Dimension* zDimension) override;
+    void prepareTick(const Dimension* zDimension) override;
+    void tick(const Dimension* zDimension) override;
 
-	void onFall(float collisionSpeed) override;
-	bool hasDefaultModel() const override;
-	ModelInfo getSpecialModel() const override;
+    void onFall(float collisionSpeed) override;
+    bool hasDefaultModel() const override;
+    ModelInfo getSpecialModel() const override;
 
-	friend ItemEntityType;
+    friend ItemEntityType;
 };
 
 class ItemEntityType : public EntityType
 {
 public:
-	ItemEntityType();
+    ItemEntityType();
 
-	virtual Entity* createEntity(Framework::Vec3<float> position, int dimensionId, int entityId) const override;
+    virtual Entity* createEntity(Framework::Vec3<float> position,
+        int dimensionId,
+        int entityId) const override;
 };

+ 36 - 40
FactoryCraft/ItemFilter.cpp

@@ -1,116 +1,112 @@
 #include "ItemFilter.h"
-#include "ItemType.h"
+
 #include "Item.h"
 #include "ItemSlot.h"
-
+#include "ItemType.h"
 
 ItemFilter::ItemFilter()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {}
 
 bool ItemFilter::matchItem(const Item* zItem) const
 {
-	return 1;
+    return 1;
 }
 
 bool ItemFilter::matchSourceSlot(ItemSlot* zSlot) const
 {
-	return zSlot->zStack() ? matchItem(zSlot->zStack()->zItem()) : 0;
+    return zSlot->zStack() ? matchItem(zSlot->zStack()->zItem()) : 0;
 }
 
 bool ItemFilter::matchTargetSlot(ItemSlot* zSlot) const
 {
-	return 1;
+    return 1;
 }
 
-
-CombinedItemFilter::CombinedItemFilter(ItemFilter* filterA, ItemFilter* filterB, std::function<bool(bool, bool)> op)
-	: ItemFilter(),
-	filterA(filterA),
-	filterB(filterB),
-	op(op)
+CombinedItemFilter::CombinedItemFilter(ItemFilter* filterA,
+    ItemFilter* filterB,
+    std::function<bool(bool, bool)> op)
+    : ItemFilter(),
+      filterA(filterA),
+      filterB(filterB),
+      op(op)
 {}
 
 CombinedItemFilter::~CombinedItemFilter()
 {
-	filterA->release();
-	filterB->release();
+    filterA->release();
+    filterB->release();
 }
 
 bool CombinedItemFilter::matchItem(const Item* zItem) const
 {
-	return op(filterA->matchItem(zItem), filterB->matchItem(zItem));
+    return op(filterA->matchItem(zItem), filterB->matchItem(zItem));
 }
 
 bool CombinedItemFilter::matchSourceSlot(ItemSlot* zSlot) const
 {
-	return op(filterA->matchSourceSlot(zSlot), filterB->matchSourceSlot(zSlot));
+    return op(filterA->matchSourceSlot(zSlot), filterB->matchSourceSlot(zSlot));
 }
 
 bool CombinedItemFilter::matchTargetSlot(ItemSlot* zSlot) const
 {
-	return op(filterA->matchTargetSlot(zSlot), filterB->matchTargetSlot(zSlot));
+    return op(filterA->matchTargetSlot(zSlot), filterB->matchTargetSlot(zSlot));
 }
 
-
 AnyItemFilter::AnyItemFilter()
-	: ItemFilter()
+    : ItemFilter()
 {}
 
 bool AnyItemFilter::matchItem(const Item* zItem) const
 {
-	return true;
+    return true;
 }
 
-
 TypeItemFilter::TypeItemFilter(const ItemType* zType)
-	: ItemFilter(),
-	zType(zType)
+    : ItemFilter(),
+      zType(zType)
 {}
 
 bool TypeItemFilter::matchItem(const Item* zItem) const
 {
-	return zItem->zItemType() == zType;
+    return zItem->zItemType() == zType;
 }
 
-
 SpecificSlotFilter::SpecificSlotFilter(int sourceSlotId, int targetSlotId)
-	: ItemFilter(),
-	sourceSlotId(sourceSlotId),
-	targetSlotId(targetSlotId)
+    : ItemFilter(),
+      sourceSlotId(sourceSlotId),
+      targetSlotId(targetSlotId)
 {}
 
 bool SpecificSlotFilter::matchSourceSlot(ItemSlot* zSlot) const
 {
-	return sourceSlotId == zSlot->getId();
+    return sourceSlotId == zSlot->getId();
 }
 
 bool SpecificSlotFilter::matchTargetSlot(ItemSlot* zSlot) const
 {
-	return targetSlotId == zSlot->getId();
+    return targetSlotId == zSlot->getId();
 }
 
-
 SourceSlotBlacklistFilter::SourceSlotBlacklistFilter()
-	: ItemFilter()
+    : ItemFilter()
 {}
 
 void SourceSlotBlacklistFilter::addBlackListSlotId(int id)
 {
-	blackList.add(id);
+    blackList.add(id);
 }
 
 bool SourceSlotBlacklistFilter::matchSourceSlot(ItemSlot* zSlot) const
 {
-	for (int black : blackList)
-	{
-		if (black == zSlot->getId())
-			return 0;
-	}
-	return 1;
+    for (int black : blackList)
+    {
+        if (black == zSlot->getId()) return 0;
+    }
+    return 1;
 }
 
 bool SourceSlotBlacklistFilter::matchTargetSlot(ItemSlot* zSlot) const
 {
-	return 1;
+    return 1;
 }

+ 31 - 34
FactoryCraft/ItemFilter.h

@@ -1,8 +1,8 @@
 #pragma once
 
-#include <ReferenceCounter.h>
-#include <functional>
 #include <Array.h>
+#include <functional>
+#include <ReferenceCounter.h>
 
 class Item;
 class ItemType;
@@ -11,69 +11,66 @@ class ItemSlot;
 class ItemFilter : public virtual Framework::ReferenceCounter
 {
 public:
-	ItemFilter();
-	virtual bool matchItem(const Item* zItem) const;
-	virtual bool matchSourceSlot(ItemSlot* zSlot) const;
-	virtual bool matchTargetSlot(ItemSlot* zSlot) const;
+    ItemFilter();
+    virtual bool matchItem(const Item* zItem) const;
+    virtual bool matchSourceSlot(ItemSlot* zSlot) const;
+    virtual bool matchTargetSlot(ItemSlot* zSlot) const;
 };
 
-
 class CombinedItemFilter : public ItemFilter
 {
 private:
-	ItemFilter* filterA;
-	ItemFilter* filterB;
-	std::function<bool(bool, bool)> op;
+    ItemFilter* filterA;
+    ItemFilter* filterB;
+    std::function<bool(bool, bool)> op;
 
 public:
-	CombinedItemFilter(ItemFilter* filterA, ItemFilter* filterB, std::function<bool(bool, bool)> op);
-	~CombinedItemFilter();
-	bool matchItem(const Item* zItem) const override;
-	bool matchSourceSlot(ItemSlot* zSlot) const override;
-	bool matchTargetSlot(ItemSlot* zSlot) const override;
+    CombinedItemFilter(ItemFilter* filterA,
+        ItemFilter* filterB,
+        std::function<bool(bool, bool)> op);
+    ~CombinedItemFilter();
+    bool matchItem(const Item* zItem) const override;
+    bool matchSourceSlot(ItemSlot* zSlot) const override;
+    bool matchTargetSlot(ItemSlot* zSlot) const override;
 };
 
-
 class AnyItemFilter : public ItemFilter
 {
 public:
-	AnyItemFilter();
-	bool matchItem(const Item* zItem) const override;
+    AnyItemFilter();
+    bool matchItem(const Item* zItem) const override;
 };
 
-
 class TypeItemFilter : public ItemFilter
 {
 private:
-	const ItemType* zType;
+    const ItemType* zType;
 
 public:
-	TypeItemFilter(const ItemType* zType);
-	bool matchItem(const Item* zItem) const override;
+    TypeItemFilter(const ItemType* zType);
+    bool matchItem(const Item* zItem) const override;
 };
 
-
 class SpecificSlotFilter : public ItemFilter
 {
 private:
-	int sourceSlotId;
-	int targetSlotId;
+    int sourceSlotId;
+    int targetSlotId;
 
 public:
-	SpecificSlotFilter(int sourceSlotId, int targetSlotId);
-	bool matchSourceSlot(ItemSlot* zSlot) const override;
-	bool matchTargetSlot(ItemSlot* zSlot) const override;
+    SpecificSlotFilter(int sourceSlotId, int targetSlotId);
+    bool matchSourceSlot(ItemSlot* zSlot) const override;
+    bool matchTargetSlot(ItemSlot* zSlot) const override;
 };
 
-
 class SourceSlotBlacklistFilter : public ItemFilter
 {
 private:
-	Framework::Array<int> blackList;
+    Framework::Array<int> blackList;
 
 public:
-	SourceSlotBlacklistFilter();
-	void addBlackListSlotId(int id);
-	bool matchSourceSlot(ItemSlot* zSlot) const override;
-	bool matchTargetSlot(ItemSlot* zSlot) const override;
+    SourceSlotBlacklistFilter();
+    void addBlackListSlotId(int id);
+    bool matchSourceSlot(ItemSlot* zSlot) const override;
+    bool matchTargetSlot(ItemSlot* zSlot) const override;
 };

+ 29 - 30
FactoryCraft/ItemModifier.cpp

@@ -3,51 +3,50 @@
 using namespace Framework;
 
 ItemModifier::ItemModifier()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {}
 
-
-AttributeItemModifier::AttributeItemModifier(Framework::Text attribute, Framework::Text value)
-	: ItemModifier(),
-	attribute(attribute),
-	value(value)
+AttributeItemModifier::AttributeItemModifier(
+    Framework::Text attribute, Framework::Text value)
+    : ItemModifier(),
+      attribute(attribute),
+      value(value)
 {}
 
 void AttributeItemModifier::applyOn(Item* zItem)
 {
-	if (attribute.istGleich("hp"))
-	{
-		float hp = 0;
-		if (value.positionVon("+=") == 0 || value.positionVon("-=") == 0)
-		{
-			hp = zItem->getHp();
-			if (value.positionVon("+=") == 0)
-				hp += TextZuFloat(value.getText() + 2);
-			if (value.positionVon("-=") == 0)
-				hp -= TextZuFloat(value.getText() + 2);
-		}
-		if (value.positionVon("=") == 0)
-		{
-			hp = TextZuFloat(value.getText() + 1);
-		}
-		zItem->setHp(hp);
-	}
+    if (attribute.istGleich("hp"))
+    {
+        float hp = 0;
+        if (value.positionVon("+=") == 0 || value.positionVon("-=") == 0)
+        {
+            hp = zItem->getHp();
+            if (value.positionVon("+=") == 0)
+                hp += TextZuFloat(value.getText() + 2);
+            if (value.positionVon("-=") == 0)
+                hp -= TextZuFloat(value.getText() + 2);
+        }
+        if (value.positionVon("=") == 0)
+        {
+            hp = TextZuFloat(value.getText() + 1);
+        }
+        zItem->setHp(hp);
+    }
 }
 
-
 CombinedItemModifier::CombinedItemModifier()
-	: ItemModifier()
+    : ItemModifier()
 {}
 
 void CombinedItemModifier::addModifier(ItemModifier* modifier)
 {
-	modifiers.add(modifier);
+    modifiers.add(modifier);
 }
 
 void CombinedItemModifier::applyOn(Item* zItem)
 {
-	for (ItemModifier* modifier : modifiers)
-	{
-		modifier->applyOn(zItem);
-	}
+    for (ItemModifier* modifier : modifiers)
+    {
+        modifier->applyOn(zItem);
+    }
 }

+ 10 - 11
FactoryCraft/ItemModifier.h

@@ -5,31 +5,30 @@
 
 #include "Item.h"
 
-
 class ItemModifier : public virtual Framework::ReferenceCounter
 {
 public:
-	ItemModifier();
-	virtual void applyOn(Item* zItem) = 0;
+    ItemModifier();
+    virtual void applyOn(Item* zItem) = 0;
 };
 
 class AttributeItemModifier : public ItemModifier
 {
 private:
-	Framework::Text attribute;
-	Framework::Text value;
+    Framework::Text attribute;
+    Framework::Text value;
 
 public:
-	AttributeItemModifier(Framework::Text attribute, Framework::Text value);
-	void applyOn(Item* zItem) override;
+    AttributeItemModifier(Framework::Text attribute, Framework::Text value);
+    void applyOn(Item* zItem) override;
 };
 
 class CombinedItemModifier : public ItemModifier
 {
-	Framework::RCArray<ItemModifier> modifiers;
+    Framework::RCArray<ItemModifier> modifiers;
 
 public:
-	CombinedItemModifier();
-	void addModifier(ItemModifier* modifier);
-	void applyOn(Item* zItem) override;
+    CombinedItemModifier();
+    void addModifier(ItemModifier* modifier);
+    void applyOn(Item* zItem) override;
 };

+ 1 - 2
FactoryCraft/ItemSkill.cpp

@@ -15,10 +15,9 @@ const ItemType* ItemSkill::zSkillType()
 
 int ItemSkill::getTypeId()
 {
-	return itemTypeId;
+    return itemTypeId;
 }
 
-
 BasicItemSkill::BasicItemSkill(int itemTypeId,
     float maxXP,
     float durabilityModifier,

+ 74 - 68
FactoryCraft/ItemSlot.cpp

@@ -1,127 +1,133 @@
 #include "ItemSlot.h"
 
-
-ItemSlot::ItemSlot(Framework::Text name, int maxSize, int pullPriority, int pushPriority, int allowedPullSide, int allowedPushSides, bool allowHigherStackSize)
-	: ReferenceCounter(),
-	items(0),
-	maxSize(maxSize),
-	allowedPullSide(allowedPullSide),
-	allowedPushSides(allowedPushSides),
-	pullPriority(pullPriority),
-	pushPriority(pushPriority),
-	allowHigherStackSize(allowHigherStackSize),
-	name(name),
-	id(0)
+ItemSlot::ItemSlot(Framework::Text name,
+    int maxSize,
+    int pullPriority,
+    int pushPriority,
+    int allowedPullSide,
+    int allowedPushSides,
+    bool allowHigherStackSize)
+    : ReferenceCounter(),
+      items(0),
+      maxSize(maxSize),
+      allowedPullSide(allowedPullSide),
+      allowedPushSides(allowedPushSides),
+      pullPriority(pullPriority),
+      pushPriority(pushPriority),
+      allowHigherStackSize(allowHigherStackSize),
+      name(name),
+      id(0)
 {}
 
 ItemSlot::~ItemSlot()
 {
-	if (items)
-		items->release();
+    if (items) items->release();
 }
 
 void ItemSlot::setId(int id)
 {
-	this->id = id;
+    this->id = id;
 }
 
 ItemStack* ItemSlot::takeItemsOut(int count, Direction dir)
 {
-	if (!items)
-		return 0;
-	if ((dir | allowedPullSide) == allowedPullSide)
-	{
-		ItemStack* result = items->split(count);
-		if (items->getSize() == 0)
-		{
-			items->release();
-			items = 0;
-		}
-		return result;
-	}
-	return 0;
+    if (!items) return 0;
+    if ((dir | allowedPullSide) == allowedPullSide)
+    {
+        ItemStack* result = items->split(count);
+        if (items->getSize() == 0)
+        {
+            items->release();
+            items = 0;
+        }
+        return result;
+    }
+    return 0;
 }
 
 void ItemSlot::addItems(ItemStack* zStack, Direction dir)
 {
-	if ((dir | allowedPushSides) == allowedPushSides)
-	{
-		if (!items)
-		{
-			if (allowHigherStackSize)
-			{
-				items = zStack->split(maxSize);
-				items->setMaxSize(maxSize);
-			}
-			else
-			{
-				items = zStack->split(MIN(maxSize, zStack->zItem()->getMaxStackSize()));
-				items->setMaxSize(MIN(maxSize, items->zItem()->getMaxStackSize()));
-			}
-		}
-		else
-			items->addItemStack(zStack);
-	}
+    if ((dir | allowedPushSides) == allowedPushSides)
+    {
+        if (!items)
+        {
+            if (allowHigherStackSize)
+            {
+                items = zStack->split(maxSize);
+                items->setMaxSize(maxSize);
+            }
+            else
+            {
+                items = zStack->split(
+                    MIN(maxSize, zStack->zItem()->getMaxStackSize()));
+                items->setMaxSize(
+                    MIN(maxSize, items->zItem()->getMaxStackSize()));
+            }
+        }
+        else
+            items->addItemStack(zStack);
+    }
 }
 
 int ItemSlot::numberOfAddableItems(const ItemStack* zStack, Direction dir) const
 {
-	if ((dir | allowedPushSides) == allowedPushSides)
-	{
-		if (!items)
-		{
-			if (allowHigherStackSize)
-				return maxSize;
-			else
-				return MIN(maxSize, zStack->zItem()->getMaxStackSize());
-		}
-		else if(zStack->zItem() && items->zItem()->canBeStackedWith(zStack->zItem()))
-			return items->getMaxSize() - items->getSize();
-	}
-	return 0;
+    if ((dir | allowedPushSides) == allowedPushSides)
+    {
+        if (!items)
+        {
+            if (allowHigherStackSize)
+                return maxSize;
+            else
+                return MIN(maxSize, zStack->zItem()->getMaxStackSize());
+        }
+        else if (zStack->zItem()
+                 && items->zItem()->canBeStackedWith(zStack->zItem()))
+            return items->getMaxSize() - items->getSize();
+    }
+    return 0;
 }
 
 const ItemStack* ItemSlot::zStack() const
 {
-	return items;
+    return items;
 }
 
 int ItemSlot::getPullPriority() const
 {
-	return pullPriority;
+    return pullPriority;
 }
 
 int ItemSlot::getPushPriority() const
 {
-	return pushPriority;
+    return pushPriority;
 }
 
 bool ItemSlot::isFull() const
 {
-	return items ? items->getSize() >= items->getMaxSize() : maxSize == 0;
+    return items ? items->getSize() >= items->getMaxSize() : maxSize == 0;
 }
 
 int ItemSlot::getFreeSpace() const
 {
-	return items ? items->getMaxSize() - items->getSize() : maxSize;
+    return items ? items->getMaxSize() - items->getSize() : maxSize;
 }
 
 bool ItemSlot::isEmpty() const
 {
-	return !items;
+    return !items;
 }
 
 int ItemSlot::getNumberOfItems() const
 {
-	return items ? items->getSize() : 0;
+    return items ? items->getSize() : 0;
 }
 
 const Framework::Text& ItemSlot::getName() const
 {
-	return name;
+    return name;
 }
 
 int ItemSlot::getId() const
 {
-	return id;
+    return id;
 }

+ 39 - 31
FactoryCraft/ItemSlot.h

@@ -1,47 +1,55 @@
 #pragma once
 
-#include "ItemStack.h"
 #include "Area.h"
+#include "ItemStack.h"
 
 class Inventory;
+
 class ItemSlotIDSetter
 {
 protected:
-	virtual void setId(int id) = 0;
+    virtual void setId(int id) = 0;
 
-	friend Inventory;
+    friend Inventory;
 };
 
-class ItemSlot : public virtual Framework::ReferenceCounter, public ItemSlotIDSetter
+class ItemSlot : public virtual Framework::ReferenceCounter,
+                 public ItemSlotIDSetter
 {
 private:
-	ItemStack* items;
-	int maxSize;
-	Directions allowedPullSide;
-	Directions allowedPushSides;
-	int pullPriority;
-	int pushPriority;
-	bool allowHigherStackSize;
-	Framework::Text name;
-	int id;
-
-	void setId(int id) override;
+    ItemStack* items;
+    int maxSize;
+    Directions allowedPullSide;
+    Directions allowedPushSides;
+    int pullPriority;
+    int pushPriority;
+    bool allowHigherStackSize;
+    Framework::Text name;
+    int id;
+
+    void setId(int id) override;
 
 public:
-	ItemSlot(Framework::Text name, int maxSize, int pullPriority, int pushPriority, int allowedPullSide, int allowedPushSides, bool allowHigherStackSize);
-	~ItemSlot();
-
-	ItemStack* takeItemsOut(int count, Direction dir);
-	void addItems(ItemStack* zStack, Direction dir);
-
-	int numberOfAddableItems(const ItemStack* zStack, Direction dir) const;
-	const ItemStack* zStack() const;
-	int getPullPriority() const;
-	int getPushPriority() const;
-	bool isFull() const;
-	int getFreeSpace() const;
-	bool isEmpty() const;
-	int getNumberOfItems() const;
-	const Framework::Text& getName() const;
-	int getId() const;
+    ItemSlot(Framework::Text name,
+        int maxSize,
+        int pullPriority,
+        int pushPriority,
+        int allowedPullSide,
+        int allowedPushSides,
+        bool allowHigherStackSize);
+    ~ItemSlot();
+
+    ItemStack* takeItemsOut(int count, Direction dir);
+    void addItems(ItemStack* zStack, Direction dir);
+
+    int numberOfAddableItems(const ItemStack* zStack, Direction dir) const;
+    const ItemStack* zStack() const;
+    int getPullPriority() const;
+    int getPushPriority() const;
+    bool isFull() const;
+    int getFreeSpace() const;
+    bool isEmpty() const;
+    int getNumberOfItems() const;
+    const Framework::Text& getName() const;
+    int getId() const;
 };

+ 33 - 34
FactoryCraft/ItemStack.cpp

@@ -1,82 +1,81 @@
 #include "ItemStack.h"
-#include "Item.h"
 
+#include "Item.h"
 
 ItemStack::ItemStack(Item* item, int currentSize, int maxSize)
-	: ReferenceCounter(),
-	item(item),
-	size(currentSize),
-	maxSize(maxSize)
+    : ReferenceCounter(),
+      item(item),
+      size(currentSize),
+      maxSize(maxSize)
 {}
 
 ItemStack::ItemStack(Item* item, int currentSize)
-	: ItemStack(item, currentSize, item->getMaxStackSize())
+    : ItemStack(item, currentSize, item->getMaxStackSize())
 {}
 
 ItemStack::~ItemStack()
 {
-	if (item)
-		item->release();
+    if (item) item->release();
 }
 
 void ItemStack::setMaxSize(int size)
 {
-	maxSize = size;
+    maxSize = size;
 }
 
 ItemStack* ItemStack::split(int size)
 {
-	size = MIN(size, this->size);
-	this->size -= size;
-	return new ItemStack(dynamic_cast<Item*>(item->getThis()), size, item->getMaxStackSize());
+    size = MIN(size, this->size);
+    this->size -= size;
+    return new ItemStack(
+        dynamic_cast<Item*>(item->getThis()), size, item->getMaxStackSize());
 }
 
 Item* ItemStack::extractFromStack()
 {
-	if (size == 0)
-		return 0;
-	--size;
-	return item->zItemType()->cloneItem(item);
+    if (size == 0) return 0;
+    --size;
+    return item->zItemType()->cloneItem(item);
 }
 
 bool ItemStack::addToStack(Item* item)
 {
-	if (size < maxSize && this->item->canBeStackedWith(item))
-	{
-		++size;
-		item->release();
-		return true;
-	}
-	item->release();
-	return false;
+    if (size < maxSize && this->item->canBeStackedWith(item))
+    {
+        ++size;
+        item->release();
+        return true;
+    }
+    item->release();
+    return false;
 }
 
 void ItemStack::addItemStack(ItemStack* zItemStack)
 {
-	if (zItemStack->zItem()->canBeStackedWith(item))
-	{
-		int numToAdd = MIN(zItemStack->getSize(), maxSize - size);
-		size += numToAdd;
-		zItemStack->size -= numToAdd;
-	}
+    if (zItemStack->zItem()->canBeStackedWith(item))
+    {
+        int numToAdd = MIN(zItemStack->getSize(), maxSize - size);
+        size += numToAdd;
+        zItemStack->size -= numToAdd;
+    }
 }
 
 bool ItemStack::isStackable(Item* zItem) const
 {
-	return item->canBeStackedWith(zItem);
+    return item->canBeStackedWith(zItem);
 }
 
 const Item* ItemStack::zItem() const
 {
-	return item;
+    return item;
 }
 
 int ItemStack::getSize() const
 {
-	return size;
+    return size;
 }
 
 int ItemStack::getMaxSize() const
 {
-	return maxSize;
+    return maxSize;
 }

+ 15 - 15
FactoryCraft/ItemStack.h

@@ -5,23 +5,23 @@
 class ItemStack : public virtual Framework::ReferenceCounter
 {
 private:
-	Item* item;
-	int size;
-	int maxSize;
+    Item* item;
+    int size;
+    int maxSize;
 
 public:
-	ItemStack(Item* item, int currentSize, int maxSize);
-	ItemStack(Item* item, int currentSize);
-	~ItemStack();
+    ItemStack(Item* item, int currentSize, int maxSize);
+    ItemStack(Item* item, int currentSize);
+    ~ItemStack();
 
-	void setMaxSize(int size);
-	ItemStack* split(int size);
-	Item* extractFromStack();
-	bool addToStack(Item* item);
-	void addItemStack(ItemStack* zItemStack);
+    void setMaxSize(int size);
+    ItemStack* split(int size);
+    Item* extractFromStack();
+    bool addToStack(Item* item);
+    void addItemStack(ItemStack* zItemStack);
 
-	bool isStackable(Item* zItem) const;
-	const Item* zItem() const;
-	int getSize() const;
-	int getMaxSize() const;
+    bool isStackable(Item* zItem) const;
+    const Item* zItem() const;
+    int getSize() const;
+    int getMaxSize() const;
 };

+ 2 - 1
FactoryCraft/ItemType.cpp

@@ -148,7 +148,8 @@ const ModelInfo& ItemType::getModel() const
     return model;
 }
 
-Item* ItemType::createBasicItem(int id, const char* name,
+Item* ItemType::createBasicItem(int id,
+    const char* name,
     float hp,
     float maxHp,
     float durability,

+ 79 - 73
FactoryCraft/LightSources.cpp

@@ -2,17 +2,17 @@
 
 LightSourceItem::LightSourceItem(int itemType, int blockType, const char* name)
     : BasicBlockItem(itemType, blockType, name),
-	color(0XFFFFFFFF)
+      color(0XFFFFFFFF)
 {}
 
 bool LightSourceItem::canBeStackedWith(const Item* zItem) const
 {
-	const LightSourceItem* other = dynamic_cast<const LightSourceItem*>(zItem);
-	return BasicBlockItem::canBeStackedWith(zItem) && other->color == color;
+    const LightSourceItem* other = dynamic_cast<const LightSourceItem*>(zItem);
+    return BasicBlockItem::canBeStackedWith(zItem) && other->color == color;
 }
 
-
-LightSourceItemType::LightSourceItemType(int id, const char* name, const ModelInfo model, int blockTypeId)
+LightSourceItemType::LightSourceItemType(
+    int id, const char* name, const ModelInfo model, int blockTypeId)
     : BasicBlockItemType(id, name, 0, 0, model, blockTypeId)
 {
     transparent = 1;
@@ -20,123 +20,129 @@ LightSourceItemType::LightSourceItemType(int id, const char* name, const ModelIn
     hardness = 0;
 }
 
-void LightSourceItemType::loadSuperItem(Item* zItem, Framework::StreamReader* zReader) const
+void LightSourceItemType::loadSuperItem(
+    Item* zItem, Framework::StreamReader* zReader) const
 {
-	LightSourceItem* item = dynamic_cast<LightSourceItem*>(zItem);
-	zReader->lese((char*)&item->color, 4);
-	BasicBlockItemType::loadSuperItem(zItem, zReader);
+    LightSourceItem* item = dynamic_cast<LightSourceItem*>(zItem);
+    zReader->lese((char*)&item->color, 4);
+    BasicBlockItemType::loadSuperItem(zItem, zReader);
 }
 
-void LightSourceItemType::saveSuperItem(const Item* zItem, Framework::StreamWriter* zWriter) const
+void LightSourceItemType::saveSuperItem(
+    const Item* zItem, Framework::StreamWriter* zWriter) const
 {
-	const LightSourceItem* item = dynamic_cast<const LightSourceItem*>(zItem);
-	zWriter->schreibe((char*)&item->color, 4);
-	BasicBlockItemType::saveSuperItem(zItem, zWriter);
+    const LightSourceItem* item = dynamic_cast<const LightSourceItem*>(zItem);
+    zWriter->schreibe((char*)&item->color, 4);
+    BasicBlockItemType::saveSuperItem(zItem, zWriter);
 }
 
 Item* LightSourceItemType::createItem() const
 {
-    LightSourceItem* item
-        = new LightSourceItem(id, blockTypeId, name);
+    LightSourceItem* item = new LightSourceItem(id, blockTypeId, name);
     item->color = color;
     return item;
 }
 
-
-
 LightSourceItemType* LightSourceItemType::setColor(int color)
 {
-	this->color = color;
-	return this;
+    this->color = color;
+    return this;
 }
 
-
 BasicLightSource::BasicLightSource(int typeId, Framework::Vec3<int> pos)
-	: Block(typeId, 0, pos, 0)
+    : Block(typeId, 0, pos, 0)
 {}
 
 void BasicLightSource::setLight(int light)
 {
-	lightEmisionColor[0] = (unsigned char)((light >> 16) & 0xFF);
-	lightEmisionColor[1] = (unsigned char)((light >> 8) & 0xFF);
-	lightEmisionColor[2] = (unsigned char)(light & 0xFF);
+    lightEmisionColor[0] = (unsigned char)((light >> 16) & 0xFF);
+    lightEmisionColor[1] = (unsigned char)((light >> 8) & 0xFF);
+    lightEmisionColor[2] = (unsigned char)(light & 0xFF);
 }
 
 bool BasicLightSource::onTick(TickQueue* zQueue, int numTicks, bool& blocked)
 {
-	return 0;
+    return 0;
 }
 
-void BasicLightSource::onPostTick()
-{}
-
+void BasicLightSource::onPostTick() {}
 
-BasicLightSourceBlockType::BasicLightSourceBlockType(int typeId, int itemTypeId, ModelInfo model)
-	: BlockType(typeId, 0, model, 1, 1, 1),
-	itemType(itemTypeId),
-	transparent(1),
-	passable(1),
-	hardness(1.f),
-	interactable(1)
+BasicLightSourceBlockType::BasicLightSourceBlockType(
+    int typeId, int itemTypeId, ModelInfo model)
+    : BlockType(typeId, 0, model, 1, 1, 1),
+      itemType(itemTypeId),
+      transparent(1),
+      passable(1),
+      hardness(1.f),
+      interactable(1)
 {}
 
-void BasicLightSourceBlockType::createSuperBlock(Block* zBlock, Item* zItem) const
+void BasicLightSourceBlockType::createSuperBlock(
+    Block* zBlock, Item* zItem) const
 {
-	BasicLightSource* block = dynamic_cast<BasicLightSource*>(zBlock);
-	if (!block)
-		throw "BasicLightSourceBlockType::createSuperBlock was called with a block witch is not an instance of BasicLightSource";
-	block->transparent = transparent;
-	block->passable = passable;
-	block->hp = (float)getInitialMaxHP();
-	block->maxHP = (float)getInitialMaxHP();
-	block->hardness = hardness;
-	block->zTool = 0;
-	block->speedModifier = 1;
-	block->interactable = interactable;
-	block->setLight(color);
-	BlockType::createSuperBlock(zBlock, zItem);
-	if (zItem)
-	{
-		dynamic_cast<BasicLightSource*>(zBlock)->setLight(dynamic_cast<LightSourceItem*>(zItem)->color);
-	}
+    BasicLightSource* block = dynamic_cast<BasicLightSource*>(zBlock);
+    if (!block)
+        throw "BasicLightSourceBlockType::createSuperBlock was called with a "
+              "block witch is not an instance of BasicLightSource";
+    block->transparent = transparent;
+    block->passable = passable;
+    block->hp = (float)getInitialMaxHP();
+    block->maxHP = (float)getInitialMaxHP();
+    block->hardness = hardness;
+    block->zTool = 0;
+    block->speedModifier = 1;
+    block->interactable = interactable;
+    block->setLight(color);
+    BlockType::createSuperBlock(zBlock, zItem);
+    if (zItem)
+    {
+        dynamic_cast<BasicLightSource*>(zBlock)->setLight(
+            dynamic_cast<LightSourceItem*>(zItem)->color);
+    }
 }
 
-void BasicLightSourceBlockType::loadSuperBlock(Block* zBlock, Framework::StreamReader* zReader, int dimensionId) const
+void BasicLightSourceBlockType::loadSuperBlock(
+    Block* zBlock, Framework::StreamReader* zReader, int dimensionId) const
 {
-	BlockType::loadSuperBlock(zBlock, zReader, dimensionId);
-	BasicLightSource* block = dynamic_cast<BasicLightSource*>(zBlock);
-	if (!block)
-		throw "BasicLightSourceBlockType::loadSuperBlock was called with a block witch is not an instance of BasicLightSource";
-	zReader->lese((char*)&block->lightEmisionColor, 4);
+    BlockType::loadSuperBlock(zBlock, zReader, dimensionId);
+    BasicLightSource* block = dynamic_cast<BasicLightSource*>(zBlock);
+    if (!block)
+        throw "BasicLightSourceBlockType::loadSuperBlock was called with a "
+              "block witch is not an instance of BasicLightSource";
+    zReader->lese((char*)&block->lightEmisionColor, 4);
 }
 
-void BasicLightSourceBlockType::saveSuperBlock(Block* zBlock, Framework::StreamWriter* zWriter) const
+void BasicLightSourceBlockType::saveSuperBlock(
+    Block* zBlock, Framework::StreamWriter* zWriter) const
 {
-	BlockType::saveSuperBlock(zBlock, zWriter);
-	BasicLightSource* block = dynamic_cast<BasicLightSource*>(zBlock);
-	if (!block)
-		throw "BasicLightSourceBlockType::saveSuperBlock was called with a block witch is not an instance of BasicLightSource";
-	zWriter->schreibe((char*)&block->lightEmisionColor, 4);
+    BlockType::saveSuperBlock(zBlock, zWriter);
+    BasicLightSource* block = dynamic_cast<BasicLightSource*>(zBlock);
+    if (!block)
+        throw "BasicLightSourceBlockType::saveSuperBlock was called with a "
+              "block witch is not an instance of BasicLightSource";
+    zWriter->schreibe((char*)&block->lightEmisionColor, 4);
 }
 
-Block* BasicLightSourceBlockType::createBlock(Framework::Vec3<int> position) const
+Block* BasicLightSourceBlockType::createBlock(
+    Framework::Vec3<int> position) const
 {
-	return new BasicLightSource(getId(), position);
+    return new BasicLightSource(getId(), position);
 }
 
 Item* BasicLightSourceBlockType::createItem() const
 {
-	return StaticRegistry<ItemType>::INSTANCE.zElement(itemType)->createItem();
+    return StaticRegistry<ItemType>::INSTANCE.zElement(itemType)->createItem();
 }
 
-BasicLightSourceBlockType* BasicLightSourceBlockType::setHardness(float hardness)
+BasicLightSourceBlockType* BasicLightSourceBlockType::setHardness(
+    float hardness)
 {
-	this->hardness = hardness;
-	return this;
+    this->hardness = hardness;
+    return this;
 }
 
 BasicLightSourceBlockType* BasicLightSourceBlockType::setColor(int color)
 {
-	this->color = color;
-	return this;
+    this->color = color;
+    return this;
 }

+ 21 - 19
FactoryCraft/ModelInfo.cpp

@@ -2,31 +2,33 @@
 
 using namespace Framework;
 
-ModelInfo::ModelInfo(const char* modelPath, const char* texturPath, int textureCount)
-	: modelPath(modelPath)
+ModelInfo::ModelInfo(
+    const char* modelPath, const char* texturPath, int textureCount)
+    : modelPath(modelPath)
 {
-	for (int i = 0; i < textureCount; i++)
-		texturePaths.add(new Text(texturPath));
+    for (int i = 0; i < textureCount; i++)
+        texturePaths.add(new Text(texturPath));
 }
 
-ModelInfo::ModelInfo(const char* modelPath, std::initializer_list<const char*> texturePaths)
-	: modelPath(modelPath)
+ModelInfo::ModelInfo(
+    const char* modelPath, std::initializer_list<const char*> texturePaths)
+    : modelPath(modelPath)
 {
-	for (const char* texturPath : texturePaths)
-		this->texturePaths.add(new Text(texturPath));
+    for (const char* texturPath : texturePaths)
+        this->texturePaths.add(new Text(texturPath));
 }
 
 void ModelInfo::writeTo(Framework::StreamWriter* zWriter) const
 {
-	char len = (char)modelPath.getLength();
-	zWriter->schreibe(&len, 1);
-	zWriter->schreibe(modelPath.getText(), (int)len);
-	short count = (short)texturePaths.getEintragAnzahl();
-	zWriter->schreibe((char*)&count, 2);
-	for (Text* t : texturePaths)
-	{
-		len = (char)t->getLength();
-		zWriter->schreibe(&len, 1);
-		zWriter->schreibe(t->getText(), (int)len);
-	}
+    char len = (char)modelPath.getLength();
+    zWriter->schreibe(&len, 1);
+    zWriter->schreibe(modelPath.getText(), (int)len);
+    short count = (short)texturePaths.getEintragAnzahl();
+    zWriter->schreibe((char*)&count, 2);
+    for (Text* t : texturePaths)
+    {
+        len = (char)t->getLength();
+        zWriter->schreibe(&len, 1);
+        zWriter->schreibe(t->getText(), (int)len);
+    }
 }

+ 7 - 7
FactoryCraft/ModelInfo.h

@@ -1,18 +1,18 @@
 #pragma once
 
-#include <Text.h>
 #include <Array.h>
+#include <Text.h>
 #include <Writer.h>
 
-
 class ModelInfo
 {
 private:
-	const Framework::Text modelPath;
-	Framework::RCArray<Framework::Text> texturePaths;
+    const Framework::Text modelPath;
+    Framework::RCArray<Framework::Text> texturePaths;
 
 public:
-	ModelInfo(const char* modelPath, const char* texturPath, int textureCount);
-	ModelInfo(const char* modelPath, std::initializer_list<const char*> texturePaths);
-	void writeTo(Framework::StreamWriter* zWriter) const;
+    ModelInfo(const char* modelPath, const char* texturPath, int textureCount);
+    ModelInfo(
+        const char* modelPath, std::initializer_list<const char*> texturePaths);
+    void writeTo(Framework::StreamWriter* zWriter) const;
 };

+ 116 - 113
FactoryCraft/MultiblockStructure.cpp

@@ -1,184 +1,187 @@
 #include "MultiblockStructure.h"
+
 #include "Game.h"
 
 using namespace Framework;
 
-MultiblockStructure::MultiblockStructure(int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition, int structureTypeId)
-	: ReferenceCounter(),
-	uniquePosition(uniquePosition),
-	dimensionId(dimensionId),
-	structureId(structureId),
-	structureTypeId(structureTypeId),
-	isLoading(1)
+MultiblockStructure::MultiblockStructure(int dimensionId,
+    __int64 structureId,
+    Framework::Vec3<int> uniquePosition,
+    int structureTypeId)
+    : ReferenceCounter(),
+      uniquePosition(uniquePosition),
+      dimensionId(dimensionId),
+      structureId(structureId),
+      structureTypeId(structureTypeId),
+      isLoading(1)
 {}
 
-MultiblockStructure::~MultiblockStructure()
-{}
+MultiblockStructure::~MultiblockStructure() {}
 
 void MultiblockStructure::onBlockLoaded(Block* block)
 {
-	if (isBlockMember(block))
-	{
-		loadedMembers.add(block);
-		isLoading = 0;
-	}
-	else
-		block->release();
+    if (isBlockMember(block))
+    {
+        loadedMembers.add(block);
+        isLoading = 0;
+    }
+    else
+        block->release();
 }
 
 void MultiblockStructure::onBlockUnloaded(Block* zBlock)
 {
-	for (auto i = loadedMembers.begin(); i; ++i)
-	{
-		if ((Block*)i == zBlock)
-		{
-			i.remove();
-			return;
-		}
-	}
+    for (auto i = loadedMembers.begin(); i; ++i)
+    {
+        if ((Block*)i == zBlock)
+        {
+            i.remove();
+            return;
+        }
+    }
 }
 
-void MultiblockStructure::addMemberPosition(Framework::Vec3<int > blockPos)
+void MultiblockStructure::addMemberPosition(Framework::Vec3<int> blockPos)
 {
-	memberBlockPositions.add(blockPos);
-	Punkt center = Game::INSTANCE->getChunkCenter(blockPos.x, blockPos.y);
-	for (const Punkt& p : affectedChunks)
-	{
-		if (p == center)
-			return;
-	}
-	affectedChunks.add(center);
+    memberBlockPositions.add(blockPos);
+    Punkt center = Game::INSTANCE->getChunkCenter(blockPos.x, blockPos.y);
+    for (const Punkt& p : affectedChunks)
+    {
+        if (p == center) return;
+    }
+    affectedChunks.add(center);
 }
 
 void MultiblockStructure::onBlockRemoved(Block* zBlock)
 {
-	for (auto i = memberBlockPositions.begin(); i; ++i)
-	{
-		if (i.val() == zBlock->getPos())
-		{
-			Punkt center = Game::INSTANCE->getChunkCenter(i.val().x, i.val().y);
-			i.remove();
-			// check if other blocks in the same chunk exists
-			for (Vec3<int> pos : memberBlockPositions)
-			{
-				if (center == Game::INSTANCE->getChunkCenter(pos.x, pos.y))
-					return;
-			}
-			// remove chunk from affected chunks if no other block is in this chunk
-			for (auto p = affectedChunks.begin(); p; ++p)
-			{
-				if (p.val() == center)
-					p.remove();
-			}
-			return;
-		}
-	}
+    for (auto i = memberBlockPositions.begin(); i; ++i)
+    {
+        if (i.val() == zBlock->getPos())
+        {
+            Punkt center = Game::INSTANCE->getChunkCenter(i.val().x, i.val().y);
+            i.remove();
+            // check if other blocks in the same chunk exists
+            for (Vec3<int> pos : memberBlockPositions)
+            {
+                if (center == Game::INSTANCE->getChunkCenter(pos.x, pos.y))
+                    return;
+            }
+            // remove chunk from affected chunks if no other block is in this
+            // chunk
+            for (auto p = affectedChunks.begin(); p; ++p)
+            {
+                if (p.val() == center) p.remove();
+            }
+            return;
+        }
+    }
 }
 
 bool MultiblockStructure::isEmpty() const
 {
-	return memberBlockPositions.getEintragAnzahl() == 0 && !isLoading;
+    return memberBlockPositions.getEintragAnzahl() == 0 && !isLoading;
 }
 
 bool MultiblockStructure::isFullyLoaded() const
 {
-	for (Punkt p : affectedChunks)
-	{
-		if (!Game::INSTANCE->isChunkLoaded(p.x, p.y, dimensionId))
-			return 0;
-	}
-	return 1;
+    for (Punkt p : affectedChunks)
+    {
+        if (!Game::INSTANCE->isChunkLoaded(p.x, p.y, dimensionId)) return 0;
+    }
+    return 1;
 }
 
 bool MultiblockStructure::isFullyUnloaded() const
 {
-	if (isLoading)
-		return 0;
-	for (Punkt p : affectedChunks)
-	{
-		if (Game::INSTANCE->isChunkLoaded(p.x, p.y, dimensionId))
-			return 0;
-	}
-	return 1;
+    if (isLoading) return 0;
+    for (Punkt p : affectedChunks)
+    {
+        if (Game::INSTANCE->isChunkLoaded(p.x, p.y, dimensionId)) return 0;
+    }
+    return 1;
 }
 
 bool MultiblockStructure::isBlockMember(Block* zBlock) const
 {
-	for (const Vec3<int>& pos : memberBlockPositions)
-	{
-		if (pos == zBlock->getPos())
-			return 1;
-	}
-	return 0;
+    for (const Vec3<int>& pos : memberBlockPositions)
+    {
+        if (pos == zBlock->getPos()) return 1;
+    }
+    return 0;
 }
 
 __int64 MultiblockStructure::getStructureId() const
 {
-	return structureId;
+    return structureId;
 }
 
 Framework::Vec3<int> MultiblockStructure::getUniquePosition() const
 {
-	return uniquePosition;
+    return uniquePosition;
 }
 
 int MultiblockStructure::getStructureTypeId() const
 {
-	return structureTypeId;
+    return structureTypeId;
 }
 
-
 MultiblockStructureType::MultiblockStructureType(int id)
-	: ReferenceCounter(),
-	id(id)
+    : ReferenceCounter(),
+      id(id)
 {
-	StaticRegistry<MultiblockStructureType>::INSTANCE.registerT(this, id);
+    StaticRegistry<MultiblockStructureType>::INSTANCE.registerT(this, id);
 }
 
-MultiblockStructureType::~MultiblockStructureType()
-{}
+MultiblockStructureType::~MultiblockStructureType() {}
 
-void MultiblockStructureType::loadSuperStructure(MultiblockStructure* zStructure, Framework::StreamReader* zReader) const
+void MultiblockStructureType::loadSuperStructure(
+    MultiblockStructure* zStructure, Framework::StreamReader* zReader) const
 {
-	zStructure->affectedChunks.leeren();
-	zStructure->memberBlockPositions.leeren();
-	int blockCount;
-	zReader->lese((char*)&blockCount, 4);
-	for (int i = 0; i < blockCount; i++)
-	{
-		Framework::Vec3<int> pos;
-		zReader->lese((char*)&pos.x, 4);
-		zReader->lese((char*)&pos.y, 4);
-		zReader->lese((char*)&pos.z, 4);
-		zStructure->addMemberPosition(pos);
-	}
+    zStructure->affectedChunks.leeren();
+    zStructure->memberBlockPositions.leeren();
+    int blockCount;
+    zReader->lese((char*)&blockCount, 4);
+    for (int i = 0; i < blockCount; i++)
+    {
+        Framework::Vec3<int> pos;
+        zReader->lese((char*)&pos.x, 4);
+        zReader->lese((char*)&pos.y, 4);
+        zReader->lese((char*)&pos.z, 4);
+        zStructure->addMemberPosition(pos);
+    }
 }
 
-void MultiblockStructureType::saveSuperStructure(MultiblockStructure* zStructure, Framework::StreamWriter* zWriter) const
+void MultiblockStructureType::saveSuperStructure(
+    MultiblockStructure* zStructure, Framework::StreamWriter* zWriter) const
 {
-	int blockCount = zStructure->memberBlockPositions.getEintragAnzahl();
-	zWriter->schreibe((char*)&blockCount, 4);
-	for (Framework::Vec3<int> pos : zStructure->memberBlockPositions)
-	{
-		zWriter->schreibe((char*)&pos.x, 4);
-		zWriter->schreibe((char*)&pos.y, 4);
-		zWriter->schreibe((char*)&pos.z, 4);
-	}
+    int blockCount = zStructure->memberBlockPositions.getEintragAnzahl();
+    zWriter->schreibe((char*)&blockCount, 4);
+    for (Framework::Vec3<int> pos : zStructure->memberBlockPositions)
+    {
+        zWriter->schreibe((char*)&pos.x, 4);
+        zWriter->schreibe((char*)&pos.y, 4);
+        zWriter->schreibe((char*)&pos.z, 4);
+    }
 }
 
-MultiblockStructure* MultiblockStructureType::loadStructure(int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition, Framework::StreamReader* zReader) const
+MultiblockStructure* MultiblockStructureType::loadStructure(int dimensionId,
+    __int64 structureId,
+    Framework::Vec3<int> uniquePosition,
+    Framework::StreamReader* zReader) const
 {
-	MultiblockStructure* str = createStructure(dimensionId, structureId, uniquePosition);
-	loadSuperStructure(str, zReader);
-	return str;
+    MultiblockStructure* str
+        = createStructure(dimensionId, structureId, uniquePosition);
+    loadSuperStructure(str, zReader);
+    return str;
 }
 
-void MultiblockStructureType::saveStructure(MultiblockStructure* zStructure, Framework::StreamWriter* zWriter) const
+void MultiblockStructureType::saveStructure(
+    MultiblockStructure* zStructure, Framework::StreamWriter* zWriter) const
 {
-	saveSuperStructure(zStructure, zWriter);
+    saveSuperStructure(zStructure, zWriter);
 }
 
 int MultiblockStructureType::getId() const
 {
-	return id;
+    return id;
 }

+ 43 - 32
FactoryCraft/MultiblockStructure.h

@@ -1,7 +1,7 @@
 #pragma once
 
-#include <ReferenceCounter.h>
 #include <Punkt.h>
+#include <ReferenceCounter.h>
 
 #include "Block.h"
 
@@ -16,50 +16,61 @@ public:
 class MultiblockStructure : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::Array<Framework::Punkt> affectedChunks;
-	Framework::Array<Framework::Vec3<int>> memberBlockPositions;
-	Framework::Vec3<int> uniquePosition;
-	int dimensionId;
-	__int64 structureId;
-	int structureTypeId;
-	bool isLoading;
+    Framework::Array<Framework::Punkt> affectedChunks;
+    Framework::Array<Framework::Vec3<int>> memberBlockPositions;
+    Framework::Vec3<int> uniquePosition;
+    int dimensionId;
+    __int64 structureId;
+    int structureTypeId;
+    bool isLoading;
 
 protected:
-	Framework::RCArray<Block> loadedMembers;
+    Framework::RCArray<Block> loadedMembers;
 
 public:
-	MultiblockStructure(int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition, int structureTypeId);
-	~MultiblockStructure();
-	void onBlockLoaded(Block* block);
-	void onBlockUnloaded(Block* zBlock);
-	void addMemberPosition(Framework::Vec3<int > blockPos);
-	virtual void onBlockRemoved(Block* zBlock);
+    MultiblockStructure(int dimensionId,
+        __int64 structureId,
+        Framework::Vec3<int> uniquePosition,
+        int structureTypeId);
+    ~MultiblockStructure();
+    void onBlockLoaded(Block* block);
+    void onBlockUnloaded(Block* zBlock);
+    void addMemberPosition(Framework::Vec3<int> blockPos);
+    virtual void onBlockRemoved(Block* zBlock);
 
-	bool isEmpty() const;
-	bool isFullyLoaded() const;
-	bool isFullyUnloaded() const;
-	bool isBlockMember(Block* zBlock) const;
-	__int64 getStructureId() const;
-	Framework::Vec3<int> getUniquePosition() const;
-	int getStructureTypeId() const;
+    bool isEmpty() const;
+    bool isFullyLoaded() const;
+    bool isFullyUnloaded() const;
+    bool isBlockMember(Block* zBlock) const;
+    __int64 getStructureId() const;
+    Framework::Vec3<int> getUniquePosition() const;
+    int getStructureTypeId() const;
 
-	friend MultiblockStructureType;
+    friend MultiblockStructureType;
 };
 
 class MultiblockStructureType : public Framework::ReferenceCounter
 {
 private:
-	const int id;
+    const int id;
 
 protected:
-	MultiblockStructureType(int id);
-	~MultiblockStructureType();
-	virtual void loadSuperStructure(MultiblockStructure* zStructure, Framework::StreamReader* zReader) const;
-	virtual void saveSuperStructure(MultiblockStructure* zStructure, Framework::StreamWriter* zWriter) const;
-	virtual MultiblockStructure* createStructure(int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition) const = 0;
+    MultiblockStructureType(int id);
+    ~MultiblockStructureType();
+    virtual void loadSuperStructure(MultiblockStructure* zStructure,
+        Framework::StreamReader* zReader) const;
+    virtual void saveSuperStructure(MultiblockStructure* zStructure,
+        Framework::StreamWriter* zWriter) const;
+    virtual MultiblockStructure* createStructure(int dimensionId,
+        __int64 structureId,
+        Framework::Vec3<int> uniquePosition) const = 0;
 
 public:
-	MultiblockStructure* loadStructure(int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition, Framework::StreamReader* zReader) const;
-	void saveStructure(MultiblockStructure* zStructure, Framework::StreamWriter* zWriter) const;
-	int getId() const;
+    MultiblockStructure* loadStructure(int dimensionId,
+        __int64 structureId,
+        Framework::Vec3<int> uniquePosition,
+        Framework::StreamReader* zReader) const;
+    void saveStructure(MultiblockStructure* zStructure,
+        Framework::StreamWriter* zWriter) const;
+    int getId() const;
 };

+ 66 - 64
FactoryCraft/MultiblockTree.cpp

@@ -2,80 +2,82 @@
 
 using namespace Framework;
 
-MultiblockTree::MultiblockTree(int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition)
+MultiblockTree::MultiblockTree(
+    int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition)
     : MultiblockStructure(
         dimensionId, structureId, uniquePosition, MultiblockStructureEnum::TREE)
 {}
 
 void MultiblockTree::onBlockRemoved(Block* zBlock)
 {
-	if (isBlockMember(zBlock))
-	{
-		MultiblockStructure::onBlockRemoved(zBlock);
-		for (int d = 4; d >= 0; d--)
-		{
-			bool foundStablizer = 0;
-			Array<Block*> checked;
-			Array<Block*> queue;
-			Block* current = zBlock->zNeighbor(getDirectionFromIndex(d));
-			if (current && isBlockMember(current))
-				queue.add(current);
-			while (queue.getEintragAnzahl() > 0)
-			{
-				current = queue.get(0);
-				queue.remove(0);
-				Block* bottom = current->zNeighbor(BOTTOM);
-				if (bottom && isBlockMember(bottom))
-				{
-					foundStablizer = 1;
-					break;
-				}
-				checked.add(current);
-				for (int i = 0; i < 4; i++)
-				{
-					Block* neighbor = current->zNeighbor(getDirectionFromIndex(i));
-					if (neighbor && isBlockMember(neighbor))
-					{
-						bool found = 0;
-						for (Block* b : checked)
-						{
-							if (b == neighbor)
-							{
-								found = 1;
-								break;
-							}
-						}
-						if (!found)
-						{
-							for (Block* b : queue)
-							{
-								if (b == neighbor)
-								{
-									found = 1;
-									break;
-								}
-							}
-						}
-						if (!found)
-							queue.add(neighbor);
-					}
-				}
-			}
-			if (!foundStablizer)
-			{
-				for (Block* b : checked)
-					b->setHP(0);
-			}
-		}
-	}
+    if (isBlockMember(zBlock))
+    {
+        MultiblockStructure::onBlockRemoved(zBlock);
+        for (int d = 4; d >= 0; d--)
+        {
+            bool foundStablizer = 0;
+            Array<Block*> checked;
+            Array<Block*> queue;
+            Block* current = zBlock->zNeighbor(getDirectionFromIndex(d));
+            if (current && isBlockMember(current)) queue.add(current);
+            while (queue.getEintragAnzahl() > 0)
+            {
+                current = queue.get(0);
+                queue.remove(0);
+                Block* bottom = current->zNeighbor(BOTTOM);
+                if (bottom && isBlockMember(bottom))
+                {
+                    foundStablizer = 1;
+                    break;
+                }
+                checked.add(current);
+                for (int i = 0; i < 4; i++)
+                {
+                    Block* neighbor
+                        = current->zNeighbor(getDirectionFromIndex(i));
+                    if (neighbor && isBlockMember(neighbor))
+                    {
+                        bool found = 0;
+                        for (Block* b : checked)
+                        {
+                            if (b == neighbor)
+                            {
+                                found = 1;
+                                break;
+                            }
+                        }
+                        if (!found)
+                        {
+                            for (Block* b : queue)
+                            {
+                                if (b == neighbor)
+                                {
+                                    found = 1;
+                                    break;
+                                }
+                            }
+                        }
+                        if (!found) queue.add(neighbor);
+                    }
+                }
+            }
+            if (!foundStablizer)
+            {
+                for (Block* b : checked)
+                    b->setHP(0);
+            }
+        }
+    }
 }
 
-
 MultiblockTreeStructureType::MultiblockTreeStructureType()
-	: MultiblockStructureType(MultiblockStructureEnum::TREE)
+    : MultiblockStructureType(MultiblockStructureEnum::TREE)
 {}
 
-MultiblockStructure* MultiblockTreeStructureType::createStructure(int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition) const
+MultiblockStructure* MultiblockTreeStructureType::createStructure(
+    int dimensionId,
+    __int64 structureId,
+    Framework::Vec3<int> uniquePosition) const
 {
-	return new MultiblockTree(dimensionId, structureId, uniquePosition);
+    return new MultiblockTree(dimensionId, structureId, uniquePosition);
 }

+ 78 - 77
FactoryCraft/NetworkMessage.cpp

@@ -1,144 +1,145 @@
 #include "NetworkMessage.h"
+
 #include "Chunk.h"
 #include "Entity.h"
 #include "Game.h"
 
 NetworkMessage::NetworkMessage()
-	: Framework::ReferenceCounter()
-{
-	address = 0;
-	addressLength = 0;
-	broadcast = 0;
-	message = 0;
-	msgLength = 0;
-	useBackground = 0;
+    : Framework::ReferenceCounter()
+{
+    address = 0;
+    addressLength = 0;
+    broadcast = 0;
+    message = 0;
+    msgLength = 0;
+    useBackground = 0;
 }
 
 NetworkMessage::~NetworkMessage()
 {
-	delete[] message;
-	delete[] address;
+    delete[] message;
+    delete[] address;
 }
 
 void NetworkMessage::addressChunck(Chunk* zChunk)
 {
-	delete[] address;
-	addressLength = 10;
-	address = new char[addressLength];
-	address[0] = 1; // dimension response
-	address[1] = 1; // chunck
-	Framework::Punkt center = zChunk->getCenter();
-	*(int*)(address + 2) = center.x;
-	*(int*)(address + 6) = center.y;
+    delete[] address;
+    addressLength = 10;
+    address = new char[addressLength];
+    address[0] = 1; // dimension response
+    address[1] = 1; // chunck
+    Framework::Punkt center = zChunk->getCenter();
+    *(int*)(address + 2) = center.x;
+    *(int*)(address + 6) = center.y;
 }
 
 void NetworkMessage::addressEntity(Entity* zEntity)
 {
-	delete[] address;
-	addressLength = 6;
-	address = new char[addressLength];
-	address[0] = 1; // dimension response
-	address[1] = 2; // entity
-	*(int*)(address + 2) = zEntity->getId();
+    delete[] address;
+    addressLength = 6;
+    address = new char[addressLength];
+    address[0] = 1; // dimension response
+    address[1] = 2; // entity
+    *(int*)(address + 2) = zEntity->getId();
 }
 
 void NetworkMessage::addressDimension()
 {
-	delete[] address;
-	addressLength = 1;
-	address = new char[1];
-	address[0] = 1; // dimension response
+    delete[] address;
+    addressLength = 1;
+    address = new char[1];
+    address[0] = 1; // dimension response
 }
 
 void NetworkMessage::addressBlock(Block* zBlock)
 {
-	delete[] address;
-	addressLength = 14;
-	address = new char[addressLength];
-	address[0] = 1; // dimension response
-	address[1] = 3; // block
-	Framework::Vec3<int> pos = zBlock->getPos();
-	*(int*)(address + 2) = pos.x;
-	*(int*)(address + 6) = pos.y;
-	*(int*)(address + 10) = pos.z;
+    delete[] address;
+    addressLength = 14;
+    address = new char[addressLength];
+    address[0] = 1; // dimension response
+    address[1] = 3; // block
+    Framework::Vec3<int> pos = zBlock->getPos();
+    *(int*)(address + 2) = pos.x;
+    *(int*)(address + 6) = pos.y;
+    *(int*)(address + 10) = pos.z;
 }
 
 void NetworkMessage::openDialog(Framework::Text dialogName)
 {
-	delete[] address;
-	addressLength = (char)(4 + dialogName.getLength());
-	address = new char[addressLength];
-	address[0] = 2; // gui message
-	address[1] = 0; // open dialog
-	*(short*)(address + 2) = (short)dialogName.getLength(); // block
-	memcpy(address + 4, dialogName.getText(), dialogName.getLength());
+    delete[] address;
+    addressLength = (char)(4 + dialogName.getLength());
+    address = new char[addressLength];
+    address[0] = 2;                                         // gui message
+    address[1] = 0;                                         // open dialog
+    *(short*)(address + 2) = (short)dialogName.getLength(); // block
+    memcpy(address + 4, dialogName.getText(), dialogName.getLength());
 }
 
 void NetworkMessage::addressGui(Framework::Text elementId)
 {
-	delete[] address;
-	addressLength = (char)(4 + elementId.getLength());
-	address = new char[addressLength];
-	address[0] = 2; // gui message
-	address[1] = 1; // element message
-	*(short*)(address + 2) = (short)elementId.getLength(); // block
-	memcpy(address + 4, elementId.getText(), elementId.getLength());
+    delete[] address;
+    addressLength = (char)(4 + elementId.getLength());
+    address = new char[addressLength];
+    address[0] = 2;                                        // gui message
+    address[1] = 1;                                        // element message
+    *(short*)(address + 2) = (short)elementId.getLength(); // block
+    memcpy(address + 4, elementId.getText(), elementId.getLength());
 }
 
 void NetworkMessage::setMessage(char* msg, int length)
 {
-	delete[] message;
-	message = msg;
-	msgLength = length;
+    delete[] message;
+    message = msg;
+    msgLength = length;
 }
 
 void NetworkMessage::setUseBackground()
 {
-	useBackground = 1;
+    useBackground = 1;
 }
 
 void NetworkMessage::sendToAll()
 {
-	broadcast = true;
+    broadcast = true;
 }
 
 void NetworkMessage::writeTo(Framework::StreamWriter* zWriter) const
 {
-	int total = msgLength + addressLength;
-	if (total)
-	{
-		zWriter->schreibe((char*)&GameClient::Message::API_MESSAGE, 1);
-		zWriter->schreibe((char*)&total, 4);
-		zWriter->schreibe(address, addressLength);
-		zWriter->schreibe(message, msgLength);
-	}
+    int total = msgLength + addressLength;
+    if (total)
+    {
+        zWriter->schreibe((char*)&GameClient::Message::API_MESSAGE, 1);
+        zWriter->schreibe((char*)&total, 4);
+        zWriter->schreibe(address, addressLength);
+        zWriter->schreibe(message, msgLength);
+    }
 }
 
 bool NetworkMessage::isBroadcast() const
 {
-	return broadcast;
+    return broadcast;
 }
 
 bool NetworkMessage::isEmpty() const
 {
-	return msgLength + addressLength <= 0;
+    return msgLength + addressLength <= 0;
 }
 
 bool NetworkMessage::isUseBackground() const
 {
-	return useBackground;
+    return useBackground;
 }
 
 NetworkMessage* NetworkMessage::clone() const
 {
-	NetworkMessage* result = new NetworkMessage();
-	result->message = new char[(int)msgLength];
-	memcpy(result->message, message, (int)msgLength);
-	result->msgLength = msgLength;
-	result->address = new char[(int)addressLength];
-	memcpy(result->address, address, (int)addressLength);
-	result->addressLength = addressLength;
-	result->broadcast = broadcast;
-	result->useBackground = useBackground;
-	return result;
+    NetworkMessage* result = new NetworkMessage();
+    result->message = new char[(int)msgLength];
+    memcpy(result->message, message, (int)msgLength);
+    result->msgLength = msgLength;
+    result->address = new char[(int)addressLength];
+    memcpy(result->address, address, (int)addressLength);
+    result->addressLength = addressLength;
+    result->broadcast = broadcast;
+    result->useBackground = useBackground;
+    return result;
 }

+ 25 - 24
FactoryCraft/NetworkMessage.h

@@ -1,8 +1,8 @@
 #pragma once
 
-#include <Writer.h>
-#include <Vec3.h>
 #include <ReferenceCounter.h>
+#include <Vec3.h>
+#include <Writer.h>
 
 class Chunk;
 class Block;
@@ -11,30 +11,31 @@ class Entity;
 class NetworkMessage : public virtual Framework::ReferenceCounter
 {
 private:
-	char* address;
-	char addressLength;
-	bool broadcast;
-	char* message;
-	int msgLength;
-	bool useBackground;
+    char* address;
+    char addressLength;
+    bool broadcast;
+    char* message;
+    int msgLength;
+    bool useBackground;
 
 public:
-	NetworkMessage();
-	~NetworkMessage();
+    NetworkMessage();
+    ~NetworkMessage();
 
-	void addressChunck(Chunk* zChunk);
-	void addressEntity(Entity* zEntity);
-	void addressBlock(Block* zBlock);;
-	void addressDimension();
-	void openDialog(Framework::Text dialogName);
-	void addressGui(Framework::Text elementId);
-	void setMessage(char* msg, int length);
-	void setUseBackground();
-	void sendToAll();
+    void addressChunck(Chunk* zChunk);
+    void addressEntity(Entity* zEntity);
+    void addressBlock(Block* zBlock);
+    ;
+    void addressDimension();
+    void openDialog(Framework::Text dialogName);
+    void addressGui(Framework::Text elementId);
+    void setMessage(char* msg, int length);
+    void setUseBackground();
+    void sendToAll();
 
-	void writeTo(Framework::StreamWriter* zWriter) const;
-	bool isBroadcast() const;
-	bool isEmpty() const;
-	bool isUseBackground() const;
-	NetworkMessage* clone() const;
+    void writeTo(Framework::StreamWriter* zWriter) const;
+    bool isBroadcast() const;
+    bool isEmpty() const;
+    bool isUseBackground() const;
+    NetworkMessage* clone() const;
 };

+ 30 - 32
FactoryCraft/NoBlock.cpp

@@ -1,83 +1,81 @@
 #include "NoBlock.h"
 
-
 NoBlockBlockType::NoBlockBlockType(int id, const Block* defaultB)
-	: BlockType(id, 0, ModelInfo("", "", 0), 0, 1, 0),
-	defaultB(defaultB)
+    : BlockType(id, 0, ModelInfo("", "", 0), 0, 1, 0),
+      defaultB(defaultB)
 {}
 
 Block* NoBlockBlockType::createBlock(Framework::Vec3<int> position) const
 {
-	return 0;
+    return 0;
 }
 
 Item* NoBlockBlockType::createItem() const
 {
-	return 0;
+    return 0;
 }
 
-Block* NoBlockBlockType::loadBlock(Framework::Vec3<int> position, Framework::StreamReader* zReader, int dimensionId) const
+Block* NoBlockBlockType::loadBlock(Framework::Vec3<int> position,
+    Framework::StreamReader* zReader,
+    int dimensionId) const
 {
-	return 0;
+    return 0;
 }
 
-void NoBlockBlockType::saveBlock(Block* zBlock, Framework::StreamWriter* zWriter) const
+void NoBlockBlockType::saveBlock(
+    Block* zBlock, Framework::StreamWriter* zWriter) const
 {}
 
 Item* NoBlockBlockType::getItemFromBlock(Block* zBlock) const
 {
-	return 0;
+    return 0;
 }
 
-Block* NoBlockBlockType::createBlockAt(Framework::Vec3<int> position, Item* zUsedItem) const
+Block* NoBlockBlockType::createBlockAt(
+    Framework::Vec3<int> position, Item* zUsedItem) const
 {
-	return 0;
+    return 0;
 }
 
 const Block* NoBlockBlockType::zDefault() const
 {
-	return defaultB;
+    return defaultB;
 }
 
-
-
 NoBlock::NoBlock()
-	: Block(BlockTypeEnum::NO_BLOCK, 0, { 0,0,0 }, false)
+    : Block(BlockTypeEnum::NO_BLOCK, 0, {0, 0, 0}, false)
 {
-	transparent = 0;
-	passable = 0;
-	hp = 0;
-	maxHP = 0;
-	hardness = 0;
+    transparent = 0;
+    passable = 0;
+    hp = 0;
+    maxHP = 0;
+    hardness = 0;
 }
 
 bool NoBlock::onTick(TickQueue* zQueue, int numTicks, bool& blocked)
 {
-	return 0;
+    return 0;
 }
 
 void NoBlock::onPostTick() {}
 
 const NoBlock NoBlock::INSTANCE;
 
-
-
 AirBlock::AirBlock()
-	: Block(BlockTypeEnum::AIR, 0, { 0,0,0 }, false)
+    : Block(BlockTypeEnum::AIR, 0, {0, 0, 0}, false)
 {
-	transparent = 1;
-	passable = 1;
-	hp = 0;
-	maxHP = 0;
-	hardness = 0;
+    transparent = 1;
+    passable = 1;
+    hp = 0;
+    maxHP = 0;
+    hardness = 0;
 }
 
 bool AirBlock::onTick(TickQueue* zQueue, int numTicks, bool& blocked)
 {
-	return 0;
+    return 0;
 }
 
-void AirBlock::onPostTick()
-{}
+void AirBlock::onPostTick() {}
 
 const AirBlock AirBlock::INSTANCE;

+ 24 - 20
FactoryCraft/NoBlock.h

@@ -1,48 +1,52 @@
 #pragma once
 
-#include "BlockType.h"
 #include "Block.h"
+#include "BlockType.h"
 
 class NoBlockBlockType : public BlockType
 {
 private:
-	const Block* defaultB;
+    const Block* defaultB;
 
 protected:
-	virtual Block* createBlock(Framework::Vec3<int> position) const override;
-	virtual Item* createItem() const override;
-	virtual Block* loadBlock(Framework::Vec3<int> position, Framework::StreamReader* zReader, int dimensionId) const override;
-	virtual void saveBlock(Block* zBlock, Framework::StreamWriter* zWriter) const override;
-	virtual Item* getItemFromBlock(Block* zBlock) const override;
-	virtual Block* createBlockAt(Framework::Vec3<int> position, Item* zUsedItem) const override;
-	virtual const Block* zDefault() const override;
+    virtual Block* createBlock(Framework::Vec3<int> position) const override;
+    virtual Item* createItem() const override;
+    virtual Block* loadBlock(Framework::Vec3<int> position,
+        Framework::StreamReader* zReader,
+        int dimensionId) const override;
+    virtual void saveBlock(
+        Block* zBlock, Framework::StreamWriter* zWriter) const override;
+    virtual Item* getItemFromBlock(Block* zBlock) const override;
+    virtual Block* createBlockAt(
+        Framework::Vec3<int> position, Item* zUsedItem) const override;
+    virtual const Block* zDefault() const override;
 
 public:
-	NoBlockBlockType(int id, const Block* defaultB);
+    NoBlockBlockType(int id, const Block* defaultB);
 };
 
-
 class NoBlock : public Block
 {
 public:
-	static const NoBlock INSTANCE;
+    static const NoBlock INSTANCE;
 
 protected:
-	NoBlock();
+    NoBlock();
 
-	virtual bool onTick(TickQueue* zQueue, int numTicks, bool& blocked) override;
-	virtual void onPostTick() override;
+    virtual bool onTick(
+        TickQueue* zQueue, int numTicks, bool& blocked) override;
+    virtual void onPostTick() override;
 };
 
-
 class AirBlock : public Block
 {
 public:
-	static const AirBlock INSTANCE;
+    static const AirBlock INSTANCE;
 
 protected:
-	AirBlock();
+    AirBlock();
 
-	virtual bool onTick(TickQueue* zQueue, int numTicks, bool& blocked) override;
-	virtual void onPostTick() override;
+    virtual bool onTick(
+        TickQueue* zQueue, int numTicks, bool& blocked) override;
+    virtual void onPostTick() override;
 };

+ 2 - 3
FactoryCraft/Noise.cpp

@@ -1,11 +1,10 @@
 #include "Noise.h"
 
-
 Noise::Noise()
-	: Framework::ReferenceCounter()
+    : Framework::ReferenceCounter()
 {}
 
 double Noise::getNoise(Framework::Vec3<double>& pos)
 {
-	return getNoise(pos.x, pos.y, pos.z);
+    return getNoise(pos.x, pos.y, pos.z);
 }

+ 12 - 12
FactoryCraft/Noise.h

@@ -1,20 +1,20 @@
 #pragma once
 
-#include <Vec3.h>
 #include <ReferenceCounter.h>
+#include <Vec3.h>
 
 class Noise : public virtual Framework::ReferenceCounter
 {
 public:
-	Noise();
-	virtual int getSeed() const = 0;
-	/// <summary>
-	/// get the noise value at a certain destination
-	/// </summary>
-	/// <param name="x">the x coord of the noice value</param>
-	/// <param name="y">the y coord of the noice value</param>
-	/// <param name="z">the z coord of the noice value</param>
-	/// <returns>the noise value scaled to a range from 0 to 1</returns>
-	virtual double getNoise(double x, double y, double z) = 0;
-	double getNoise(Framework::Vec3<double>& pos);
+    Noise();
+    virtual int getSeed() const = 0;
+    /// <summary>
+    /// get the noise value at a certain destination
+    /// </summary>
+    /// <param name="x">the x coord of the noice value</param>
+    /// <param name="y">the y coord of the noice value</param>
+    /// <param name="z">the z coord of the noice value</param>
+    /// <returns>the noise value scaled to a range from 0 to 1</returns>
+    virtual double getNoise(double x, double y, double z) = 0;
+    double getNoise(Framework::Vec3<double>& pos);
 };

+ 29 - 26
FactoryCraft/NoiseInterpolator.cpp

@@ -1,44 +1,47 @@
 #include "NoiseInterpolator.h"
+
 #include "Text.h"
 
 using namespace Framework;
 
-NoiseInterpolator::NoiseInterpolator(int seed, std::function<Noise* (int)> noiseSupplier, int width, int height)
-	: Noise(),
-	noiseSize(width, height),
-	cache(10, [](int k) { return k; }, CacheCleanupStrategy::LONGEST_NOT_USED),
-	noiseSupplier(noiseSupplier),
-	seed(seed)
+NoiseInterpolator::NoiseInterpolator(
+    int seed, std::function<Noise*(int)> noiseSupplier, int width, int height)
+    : Noise(),
+      noiseSize(width, height),
+      cache(
+          10, [](int k) { return k; }, CacheCleanupStrategy::LONGEST_NOT_USED),
+      noiseSupplier(noiseSupplier),
+      seed(seed)
 {}
 
 double NoiseInterpolator::getRealNoise(double x, double y, double z)
 {
-	int ix = (int)ceil(x), iy = (int)ceil(y);
-	int xOff = ix % noiseSize.x, yOff = iy % noiseSize.y;
-	int xI = ix / noiseSize.x, yI = iy / noiseSize.y;
-	if (ix < 0)
-		xI--;
-	if (iy < 0)
-		yI--;
-	int key = ((xI & 0xFFFF) << 16) | (yI & 0xFFFF);
-	if (!cache.has(key))
-		cache.put(key, RCPointer<Noise>::of(noiseSupplier(key + seed)));
-	return cache.get(key)->getNoise((xOff + 1 - (ix - x)), (yOff + 1 - (iy - y)), z);
+    int ix = (int)ceil(x), iy = (int)ceil(y);
+    int xOff = ix % noiseSize.x, yOff = iy % noiseSize.y;
+    int xI = ix / noiseSize.x, yI = iy / noiseSize.y;
+    if (ix < 0) xI--;
+    if (iy < 0) yI--;
+    int key = ((xI & 0xFFFF) << 16) | (yI & 0xFFFF);
+    if (!cache.has(key))
+        cache.put(key, RCPointer<Noise>::of(noiseSupplier(key + seed)));
+    return cache.get(key)->getNoise(
+        (xOff + 1 - (ix - x)), (yOff + 1 - (iy - y)), z);
 }
 
 double NoiseInterpolator::getNoise(double x, double y, double z)
 {
-	const double weights[6] = { 0.32, 0.17, 0.09, 0.05, 0.03, 0.02 };
-	double sum = 0;
-	for (int xi = -5; xi <= 5; xi++)
-	{
-		for (int yi = -5; yi <= 5; yi++)
-			sum += getRealNoise(x + xi, y + yi, z) * weights[abs(xi)] * weights[abs(yi)];
-	}
-	return sum;
+    const double weights[6] = {0.32, 0.17, 0.09, 0.05, 0.03, 0.02};
+    double sum = 0;
+    for (int xi = -5; xi <= 5; xi++)
+    {
+        for (int yi = -5; yi <= 5; yi++)
+            sum += getRealNoise(x + xi, y + yi, z) * weights[abs(xi)]
+                 * weights[abs(yi)];
+    }
+    return sum;
 }
 
 int NoiseInterpolator::getSeed() const
 {
-	return seed;
+    return seed;
 }

+ 12 - 9
FactoryCraft/NoiseInterpolator.h

@@ -1,21 +1,24 @@
 #pragma once
 
+#include "Cache.h"
 #include "Noise.h"
 #include "Punkt.h"
-#include "Cache.h"
 #include "RCPointer.h"
 
 class NoiseInterpolator : public Noise
 {
-	Framework::Punkt noiseSize;
-	Framework::Cache<int, Framework::RCPointer<Noise>> cache;
-	std::function<Noise* (int)> noiseSupplier;
-	int seed;
+    Framework::Punkt noiseSize;
+    Framework::Cache<int, Framework::RCPointer<Noise>> cache;
+    std::function<Noise*(int)> noiseSupplier;
+    int seed;
 
-	double getRealNoise(double x, double y, double z);
+    double getRealNoise(double x, double y, double z);
 
 public:
-	NoiseInterpolator(int seed, std::function<Noise* (int)> noiseSupplier, int width, int height);
-	double getNoise(double x, double y, double z) override;
-	int getSeed() const override;
+    NoiseInterpolator(int seed,
+        std::function<Noise*(int)> noiseSupplier,
+        int width,
+        int height);
+    double getNoise(double x, double y, double z) override;
+    int getSeed() const override;
 };

+ 27 - 27
FactoryCraft/OverworldDimension.cpp

@@ -1,49 +1,49 @@
 #include "OverworldDimension.h"
-#include "GrasslandBiom.h"
+
 #include "FastNoiseWrapper.h"
+#include "GrasslandBiom.h"
 #include "RandNoise.h"
 #include "WormCaveGenerator.h"
 
-
 OverworldDimension::OverworldDimension()
     : DimensionGenerator(
         DimensionEnum::OVERWORLD, new WormCaveGenerator(75, 150, 1, 6, 0.1f))
 {
-	registerBiom(new GrasslandBiom(), 1.0);
-	biomNoise = 0;
-	structureNoise = 0;
+    registerBiom(new GrasslandBiom(), 1.0);
+    biomNoise = 0;
+    structureNoise = 0;
 }
 
 OverworldDimension::~OverworldDimension()
 {
-	if (biomNoise)
-		biomNoise->release();
-	if (structureNoise)
-		structureNoise->release();
+    if (biomNoise) biomNoise->release();
+    if (structureNoise) structureNoise->release();
 }
 
 Noise* OverworldDimension::zBiomNoise()
 {
-	if (biomNoise)
-		return biomNoise;
-	FastNoiseLite* noise = new FastNoiseLite(seed);
-	noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Cellular);
-	noise->SetRotationType3D(FastNoiseLite::RotationType3D::RotationType3D_None);
-	noise->SetFrequency(0.015f);
-	noise->SetFractalType(FastNoiseLite::FractalType::FractalType_None);
-	noise->SetCellularDistanceFunction(FastNoiseLite::CellularDistanceFunction::CellularDistanceFunction_Hybrid);
-	noise->SetCellularReturnType(FastNoiseLite::CellularReturnType::CellularReturnType_CellValue);
-	noise->SetCellularJitter(1.f);
-	noise->SetDomainWarpType(FastNoiseLite::DomainWarpType::DomainWarpType_OpenSimplex2Reduced);
-	noise->SetDomainWarpAmp(30.f);
-	biomNoise = new FastNoiseWrapper(noise, seed);
-	return biomNoise;
+    if (biomNoise) return biomNoise;
+    FastNoiseLite* noise = new FastNoiseLite(seed);
+    noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Cellular);
+    noise->SetRotationType3D(
+        FastNoiseLite::RotationType3D::RotationType3D_None);
+    noise->SetFrequency(0.015f);
+    noise->SetFractalType(FastNoiseLite::FractalType::FractalType_None);
+    noise->SetCellularDistanceFunction(FastNoiseLite::CellularDistanceFunction::
+            CellularDistanceFunction_Hybrid);
+    noise->SetCellularReturnType(
+        FastNoiseLite::CellularReturnType::CellularReturnType_CellValue);
+    noise->SetCellularJitter(1.f);
+    noise->SetDomainWarpType(
+        FastNoiseLite::DomainWarpType::DomainWarpType_OpenSimplex2Reduced);
+    noise->SetDomainWarpAmp(30.f);
+    biomNoise = new FastNoiseWrapper(noise, seed);
+    return biomNoise;
 }
 
 Noise* OverworldDimension::zStructureNoise()
 {
-	if (structureNoise)
-		return structureNoise;
-	structureNoise = new RandNoise(seed);
-	return structureNoise;
+    if (structureNoise) return structureNoise;
+    structureNoise = new RandNoise(seed);
+    return structureNoise;
 }

+ 7 - 7
FactoryCraft/OverworldDimension.h

@@ -1,18 +1,18 @@
 #pragma once
 
 #include "DimensionGenerator.h"
-#include "StaticRegistry.h"
 #include "Noise.h"
+#include "StaticRegistry.h"
 
 class OverworldDimension : public DimensionGenerator
 {
 private:
-	Noise* biomNoise;
-	Noise* structureNoise;
+    Noise* biomNoise;
+    Noise* structureNoise;
 
 public:
-	OverworldDimension();
-	~OverworldDimension();
-	Noise* zBiomNoise() override;
-	Noise* zStructureNoise() override;
+    OverworldDimension();
+    ~OverworldDimension();
+    Noise* zBiomNoise() override;
+    Noise* zStructureNoise() override;
 };

+ 341 - 312
FactoryCraft/Player.cpp

@@ -1,372 +1,401 @@
 #include "Player.h"
+
 #include "Game.h"
-#include "PlayerHand.h"
 #include "ItemFilter.h"
-
+#include "PlayerHand.h"
 
 Player::Player(Framework::Vec3<float> location, int dimensionId, int entityId)
-	: Entity(EntityTypeEnum::PLAYER, location, dimensionId, entityId),
-	BasicShapedCrafter(3, 3, this, "inventory")
+    : Entity(EntityTypeEnum::PLAYER, location, dimensionId, entityId),
+      BasicShapedCrafter(3, 3, this, "inventory")
 {
-	for (int i = 0; i < 10; i++)
-	{
-		ItemSlot* slot = new ItemSlot("ItemBar", 50, 0, i, 0, ANY_DIRECTION, 0);
-		itemBar.add(slot);
-		addSlot(slot);
-	}
-	for (int i = 0; i < 30; i++)
-	{
-		ItemSlot* slot = new ItemSlot("Inventory", 50, 0, i + 10, 0, ANY_DIRECTION, 0);
-		addSlot(slot);
-	}
-	leftHandPosition = 0;
-	maxHP = 10;
-	currentHP = 10;
-	stamina = 10;
-	maxStamina = 10;
-	hunger = 10;
-	maxHunger = 10;
-	thirst = 10;
-	maxThirst = 10;
-	keyState = 0;
-	jumping = 0;
-	faceOffset = { 0.f, 0.f, 1.5f };
-	targetDistanceLimit = 4;
-	maxMovementSpeed = 4;
+    for (int i = 0; i < 10; i++)
+    {
+        ItemSlot* slot = new ItemSlot("ItemBar", 50, 0, i, 0, ANY_DIRECTION, 0);
+        itemBar.add(slot);
+        addSlot(slot);
+    }
+    for (int i = 0; i < 30; i++)
+    {
+        ItemSlot* slot
+            = new ItemSlot("Inventory", 50, 0, i + 10, 0, ANY_DIRECTION, 0);
+        addSlot(slot);
+    }
+    leftHandPosition = 0;
+    maxHP = 10;
+    currentHP = 10;
+    stamina = 10;
+    maxStamina = 10;
+    hunger = 10;
+    maxHunger = 10;
+    thirst = 10;
+    maxThirst = 10;
+    keyState = 0;
+    jumping = 0;
+    faceOffset = {0.f, 0.f, 1.5f};
+    targetDistanceLimit = 4;
+    maxMovementSpeed = 4;
 }
 
 void Player::onTargetChange()
 {
-	NetworkMessage* msg = new NetworkMessage();
-	ActionTarget::toMessage(zTarget(), msg);
-	Game::INSTANCE->sendMessage(msg, this);
+    NetworkMessage* msg = new NetworkMessage();
+    ActionTarget::toMessage(zTarget(), msg);
+    Game::INSTANCE->sendMessage(msg, this);
 }
 
 Framework::Text Player::getInventoryUIML()
 {
-	Framework::Text result = "<dialog id=\"player_inventory\" title=\"Inventory\" width=\"610\" height=\"450\">";
+    Framework::Text result
+        = "<dialog id=\"player_inventory\" title=\"Inventory\" width=\"610\" "
+          "height=\"450\">";
 
-	result += "<craftingGrid id=\"crafting\" margin-top=\"9\" align-top=\"start\" align-left=\"start\" margin-left=\"9\" width=\"282\" height=\"172\" rowSize=\"3\" colSize=\"3\" numOutputSlots=\"1\" target=\"";
-	result += getId();
-	result += "\"/>";
+    result += "<craftingGrid id=\"crafting\" margin-top=\"9\" "
+              "align-top=\"start\" align-left=\"start\" margin-left=\"9\" "
+              "width=\"282\" height=\"172\" rowSize=\"3\" colSize=\"3\" "
+              "numOutputSlots=\"1\" target=\"";
+    result += getId();
+    result += "\"/>";
 
-	result += "<inventory id=\"inventory\" margin-bottom=\"18\" align-bottom=\"item_bar\" align-left=\"start\" margin-left=\"9\" width=\"592\" height=\"172\" rowSize=\"10\" numSlots=\"30\" slotNameFilter=\"Inventory\" target=\"";
-	result += getId();
-	result += "\"/>";
+    result += "<inventory id=\"inventory\" margin-bottom=\"18\" "
+              "align-bottom=\"item_bar\" align-left=\"start\" "
+              "margin-left=\"9\" width=\"592\" height=\"172\" rowSize=\"10\" "
+              "numSlots=\"30\" slotNameFilter=\"Inventory\" target=\"";
+    result += getId();
+    result += "\"/>";
 
-	result += "<inventory id=\"item_bar\" margin-bottom=\"9\" align-bottom=\"end\" align-left=\"start\" margin-left=\"9\" width=\"592\" height=\"52\" rowSize=\"10\" numSlots=\"10\" slotNameFilter=\"ItemBar\" target=\"";
-	result += getId();
-	result += "\"/>";
+    result += "<inventory id=\"item_bar\" margin-bottom=\"9\" "
+              "align-bottom=\"end\" align-left=\"start\" margin-left=\"9\" "
+              "width=\"592\" height=\"52\" rowSize=\"10\" numSlots=\"10\" "
+              "slotNameFilter=\"ItemBar\" target=\"";
+    result += getId();
+    result += "\"/>";
 
-	result += "</dialog>";
-	return result;
+    result += "</dialog>";
+    return result;
 }
 
 Framework::Text Player::getPlayerGUI()
 {
-	Framework::Text result = "<gui id=\"player_gui\">";
+    Framework::Text result = "<gui id=\"player_gui\">";
 
-	result += "<itemBar id=\"gui_item_bar\" margin-bottom=\"9\" align-bottom=\"end\" align-left=\"center\" width=\"592\" height=\"52\" rowSize=\"10\" slotNameFilter=\"ItemBar\" target=\"";
-	result += getId();
-	result += "\"/>";
+    result
+        += "<itemBar id=\"gui_item_bar\" margin-bottom=\"9\" "
+           "align-bottom=\"end\" align-left=\"center\" width=\"592\" "
+           "height=\"52\" rowSize=\"10\" slotNameFilter=\"ItemBar\" target=\"";
+    result += getId();
+    result += "\"/>";
 
-	result += "</gui>";
-	return result;
+    result += "</gui>";
+    return result;
 }
 
 void Player::useItemSlot(ItemSlot* zSlot)
 {
-	if (zSlot->zStack())
-	{
-		ItemStack* stack = takeItemsOut(zSlot, 1, NO_DIRECTION);
-		if (stack)
-		{
-			Item* item = stack->extractFromStack();
-			Entity::useItem(item->getTypeId(), item);
-			if (item->getHp() > 0)
-			{
-				if (item->getDurability() > 0)
-				{ // put used item back
-					stack->addToStack(item);
-					if (!zSlot->numberOfAddableItems(stack, NO_DIRECTION))
-					{ // move other items to other space
-						ItemStack* oldItems = takeItemsOut(zSlot, zSlot->zStack()->getSize(), NO_DIRECTION);
-						addItems(zSlot, stack, NO_DIRECTION);
-						addItems(oldItems, NO_DIRECTION);
-						if (oldItems->getSize() > 0)
-						{
-							// TODO: drop remaining items
-						}
-					}
-					else
-						addItems(zSlot, stack, NO_DIRECTION);
-				}
-				else
-				{ // item is broken
-					// move other items of the same type to the slot
-					Array< ItemSlot*> fromSlots;
-					for (ItemSlot* slot : *this)
-					{
-						if (slot != zSlot)
-							fromSlots.add(slot);
-					}
-					Array<ItemSlot*> targetSlots;
-					targetSlots.add(zSlot);
-					TypeItemFilter filter(item->zItemType());
-					localTransaction(&fromSlots, &targetSlots, &filter, zSlot->getFreeSpace(), NO_DIRECTION, NO_DIRECTION);
-					// place broken item in inventory
-					const ItemType* brokenType = item->zItemType()->zBrokenItemType();
-					if (brokenType)
-					{
-						Item* broken = item->zItemType()->breakItem(item);
-						if (broken)
-						{
-							stack->addToStack(broken);
-							addItems(stack, NO_DIRECTION);
-							if (stack->getSize() > 0)
-							{
-								// TODO: drop remaining items
-							}
-						}
-					}
-					item->release();
-				}
-			}
-			else
-				item->release();
-			stack->release();
-		}
-	}
-	else
-		Entity::useItem(ItemTypeEnum::PLAYER_HAND, 0); // hand usage
+    if (zSlot->zStack())
+    {
+        ItemStack* stack = takeItemsOut(zSlot, 1, NO_DIRECTION);
+        if (stack)
+        {
+            Item* item = stack->extractFromStack();
+            Entity::useItem(item->getTypeId(), item);
+            if (item->getHp() > 0)
+            {
+                if (item->getDurability() > 0)
+                { // put used item back
+                    stack->addToStack(item);
+                    if (!zSlot->numberOfAddableItems(stack, NO_DIRECTION))
+                    { // move other items to other space
+                        ItemStack* oldItems = takeItemsOut(
+                            zSlot, zSlot->zStack()->getSize(), NO_DIRECTION);
+                        addItems(zSlot, stack, NO_DIRECTION);
+                        addItems(oldItems, NO_DIRECTION);
+                        if (oldItems->getSize() > 0)
+                        {
+                            // TODO: drop remaining items
+                        }
+                    }
+                    else
+                        addItems(zSlot, stack, NO_DIRECTION);
+                }
+                else
+                { // item is broken
+                    // move other items of the same type to the slot
+                    Array<ItemSlot*> fromSlots;
+                    for (ItemSlot* slot : *this)
+                    {
+                        if (slot != zSlot) fromSlots.add(slot);
+                    }
+                    Array<ItemSlot*> targetSlots;
+                    targetSlots.add(zSlot);
+                    TypeItemFilter filter(item->zItemType());
+                    localTransaction(&fromSlots,
+                        &targetSlots,
+                        &filter,
+                        zSlot->getFreeSpace(),
+                        NO_DIRECTION,
+                        NO_DIRECTION);
+                    // place broken item in inventory
+                    const ItemType* brokenType
+                        = item->zItemType()->zBrokenItemType();
+                    if (brokenType)
+                    {
+                        Item* broken = item->zItemType()->breakItem(item);
+                        if (broken)
+                        {
+                            stack->addToStack(broken);
+                            addItems(stack, NO_DIRECTION);
+                            if (stack->getSize() > 0)
+                            {
+                                // TODO: drop remaining items
+                            }
+                        }
+                    }
+                    item->release();
+                }
+            }
+            else
+                item->release();
+            stack->release();
+        }
+    }
+    else
+        Entity::useItem(ItemTypeEnum::PLAYER_HAND, 0); // hand usage
 }
 
 void Player::setName(Framework::Text name)
 {
-	this->name = name;
+    this->name = name;
 }
 
 const char* Player::getName() const
 {
-	return name;
+    return name;
 }
 
 void Player::tick(const Dimension* zDimension)
 {
-	if ((keyState | Key::LEFT_HAND_ACTION) == keyState)
-		useItemSlot(itemBar.get(leftHandPosition));
-	if ((keyState | Key::RIGHT_HAND_ACTION) == keyState)
-		useItemSlot(itemBar.get((leftHandPosition + 1) % itemBar.getEintragAnzahl()));
-	return Entity::tick(zDimension);
+    if ((keyState | Key::LEFT_HAND_ACTION) == keyState)
+        useItemSlot(itemBar.get(leftHandPosition));
+    if ((keyState | Key::RIGHT_HAND_ACTION) == keyState)
+        useItemSlot(
+            itemBar.get((leftHandPosition + 1) % itemBar.getEintragAnzahl()));
+    return Entity::tick(zDimension);
 }
 
-void Player::playerApi(Framework::StreamReader* zRequest, NetworkMessage* zResponse)
+void Player::playerApi(
+    Framework::StreamReader* zRequest, NetworkMessage* zResponse)
 {
-	char byte;
-	zRequest->lese(&byte, 1);
-	switch (byte)
-	{
-	case 0:
-		// stop action
-		zRequest->lese(&byte, 1);
-		switch (byte)
-		{
-		case 8:
-			keyState = keyState & ~Key::LEFT_HAND_ACTION;
-			break;
-		case 9:
-			keyState = keyState & ~Key::RIGHT_HAND_ACTION;
-			break;
-		}
-		break;
-	case 1:
-		// begin action
-		zRequest->lese(&byte, 1);
-		switch (byte)
-		{
-		case 8:
-			keyState = keyState | Key::LEFT_HAND_ACTION;
-			break;
-		case 9:
-			keyState = keyState | Key::RIGHT_HAND_ACTION;
-			break;
-		}
-		break;
-	case 2:
-		// set movement
-	{
-		MovementFrame frame;
-		zRequest->lese((char*)&frame.direction.x, 4);
-		zRequest->lese((char*)&frame.direction.y, 4);
-		zRequest->lese((char*)&frame.direction.z, 4);
-		zRequest->lese((char*)&frame.targetPosition.x, 4);
-		zRequest->lese((char*)&frame.targetPosition.y, 4);
-		zRequest->lese((char*)&frame.targetPosition.z, 4);
-		zRequest->lese((char*)&frame.movementFlags, 4);
-		zRequest->lese((char*)&frame.duration, 8);
-		addMovementFrame(frame);
-		calculateTarget(frame.targetPosition, frame.direction);
-		break;
-	}
-	case 3:
-	{ // switch item bar position
-		zRequest->lese((char*)&leftHandPosition, 4);
-		leftHandPosition = leftHandPosition % itemBar.getEintragAnzahl();
-		NetworkMessage* msg = new NetworkMessage();
-		msg->addressGui("gui_item_bar");
-		char* message = new char[5];
-		message[0] = 3; // set selected slot
-		*(int*)(message + 1) = leftHandPosition;
-		msg->setMessage(message, 5);
-		Game::INSTANCE->sendMessage(msg, this);
-		break;
-	}
-	case 4:
-	{
-		// open inventory
-		zResponse->openDialog("player_inventory");
-		Text uiml = getInventoryUIML();
-		int msgSize = 4 + uiml.getLength();
-		char* msg = new char[msgSize];
-		*(int*)msg = uiml.getLength();
-		memcpy(msg + 4, uiml.getText(), uiml.getLength());
-		zResponse->setMessage(msg, msgSize);
-		break;
-	}
-	case 5:
-	{
-		// request gui
-		Text uiml = getPlayerGUI();
-		int msgSize = 6 + uiml.getLength();
-		char* msg = new char[msgSize];
-		msg[0] = 2; // gui message
-		msg[1] = 2; // set gui
-		*(int*)(msg + 2) = uiml.getLength();
-		memcpy(msg + 6, uiml.getText(), uiml.getLength());
-		zResponse->setMessage(msg, msgSize);
-		break;
-	}
-	case 6:
-	{ // inventory transaction
-		bool isEntity;
-		zRequest->lese((char*)&isEntity, 1);
-		Inventory* source;
-		if (isEntity)
-		{
-			int id;
-			zRequest->lese((char*)&id, 4);
-			source = Game::INSTANCE->zEntity(id, getCurrentDimensionId());
-		}
-		else
-		{
-			int dim;
-			Framework::Vec3<int> pos;
-			zRequest->lese((char*)&dim, 4);
-			zRequest->lese((char*)&pos.x, 4);
-			zRequest->lese((char*)&pos.y, 4);
-			zRequest->lese((char*)&pos.z, 4);
-			source = Game::INSTANCE->zBlockAt(pos, dim);
-		}
-		int sourceSlotId;
-		zRequest->lese((char*)&sourceSlotId, 4);
-		zRequest->lese((char*)&isEntity, 1);
-		Inventory* target;
-		if (isEntity)
-		{
-			int id;
-			zRequest->lese((char*)&id, 4);
-			target = Game::INSTANCE->zEntity(id, getCurrentDimensionId());
-		}
-		else
-		{
-			int dim;
-			Framework::Vec3<int> pos;
-			zRequest->lese((char*)&dim, 4);
-			zRequest->lese((char*)&pos.x, 4);
-			zRequest->lese((char*)&pos.y, 4);
-			zRequest->lese((char*)&pos.z, 4);
-			target = Game::INSTANCE->zBlockAt(pos, dim);
-		}
-		if (source && target)
-		{
-			int targetSlotId;
-			zRequest->lese((char*)&targetSlotId, 4);
-			SpecificSlotFilter filter(sourceSlotId, targetSlotId);
-			source->interactWith(target, Direction::NO_DIRECTION).pushItems(source->zSlot(sourceSlotId)->getNumberOfItems(), &filter);
-		}
-		break;
-	}
-	case 7: // craft action
-	{
-		bool isEntity;
-		zRequest->lese((char*)&isEntity, 1);
-		BasicShapedCrafter* target;
-		if (isEntity)
-		{
-			int id;
-			zRequest->lese((char*)&id, 4);
-			target = dynamic_cast<BasicShapedCrafter*>(Game::INSTANCE->zEntity(id, getCurrentDimensionId()));
-		}
-		else
-		{
-			int dim;
-			Framework::Vec3<int> pos;
-			zRequest->lese((char*)&dim, 4);
-			zRequest->lese((char*)&pos.x, 4);
-			zRequest->lese((char*)&pos.y, 4);
-			zRequest->lese((char*)&pos.z, 4);
-			target = dynamic_cast<BasicShapedCrafter*>(Game::INSTANCE->zRealBlockInstance(pos, dim));
-		}
-		if (target)
-			target->applyCurrentRecipie();
-		break;
-	}
-	}
+    char byte;
+    zRequest->lese(&byte, 1);
+    switch (byte)
+    {
+    case 0:
+        // stop action
+        zRequest->lese(&byte, 1);
+        switch (byte)
+        {
+        case 8:
+            keyState = keyState & ~Key::LEFT_HAND_ACTION;
+            break;
+        case 9:
+            keyState = keyState & ~Key::RIGHT_HAND_ACTION;
+            break;
+        }
+        break;
+    case 1:
+        // begin action
+        zRequest->lese(&byte, 1);
+        switch (byte)
+        {
+        case 8:
+            keyState = keyState | Key::LEFT_HAND_ACTION;
+            break;
+        case 9:
+            keyState = keyState | Key::RIGHT_HAND_ACTION;
+            break;
+        }
+        break;
+    case 2:
+        // set movement
+        {
+            MovementFrame frame;
+            zRequest->lese((char*)&frame.direction.x, 4);
+            zRequest->lese((char*)&frame.direction.y, 4);
+            zRequest->lese((char*)&frame.direction.z, 4);
+            zRequest->lese((char*)&frame.targetPosition.x, 4);
+            zRequest->lese((char*)&frame.targetPosition.y, 4);
+            zRequest->lese((char*)&frame.targetPosition.z, 4);
+            zRequest->lese((char*)&frame.movementFlags, 4);
+            zRequest->lese((char*)&frame.duration, 8);
+            addMovementFrame(frame);
+            calculateTarget(frame.targetPosition, frame.direction);
+            break;
+        }
+    case 3:
+        { // switch item bar position
+            zRequest->lese((char*)&leftHandPosition, 4);
+            leftHandPosition = leftHandPosition % itemBar.getEintragAnzahl();
+            NetworkMessage* msg = new NetworkMessage();
+            msg->addressGui("gui_item_bar");
+            char* message = new char[5];
+            message[0] = 3; // set selected slot
+            *(int*)(message + 1) = leftHandPosition;
+            msg->setMessage(message, 5);
+            Game::INSTANCE->sendMessage(msg, this);
+            break;
+        }
+    case 4:
+        {
+            // open inventory
+            zResponse->openDialog("player_inventory");
+            Text uiml = getInventoryUIML();
+            int msgSize = 4 + uiml.getLength();
+            char* msg = new char[msgSize];
+            *(int*)msg = uiml.getLength();
+            memcpy(msg + 4, uiml.getText(), uiml.getLength());
+            zResponse->setMessage(msg, msgSize);
+            break;
+        }
+    case 5:
+        {
+            // request gui
+            Text uiml = getPlayerGUI();
+            int msgSize = 6 + uiml.getLength();
+            char* msg = new char[msgSize];
+            msg[0] = 2; // gui message
+            msg[1] = 2; // set gui
+            *(int*)(msg + 2) = uiml.getLength();
+            memcpy(msg + 6, uiml.getText(), uiml.getLength());
+            zResponse->setMessage(msg, msgSize);
+            break;
+        }
+    case 6:
+        { // inventory transaction
+            bool isEntity;
+            zRequest->lese((char*)&isEntity, 1);
+            Inventory* source;
+            if (isEntity)
+            {
+                int id;
+                zRequest->lese((char*)&id, 4);
+                source = Game::INSTANCE->zEntity(id, getCurrentDimensionId());
+            }
+            else
+            {
+                int dim;
+                Framework::Vec3<int> pos;
+                zRequest->lese((char*)&dim, 4);
+                zRequest->lese((char*)&pos.x, 4);
+                zRequest->lese((char*)&pos.y, 4);
+                zRequest->lese((char*)&pos.z, 4);
+                source = Game::INSTANCE->zBlockAt(pos, dim);
+            }
+            int sourceSlotId;
+            zRequest->lese((char*)&sourceSlotId, 4);
+            zRequest->lese((char*)&isEntity, 1);
+            Inventory* target;
+            if (isEntity)
+            {
+                int id;
+                zRequest->lese((char*)&id, 4);
+                target = Game::INSTANCE->zEntity(id, getCurrentDimensionId());
+            }
+            else
+            {
+                int dim;
+                Framework::Vec3<int> pos;
+                zRequest->lese((char*)&dim, 4);
+                zRequest->lese((char*)&pos.x, 4);
+                zRequest->lese((char*)&pos.y, 4);
+                zRequest->lese((char*)&pos.z, 4);
+                target = Game::INSTANCE->zBlockAt(pos, dim);
+            }
+            if (source && target)
+            {
+                int targetSlotId;
+                zRequest->lese((char*)&targetSlotId, 4);
+                SpecificSlotFilter filter(sourceSlotId, targetSlotId);
+                source->interactWith(target, Direction::NO_DIRECTION)
+                    .pushItems(source->zSlot(sourceSlotId)->getNumberOfItems(),
+                        &filter);
+            }
+            break;
+        }
+    case 7: // craft action
+        {
+            bool isEntity;
+            zRequest->lese((char*)&isEntity, 1);
+            BasicShapedCrafter* target;
+            if (isEntity)
+            {
+                int id;
+                zRequest->lese((char*)&id, 4);
+                target = dynamic_cast<BasicShapedCrafter*>(
+                    Game::INSTANCE->zEntity(id, getCurrentDimensionId()));
+            }
+            else
+            {
+                int dim;
+                Framework::Vec3<int> pos;
+                zRequest->lese((char*)&dim, 4);
+                zRequest->lese((char*)&pos.x, 4);
+                zRequest->lese((char*)&pos.y, 4);
+                zRequest->lese((char*)&pos.z, 4);
+                target = dynamic_cast<BasicShapedCrafter*>(
+                    Game::INSTANCE->zRealBlockInstance(pos, dim));
+            }
+            if (target) target->applyCurrentRecipie();
+            break;
+        }
+    }
 }
 
 void Player::onFall(float collisionSpeed)
 {
-	Entity::onFall(collisionSpeed);
-	gravityMultiplier = 1.f;
-	jumping = 0;
+    Entity::onFall(collisionSpeed);
+    gravityMultiplier = 1.f;
+    jumping = 0;
 }
 
-
-
 PlayerEntityType::PlayerEntityType()
-    : EntityType(
-        EntityTypeEnum::PLAYER, ModelInfo("player", "player.ltdb/player.png", 6))
+    : EntityType(EntityTypeEnum::PLAYER,
+        ModelInfo("player", "player.ltdb/player.png", 6))
 {}
 
-void PlayerEntityType::loadSuperEntity(Entity* zEntity, Framework::StreamReader* zReader) const
+void PlayerEntityType::loadSuperEntity(
+    Entity* zEntity, Framework::StreamReader* zReader) const
 {
-	Player* zPlayer = dynamic_cast<Player*>(zEntity);
-	if (!zPlayer)
-		throw "PlayerEntityType::loadSuperEntity was called with an entity witch is not an instance of Player";
-	zReader->lese((char*)&zPlayer->leftHandPosition, 4);
-	char len;
-	zReader->lese(&len, 1);
-	char* name = new char[(int)len + 1];
-	zReader->lese(name, (int)len);
-	name[(int)len] = 0;
-	zPlayer->name = name;
-	delete[] name;
-	EntityType::loadSuperEntity(zPlayer, zReader);
+    Player* zPlayer = dynamic_cast<Player*>(zEntity);
+    if (!zPlayer)
+        throw "PlayerEntityType::loadSuperEntity was called with an entity "
+              "witch is not an instance of Player";
+    zReader->lese((char*)&zPlayer->leftHandPosition, 4);
+    char len;
+    zReader->lese(&len, 1);
+    char* name = new char[(int)len + 1];
+    zReader->lese(name, (int)len);
+    name[(int)len] = 0;
+    zPlayer->name = name;
+    delete[] name;
+    EntityType::loadSuperEntity(zPlayer, zReader);
 }
 
-void PlayerEntityType::saveSuperEntity(Entity* zEntity, Framework::StreamWriter* zWriter) const
+void PlayerEntityType::saveSuperEntity(
+    Entity* zEntity, Framework::StreamWriter* zWriter) const
 {
-	Player* zPlayer = dynamic_cast<Player*>(zEntity);
-	if (!zPlayer)
-		throw "PlayerEntityType::saveSuperEntity was called with an entity witch is not an instance of Player";
-	zWriter->schreibe((char*)&zPlayer->leftHandPosition, 4);
-	char len = (char)textLength(zPlayer->getName());
-	zWriter->schreibe(&len, 1);
-	zWriter->schreibe(zPlayer->getName(), (int)len);
-	EntityType::saveSuperEntity(zEntity, zWriter);
+    Player* zPlayer = dynamic_cast<Player*>(zEntity);
+    if (!zPlayer)
+        throw "PlayerEntityType::saveSuperEntity was called with an entity "
+              "witch is not an instance of Player";
+    zWriter->schreibe((char*)&zPlayer->leftHandPosition, 4);
+    char len = (char)textLength(zPlayer->getName());
+    zWriter->schreibe(&len, 1);
+    zWriter->schreibe(zPlayer->getName(), (int)len);
+    EntityType::saveSuperEntity(zEntity, zWriter);
 }
 
-Entity* PlayerEntityType::createEntity(Framework::Vec3<float> position, int dimensionId, int entityId) const
+Entity* PlayerEntityType::createEntity(
+    Framework::Vec3<float> position, int dimensionId, int entityId) const
 {
-	return new Player(position, dimensionId, entityId);
+    return new Player(position, dimensionId, entityId);
 }

+ 37 - 30
FactoryCraft/Player.h

@@ -1,56 +1,63 @@
 #pragma once
 
+#include <Array.h>
+
+#include "CraftingStorage.h"
 #include "Entity.h"
 #include "EntityType.h"
-#include "CraftingStorage.h"
-#include <Array.h>
 
 class PlayerEntityType;
 
-class Player : public Entity, public BasicShapedCrafter
+class Player : public Entity,
+               public BasicShapedCrafter
 {
 public:
-	class Key
-	{
-	public:
-		const static __int64 LEFT_HAND_ACTION = 0x100;
-		const static __int64 RIGHT_HAND_ACTION = 0x200;
-	};
+    class Key
+    {
+    public:
+        static const __int64 LEFT_HAND_ACTION = 0x100;
+        static const __int64 RIGHT_HAND_ACTION = 0x200;
+    };
 
 private:
-	Framework::Text name;
-	Framework::Array<ItemSlot*> itemBar;
-	Framework::Array<ItemSlot*> crafting;
-	int leftHandPosition;
-	bool jumping;
-	__int64 keyState;
+    Framework::Text name;
+    Framework::Array<ItemSlot*> itemBar;
+    Framework::Array<ItemSlot*> crafting;
+    int leftHandPosition;
+    bool jumping;
+    __int64 keyState;
 
-	void useItemSlot(ItemSlot* zSlot);
-	Player(Framework::Vec3<float> location, int dimensionId, int entityId);
+    void useItemSlot(ItemSlot* zSlot);
+    Player(Framework::Vec3<float> location, int dimensionId, int entityId);
 
-	virtual void onTargetChange() override;
-	Framework::Text getInventoryUIML();
-	Framework::Text getPlayerGUI();
+    virtual void onTargetChange() override;
+    Framework::Text getInventoryUIML();
+    Framework::Text getPlayerGUI();
 
 public:
-	void setName(Framework::Text name);
-	const char* getName() const;
-	void tick(const Dimension* zDimension) override;
+    void setName(Framework::Text name);
+    const char* getName() const;
+    void tick(const Dimension* zDimension) override;
 
-	void playerApi(Framework::StreamReader* zRequest, NetworkMessage* zResponse);
-	void onFall(float collisionSpeed) override;
+    void playerApi(
+        Framework::StreamReader* zRequest, NetworkMessage* zResponse);
+    void onFall(float collisionSpeed) override;
 
-	friend PlayerEntityType;
+    friend PlayerEntityType;
 };
 
 class PlayerEntityType : public EntityType
 {
 protected:
-	virtual void loadSuperEntity(Entity* zEntity, Framework::StreamReader* zReader) const override;
-	virtual void saveSuperEntity(Entity* zEntity, Framework::StreamWriter* zWriter) const override;
+    virtual void loadSuperEntity(
+        Entity* zEntity, Framework::StreamReader* zReader) const override;
+    virtual void saveSuperEntity(
+        Entity* zEntity, Framework::StreamWriter* zWriter) const override;
 
 public:
-	PlayerEntityType();
+    PlayerEntityType();
 
-	virtual Entity* createEntity(Framework::Vec3<float> position, int dimensionId, int entityId) const override;
+    virtual Entity* createEntity(Framework::Vec3<float> position,
+        int dimensionId,
+        int entityId) const override;
 };

+ 19 - 17
FactoryCraft/PlayerHand.cpp

@@ -1,6 +1,6 @@
 #include "PlayerHand.h"
-#include "Block.h"
 
+#include "Block.h"
 
 PlayerHandItemType::PlayerHandItemType()
     : ItemType(ItemTypeEnum::PLAYER_HAND,
@@ -10,48 +10,50 @@ PlayerHandItemType::PlayerHandItemType()
         ModelInfo("", "", 0))
 {}
 
-void PlayerHandItemType::loadSuperItemSkill(ItemSkill* zSkill, Framework::StreamReader* zReader) const
+void PlayerHandItemType::loadSuperItemSkill(
+    ItemSkill* zSkill, Framework::StreamReader* zReader) const
 {
-	// TODO: load skill data
+    // TODO: load skill data
 }
 
-void PlayerHandItemType::saveSuperItemSkill(const ItemSkill* zSkill, Framework::StreamWriter* zWriter) const
+void PlayerHandItemType::saveSuperItemSkill(
+    const ItemSkill* zSkill, Framework::StreamWriter* zWriter) const
 {
-	// TODO: store skill data
+    // TODO: store skill data
 }
 
 Item* PlayerHandItemType::createItem() const
 {
-	return 0; // there is no player hand item
+    return 0; // there is no player hand item
 }
 
 ItemSkill* PlayerHandItemType::createDefaultItemSkill() const
 {
-	return new PlayerHandSkill();
+    return new PlayerHandSkill();
 }
 
-
 PlayerHandLevelUpRule::PlayerHandLevelUpRule()
-	: ItemSkillLevelUpRule()
+    : ItemSkillLevelUpRule()
 {}
 
 void PlayerHandLevelUpRule::applyOn(ItemSkill* zSkill)
 {
-	// TODO: level up the skill
+    // TODO: level up the skill
 }
 
-
-PlayerHandSkill::PlayerHandSkill() : ItemSkill(ItemTypeEnum::PLAYER_HAND) {}
+PlayerHandSkill::PlayerHandSkill()
+    : ItemSkill(ItemTypeEnum::PLAYER_HAND)
+{}
 
 void PlayerHandSkill::use(Entity* zActor, Item* zUsedItem, Block* zTarget)
 {
-	if (zTarget && zTarget->getHardness() <= 1)
-	{
-		zTarget->setHP(zTarget->getHP() - 1 / (zTarget->getHardness() + 1));
-	}
+    if (zTarget && zTarget->getHardness() <= 1)
+    {
+        zTarget->setHP(zTarget->getHP() - 1 / (zTarget->getHardness() + 1));
+    }
 }
 
 void PlayerHandSkill::use(Entity* zActor, Item* zUsedItem, Entity* zTarget)
 {
-	// TODO: make damage on the entity
+    // TODO: make damage on the entity
 }

+ 18 - 17
FactoryCraft/RandNoise.cpp

@@ -1,39 +1,40 @@
+#include "RandNoise.h"
+
 #include <Random.h>
 #include <stdlib.h>
 
-#include "RandNoise.h"
 #include "Constants.h"
 #include "FastNoiseLite.h"
 #include "FastNoiseWrapper.h"
 
-
 RandNoise::RandNoise(int seed)
-	: Noise(),
-	seed(seed)
+    : Noise(),
+      seed(seed)
 {
-	FastNoiseLite* n = new FastNoiseLite(seed);
-	n->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_OpenSimplex2S);
-	n->SetRotationType3D(FastNoiseLite::RotationType3D::RotationType3D_None);
-	n->SetFrequency(0.333f);
-	n->SetFractalOctaves(1);
-	n->SetFractalType(FastNoiseLite::FractalType::FractalType_None);
-	n->SetDomainWarpAmp(30.f);
-	noise = new FastNoiseWrapper(n, seed);
+    FastNoiseLite* n = new FastNoiseLite(seed);
+    n->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_OpenSimplex2S);
+    n->SetRotationType3D(FastNoiseLite::RotationType3D::RotationType3D_None);
+    n->SetFrequency(0.333f);
+    n->SetFractalOctaves(1);
+    n->SetFractalType(FastNoiseLite::FractalType::FractalType_None);
+    n->SetDomainWarpAmp(30.f);
+    noise = new FastNoiseWrapper(n, seed);
 }
 
 RandNoise::~RandNoise()
 {
-	delete noise;
+    delete noise;
 }
 
 int RandNoise::getSeed() const
 {
-	return seed;
+    return seed;
 }
 
 double RandNoise::getNoise(double x, double y, double z)
 {
-	double n = noise->getNoise(x * 4 + y + z * 7, 7 * x + 4 * y + z, x + 7 * y + 4 * z);
-	assert(n >= 0 && n <= 1);
-	return n;
+    double n = noise->getNoise(
+        x * 4 + y + z * 7, 7 * x + 4 * y + z, x + 7 * y + 4 * z);
+    assert(n >= 0 && n <= 1);
+    return n;
 }

+ 6 - 6
FactoryCraft/RandNoise.h

@@ -7,13 +7,13 @@ class FastNoiseWrapper;
 class RandNoise : public Noise
 {
 private:
-	int seed;
-	FastNoiseWrapper* noise;
+    int seed;
+    FastNoiseWrapper* noise;
 
 public:
-	RandNoise(int seed);
-	~RandNoise();
+    RandNoise(int seed);
+    ~RandNoise();
 
-	int getSeed() const override;
-	double getNoise(double x, double y, double z) override;
+    int getSeed() const override;
+    double getNoise(double x, double y, double z) override;
 };

+ 58 - 54
FactoryCraft/Recipie.cpp

@@ -1,101 +1,105 @@
 #include "Recipie.h"
+
 #include "CraftingStorage.h"
 
 Recipie::Recipie()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {}
 
 void Recipie::addIngredient(ItemFilter* filter, int amount)
 {
-	filters.add(filter);
-	inputAmount.add(amount);
+    filters.add(filter);
+    inputAmount.add(amount);
 }
 
 void Recipie::addOutput(Item* item, int amount)
 {
-	outputs.add(item);
-	outputAmount.add(amount);
+    outputs.add(item);
+    outputAmount.add(amount);
 }
 
 bool Recipie::testApplicability(CraftingStorage* zStorage)
 {
-	for (int i = 0; i < outputs.getEintragAnzahl(); i++)
-	{
-		if (!zStorage->hasFreeSpace(outputs.z(i), outputAmount.get(i)))
-			return 0;
-	}
-	return zStorage->isAllAvailable(filters, inputAmount);
+    for (int i = 0; i < outputs.getEintragAnzahl(); i++)
+    {
+        if (!zStorage->hasFreeSpace(outputs.z(i), outputAmount.get(i)))
+            return 0;
+    }
+    return zStorage->isAllAvailable(filters, inputAmount);
 }
 
 void Recipie::apply(CraftingStorage* zStorage)
 {
-	zStorage->consume(filters, inputAmount);
-	for (int i = 0; i < outputs.getEintragAnzahl(); i++)
-	{
-		ItemStack* stack = new ItemStack(outputs.z(i)->zItemType()->cloneItem(outputs.z(i)), outputAmount.get(i));
-		zStorage->addCraftingResult(stack);
-		stack->release();
-	}
+    zStorage->consume(filters, inputAmount);
+    for (int i = 0; i < outputs.getEintragAnzahl(); i++)
+    {
+        ItemStack* stack
+            = new ItemStack(outputs.z(i)->zItemType()->cloneItem(outputs.z(i)),
+                outputAmount.get(i));
+        zStorage->addCraftingResult(stack);
+        stack->release();
+    }
 }
 
-
 ShapedRecipie::ShapedRecipie(int width, int height)
-	:ReferenceCounter(),
-	width(width),
-	height(height),
-	output(0),
-	outputAmount(0)
+    : ReferenceCounter(),
+      width(width),
+      height(height),
+      output(0),
+      outputAmount(0)
 {
-	for (int i = 0; i < width * height; i++)
-	{
-		filters.add(0);
-		modifiers.add(0);
-	}
+    for (int i = 0; i < width * height; i++)
+    {
+        filters.add(0);
+        modifiers.add(0);
+    }
 }
 
 ShapedRecipie::~ShapedRecipie()
 {
-	if (output)
-		output->release();
+    if (output) output->release();
 }
 
-void ShapedRecipie::setIngredient(int x, int y, ItemFilter* filter, ItemModifier* modifier)
+void ShapedRecipie::setIngredient(
+    int x, int y, ItemFilter* filter, ItemModifier* modifier)
 {
-	filters.set(filter, width * y + x);
-	modifiers.set(modifier, width * y + x);
+    filters.set(filter, width * y + x);
+    modifiers.set(modifier, width * y + x);
 }
 
 void ShapedRecipie::setOutput(Item* item, int amount)
 {
-	if (output)
-		output->release();
-	output = item;
-	outputAmount = amount;
+    if (output) output->release();
+    output = item;
+    outputAmount = amount;
 }
 
 bool ShapedRecipie::testApplicability(ShapedCraftingStorage* zStorage)
 {
-	return zStorage->isAllAvailable(filters, width, height) && zStorage->hasFreeSpace(output, outputAmount);
+    return zStorage->isAllAvailable(filters, width, height)
+        && zStorage->hasFreeSpace(output, outputAmount);
 }
 
 void ShapedRecipie::apply(ShapedCraftingStorage* zStorage)
 {
-	zStorage->consume(filters, modifiers, width, height);
-	ItemStack* stack = new ItemStack(output->zItemType()->cloneItem(output), outputAmount);
-	zStorage->addCraftingResult(stack);
-	stack->release();
+    zStorage->consume(filters, modifiers, width, height);
+    ItemStack* stack
+        = new ItemStack(output->zItemType()->cloneItem(output), outputAmount);
+    zStorage->addCraftingResult(stack);
+    stack->release();
 }
 
-Framework::Array<ItemInfo> ShapedRecipie::getOutput(ShapedCraftingStorage* zStorage)
+Framework::Array<ItemInfo> ShapedRecipie::getOutput(
+    ShapedCraftingStorage* zStorage)
 {
-	Framework::Array<ItemInfo> result;
-	ItemInfo info;
-	info.count = outputAmount;
-	info.type = output->zItemType()->getId();
-	info.hp = output->getHp();
-	info.durability = output->getDurability();
-	info.maxHp = output->getMaxHp();
-	info.maxDurability = output->getMaxDurability();
-	result.add(info);
-	return result;
+    Framework::Array<ItemInfo> result;
+    ItemInfo info;
+    info.count = outputAmount;
+    info.type = output->zItemType()->getId();
+    info.hp = output->getHp();
+    info.durability = output->getDurability();
+    info.maxHp = output->getMaxHp();
+    info.maxDurability = output->getMaxDurability();
+    result.add(info);
+    return result;
 }

+ 29 - 28
FactoryCraft/Recipie.h

@@ -10,46 +10,47 @@ class ShapedCraftingStorage;
 
 struct ItemInfo
 {
-	int type;
-	int count;
-	float hp;
-	float maxHp;
-	float durability;
-	float maxDurability;
+    int type;
+    int count;
+    float hp;
+    float maxHp;
+    float durability;
+    float maxDurability;
 };
 
 class Recipie : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::RCArray<ItemFilter> filters;
-	Framework::Array<int> inputAmount;
-	Framework::RCArray<Item> outputs;
-	Framework::Array<int> outputAmount;
+    Framework::RCArray<ItemFilter> filters;
+    Framework::Array<int> inputAmount;
+    Framework::RCArray<Item> outputs;
+    Framework::Array<int> outputAmount;
 
 public:
-	Recipie();
-	void addIngredient(ItemFilter* filter, int amount);
-	void addOutput(Item* item, int amount);
-	bool testApplicability(CraftingStorage* zStorage);
-	void apply(CraftingStorage* zStorage);
+    Recipie();
+    void addIngredient(ItemFilter* filter, int amount);
+    void addOutput(Item* item, int amount);
+    bool testApplicability(CraftingStorage* zStorage);
+    void apply(CraftingStorage* zStorage);
 };
 
 class ShapedRecipie : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::RCArray<ItemFilter> filters;
-	Framework::RCArray<ItemModifier> modifiers;
-	int width;
-	int height;
-	Item* output;
-	int outputAmount;
+    Framework::RCArray<ItemFilter> filters;
+    Framework::RCArray<ItemModifier> modifiers;
+    int width;
+    int height;
+    Item* output;
+    int outputAmount;
 
 public:
-	ShapedRecipie(int width, int height);
-	~ShapedRecipie();
-	void setIngredient(int x, int y, ItemFilter* filter, ItemModifier* modifier);
-	void setOutput(Item* item, int amount);
-	bool testApplicability(ShapedCraftingStorage* zStorage);
-	void apply(ShapedCraftingStorage* zStorage);
-	Framework::Array<ItemInfo> getOutput(ShapedCraftingStorage* zStorage);
+    ShapedRecipie(int width, int height);
+    ~ShapedRecipie();
+    void setIngredient(
+        int x, int y, ItemFilter* filter, ItemModifier* modifier);
+    void setOutput(Item* item, int amount);
+    bool testApplicability(ShapedCraftingStorage* zStorage);
+    void apply(ShapedCraftingStorage* zStorage);
+    Framework::Array<ItemInfo> getOutput(ShapedCraftingStorage* zStorage);
 };

+ 25 - 25
FactoryCraft/RecipieList.h

@@ -1,39 +1,39 @@
 #pragma once
 #include <Text.h>
+
 #include "Recipie.h"
 
-template <typename T, typename S>
-class RecipieListType : public virtual Framework::ReferenceCounter
+template<typename T, typename S> class RecipieListType
+    : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::RCArray<T> recipies;
-	Framework::Text name;
+    Framework::RCArray<T> recipies;
+    Framework::Text name;
 
 public:
-	RecipieListType(const char* name)
-		: ReferenceCounter(),
-		name(name)
-	{}
+    RecipieListType(const char* name)
+        : ReferenceCounter(),
+          name(name)
+    {}
 
-	void addRecipie(T* recipie)
-	{
-		recipies.add(recipie);
-	}
+    void addRecipie(T* recipie)
+    {
+        recipies.add(recipie);
+    }
 
-	T* zFirstRecipie(S* zStorage)
-	{
-		for (T* recipie : recipies)
-		{
-			if (recipie->testApplicability(zStorage))
-				return recipie;
-		}
-		return 0;
-	}
+    T* zFirstRecipie(S* zStorage)
+    {
+        for (T* recipie : recipies)
+        {
+            if (recipie->testApplicability(zStorage)) return recipie;
+        }
+        return 0;
+    }
 
-	const Framework::Text& getName() const
-	{
-		return name;
-	}
+    const Framework::Text& getName() const
+    {
+        return name;
+    }
 };
 
 typedef RecipieListType<Recipie, CraftingStorage> RecipieList;

+ 6 - 6
FactoryCraft/RecipieLoader.cpp

@@ -85,10 +85,10 @@ void RecipieLoader::loadRecipie(JSONObject* zRecipie)
         Item* item = 0;
         for (int i = 0; i < StaticRegistry<ItemType>::INSTANCE.getCount(); i++)
         {
-            if (StaticRegistry<ItemType>::INSTANCE
-                    .zElement(i) && StaticRegistry<ItemType>::INSTANCE.zElement(i)
-                    ->getName()
-                    .istGleich(outputType))
+            if (StaticRegistry<ItemType>::INSTANCE.zElement(i)
+                && StaticRegistry<ItemType>::INSTANCE.zElement(i)
+                       ->getName()
+                       .istGleich(outputType))
             {
                 item = StaticRegistry<ItemType>::INSTANCE.zElement(i)
                            ->createItem();
@@ -131,8 +131,8 @@ void RecipieLoader::loadRecipie(JSONObject* zRecipie)
             {
                 if (StaticRegistry<ItemType>::INSTANCE.zElement(i)
                     && StaticRegistry<ItemType>::INSTANCE.zElement(i)
-                        ->getName()
-                        .istGleich(outputType))
+                           ->getName()
+                           .istGleich(outputType))
                 {
                     item = StaticRegistry<ItemType>::INSTANCE.zElement(i)
                                ->createItem();

+ 15 - 14
FactoryCraft/RecipieLoader.h

@@ -1,26 +1,27 @@
 #pragma once
 #include <Array.h>
+
 #include "RecipieList.h"
 
 class RecipieLoader : public virtual Framework::ReferenceCounter
 {
 private:
-	Framework::RCArray<RecipieList> lists;
-	Framework::RCArray<ShapedRecipieList> shapedLists;
-	Framework::JSON::Validator::JSONValidator* validator;
+    Framework::RCArray<RecipieList> lists;
+    Framework::RCArray<ShapedRecipieList> shapedLists;
+    Framework::JSON::Validator::JSONValidator* validator;
 
 public:
-	RecipieLoader();
-	~RecipieLoader();
-	void loadRecipies(const char* path);
-	RecipieList* zRecipieList(const char* name) const;
-	ShapedRecipieList* zShapedRecipieList(const char* name) const;
-	void registerRecipieList(const char* name);
-	void registerShapedRecipieList(const char* name);
+    RecipieLoader();
+    ~RecipieLoader();
+    void loadRecipies(const char* path);
+    RecipieList* zRecipieList(const char* name) const;
+    ShapedRecipieList* zShapedRecipieList(const char* name) const;
+    void registerRecipieList(const char* name);
+    void registerShapedRecipieList(const char* name);
 
 private:
-	void loadRecipie(Framework::JSON::JSONObject* zRecipie);
-	ItemFilter* loadFilter(Framework::JSON::JSONObject* zFilter);
-	ItemModifier* loadModifier(Framework::JSON::JSONObject* zModifier);
-	Framework::JSON::Validator::JSONValidator* zRecipieValidator();
+    void loadRecipie(Framework::JSON::JSONObject* zRecipie);
+    ItemFilter* loadFilter(Framework::JSON::JSONObject* zFilter);
+    ItemModifier* loadModifier(Framework::JSON::JSONObject* zModifier);
+    Framework::JSON::Validator::JSONValidator* zRecipieValidator();
 };

+ 293 - 298
FactoryCraft/Server.cpp

@@ -1,377 +1,372 @@
 #include "Server.h"
-#include <iostream>
-#include <Klient.h>
+
+#include <AsynchronCall.h>
 #include <Globals.h>
 #include <HttpRequest.h>
+#include <iostream>
 #include <JSON.h>
-#include <AsynchronCall.h>
+#include <Klient.h>
 
 // Inhalt der LoginServer Klasse aus LoginServer.h
-// Konstruktor 
+// Konstruktor
 FactoryCraftServer::FactoryCraftServer(InitDatei* zIni)
-	: ReferenceCounter()
+    : ReferenceCounter()
 {
-	Network::Start(100);
-	runningThreads = 0;
-	klients = new RCArray< FCKlient >();
-	ini = dynamic_cast<InitDatei*>(zIni->getThis());
-	id = (int)*zIni->zWert("ServerId");
-	sslServer = new SSLServer();
-	sslServer->setPrivateKeyPassword(zIni->zWert("SSLPasswort")->getText());
-	sslServer->setCertificateFile(zIni->zWert("SSLCert")->getText());
-	std::cout << "using cert file " << zIni->zWert("SSLCert")->getText() << "\n";
-	sslServer->setPrivateKeyFile(zIni->zWert("SSLKey")->getText());
-	std::cout << "using private key " << zIni->zWert("SSLKey")->getText() << "\n";
-	server = new Server();
-	std::cout << "Server Port: " << ini->zWert("Port")->getText() << "\n";
-	if (!server->verbinde((unsigned short)TextZuInt(ini->zWert("Port")->getText(), 10), 10))
-	{
-		std::cout << "Der Server konnte nicht gestartet werden.\n";
-		exit(1);
-	}
-	std::cout << "SSL Server Port: " << ini->zWert("SSLPort")->getText() << "\n";
-	if (!sslServer->verbinde((unsigned short)TextZuInt(ini->zWert("SSLPort")->getText(), 10), 10))
-	{
-		std::cout << "Der SSL Server konnte nicht gestartet werden.\n";
-		exit(2);
-	}
-	Game::initialize(zIni->zWert("World")->getText(), zIni->zWert("SaveDir")->getText());
-	new Framework::AsynchronCall("Server", [this]()
-		{
-			runningThreads++;
-			while (server->isConnected())
-			{
-				SKlient* klient = server->getKlient();
-				if (!klient)
-					continue;
-				unsigned short len;
-				klient->setEmpfangTimeout(5000);
-				klient->getNachricht((char*)&len, 2);
-				char* key = new char[len];
-				klient->getNachricht((char*)key, len);
-				bool bg;
-				klient->getNachricht((char*)&bg, 1);
-				klient->setEmpfangTimeout(0);
-				bool found = 0;
-				EnterCriticalSection(&cs);
-				for (FCKlient* client : *klients)
-				{
-					if (client->matchAuthKey(key, len))
-					{
-						if (bg)
-							client->setBackgroundClient(klient);
-						else
-							client->setForegroundClient(klient);
-						found = 1;
-						break;
-					}
-				}
-				LeaveCriticalSection(&cs);
-				if (!found)
-					klient->release();
-			}
-			runningThreads--;
-		});
-	InitializeCriticalSection(&cs);
+    Network::Start(100);
+    runningThreads = 0;
+    klients = new RCArray<FCKlient>();
+    ini = dynamic_cast<InitDatei*>(zIni->getThis());
+    id = (int)*zIni->zWert("ServerId");
+    sslServer = new SSLServer();
+    sslServer->setPrivateKeyPassword(zIni->zWert("SSLPasswort")->getText());
+    sslServer->setCertificateFile(zIni->zWert("SSLCert")->getText());
+    std::cout << "using cert file " << zIni->zWert("SSLCert")->getText()
+              << "\n";
+    sslServer->setPrivateKeyFile(zIni->zWert("SSLKey")->getText());
+    std::cout << "using private key " << zIni->zWert("SSLKey")->getText()
+              << "\n";
+    server = new Server();
+    std::cout << "Server Port: " << ini->zWert("Port")->getText() << "\n";
+    if (!server->verbinde(
+            (unsigned short)TextZuInt(ini->zWert("Port")->getText(), 10), 10))
+    {
+        std::cout << "Der Server konnte nicht gestartet werden.\n";
+        exit(1);
+    }
+    std::cout << "SSL Server Port: " << ini->zWert("SSLPort")->getText()
+              << "\n";
+    if (!sslServer->verbinde(
+            (unsigned short)TextZuInt(ini->zWert("SSLPort")->getText(), 10),
+            10))
+    {
+        std::cout << "Der SSL Server konnte nicht gestartet werden.\n";
+        exit(2);
+    }
+    Game::initialize(
+        zIni->zWert("World")->getText(), zIni->zWert("SaveDir")->getText());
+    new Framework::AsynchronCall("Server", [this]() {
+        runningThreads++;
+        while (server->isConnected())
+        {
+            SKlient* klient = server->getKlient();
+            if (!klient) continue;
+            unsigned short len;
+            klient->setEmpfangTimeout(5000);
+            klient->getNachricht((char*)&len, 2);
+            char* key = new char[len];
+            klient->getNachricht((char*)key, len);
+            bool bg;
+            klient->getNachricht((char*)&bg, 1);
+            klient->setEmpfangTimeout(0);
+            bool found = 0;
+            EnterCriticalSection(&cs);
+            for (FCKlient* client : *klients)
+            {
+                if (client->matchAuthKey(key, len))
+                {
+                    if (bg)
+                        client->setBackgroundClient(klient);
+                    else
+                        client->setForegroundClient(klient);
+                    found = 1;
+                    break;
+                }
+            }
+            LeaveCriticalSection(&cs);
+            if (!found) klient->release();
+        }
+        runningThreads--;
+    });
+    InitializeCriticalSection(&cs);
 }
 
-// Destruktor 
+// Destruktor
 FactoryCraftServer::~FactoryCraftServer()
 {
-	sslServer->trenne();
-	server->trenne();
-	while (runningThreads > 0)
-		Sleep(100);
-	sslServer->release();
-	server->release();
-	if (klients)
-		klients->release();
-	ini->release();
-	Game::INSTANCE->requestStop();
-	Game::INSTANCE->release();
-	DeleteCriticalSection(&cs);
+    sslServer->trenne();
+    server->trenne();
+    while (runningThreads > 0)
+        Sleep(100);
+    sslServer->release();
+    server->release();
+    if (klients) klients->release();
+    ini->release();
+    Game::INSTANCE->requestStop();
+    Game::INSTANCE->release();
+    DeleteCriticalSection(&cs);
 }
 
-// nicht constant 
+// nicht constant
 void FactoryCraftServer::run()
 {
-	runningThreads++;
-	while (sslServer->isConnected())
-	{
-		SSLSKlient* klient = sslServer->getKlient();
-		if (!klient)
-			continue;
-		Framework::getThreadRegister()->cleanUpClosedThreads();
-		FCKlient* clHandle = new FCKlient(klient, dynamic_cast<FactoryCraftServer*>(getThis()));
-		EnterCriticalSection(&cs);
-		klients->add(clHandle);
-		LeaveCriticalSection(&cs);
-		clHandle->start();
-	}
-	runningThreads--;
+    runningThreads++;
+    while (sslServer->isConnected())
+    {
+        SSLSKlient* klient = sslServer->getKlient();
+        if (!klient) continue;
+        Framework::getThreadRegister()->cleanUpClosedThreads();
+        FCKlient* clHandle = new FCKlient(
+            klient, dynamic_cast<FactoryCraftServer*>(getThis()));
+        EnterCriticalSection(&cs);
+        klients->add(clHandle);
+        LeaveCriticalSection(&cs);
+        clHandle->start();
+    }
+    runningThreads--;
 }
 
 void FactoryCraftServer::close()
 {
-	sslServer->trenne();
-	EnterCriticalSection(&cs);
-	for (int i = 0; i < klients->getEintragAnzahl(); i++)
-		klients->z(i)->absturz();
-	klients = (RCArray< FCKlient > *)klients->release();
-	Game::INSTANCE->save();
-	LeaveCriticalSection(&cs);
+    sslServer->trenne();
+    EnterCriticalSection(&cs);
+    for (int i = 0; i < klients->getEintragAnzahl(); i++)
+        klients->z(i)->absturz();
+    klients = (RCArray<FCKlient>*)klients->release();
+    Game::INSTANCE->save();
+    LeaveCriticalSection(&cs);
 }
 
 bool FactoryCraftServer::absturzKlient(int accountId)
 {
-	bool gefunden = 0;
-	EnterCriticalSection(&cs);
-	for (int i = 0; i < klients->getEintragAnzahl(); i++)
-	{
-		if (klients->z(i) && klients->z(i)->getAccountId() == accountId)
-		{
-			klients->z(i)->absturz();
-			klients->remove(i);
-			gefunden = 1;
-			break;
-		}
-	}
-	LeaveCriticalSection(&cs);
-	return gefunden;
+    bool gefunden = 0;
+    EnterCriticalSection(&cs);
+    for (int i = 0; i < klients->getEintragAnzahl(); i++)
+    {
+        if (klients->z(i) && klients->z(i)->getAccountId() == accountId)
+        {
+            klients->z(i)->absturz();
+            klients->remove(i);
+            gefunden = 1;
+            break;
+        }
+    }
+    LeaveCriticalSection(&cs);
+    return gefunden;
 }
 
 bool FactoryCraftServer::removeKlient(FCKlient* zKlient)
 {
-	bool gefunden = 0;
-	EnterCriticalSection(&cs);
-	for (int i = 0; i < klients->getEintragAnzahl(); i++)
-	{
-		if (klients->z(i) == zKlient)
-		{
-			klients->remove(i);
-			gefunden = 1;
-			break;
-		}
-	}
-	LeaveCriticalSection(&cs);
-	return gefunden;
+    bool gefunden = 0;
+    EnterCriticalSection(&cs);
+    for (int i = 0; i < klients->getEintragAnzahl(); i++)
+    {
+        if (klients->z(i) == zKlient)
+        {
+            klients->remove(i);
+            gefunden = 1;
+            break;
+        }
+    }
+    LeaveCriticalSection(&cs);
+    return gefunden;
 }
 
 bool FactoryCraftServer::hatClients() const
 {
-	return klients->hat(0);
+    return klients->hat(0);
 }
 
 int FactoryCraftServer::getUnencryptedPort() const
 {
-	return server->getPort();
+    return server->getPort();
 }
 
 // Inhalt der LSKlient aus LoginServer.h
 // Konstruktor
 FCKlient::FCKlient(SSLSKlient* klient, FactoryCraftServer* ls)
-	: Thread()
+    : Thread()
 {
-	this->klient = klient;
-	background = 0;
-	foreground = 0;
-	accountId = 0;
-	this->ls = ls;
-	zGameClient = 0;
-	backgroundReader = 0;
-	foregroundReader = 0;
-	backgroundWriter = 0;
-	foregroundWriter = 0;
-	authKey = randomKey(authKeyLen);
+    this->klient = klient;
+    background = 0;
+    foreground = 0;
+    accountId = 0;
+    this->ls = ls;
+    zGameClient = 0;
+    backgroundReader = 0;
+    foregroundReader = 0;
+    backgroundWriter = 0;
+    foregroundWriter = 0;
+    authKey = randomKey(authKeyLen);
 }
 
-// Destruktor 
+// Destruktor
 FCKlient::~FCKlient()
 {
-	if (zGameClient)
-	{
-		zGameClient->logout();
-		zGameClient = (GameClient*)zGameClient->release();
-	}
-	if (background)
-		background->release();
-	if (foreground)
-		foreground->release();
-	delete backgroundReader;
-	delete foregroundReader;
-	delete backgroundWriter;
-	delete foregroundWriter;
-	klient->release();
-	ls->release();
-	delete[] authKey;
+    if (zGameClient)
+    {
+        zGameClient->logout();
+        zGameClient = (GameClient*)zGameClient->release();
+    }
+    if (background) background->release();
+    if (foreground) foreground->release();
+    delete backgroundReader;
+    delete foregroundReader;
+    delete backgroundWriter;
+    delete foregroundWriter;
+    klient->release();
+    ls->release();
+    delete[] authKey;
 }
 
-// nicht constant 
+// nicht constant
 void FCKlient::setForegroundClient(SKlient* foreground)
 {
-	this->foreground = foreground;
-	foregroundReader = new NetworkReader(foreground);
-	foregroundWriter = new NetworkWriter(foreground);
-	if (foreground && background)
-		zGameClient = Game::INSTANCE->addPlayer(dynamic_cast<FCKlient*>(getThis()), Framework::Text((int)accountId));
-	new AsynchronCall([this]()
-		{
-			while (this->foreground->waitForNextMessage())
-			{
-				if (zGameClient)
-					zGameClient->addMessage(foregroundReader);
-				if (!zGameClient)
-					Sleep(100);
-			}
-			zGameClient->logout();
-			ls->removeKlient(this);
-		});
+    this->foreground = foreground;
+    foregroundReader = new NetworkReader(foreground);
+    foregroundWriter = new NetworkWriter(foreground);
+    if (foreground && background)
+        zGameClient
+            = Game::INSTANCE->addPlayer(dynamic_cast<FCKlient*>(getThis()),
+                Framework::Text((int)accountId));
+    new AsynchronCall([this]() {
+        while (this->foreground->waitForNextMessage())
+        {
+            if (zGameClient) zGameClient->addMessage(foregroundReader);
+            if (!zGameClient) Sleep(100);
+        }
+        zGameClient->logout();
+        ls->removeKlient(this);
+    });
 }
 
 void FCKlient::setBackgroundClient(SKlient* background)
 {
-	this->background = background;
-	backgroundReader = new NetworkReader(background);
-	backgroundWriter = new NetworkWriter(background);
-	if (foreground && background)
-		zGameClient = Game::INSTANCE->addPlayer(dynamic_cast<FCKlient*>(getThis()), Framework::Text((int)accountId));
-	new AsynchronCall([this]()
-		{
-			while (this->background->waitForNextMessage())
-			{
-				if (zGameClient)
-					zGameClient->addMessage(backgroundReader);
-				if (!zGameClient)
-					Sleep(100);
-			}
-			zGameClient->logout();
-			ls->removeKlient(this);
-		});
+    this->background = background;
+    backgroundReader = new NetworkReader(background);
+    backgroundWriter = new NetworkWriter(background);
+    if (foreground && background)
+        zGameClient
+            = Game::INSTANCE->addPlayer(dynamic_cast<FCKlient*>(getThis()),
+                Framework::Text((int)accountId));
+    new AsynchronCall([this]() {
+        while (this->background->waitForNextMessage())
+        {
+            if (zGameClient) zGameClient->addMessage(backgroundReader);
+            if (!zGameClient) Sleep(100);
+        }
+        zGameClient->logout();
+        ls->removeKlient(this);
+    });
 }
 
 void FCKlient::absturz()
 {
-	ende();
-	klient->trenne();
+    ende();
+    klient->trenne();
 }
 
 void FCKlient::thread()
 {
-	while (1)
-	{
-		char c = 0;
-		if (!klient->getNachricht(&c, 1))
-			break;
-		else
-		{
-			bool br = 0;
-			switch (c)
-			{
-			case 1: // Klient identifikation
-			{
-				char len;
-				klient->getNachricht(&len, 1);
-				char* name = new char[len + 1];
-				klient->getNachricht(name, len);
-				name[(int)len] = 0;
-				unsigned short sLen;
-				klient->getNachricht((char*)&sLen, 2);
-				char* secret = new char[sLen + 1];
-				klient->getNachricht(secret, sLen);
-				secret[sLen] = 0;
-				if (!Game::INSTANCE->checkPlayer(name, secret))
-				{
-					klient->sende("\0", 1);
-					delete[] name;
-					delete[] secret;
-					break;
-				}
-				if (!Game::INSTANCE->existsPlayer(name))
-				{
-					Text secret = Game::INSTANCE->createPlayer(name);
-					klient->sende("\2", 1);
-					short len = (short)secret.getLength();
-					klient->sende((char*)&len, 2);
-					klient->sende(secret.getText(), len);
-				}
-				else
-				{
-					klient->sende("\1", 1);
-				}
-				klient->sende((char*)&authKeyLen, 4);
-				klient->sende(authKey, authKeyLen);
-				delete[] name;
-				delete[] secret;
-				break;
-			}
-			case 2: // Verbindungsende
-				br = 1;
-				if (zGameClient)
-				{
-					zGameClient->logout();
-					zGameClient = (GameClient*)zGameClient->release();
-				}
-				klient->sende("\1", 1);
-				break;
-			case 3: // ping
-				klient->sende("\1", 1);
-				break;
-			case 4: // check player name valid
-			{
-				klient->sende("\1", 1);
-				char len;
-				klient->getNachricht(&len, 1);
-				char* name = new char[len + 1];
-				klient->getNachricht(name, len);
-				name[(int)len] = 0;
-				short sLen;
-				klient->getNachricht((char*)&sLen, 2);
-				char* secret = new char[sLen + 1];
-				klient->getNachricht(secret, sLen);
-				secret[sLen] = 0;
-				char res = 0;
-				if (Game::INSTANCE->checkPlayer(name, secret))
-					res = 1;
-				klient->sende(&res, 1);
-				delete[] name;
-				delete[] secret;
-				break;
-			}
-			default:
-				br = 1;
-				break;
-			}
-			if (br)
-				break;
-		}
-	}
+    while (1)
+    {
+        char c = 0;
+        if (!klient->getNachricht(&c, 1))
+            break;
+        else
+        {
+            bool br = 0;
+            switch (c)
+            {
+            case 1: // Klient identifikation
+                {
+                    char len;
+                    klient->getNachricht(&len, 1);
+                    char* name = new char[len + 1];
+                    klient->getNachricht(name, len);
+                    name[(int)len] = 0;
+                    unsigned short sLen;
+                    klient->getNachricht((char*)&sLen, 2);
+                    char* secret = new char[sLen + 1];
+                    klient->getNachricht(secret, sLen);
+                    secret[sLen] = 0;
+                    if (!Game::INSTANCE->checkPlayer(name, secret))
+                    {
+                        klient->sende("\0", 1);
+                        delete[] name;
+                        delete[] secret;
+                        break;
+                    }
+                    if (!Game::INSTANCE->existsPlayer(name))
+                    {
+                        Text secret = Game::INSTANCE->createPlayer(name);
+                        klient->sende("\2", 1);
+                        short len = (short)secret.getLength();
+                        klient->sende((char*)&len, 2);
+                        klient->sende(secret.getText(), len);
+                    }
+                    else
+                    {
+                        klient->sende("\1", 1);
+                    }
+                    klient->sende((char*)&authKeyLen, 4);
+                    klient->sende(authKey, authKeyLen);
+                    delete[] name;
+                    delete[] secret;
+                    break;
+                }
+            case 2: // Verbindungsende
+                br = 1;
+                if (zGameClient)
+                {
+                    zGameClient->logout();
+                    zGameClient = (GameClient*)zGameClient->release();
+                }
+                klient->sende("\1", 1);
+                break;
+            case 3: // ping
+                klient->sende("\1", 1);
+                break;
+            case 4: // check player name valid
+                {
+                    klient->sende("\1", 1);
+                    char len;
+                    klient->getNachricht(&len, 1);
+                    char* name = new char[len + 1];
+                    klient->getNachricht(name, len);
+                    name[(int)len] = 0;
+                    short sLen;
+                    klient->getNachricht((char*)&sLen, 2);
+                    char* secret = new char[sLen + 1];
+                    klient->getNachricht(secret, sLen);
+                    secret[sLen] = 0;
+                    char res = 0;
+                    if (Game::INSTANCE->checkPlayer(name, secret)) res = 1;
+                    klient->sende(&res, 1);
+                    delete[] name;
+                    delete[] secret;
+                    break;
+                }
+            default:
+                br = 1;
+                break;
+            }
+            if (br) break;
+        }
+    }
 }
 
 int FCKlient::getAccountId() const // gibt die KlientId zurück
 {
-	return accountId;
+    return accountId;
 }
 
 NetworkWriter* FCKlient::zBackgroundWriter() const
 {
-	return backgroundWriter;
+    return backgroundWriter;
 }
 
 NetworkWriter* FCKlient::zForegroundWriter() const
 {
-	return foregroundWriter;
+    return foregroundWriter;
 }
 
 bool FCKlient::matchAuthKey(char* key, int len) const
 {
-	if (foreground && background)
-		return 0;
-	if (len != authKeyLen)
-		return 0;
-	for (int i = 0; i < len; i++)
-	{
-		if (key[i] != authKey[i])
-			return 0;
-	}
-	return 1;
+    if (foreground && background) return 0;
+    if (len != authKeyLen) return 0;
+    for (int i = 0; i < len; i++)
+    {
+        if (key[i] != authKey[i]) return 0;
+    }
+    return 1;
 }

+ 47 - 47
FactoryCraft/Server.h

@@ -1,10 +1,10 @@
 #pragma once
 
-#include <Server.h>
-#include <Thread.h>
 #include <Datei.h>
-#include <Text.h>
 #include <InitDatei.h>
+#include <Server.h>
+#include <Text.h>
+#include <Thread.h>
 
 #include "Game.h"
 
@@ -17,57 +17,57 @@ class GameClient;
 class FactoryCraftServer : virtual public ReferenceCounter
 {
 private:
-	SSLServer* sslServer;
-	Server* server;
-	InitDatei* ini;
-	CRITICAL_SECTION cs;
-	RCArray< FCKlient >* klients;
-	int runningThreads;
-	int id;
+    SSLServer* sslServer;
+    Server* server;
+    InitDatei* ini;
+    CRITICAL_SECTION cs;
+    RCArray<FCKlient>* klients;
+    int runningThreads;
+    int id;
 
 public:
-	// Konstruktor 
-	FactoryCraftServer(InitDatei* zIni);
-	// Destruktor 
-	virtual ~FactoryCraftServer();
-	// nicht constant
-	void run();
-	void close();
-	bool absturzKlient(int accountId);
-	bool removeKlient(FCKlient* zKlient);
-	bool hatClients() const;
-	int getUnencryptedPort() const;
+    // Konstruktor
+    FactoryCraftServer(InitDatei* zIni);
+    // Destruktor
+    virtual ~FactoryCraftServer();
+    // nicht constant
+    void run();
+    void close();
+    bool absturzKlient(int accountId);
+    bool removeKlient(FCKlient* zKlient);
+    bool hatClients() const;
+    int getUnencryptedPort() const;
 };
 
 class FCKlient : public Thread
 {
 private:
-	SSLSKlient* klient;
-	SKlient* background;
-	SKlient* foreground;
-	unsigned int accountId;
-	FactoryCraftServer* ls;
-	GameClient* zGameClient;
-	NetworkReader* backgroundReader;
-	NetworkReader* foregroundReader;
-	NetworkWriter* backgroundWriter;
-	NetworkWriter* foregroundWriter;
-	char* authKey;
-	int authKeyLen;
+    SSLSKlient* klient;
+    SKlient* background;
+    SKlient* foreground;
+    unsigned int accountId;
+    FactoryCraftServer* ls;
+    GameClient* zGameClient;
+    NetworkReader* backgroundReader;
+    NetworkReader* foregroundReader;
+    NetworkWriter* backgroundWriter;
+    NetworkWriter* foregroundWriter;
+    char* authKey;
+    int authKeyLen;
 
 public:
-	// Konstruktor 
-	FCKlient(SSLSKlient* klient, FactoryCraftServer* ls);
-	// Destruktor 
-	virtual ~FCKlient();
-	void setForegroundClient(SKlient* foreground);
-	void setBackgroundClient(SKlient* background);
-	// nicht constant 
-	void absturz();
-	void thread();
-	// constant
-	int getAccountId() const;
-	NetworkWriter* zBackgroundWriter() const;
-	NetworkWriter* zForegroundWriter() const;
-	bool matchAuthKey(char* key, int len) const;
+    // Konstruktor
+    FCKlient(SSLSKlient* klient, FactoryCraftServer* ls);
+    // Destruktor
+    virtual ~FCKlient();
+    void setForegroundClient(SKlient* foreground);
+    void setBackgroundClient(SKlient* background);
+    // nicht constant
+    void absturz();
+    void thread();
+    // constant
+    int getAccountId() const;
+    NetworkWriter* zBackgroundWriter() const;
+    NetworkWriter* zForegroundWriter() const;
+    bool matchAuthKey(char* key, int len) const;
 };

+ 70 - 67
FactoryCraft/Start.cpp

@@ -1,13 +1,13 @@
-#include <iostream>
-#include <fstream>
-#include <Zeit.h>
+#include <csignal>
+#include <cstdlib>
 #include <Datei.h>
-#include <Text.h>
+#include <fstream>
 #include <Globals.h>
-#include <sys/resource.h>
+#include <iostream>
 #include <Klient.h>
-#include <cstdlib>
-#include <csignal>
+#include <sys/resource.h>
+#include <Text.h>
+#include <Zeit.h>
 
 #include "Server.h"
 
@@ -15,77 +15,80 @@ FactoryCraftServer* mserver = 0;
 
 void exit()
 {
-	std::cout << "Der Server wird beendet...\n";
-	if (mserver)
-		mserver->close();
+    std::cout << "Der Server wird beendet...\n";
+    if (mserver) mserver->close();
 }
 
 int main()
 {
-	initializeBlockTypes();
+    initializeBlockTypes();
     initializeItemTypes();
     initializeEntityTypes();
     initializeDimensions();
     initializeMultiblockTypes();
-	
-	struct rlimit core_limits;
-	core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
-	setrlimit(RLIMIT_CORE, &core_limits);
 
-	Framework::initFramework();
-	Zeit* z = getZeit();
-	Text* pfad = new Text("log/");
-	pfad->append(z->getZeit("y-m-d_h-i-s.log"));
-	z->release();
-	DateiPfadErstellen(pfad->getText());
-	std::ofstream file;
-	file.open(pfad->getText());
-	std::streambuf* sbuf = std::cout.rdbuf();
-	//std::cout.rdbuf( file.rdbuf() );
-	pfad->release();
+    struct rlimit core_limits;
+    core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
+    setrlimit(RLIMIT_CORE, &core_limits);
+
+    Framework::initFramework();
+    Zeit* z = getZeit();
+    Text* pfad = new Text("log/");
+    pfad->append(z->getZeit("y-m-d_h-i-s.log"));
+    z->release();
+    DateiPfadErstellen(pfad->getText());
+    std::ofstream file;
+    file.open(pfad->getText());
+    std::streambuf* sbuf = std::cout.rdbuf();
+    // std::cout.rdbuf( file.rdbuf() );
+    pfad->release();
 
-	std::cout << "Startet...\n";
-	std::cout << "Lese init Datei fcInit.ini ...\n";
+    std::cout << "Startet...\n";
+    std::cout << "Lese init Datei fcInit.ini ...\n";
 
-	InitDatei* dat = new InitDatei("fcInit.ini");
-	if (!dat->laden())
-	{
-		std::cout << "error: Datei konnte nicht gelesen werden. Das Programm wird geschlossen.\n";
-		dat->release();
-		file.close();
-		std::cout.rdbuf(sbuf);
-		exit(1);
-	}
-	const char* wichtig[] = { "SSLPort", "SSLCert", "SSLKey", "SSLPasswort", "Port" };
-	for (const char* w : wichtig)
-	{
-		if (!dat->wertExistiert(w))
-		{
-			std::cout << "error: Der Wert '" << w << "' wurde nicht gefunden. Das Programm wird geschlossen.\n";
-			dat->release();
-			file.close();
-			std::cout.rdbuf(sbuf);
-			exit(1);
-		}
-	}
+    InitDatei* dat = new InitDatei("fcInit.ini");
+    if (!dat->laden())
+    {
+        std::cout << "error: Datei konnte nicht gelesen werden. Das Programm "
+                     "wird geschlossen.\n";
+        dat->release();
+        file.close();
+        std::cout.rdbuf(sbuf);
+        exit(1);
+    }
+    const char* wichtig[]
+        = {"SSLPort", "SSLCert", "SSLKey", "SSLPasswort", "Port"};
+    for (const char* w : wichtig)
+    {
+        if (!dat->wertExistiert(w))
+        {
+            std::cout
+                << "error: Der Wert '" << w
+                << "' wurde nicht gefunden. Das Programm wird geschlossen.\n";
+            dat->release();
+            file.close();
+            std::cout.rdbuf(sbuf);
+            exit(1);
+        }
+    }
 
-	mserver = new FactoryCraftServer(dat);
-	std::atexit(exit);
-	signal(SIGTERM, exit);
-	signal(SIGSEGV, exit);
-	signal(SIGILL, exit);
-	signal(SIGABRT, exit);
-	signal(SIGFPE, exit);
-	signal(SIGINT, exit);
+    mserver = new FactoryCraftServer(dat);
+    std::atexit(exit);
+    signal(SIGTERM, exit);
+    signal(SIGSEGV, exit);
+    signal(SIGILL, exit);
+    signal(SIGABRT, exit);
+    signal(SIGFPE, exit);
+    signal(SIGINT, exit);
 
-	std::cout << "Der Server läuft. Startforgang beendet.\n";
-	mserver->run();
-	mserver->release();
-	mserver = 0;
-	dat->release();
-	std::cout << "Der Server ist heruntergefahren.\n";
-	file.close();
-	std::cout.rdbuf(sbuf);
-	Framework::releaseFramework();
-	return 0;
+    std::cout << "Der Server läuft. Startforgang beendet.\n";
+    mserver->run();
+    mserver->release();
+    mserver = 0;
+    dat->release();
+    std::cout << "Der Server ist heruntergefahren.\n";
+    file.close();
+    std::cout.rdbuf(sbuf);
+    Framework::releaseFramework();
+    return 0;
 }

+ 54 - 56
FactoryCraft/StaticRegistry.h

@@ -2,74 +2,72 @@
 
 #include <iostream>
 
-template<typename T>
-class StaticRegistry
+template<typename T> class StaticRegistry
 {
 public:
-	static StaticRegistry<T> INSTANCE;
+    static StaticRegistry<T> INSTANCE;
 
 private:
-	T** registry;
-	int count;
+    T** registry;
+    int count;
 
-	StaticRegistry()
-	{
-		count = 0;
-		registry = new T * [count];
-		memset(registry, 0, sizeof(T*) * count);
-	}
+    StaticRegistry()
+    {
+        count = 0;
+        registry = new T*[count];
+        memset(registry, 0, sizeof(T*) * count);
+    }
+
+    ~StaticRegistry()
+    {
+        for (int index = 0; index < count; index++)
+        {
+            if (registry[index])
+            {
+                registry[index]->release();
+                registry[index] = 0;
+            }
+        }
+        delete[] registry;
+    }
 
-	~StaticRegistry()
-	{
-		for (int index = 0; index < count; index++)
-		{
-			if (registry[index])
-			{
-				registry[index]->release();
-				registry[index] = 0;
-			}
-		}
-		delete[]registry;
-	}
-	
 public:
-	void registerT(T* type, int id)
-	{
-		if (id >= count)
-		{
-			T** temp = new T * [id + 1];
-			memcpy(temp, registry, sizeof(T*) * count);
-			memset(temp + count, 0, sizeof(T*) * (id + 1 - count));
-			delete[]registry;
-			registry = temp;
-			count = id + 1;
-		}
-		registry[id] = type;
-	}
-	
-	T* zElement(int id)
-	{
-		if (id < 0 || id >= count)
-			return 0;
-		return registry[id];
-	}
+    void registerT(T* type, int id)
+    {
+        if (id >= count)
+        {
+            T** temp = new T*[id + 1];
+            memcpy(temp, registry, sizeof(T*) * count);
+            memset(temp + count, 0, sizeof(T*) * (id + 1 - count));
+            delete[] registry;
+            registry = temp;
+            count = id + 1;
+        }
+        registry[id] = type;
+    }
+
+    T* zElement(int id)
+    {
+        if (id < 0 || id >= count) return 0;
+        return registry[id];
+    }
 
-	int getCount() const
-	{
-		return count;
-	}
+    int getCount() const
+    {
+        return count;
+    }
 
-	bool info(int id)
-	{
-		std::cout << typeid(*registry[id]).name() << " was registered as " << typeid(T).name() << " with id " << id << std::endl;
-		return 1;
-	}
+    bool info(int id)
+    {
+        std::cout << typeid(*registry[id]).name() << " was registered as "
+                  << typeid(T).name() << " with id " << id << std::endl;
+        return 1;
+    }
 
-	friend T;
+    friend T;
 };
 
-template <typename T>
-StaticRegistry<T> StaticRegistry<T>::INSTANCE;
+template<typename T> StaticRegistry<T> StaticRegistry<T>::INSTANCE;
 
 void initializeBlockTypes();
 void initializeItemTypes();

+ 36 - 36
FactoryCraft/TickOrganizer.cpp

@@ -1,58 +1,58 @@
 #include "TickOrganizer.h"
-#include "Constants.h"
 
+#include "Constants.h"
 
 TickOrganizer::TickOrganizer()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {
-	queue = new TickQueue();
-	workerCount = NUM_TICK_WORKERS;
-	workers = new TickWorker * [workerCount];
-	for (int i = 0; i < workerCount; i++)
-		workers[i] = new TickWorker(queue);
+    queue = new TickQueue();
+    workerCount = NUM_TICK_WORKERS;
+    workers = new TickWorker*[workerCount];
+    for (int i = 0; i < workerCount; i++)
+        workers[i] = new TickWorker(queue);
 }
 
 TickOrganizer::~TickOrganizer()
 {
-	queue->requestExit();
-	for (int i = 0; i < workerCount; i++)
-	{
-		workers[i]->warteAufThread(10000);
-		workers[i]->ende();
-		workers[i]->release();
-	}
-	queue->release();
-	delete[] workers;
+    queue->requestExit();
+    for (int i = 0; i < workerCount; i++)
+    {
+        workers[i]->warteAufThread(10000);
+        workers[i]->ende();
+        workers[i]->release();
+    }
+    queue->release();
+    delete[] workers;
 }
 
 void TickOrganizer::nextTick()
 {
-	queue->startNextTick(&tickSources);
-	bool notWaiting = 0;
-	do
-	{
-		queue->waitForEmpty();
-		for (int i = 0; i < workerCount; i++)
-			notWaiting |= !workers[i]->isWaiting();
-	} while (notWaiting);
-	queue->postTick();
+    queue->startNextTick(&tickSources);
+    bool notWaiting = 0;
+    do
+    {
+        queue->waitForEmpty();
+        for (int i = 0; i < workerCount; i++)
+            notWaiting |= !workers[i]->isWaiting();
+    } while (notWaiting);
+    queue->postTick();
 }
 
 void TickOrganizer::addTickSource(Block* zBlock)
 {
-	tickSources.add(zBlock);
+    tickSources.add(zBlock);
 }
 
 void TickOrganizer::removeTickSource(Block* zBlock)
 {
-	int index = 0;
-	for (Block* block : tickSources)
-	{
-		if (block == zBlock)
-		{
-			tickSources.remove(index);
-			return;
-		}
-		index++;
-	}
+    int index = 0;
+    for (Block* block : tickSources)
+    {
+        if (block == zBlock)
+        {
+            tickSources.remove(index);
+            return;
+        }
+        index++;
+    }
 }

+ 9 - 9
FactoryCraft/TickOrganizer.h

@@ -7,17 +7,17 @@
 class TickOrganizer : public virtual Framework::ReferenceCounter
 {
 private:
-	int workerCount;
-	TickWorker** workers;
-	Framework::Array<Block*> tickSources;
-	TickQueue* queue;
+    int workerCount;
+    TickWorker** workers;
+    Framework::Array<Block*> tickSources;
+    TickQueue* queue;
 
 public:
-	TickOrganizer();
-	~TickOrganizer();
+    TickOrganizer();
+    ~TickOrganizer();
 
-	void nextTick();
+    void nextTick();
 
-	void addTickSource(Block* zBlock);
-	void removeTickSource(Block* zBlock);
+    void addTickSource(Block* zBlock);
+    void removeTickSource(Block* zBlock);
 };

+ 65 - 63
FactoryCraft/TickQueue.cpp

@@ -1,97 +1,99 @@
 #include "TickQueue.h"
-#include "Block.h"
 
+#include "Block.h"
 
 TickQueue::TickQueue()
-	: ReferenceCounter()
+    : ReferenceCounter()
 {
-	maxSize = 0;
-	readPosition = 0;
-	writePosition = 0;
-	queue = 0;
-	exit = 0;
+    maxSize = 0;
+    readPosition = 0;
+    writePosition = 0;
+    queue = 0;
+    exit = 0;
 }
 
 TickQueue::~TickQueue()
 {
-	delete[] queue;
+    delete[] queue;
 }
 
 void TickQueue::startNextTick(Framework::Array<Block*>* zSources)
 {
-	std::unique_lock<std::mutex> lk(mutex);
-	readPosition = 0;
-	writePosition = 0;
-	int count = zSources->getEintragAnzahl();
-	if (count >= maxSize)
-	{
-		Block** temp = new Block * [count + 1000];
-		memcpy(queue, temp, sizeof(Block*) * maxSize);
-		memset(temp + sizeof(Block*) * maxSize, 0, sizeof(Block*) * (count + 1000 - maxSize));
-		maxSize = count + 1000;
-		delete[]queue;
-		queue = temp;
-	}
-	for (Block* block : *zSources)
-		queue[writePosition++] = block;
-	lk.unlock();
-	hasBlocks.notify_all();
+    std::unique_lock<std::mutex> lk(mutex);
+    readPosition = 0;
+    writePosition = 0;
+    int count = zSources->getEintragAnzahl();
+    if (count >= maxSize)
+    {
+        Block** temp = new Block*[count + 1000];
+        memcpy(queue, temp, sizeof(Block*) * maxSize);
+        memset(temp + sizeof(Block*) * maxSize,
+            0,
+            sizeof(Block*) * (count + 1000 - maxSize));
+        maxSize = count + 1000;
+        delete[] queue;
+        queue = temp;
+    }
+    for (Block* block : *zSources)
+        queue[writePosition++] = block;
+    lk.unlock();
+    hasBlocks.notify_all();
 }
 
 void TickQueue::addToQueue(Block* zBlock)
 {
-	std::unique_lock<std::mutex> lk(mutex);
-	if (writePosition >= maxSize)
-	{
-		Block** temp = new Block * [maxSize + 1000];
-		memcpy(queue, temp, sizeof(Block*) * maxSize);
-		memset(temp + sizeof(Block*) * maxSize, 0, sizeof(Block*) * 1000);
-		maxSize += 1000;
-		delete[]queue;
-		queue = temp;
-	}
-	queue[writePosition++] = zBlock;
-	lk.unlock();
-	hasBlocks.notify_one();
+    std::unique_lock<std::mutex> lk(mutex);
+    if (writePosition >= maxSize)
+    {
+        Block** temp = new Block*[maxSize + 1000];
+        memcpy(queue, temp, sizeof(Block*) * maxSize);
+        memset(temp + sizeof(Block*) * maxSize, 0, sizeof(Block*) * 1000);
+        maxSize += 1000;
+        delete[] queue;
+        queue = temp;
+    }
+    queue[writePosition++] = zBlock;
+    lk.unlock();
+    hasBlocks.notify_one();
 }
 
 Block* TickQueue::zNextBlock(bool& waiting)
 {
-	std::unique_lock<std::mutex> lk(mutex);
-	if (readPosition == writePosition && exit)
-		return 0;
-	if (readPosition == writePosition)
-	{
-		lk.unlock();
-		hasNoBlocks.notify_all();
-		lk.lock();
-		waiting = 1;
-		hasBlocks.wait(lk, [this] { return readPosition < writePosition || exit; });
-		waiting = 0;
-	}
-	if (readPosition < writePosition)
-		return queue[readPosition++];
-	return 0;
+    std::unique_lock<std::mutex> lk(mutex);
+    if (readPosition == writePosition && exit) return 0;
+    if (readPosition == writePosition)
+    {
+        lk.unlock();
+        hasNoBlocks.notify_all();
+        lk.lock();
+        waiting = 1;
+        hasBlocks.wait(
+            lk, [this] { return readPosition < writePosition || exit; });
+        waiting = 0;
+    }
+    if (readPosition < writePosition) return queue[readPosition++];
+    return 0;
 }
 
 void TickQueue::requestExit()
 {
-	std::unique_lock<std::mutex> lk(mutex);
-	exit = 1;
-	lk.unlock();
-	hasBlocks.notify_all();
-	hasNoBlocks.notify_all();
+    std::unique_lock<std::mutex> lk(mutex);
+    exit = 1;
+    lk.unlock();
+    hasBlocks.notify_all();
+    hasNoBlocks.notify_all();
 }
 
 void TickQueue::waitForEmpty()
 {
-	std::unique_lock<std::mutex> lk(mutex);
-	if (readPosition != writePosition)
-		hasNoBlocks.wait(lk, [this] { return readPosition == writePosition || exit; });
+    std::unique_lock<std::mutex> lk(mutex);
+    if (readPosition != writePosition)
+        hasNoBlocks.wait(
+            lk, [this] { return readPosition == writePosition || exit; });
 }
 
 void TickQueue::postTick()
 {
-	for(int i = 0; i < writePosition; i++)
-		queue[i]->postTick();
+    for (int i = 0; i < writePosition; i++)
+        queue[i]->postTick();
 }

+ 17 - 17
FactoryCraft/TickQueue.h

@@ -1,31 +1,31 @@
 #pragma once
 
-#include <ReferenceCounter.h>
 #include <Array.h>
 #include <condition_variable>
+#include <ReferenceCounter.h>
 
 class Block;
 
 class TickQueue : public virtual Framework::ReferenceCounter
 {
 private:
-	int maxSize;
-	int readPosition;
-	int writePosition;
-	Block** queue;
-	std::mutex mutex;
-	std::condition_variable hasBlocks;
-	std::condition_variable hasNoBlocks;
-	bool exit;
+    int maxSize;
+    int readPosition;
+    int writePosition;
+    Block** queue;
+    std::mutex mutex;
+    std::condition_variable hasBlocks;
+    std::condition_variable hasNoBlocks;
+    bool exit;
 
 public:
-	TickQueue();
-	~TickQueue();
+    TickQueue();
+    ~TickQueue();
 
-	void startNextTick(Framework::Array<Block*>* zSources);
-	void addToQueue(Block* zBlock);
-	Block* zNextBlock(bool& waiting);
-	void requestExit();
-	void waitForEmpty();
-	void postTick();
+    void startNextTick(Framework::Array<Block*>* zSources);
+    void addToQueue(Block* zBlock);
+    Block* zNextBlock(bool& waiting);
+    void requestExit();
+    void waitForEmpty();
+    void postTick();
 };

+ 13 - 13
FactoryCraft/TickWorker.cpp

@@ -1,31 +1,31 @@
 #include "TickWorker.h"
-#include "Block.h"
 
+#include "Block.h"
 
 TickWorker::TickWorker(TickQueue* queue)
-	: Thread(),
-	queue(queue),
-	waiting(0)
+    : Thread(),
+      queue(queue),
+      waiting(0)
 {
-	start();
+    start();
 }
 
 TickWorker::~TickWorker()
 {
-	queue->release();
+    queue->release();
 }
 
 void TickWorker::thread()
 {
-	Block* zTickBlock = queue->zNextBlock(waiting);
-	while (zTickBlock)
-	{
-		zTickBlock->tick(queue);
-		zTickBlock = queue->zNextBlock(waiting);
-	}
+    Block* zTickBlock = queue->zNextBlock(waiting);
+    while (zTickBlock)
+    {
+        zTickBlock->tick(queue);
+        zTickBlock = queue->zNextBlock(waiting);
+    }
 }
 
 bool TickWorker::isWaiting() const
 {
-	return waiting;
+    return waiting;
 }

+ 6 - 6
FactoryCraft/TickWorker.h

@@ -7,13 +7,13 @@
 class TickWorker : public Framework::Thread
 {
 private:
-	TickQueue* queue;
-	bool waiting;
+    TickQueue* queue;
+    bool waiting;
 
 public:
-	TickWorker(TickQueue* queue);
-	~TickWorker();
+    TickWorker(TickQueue* queue);
+    ~TickWorker();
 
-	void thread() override;
-	bool isWaiting() const;
+    void thread() override;
+    bool isWaiting() const;
 };

+ 12 - 4
FactoryCraft/TreeSeblingBlock.cpp

@@ -11,7 +11,9 @@ TreeSeblingBlock::TreeSeblingBlock(int typeId,
     Framework::Vec3<int> pos,
     const BlockType* wood,
     const BlockType* leaves)
-    : Block(typeId, zTool, pos, 0), wood(wood), leaves(leaves)
+    : Block(typeId, zTool, pos, 0),
+      wood(wood),
+      leaves(leaves)
 {
     tickSource = 1;
 }
@@ -49,9 +51,15 @@ void TreeSeblingBlock::onPostTick()
 
 TreeSeblingBlockType::TreeSeblingBlockType(
     int typeId, int itemTypeId, ModelInfo model, int woodType, int leavesType)
-    : BlockType(typeId, 0, model, 1, 10, 0), itemType(itemTypeId),
-      transparent(true), passable(true), hardness(0.1f), zTool(0),
-      speedModifier(0.5f), interactable(1), woodType(woodType),
+    : BlockType(typeId, 0, model, 1, 10, 0),
+      itemType(itemTypeId),
+      transparent(true),
+      passable(true),
+      hardness(0.1f),
+      zTool(0),
+      speedModifier(0.5f),
+      interactable(1),
+      woodType(woodType),
       leavesType(leavesType)
 {}
 

+ 37 - 26
FactoryCraft/TreeSeblingBlock.h

@@ -7,41 +7,52 @@ class TreeSeblingBlockType;
 class TreeSeblingBlock : public Block
 {
 private:
-	float seblingTicks;
-	int seblingTicksMax;
-	const BlockType* wood;
-	const BlockType* leaves;
+    float seblingTicks;
+    int seblingTicksMax;
+    const BlockType* wood;
+    const BlockType* leaves;
 
 public:
-	TreeSeblingBlock(int typeId, const ItemType* zTool, Framework::Vec3<int> pos, const BlockType* wood, const BlockType* leaves);
-	virtual bool onTick(TickQueue* zQueue, int numTicks, bool& blocked) override;
-	virtual void onPostTick() override;
-
-	friend TreeSeblingBlockType;
+    TreeSeblingBlock(int typeId,
+        const ItemType* zTool,
+        Framework::Vec3<int> pos,
+        const BlockType* wood,
+        const BlockType* leaves);
+    virtual bool onTick(
+        TickQueue* zQueue, int numTicks, bool& blocked) override;
+    virtual void onPostTick() override;
+
+    friend TreeSeblingBlockType;
 };
 
-
 class TreeSeblingBlockType : public BlockType
 {
 private:
-	int itemType;
-	bool transparent;
-	bool passable;
-	float hardness;
-	const ItemType* zTool;
-	float speedModifier;
-	bool interactable;
-	int woodType;
-	int leavesType;
+    int itemType;
+    bool transparent;
+    bool passable;
+    float hardness;
+    const ItemType* zTool;
+    float speedModifier;
+    bool interactable;
+    int woodType;
+    int leavesType;
 
 protected:
-	virtual void createSuperBlock(Block* zBlock, Item* zItem) const override;
-	virtual void loadSuperBlock(Block* zBlock, Framework::StreamReader* zReader, int dimensionId) const override;
-	virtual void saveSuperBlock(Block* zBlock, Framework::StreamWriter* zWriter) const override;
-	virtual Item* createItem() const override;
-	virtual Block* createBlock(Framework::Vec3<int> position) const override;
+    virtual void createSuperBlock(Block* zBlock, Item* zItem) const override;
+    virtual void loadSuperBlock(Block* zBlock,
+        Framework::StreamReader* zReader,
+        int dimensionId) const override;
+    virtual void saveSuperBlock(
+        Block* zBlock, Framework::StreamWriter* zWriter) const override;
+    virtual Item* createItem() const override;
+    virtual Block* createBlock(Framework::Vec3<int> position) const override;
 
 public:
-	TreeSeblingBlockType(int typeId, int itemTypeId, ModelInfo model, int woodType, int leavesType);
-	TreeSeblingBlockType* setHardness(float hardness);
+    TreeSeblingBlockType(int typeId,
+        int itemTypeId,
+        ModelInfo model,
+        int woodType,
+        int leavesType);
+    TreeSeblingBlockType* setHardness(float hardness);
 };

+ 11 - 6
FactoryCraft/TreeTemplate.h

@@ -7,12 +7,17 @@ class TreeTemplate : public GenerationTemplate
 private:
     int woodBlockTypeId;
     int leaveBlockType;
-	int minHeight;
-	int maxHeight;
+    int minHeight;
+    int maxHeight;
 
 public:
-	TreeTemplate(float propability, int woodBlockTypeId, int leaveBlockType, int minHeight, int maxHeight);
-	virtual GeneratedStructure* generateAt(Framework::Vec3<int> location, Noise* zNoise, int dimensionId) override;
-	const BlockType* getWoodType() const;
-	const BlockType* getLeavesType() const;
+    TreeTemplate(float propability,
+        int woodBlockTypeId,
+        int leaveBlockType,
+        int minHeight,
+        int maxHeight);
+    virtual GeneratedStructure* generateAt(
+        Framework::Vec3<int> location, Noise* zNoise, int dimensionId) override;
+    const BlockType* getWoodType() const;
+    const BlockType* getLeavesType() const;
 };

+ 76 - 63
FactoryCraft/WorldGenerator.cpp

@@ -1,91 +1,104 @@
 #include "WorldGenerator.h"
-#include "StaticRegistry.h"
-#include "Game.h"
-#include "NoiseInterpolator.h"
 
 #include <functional>
 
+#include "Game.h"
+#include "NoiseInterpolator.h"
+#include "StaticRegistry.h"
+
 using namespace Framework;
 
 WorldGenerator::WorldGenerator(int seed)
-	: Thread(),
-	exit(0),
-	seed(seed)
+    : Thread(),
+      exit(0),
+      seed(seed)
 {
-	setName("World Generator");
-	for (int i = 0; i < StaticRegistry<DimensionGenerator>::INSTANCE.getCount(); i++)
-		StaticRegistry<DimensionGenerator>::INSTANCE.zElement(i)->initialize(seed);
-	start();
+    setName("World Generator");
+    for (int i = 0; i < StaticRegistry<DimensionGenerator>::INSTANCE.getCount();
+         i++)
+        StaticRegistry<DimensionGenerator>::INSTANCE.zElement(i)->initialize(
+            seed);
+    start();
 }
 
-WorldGenerator::~WorldGenerator()
-{}
+WorldGenerator::~WorldGenerator() {}
 
 void WorldGenerator::thread()
 {
-	while (!exit)
-	{
-		cs.lock();
-		Area next;
-		bool hasNext = 0;
-		if (requestQueue.getEintragAnzahl() > 0)
-		{
-			next = requestQueue.get(0);
-			requestQueue.remove(0);
-			hasNext = 1;
-		}
-		cs.unlock();
-		if (!hasNext)
-		{
-			sleep(1);
-			continue;
-		}
-		Punkt start = Game::INSTANCE->getChunkCenter(next.startX, next.startY);
-		Punkt end = Game::INSTANCE->getChunkCenter(next.endX, next.endY);
-		int xDir = start.x > end.x ? -1 : 1;
-		int yDir = start.y > end.y ? -1 : 1;
-		for (int x = start.x; xDir < 0 ? x >= end.x : x <= end.x; x += CHUNK_SIZE * xDir)
-		{
-			for (int y = start.y; yDir < 0 ? y >= end.y : y <= end.y; y += CHUNK_SIZE * yDir)
-			{
-				if (!Game::INSTANCE->doesChunkExist(x, y, next.dimensionId))
-				{
-					Chunk* generatedChunk = StaticRegistry<DimensionGenerator>::INSTANCE.zElement(next.dimensionId)->generateChunk(x, y);
-					generatedChunk->initializeLightning();
-					generatedChunk->removeUnusedBlocks();
-					Dimension* dim = Game::INSTANCE->zDimension(next.dimensionId);
-					if (!dim)
-					{
-						dim = new Dimension(next.dimensionId);
-						Game::INSTANCE->addDimension(dim);
-					}
-					dim->setChunk(generatedChunk, Punkt(x, y));
-				}
-			}
-		}
-	}
+    while (!exit)
+    {
+        cs.lock();
+        Area next;
+        bool hasNext = 0;
+        if (requestQueue.getEintragAnzahl() > 0)
+        {
+            next = requestQueue.get(0);
+            requestQueue.remove(0);
+            hasNext = 1;
+        }
+        cs.unlock();
+        if (!hasNext)
+        {
+            sleep(1);
+            continue;
+        }
+        Punkt start = Game::INSTANCE->getChunkCenter(next.startX, next.startY);
+        Punkt end = Game::INSTANCE->getChunkCenter(next.endX, next.endY);
+        int xDir = start.x > end.x ? -1 : 1;
+        int yDir = start.y > end.y ? -1 : 1;
+        for (int x = start.x; xDir < 0 ? x >= end.x : x <= end.x;
+             x += CHUNK_SIZE * xDir)
+        {
+            for (int y = start.y; yDir < 0 ? y >= end.y : y <= end.y;
+                 y += CHUNK_SIZE * yDir)
+            {
+                if (!Game::INSTANCE->doesChunkExist(x, y, next.dimensionId))
+                {
+                    Chunk* generatedChunk
+                        = StaticRegistry<DimensionGenerator>::INSTANCE
+                              .zElement(next.dimensionId)
+                              ->generateChunk(x, y);
+                    generatedChunk->initializeLightning();
+                    generatedChunk->removeUnusedBlocks();
+                    Dimension* dim
+                        = Game::INSTANCE->zDimension(next.dimensionId);
+                    if (!dim)
+                    {
+                        dim = new Dimension(next.dimensionId);
+                        Game::INSTANCE->addDimension(dim);
+                    }
+                    dim->setChunk(generatedChunk, Punkt(x, y));
+                }
+            }
+        }
+    }
 }
 
 void WorldGenerator::requestGeneration(Area request)
 {
-	cs.lock();
-	requestQueue.add(request);
-	cs.unlock();
+    cs.lock();
+    requestQueue.add(request);
+    cs.unlock();
 }
 
 void WorldGenerator::exitAndWait()
 {
-	exit = 1;
-	warteAufThread(10000);
-	ende();
+    exit = 1;
+    warteAufThread(10000);
+    ende();
 }
 
-Framework::Either<Block*, int> WorldGenerator::generateSingleBlock(Framework::Vec3<int> location, int dimensionId)
+Framework::Either<Block*, int> WorldGenerator::generateSingleBlock(
+    Framework::Vec3<int> location, int dimensionId)
 {
-	return StaticRegistry<DimensionGenerator>::INSTANCE.zElement(dimensionId)->generateBlock(location);
+    return StaticRegistry<DimensionGenerator>::INSTANCE.zElement(dimensionId)
+        ->generateBlock(location);
 }
 
-bool WorldGenerator::spawnStructure(Framework::Vec3<int> location, int dimensionId, std::function<bool(GenerationTemplate* tmpl)> filter)
+bool WorldGenerator::spawnStructure(Framework::Vec3<int> location,
+    int dimensionId,
+    std::function<bool(GenerationTemplate* tmpl)> filter)
 {
-	return StaticRegistry<DimensionGenerator>::INSTANCE.zElement(dimensionId)->spawnStructure(location, filter);
+    return StaticRegistry<DimensionGenerator>::INSTANCE.zElement(dimensionId)
+        ->spawnStructure(location, filter);
 }

+ 16 - 14
FactoryCraft/WorldGenerator.h

@@ -1,26 +1,28 @@
 #pragma once
 
-#include <Thread.h>
 #include <Critical.h>
+#include <Thread.h>
 
-#include "DimensionGenerator.h"
 #include "Area.h"
-
+#include "DimensionGenerator.h"
 
 class WorldGenerator : public Framework::Thread
 {
 private:
-	Framework::Critical cs;
-	Framework::Array<Area> requestQueue;
-	bool exit;
-	int seed;
+    Framework::Critical cs;
+    Framework::Array<Area> requestQueue;
+    bool exit;
+    int seed;
 
 public:
-	WorldGenerator(int seed);
-	~WorldGenerator();
-	void thread() override;
-	void requestGeneration(Area request);
-	void exitAndWait();
-	Framework::Either<Block*, int> generateSingleBlock(Framework::Vec3<int> location, int dimensionId);
-	bool spawnStructure(Framework::Vec3<int> location, int dimensionId, std::function<bool(GenerationTemplate* tmpl)> filter);
+    WorldGenerator(int seed);
+    ~WorldGenerator();
+    void thread() override;
+    void requestGeneration(Area request);
+    void exitAndWait();
+    Framework::Either<Block*, int> generateSingleBlock(
+        Framework::Vec3<int> location, int dimensionId);
+    bool spawnStructure(Framework::Vec3<int> location,
+        int dimensionId,
+        std::function<bool(GenerationTemplate* tmpl)> filter);
 };

+ 109 - 99
FactoryCraft/WorldLoader.cpp

@@ -1,126 +1,136 @@
+#include "WorldLoader.h"
+
 #include <Punkt.h>
 #include <Text.h>
 
-#include "WorldLoader.h"
 #include "Game.h"
 
 using namespace Framework;
 
 WorldLoader::WorldLoader()
-	: Thread(),
-	exit(0)
+    : Thread(),
+      exit(0)
 {
-	setName("World Loader");
-	Datei d;
-	d.setDatei(Game::INSTANCE->getWorldDirectory() + "/dim");
-	RCArray<Text>* names = d.getDateiListe();
-	if (names)
-	{
-		for (Text* name : *names)
-		{
-			Datei entities;
-			entities.setDatei(Game::INSTANCE->getWorldDirectory() + "/dim/" + Text(name->getText()) + "/entities");
-			if (entities.open(Datei::Style::lesen))
-			{
-				Dimension* dim = new Dimension((int)*name);
-				while (!entities.istEnde())
-				{
-					int type = 0;
-					entities.lese((char*)&type, 4);
-					dim->addEntity(StaticRegistry<EntityType>::INSTANCE.zElement(type)->loadEntity(&entities));
-				}
-				Game::INSTANCE->addDimension(dim);
-			}
-		}
-		names->release();
-	}
-	start();
+    setName("World Loader");
+    Datei d;
+    d.setDatei(Game::INSTANCE->getWorldDirectory() + "/dim");
+    RCArray<Text>* names = d.getDateiListe();
+    if (names)
+    {
+        for (Text* name : *names)
+        {
+            Datei entities;
+            entities.setDatei(Game::INSTANCE->getWorldDirectory() + "/dim/"
+                              + Text(name->getText()) + "/entities");
+            if (entities.open(Datei::Style::lesen))
+            {
+                Dimension* dim = new Dimension((int)*name);
+                while (!entities.istEnde())
+                {
+                    int type = 0;
+                    entities.lese((char*)&type, 4);
+                    dim->addEntity(
+                        StaticRegistry<EntityType>::INSTANCE.zElement(type)
+                            ->loadEntity(&entities));
+                }
+                Game::INSTANCE->addDimension(dim);
+            }
+        }
+        names->release();
+    }
+    start();
 }
 
-WorldLoader::~WorldLoader()
-{}
+WorldLoader::~WorldLoader() {}
 
 void WorldLoader::thread()
 {
-	while (!exit)
-	{
-		cs.lock();
-		Area next;
-		bool hasNext = 0;
-		if (requestQueue.getEintragAnzahl() > 0)
-		{
-			next = requestQueue.get(0);
-			requestQueue.remove(0);
-			hasNext = 1;
-		}
-		cs.unlock();
-		if (!hasNext)
-		{
-			Sleep(1000);
-			continue;
-		}
-		Punkt start = Game::INSTANCE->getChunkCenter(next.startX, next.startY);
-		Punkt end = Game::INSTANCE->getChunkCenter(next.endX, next.endY);
-		int xDir = start.x > end.x ? -1 : 1;
-		int yDir = start.y > end.y ? -1 : 1;
-		for (int x = start.x; xDir < 0 ? x >= end.x : x <= end.x; x += CHUNK_SIZE * xDir)
-		{
-			for (int y = start.y; yDir < 0 ? y >= end.y : y <= end.y; y += CHUNK_SIZE * yDir)
-			{
-				Dimension* zDim = Game::INSTANCE->zDimension(next.dimensionId);
-				bool revived = 0;
-				if (!zDim->zChunk(Punkt(x, y)) && zDim->hasChunck(x, y))
-				{
-					revived = zDim->reviveChunk(x, y);
-				}
-				if (!revived && !Game::INSTANCE->isChunkLoaded(x, y, next.dimensionId))
-				{
-					Datei* file = new Datei();
-					Text filePath = Game::INSTANCE->getWorldDirectory() + "/dim/" + next.dimensionId + "/";
-					filePath.appendHex(x);
-					filePath += "_";
-					filePath.appendHex(y);
-					filePath += ".chunk";
-					file->setDatei(filePath);
-					if (file->open(Datei::Style::lesen))
-					{
-						Chunk* chunk = new Chunk(Framework::Punkt(x, y), next.dimensionId, file);
-						Dimension* dim = Game::INSTANCE->zDimension(next.dimensionId);
-						if (!dim)
-						{
-							dim = new Dimension(next.dimensionId);
-							Game::INSTANCE->addDimension(dim);
-						}
-						dim->setChunk(chunk, Punkt(x, y));
-					}
-					file->close();
-					file->release();
-				}
-			}
-		}
-	}
+    while (!exit)
+    {
+        cs.lock();
+        Area next;
+        bool hasNext = 0;
+        if (requestQueue.getEintragAnzahl() > 0)
+        {
+            next = requestQueue.get(0);
+            requestQueue.remove(0);
+            hasNext = 1;
+        }
+        cs.unlock();
+        if (!hasNext)
+        {
+            Sleep(1000);
+            continue;
+        }
+        Punkt start = Game::INSTANCE->getChunkCenter(next.startX, next.startY);
+        Punkt end = Game::INSTANCE->getChunkCenter(next.endX, next.endY);
+        int xDir = start.x > end.x ? -1 : 1;
+        int yDir = start.y > end.y ? -1 : 1;
+        for (int x = start.x; xDir < 0 ? x >= end.x : x <= end.x;
+             x += CHUNK_SIZE * xDir)
+        {
+            for (int y = start.y; yDir < 0 ? y >= end.y : y <= end.y;
+                 y += CHUNK_SIZE * yDir)
+            {
+                Dimension* zDim = Game::INSTANCE->zDimension(next.dimensionId);
+                bool revived = 0;
+                if (!zDim->zChunk(Punkt(x, y)) && zDim->hasChunck(x, y))
+                {
+                    revived = zDim->reviveChunk(x, y);
+                }
+                if (!revived
+                    && !Game::INSTANCE->isChunkLoaded(x, y, next.dimensionId))
+                {
+                    Datei* file = new Datei();
+                    Text filePath = Game::INSTANCE->getWorldDirectory()
+                                  + "/dim/" + next.dimensionId + "/";
+                    filePath.appendHex(x);
+                    filePath += "_";
+                    filePath.appendHex(y);
+                    filePath += ".chunk";
+                    file->setDatei(filePath);
+                    if (file->open(Datei::Style::lesen))
+                    {
+                        Chunk* chunk = new Chunk(
+                            Framework::Punkt(x, y), next.dimensionId, file);
+                        Dimension* dim
+                            = Game::INSTANCE->zDimension(next.dimensionId);
+                        if (!dim)
+                        {
+                            dim = new Dimension(next.dimensionId);
+                            Game::INSTANCE->addDimension(dim);
+                        }
+                        dim->setChunk(chunk, Punkt(x, y));
+                    }
+                    file->close();
+                    file->release();
+                }
+            }
+        }
+    }
 }
 
 void WorldLoader::requestLoading(Area request)
 {
-	cs.lock();
-	requestQueue.add(request);
-	cs.unlock();
+    cs.lock();
+    requestQueue.add(request);
+    cs.unlock();
 }
 
 void WorldLoader::exitAndWait()
 {
-	exit = 1;
-	warteAufThread(10000);
-	ende();
+    exit = 1;
+    warteAufThread(10000);
+    ende();
 }
 
 bool WorldLoader::existsChunk(int x, int y, int dimension) const
 {
-	Text filePath = Game::INSTANCE->getWorldDirectory() + "/dim/" + dimension + "/";
-	filePath.appendHex(x);
-	filePath += "_";
-	filePath.appendHex(y);
-	filePath += ".chunk";
-	return DateiExistiert(filePath);
+    Text filePath
+        = Game::INSTANCE->getWorldDirectory() + "/dim/" + dimension + "/";
+    filePath.appendHex(x);
+    filePath += "_";
+    filePath.appendHex(y);
+    filePath += ".chunk";
+    return DateiExistiert(filePath);
 }

+ 11 - 12
FactoryCraft/WorldLoader.h

@@ -1,24 +1,23 @@
 #pragma once
 
-#include <Thread.h>
-#include <HashMap.h>
 #include <Critical.h>
+#include <HashMap.h>
+#include <Thread.h>
 
 #include "Area.h"
 
-
 class WorldLoader : public Framework::Thread
 {
 private:
-	Framework::Critical cs;
-	Framework::Array<Area> requestQueue;
-	bool exit;
+    Framework::Critical cs;
+    Framework::Array<Area> requestQueue;
+    bool exit;
 
 public:
-	WorldLoader();
-	~WorldLoader();
-	void thread() override;
-	void requestLoading(Area request);
-	void exitAndWait();
-	bool existsChunk(int x, int y, int dimension) const;
+    WorldLoader();
+    ~WorldLoader();
+    void thread() override;
+    void requestLoading(Area request);
+    void exitAndWait();
+    bool existsChunk(int x, int y, int dimension) const;
 };

+ 21 - 20
FactoryCraft/WorldUpdate.cpp

@@ -1,47 +1,48 @@
 #include "WorldUpdate.h"
 
-WorldUpdate::WorldUpdate(int type, int dimensionId, Framework::Vec3<int> minAffected, Framework::Vec3<int> maxAffected)
-	: ReferenceCounter(),
-	affectedDimensionId(dimensionId),
-	minAffected(minAffected),
-	maxAffected(maxAffected),
-	type(type)
+WorldUpdate::WorldUpdate(int type,
+    int dimensionId,
+    Framework::Vec3<int> minAffected,
+    Framework::Vec3<int> maxAffected)
+    : ReferenceCounter(),
+      affectedDimensionId(dimensionId),
+      minAffected(minAffected),
+      maxAffected(maxAffected),
+      type(type)
 {}
 
 void WorldUpdate::writeAndCheck(Framework::StreamWriter* zWriter)
 {
-	zWriter->schreibe((char*)&type, 4);
-	this->write(zWriter);
-	zWriter->schreibe((char*)&type, 4);
+    zWriter->schreibe((char*)&type, 4);
+    this->write(zWriter);
+    zWriter->schreibe((char*)&type, 4);
 }
 
 int WorldUpdate::getAffectedDimension() const
 {
-	return affectedDimensionId;
+    return affectedDimensionId;
 }
 
 const Framework::Vec3<int>& WorldUpdate::getMinAffectedPoint() const
 {
-	return minAffected;
+    return minAffected;
 }
 
 const Framework::Vec3<int>& WorldUpdate::getMaxAffectedPoint() const
 {
-	return maxAffected;
+    return maxAffected;
 }
 
 int WorldUpdate::getType() const
 {
-	return type;
+    return type;
 }
 
 int WorldUpdate::distanceTo(int x, int y) const
 {
-	int xDist = MIN(abs(x - minAffected.x), abs(x - maxAffected.x));
-	int yDist = MIN(abs(y - minAffected.y), abs(y - maxAffected.y));
-	if (x >= minAffected.x && x <= maxAffected.x)
-		xDist = 0;
-	if (y >= minAffected.y && y <= maxAffected.y)
-		yDist = 0;
-	return MIN(xDist, yDist);
+    int xDist = MIN(abs(x - minAffected.x), abs(x - maxAffected.x));
+    int yDist = MIN(abs(y - minAffected.y), abs(y - maxAffected.y));
+    if (x >= minAffected.x && x <= maxAffected.x) xDist = 0;
+    if (y >= minAffected.y && y <= maxAffected.y) yDist = 0;
+    return MIN(xDist, yDist);
 }

+ 18 - 15
FactoryCraft/WorldUpdate.h

@@ -18,23 +18,26 @@ public:
 class WorldUpdate : public Framework::ReferenceCounter
 {
 private:
-	int affectedDimensionId;
-	Framework::Vec3<int> minAffected;
-	Framework::Vec3<int> maxAffected;
-	int type;
+    int affectedDimensionId;
+    Framework::Vec3<int> minAffected;
+    Framework::Vec3<int> maxAffected;
+    int type;
 
 protected:
-	virtual void write(Framework::StreamWriter* zWriter) = 0;
+    virtual void write(Framework::StreamWriter* zWriter) = 0;
 
 public:
-	WorldUpdate(int type, int dimensionId, Framework::Vec3<int> minAffected, Framework::Vec3<int> maxAffected);
-
-	virtual void onUpdate(Dimension* zDimension) = 0;
-	void writeAndCheck(Framework::StreamWriter* zWriter);
-
-	int getAffectedDimension() const;
-	const Framework::Vec3<int>& getMinAffectedPoint() const;
-	const Framework::Vec3<int>& getMaxAffectedPoint() const;
-	int getType() const;
-	int distanceTo(int x, int y) const;
+    WorldUpdate(int type,
+        int dimensionId,
+        Framework::Vec3<int> minAffected,
+        Framework::Vec3<int> maxAffected);
+
+    virtual void onUpdate(Dimension* zDimension) = 0;
+    void writeAndCheck(Framework::StreamWriter* zWriter);
+
+    int getAffectedDimension() const;
+    const Framework::Vec3<int>& getMinAffectedPoint() const;
+    const Framework::Vec3<int>& getMaxAffectedPoint() const;
+    int getType() const;
+    int distanceTo(int x, int y) const;
 };

+ 173 - 134
FactoryCraft/WormCaveGenerator.cpp

@@ -1,176 +1,215 @@
 #include "WormCaveGenerator.h"
-#include "Game.h"
+
 #include "FastNoiseWrapper.h"
+#include "Game.h"
 #include "RandNoise.h"
 
-
-NoiseWorm3D::NoiseWorm3D(Noise* pitch, Noise* yaw, Noise* size, Framework::Vec3<int> startPos, int distant, int minRad, int maxRad)
-	: ReferenceCounter(),
-	startChunk(Game::INSTANCE->getChunkCenter(startPos.x, startPos.y))
+NoiseWorm3D::NoiseWorm3D(Noise* pitch,
+    Noise* yaw,
+    Noise* size,
+    Framework::Vec3<int> startPos,
+    int distant,
+    int minRad,
+    int maxRad)
+    : ReferenceCounter(),
+      startChunk(Game::INSTANCE->getChunkCenter(startPos.x, startPos.y))
 {
-	Vec3<float> lastPos = (Vec3<float>)startPos;
-	keyPoints.add(lastPos);
-	this->size.add((float)minRad);
-	minAffected.x = (int)lastPos.x - minRad;
-	minAffected.y = (int)lastPos.y - minRad;
-	maxAffected.x = (int)lastPos.x + minRad;
-	maxAffected.y = (int)lastPos.y + minRad;
-	while (keyPoints.getEintragAnzahl() < distant * 20)
-	{
-		Vec3<float> defaultDir(1.f, 0.f, 0.f);
-		if (keyPoints.getEintragAnzahl() > 1)
-		{
-			defaultDir = keyPoints.get(keyPoints.getEintragAnzahl() - 1) - keyPoints.get(keyPoints.getEintragAnzahl() - 2);
-		}
-		float n = (float)yaw->getNoise(lastPos.x, lastPos.y, lastPos.z);
-		defaultDir.rotateZ((n - 0.5f) / 2.f);
-		defaultDir.normalize();
-		n = (float)pitch->getNoise(lastPos.x, lastPos.y, lastPos.z);
-		defaultDir.z = ((float)n - 0.3f) * 2.f;
-		lastPos = lastPos + defaultDir;
-		if ((Vec2<float>(lastPos.x, lastPos.y) - (Vec2<float>((float)startPos.x, (float)startPos.y))).getLengthSq() >= (float)(distant * distant))
-			break;
-		keyPoints.add(lastPos);
-		float rad = (float)size->getNoise(lastPos.x, lastPos.y, lastPos.z) * (float)(maxRad - minRad) + (float)minRad;
-		this->size.add(rad);
-		minAffected.x = MIN(minAffected.x, (int)(lastPos.x - rad));
-		minAffected.y = MIN(minAffected.y, (int)(lastPos.y - rad));
-		maxAffected.x = MAX(maxAffected.x, (int)(lastPos.x + rad));
-		maxAffected.y = MAX(maxAffected.y, (int)(lastPos.y + rad));
-	}
+    Vec3<float> lastPos = (Vec3<float>)startPos;
+    keyPoints.add(lastPos);
+    this->size.add((float)minRad);
+    minAffected.x = (int)lastPos.x - minRad;
+    minAffected.y = (int)lastPos.y - minRad;
+    maxAffected.x = (int)lastPos.x + minRad;
+    maxAffected.y = (int)lastPos.y + minRad;
+    while (keyPoints.getEintragAnzahl() < distant * 20)
+    {
+        Vec3<float> defaultDir(1.f, 0.f, 0.f);
+        if (keyPoints.getEintragAnzahl() > 1)
+        {
+            defaultDir = keyPoints.get(keyPoints.getEintragAnzahl() - 1)
+                       - keyPoints.get(keyPoints.getEintragAnzahl() - 2);
+        }
+        float n = (float)yaw->getNoise(lastPos.x, lastPos.y, lastPos.z);
+        defaultDir.rotateZ((n - 0.5f) / 2.f);
+        defaultDir.normalize();
+        n = (float)pitch->getNoise(lastPos.x, lastPos.y, lastPos.z);
+        defaultDir.z = ((float)n - 0.3f) * 2.f;
+        lastPos = lastPos + defaultDir;
+        if ((Vec2<float>(lastPos.x, lastPos.y)
+                - (Vec2<float>((float)startPos.x, (float)startPos.y)))
+                .getLengthSq()
+            >= (float)(distant * distant))
+            break;
+        keyPoints.add(lastPos);
+        float rad = (float)size->getNoise(lastPos.x, lastPos.y, lastPos.z)
+                      * (float)(maxRad - minRad)
+                  + (float)minRad;
+        this->size.add(rad);
+        minAffected.x = MIN(minAffected.x, (int)(lastPos.x - rad));
+        minAffected.y = MIN(minAffected.y, (int)(lastPos.y - rad));
+        maxAffected.x = MAX(maxAffected.x, (int)(lastPos.x + rad));
+        maxAffected.y = MAX(maxAffected.y, (int)(lastPos.y + rad));
+    }
 }
 
 Framework::Punkt NoiseWorm3D::getStartChunkCenter()
 {
-	return startChunk;
+    return startChunk;
 }
 
 bool NoiseWorm3D::isChunkAffected(int x, int y)
 {
-	if (x - CHUNK_SIZE / 2 <= maxAffected.x && x + CHUNK_SIZE / 2 >= minAffected.x && y - CHUNK_SIZE / 2 <= maxAffected.y && y + CHUNK_SIZE / 2 >= minAffected.y)
-	{
-		auto pi = keyPoints.begin();
-		auto si = size.begin();
-		while (pi && si)
-		{
-			if ((Vec2<float>((float)x, (float)y) - Vec2<float>(pi.val().x, pi.val().y)).getLengthSq() < (si.val() + CHUNK_SIZE / 2) * (si.val() + CHUNK_SIZE / 2))
-				return 1;
-			++pi;
-			++si;
-		}
-	}
-	return 0;
+    if (x - CHUNK_SIZE / 2 <= maxAffected.x
+        && x + CHUNK_SIZE / 2 >= minAffected.x
+        && y - CHUNK_SIZE / 2 <= maxAffected.y
+        && y + CHUNK_SIZE / 2 >= minAffected.y)
+    {
+        auto pi = keyPoints.begin();
+        auto si = size.begin();
+        while (pi && si)
+        {
+            if ((Vec2<float>((float)x, (float)y)
+                    - Vec2<float>(pi.val().x, pi.val().y))
+                    .getLengthSq()
+                < (si.val() + CHUNK_SIZE / 2) * (si.val() + CHUNK_SIZE / 2))
+                return 1;
+            ++pi;
+            ++si;
+        }
+    }
+    return 0;
 }
 
 bool NoiseWorm3D::isInside(int x, int y, int z)
 {
-	auto pi = keyPoints.begin();
-	auto si = size.begin();
-	while (pi && si)
-	{
-		if (Vec3<float>((float)x, (float)y, (float)z).abstand(pi.val()) < si.val())
-			return 1;
-		++pi;
-		++si;
-	}
-	return 0;
+    auto pi = keyPoints.begin();
+    auto si = size.begin();
+    while (pi && si)
+    {
+        if (Vec3<float>((float)x, (float)y, (float)z).abstand(pi.val())
+            < si.val())
+            return 1;
+        ++pi;
+        ++si;
+    }
+    return 0;
 }
 
-
-WormCaveChunkGenerator::WormCaveChunkGenerator(Framework::RCArray<NoiseWorm3D> worms)
-	: CaveChunkGenerator(),
-	worms(worms)
+WormCaveChunkGenerator::WormCaveChunkGenerator(
+    Framework::RCArray<NoiseWorm3D> worms)
+    : CaveChunkGenerator(),
+      worms(worms)
 {}
 
 bool WormCaveChunkGenerator::isInCave(int x, int y, int z)
 {
-	for (NoiseWorm3D* w : worms)
-	{
-		if (w->isInside(x, y, z))
-			return 1;
-	}
-	return 0;
+    for (NoiseWorm3D* w : worms)
+    {
+        if (w->isInside(x, y, z)) return 1;
+    }
+    return 0;
 }
 
-
-WormCaveGenerator::WormCaveGenerator(int minDistant, int maxDistant, int minRadius, int maxRadius, float cavePosibillityPerChunk)
-	: CaveGenerator(),
-	maxDistant(maxDistant),
-	minDistant(minDistant),
-	maxRadius(maxRadius),
-	minRadius(minRadius),
-	cavePosibillity(cavePosibillityPerChunk)
+WormCaveGenerator::WormCaveGenerator(int minDistant,
+    int maxDistant,
+    int minRadius,
+    int maxRadius,
+    float cavePosibillityPerChunk)
+    : CaveGenerator(),
+      maxDistant(maxDistant),
+      minDistant(minDistant),
+      maxRadius(maxRadius),
+      minRadius(minRadius),
+      cavePosibillity(cavePosibillityPerChunk)
 {}
 
 WormCaveGenerator::~WormCaveGenerator()
 {
-	wormStartNoise->release();
+    wormStartNoise->release();
 }
 
 NoiseWorm3D* WormCaveGenerator::zWormOfChunk(int x, int y)
 {
-	for (NoiseWorm3D* worm : cache)
-	{
-		if (worm->getStartChunkCenter().x == x && worm->getStartChunkCenter().y == y)
-		{
-			return worm;
-		}
-	}
-	for (Punkt p : noWormChunks)
-	{
-		if (p.x == x && p.y == y)
-			return 0;
-	}
-	float cNoise = (float)wormStartNoise->getNoise(x, y, 0);
-	if (cNoise < cavePosibillity)
-	{
-		FastNoiseLite* noise = new FastNoiseLite(seed + x * y + y + x);
-		noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Perlin);
-		noise->SetFrequency(0.05f);
-		FastNoiseWrapper* pitch = new FastNoiseWrapper(noise, seed + x * y + y + x);
-		noise = new FastNoiseLite(seed + x * y + y + x);
-		noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Perlin);
-		noise->SetFrequency(0.005f);
-		FastNoiseWrapper* yaw = new FastNoiseWrapper(noise, seed - x * y - y - x);
-		Vec3<int> start((int)(cNoise / cavePosibillity * CHUNK_SIZE) + x - CHUNK_SIZE / 2, (int)(cNoise / cavePosibillity * CHUNK_SIZE) + y - CHUNK_SIZE / 2, (int)(cNoise / cavePosibillity * 200));
-		noise = new FastNoiseLite(seed + start.getLengthSq() + start.x + start.y + start.z);
-		noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Perlin);
-		noise->SetFrequency(0.005f);
-		FastNoiseWrapper* size = new FastNoiseWrapper(noise, seed + start.getLengthSq() + start.x + start.y + start.z);
-		NoiseWorm3D* worm = new NoiseWorm3D(pitch, yaw, size, start, (int)(wormStartNoise->getNoise(start.x, start.y, start.z) * (maxDistant - minDistant) + minDistant), minRadius, maxRadius);
-		if (cache.getEintragAnzahl() > (maxDistant * 2) / CHUNK_SIZE * (maxDistant * 2) / CHUNK_SIZE * 3)
-			cache.remove(0);
-		cache.add(worm);
-		return worm;
-	}
-	else
-	{
-		if (noWormChunks.getEintragAnzahl() > (maxDistant * 2) / CHUNK_SIZE * (maxDistant * 2) / CHUNK_SIZE * 3)
-			noWormChunks.remove(0);
-		noWormChunks.add(Punkt(x, y));
-	}
-	return 0;
+    for (NoiseWorm3D* worm : cache)
+    {
+        if (worm->getStartChunkCenter().x == x
+            && worm->getStartChunkCenter().y == y)
+        {
+            return worm;
+        }
+    }
+    for (Punkt p : noWormChunks)
+    {
+        if (p.x == x && p.y == y) return 0;
+    }
+    float cNoise = (float)wormStartNoise->getNoise(x, y, 0);
+    if (cNoise < cavePosibillity)
+    {
+        FastNoiseLite* noise = new FastNoiseLite(seed + x * y + y + x);
+        noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Perlin);
+        noise->SetFrequency(0.05f);
+        FastNoiseWrapper* pitch
+            = new FastNoiseWrapper(noise, seed + x * y + y + x);
+        noise = new FastNoiseLite(seed + x * y + y + x);
+        noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Perlin);
+        noise->SetFrequency(0.005f);
+        FastNoiseWrapper* yaw
+            = new FastNoiseWrapper(noise, seed - x * y - y - x);
+        Vec3<int> start(
+            (int)(cNoise / cavePosibillity * CHUNK_SIZE) + x - CHUNK_SIZE / 2,
+            (int)(cNoise / cavePosibillity * CHUNK_SIZE) + y - CHUNK_SIZE / 2,
+            (int)(cNoise / cavePosibillity * 200));
+        noise = new FastNoiseLite(
+            seed + start.getLengthSq() + start.x + start.y + start.z);
+        noise->SetNoiseType(FastNoiseLite::NoiseType::NoiseType_Perlin);
+        noise->SetFrequency(0.005f);
+        FastNoiseWrapper* size = new FastNoiseWrapper(
+            noise, seed + start.getLengthSq() + start.x + start.y + start.z);
+        NoiseWorm3D* worm = new NoiseWorm3D(pitch,
+            yaw,
+            size,
+            start,
+            (int)(wormStartNoise->getNoise(start.x, start.y, start.z)
+                      * (maxDistant - minDistant)
+                  + minDistant),
+            minRadius,
+            maxRadius);
+        if (cache.getEintragAnzahl()
+            > (maxDistant * 2) / CHUNK_SIZE * (maxDistant * 2) / CHUNK_SIZE * 3)
+            cache.remove(0);
+        cache.add(worm);
+        return worm;
+    }
+    else
+    {
+        if (noWormChunks.getEintragAnzahl()
+            > (maxDistant * 2) / CHUNK_SIZE * (maxDistant * 2) / CHUNK_SIZE * 3)
+            noWormChunks.remove(0);
+        noWormChunks.add(Punkt(x, y));
+    }
+    return 0;
 }
 
 void WormCaveGenerator::initialize(int seed)
 {
-	wormStartNoise = new RandNoise(seed);
-	CaveGenerator::initialize(seed);
+    wormStartNoise = new RandNoise(seed);
+    CaveGenerator::initialize(seed);
 }
 
 CaveChunkGenerator* WormCaveGenerator::getGeneratorForChunk(int x, int y)
 {
-	Framework::RCArray<NoiseWorm3D> affected;
-	Punkt center = Game::getChunkCenter(x, y);
-	int offset = (int)ceil((float)maxDistant / CHUNK_SIZE);
-	for (int cx = -offset; cx <= offset; cx++)
-	{
-		for (int cy = -offset; cy <= offset; cy++)
-		{
-			NoiseWorm3D* worm = zWormOfChunk(center.x + cx * CHUNK_SIZE, center.y + cy * CHUNK_SIZE);
-			if (worm && worm->isChunkAffected(x, y))
-				affected.add(dynamic_cast<NoiseWorm3D*>(worm->getThis()));
-		}
-	}
-	return new WormCaveChunkGenerator(affected);
+    Framework::RCArray<NoiseWorm3D> affected;
+    Punkt center = Game::getChunkCenter(x, y);
+    int offset = (int)ceil((float)maxDistant / CHUNK_SIZE);
+    for (int cx = -offset; cx <= offset; cx++)
+    {
+        for (int cy = -offset; cy <= offset; cy++)
+        {
+            NoiseWorm3D* worm = zWormOfChunk(
+                center.x + cx * CHUNK_SIZE, center.y + cy * CHUNK_SIZE);
+            if (worm && worm->isChunkAffected(x, y))
+                affected.add(dynamic_cast<NoiseWorm3D*>(worm->getThis()));
+        }
+    }
+    return new WormCaveChunkGenerator(affected);
 }

+ 36 - 28
FactoryCraft/WormCaveGenerator.h

@@ -1,8 +1,8 @@
 #pragma once
 
-#include <Vec3.h>
 #include <Array.h>
 #include <Punkt.h>
+#include <Vec3.h>
 
 #include "CaveGenerator.h"
 #include "Noise.h"
@@ -10,50 +10,58 @@
 class NoiseWorm3D : public Framework::ReferenceCounter
 {
 private:
-	Framework::Punkt startChunk;
-	Framework::Punkt minAffected;
-	Framework::Punkt maxAffected;
+    Framework::Punkt startChunk;
+    Framework::Punkt minAffected;
+    Framework::Punkt maxAffected;
 
-	Framework::Array<Framework::Vec3<float>> keyPoints;
-	Framework::Array<float> size;
+    Framework::Array<Framework::Vec3<float>> keyPoints;
+    Framework::Array<float> size;
 
 public:
-	NoiseWorm3D(Noise* pitch, Noise* yaw, Noise* size, Framework::Vec3<int> startPos, int distant, int minRad, int maxRad);
-	Framework::Punkt getStartChunkCenter();
-	bool isChunkAffected(int x, int y);
-	bool isInside(int x, int y, int z);
+    NoiseWorm3D(Noise* pitch,
+        Noise* yaw,
+        Noise* size,
+        Framework::Vec3<int> startPos,
+        int distant,
+        int minRad,
+        int maxRad);
+    Framework::Punkt getStartChunkCenter();
+    bool isChunkAffected(int x, int y);
+    bool isInside(int x, int y, int z);
 };
 
-
 class WormCaveChunkGenerator : public CaveChunkGenerator
 {
 private:
-	Framework::RCArray<NoiseWorm3D> worms;
+    Framework::RCArray<NoiseWorm3D> worms;
 
 public:
-	WormCaveChunkGenerator(Framework::RCArray<NoiseWorm3D> worms);
-	bool isInCave(int x, int y, int z) override;
+    WormCaveChunkGenerator(Framework::RCArray<NoiseWorm3D> worms);
+    bool isInCave(int x, int y, int z) override;
 };
 
-
 class WormCaveGenerator : public CaveGenerator
 {
 private:
-	int maxDistant;
-	int minDistant;
-	int maxRadius;
-	int minRadius;
-	float cavePosibillity;
-	Noise* wormStartNoise;
-	Framework::RCArray<NoiseWorm3D> cache;
-	Framework::Array<Framework::Punkt > noWormChunks;
+    int maxDistant;
+    int minDistant;
+    int maxRadius;
+    int minRadius;
+    float cavePosibillity;
+    Noise* wormStartNoise;
+    Framework::RCArray<NoiseWorm3D> cache;
+    Framework::Array<Framework::Punkt> noWormChunks;
 
-	NoiseWorm3D* zWormOfChunk(int x, int y);
+    NoiseWorm3D* zWormOfChunk(int x, int y);
 
 public:
-	WormCaveGenerator(int minDistant, int maxDistant, int minRadius, int maxRadius, float cavePosibillityPerChunk);
-	~WormCaveGenerator();
-	void initialize(int seed) override;
+    WormCaveGenerator(int minDistant,
+        int maxDistant,
+        int minRadius,
+        int maxRadius,
+        float cavePosibillityPerChunk);
+    ~WormCaveGenerator();
+    void initialize(int seed) override;
 
-	CaveChunkGenerator* getGeneratorForChunk(int x, int y) override;
+    CaveChunkGenerator* getGeneratorForChunk(int x, int y) override;
 };