From 47d5395d24c6f209a758a689bff9a44f68d7397b Mon Sep 17 00:00:00 2001
From: STRWarrior
Date: Sun, 30 Mar 2014 13:44:28 +0200
Subject: Added a blockface parameter to the OnProjectileHitBlock hook.
---
src/Bindings/Plugin.h | 2 +-
src/Bindings/PluginLua.cpp | 4 ++--
src/Bindings/PluginLua.h | 2 +-
src/Bindings/PluginManager.cpp | 4 ++--
src/Bindings/PluginManager.h | 2 +-
src/Entities/ProjectileEntity.cpp | 2 +-
6 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/src/Bindings/Plugin.h b/src/Bindings/Plugin.h
index df0bd4dcc..4144bc734 100644
--- a/src/Bindings/Plugin.h
+++ b/src/Bindings/Plugin.h
@@ -90,7 +90,7 @@ public:
virtual bool OnPluginsLoaded (void) = 0;
virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0;
virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0;
- virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile) = 0;
+ virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face) = 0;
virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) = 0;
virtual bool OnSpawnedEntity (cWorld & a_World, cEntity & a_Entity) = 0;
virtual bool OnSpawnedMonster (cWorld & a_World, cMonster & a_Monster) = 0;
diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp
index 7e69e0f4b..9e989a9e1 100644
--- a/src/Bindings/PluginLua.cpp
+++ b/src/Bindings/PluginLua.cpp
@@ -1108,14 +1108,14 @@ bool cPluginLua::OnPreCrafting(const cPlayer * a_Player, const cCraftingGrid * a
-bool cPluginLua::OnProjectileHitBlock(cProjectileEntity & a_Projectile)
+bool cPluginLua::OnProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face)
{
cCSLock Lock(m_CriticalSection);
bool res = false;
cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_PROJECTILE_HIT_BLOCK];
for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr)
{
- m_LuaState.Call((int)(**itr), &a_Projectile, cLuaState::Return, res);
+ m_LuaState.Call((int)(**itr), &a_Projectile, a_Face, cLuaState::Return, res);
if (res)
{
return true;
diff --git a/src/Bindings/PluginLua.h b/src/Bindings/PluginLua.h
index 59542d23a..e89baaf53 100644
--- a/src/Bindings/PluginLua.h
+++ b/src/Bindings/PluginLua.h
@@ -113,7 +113,7 @@ public:
virtual bool OnPluginsLoaded (void) override;
virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override;
virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override;
- virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile) override;
+ virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face) override;
virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) override;
virtual bool OnSpawnedEntity (cWorld & a_World, cEntity & a_Entity) override;
virtual bool OnSpawnedMonster (cWorld & a_World, cMonster & a_Monster) override;
diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp
index 6a5356c0b..7116a5826 100644
--- a/src/Bindings/PluginManager.cpp
+++ b/src/Bindings/PluginManager.cpp
@@ -1154,7 +1154,7 @@ bool cPluginManager::CallHookPreCrafting(const cPlayer * a_Player, const cCrafti
-bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile)
+bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face)
{
HookMap::iterator Plugins = m_Hooks.find(HOOK_PROJECTILE_HIT_BLOCK);
if (Plugins == m_Hooks.end())
@@ -1163,7 +1163,7 @@ bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile
}
for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr)
{
- if ((*itr)->OnProjectileHitBlock(a_Projectile))
+ if ((*itr)->OnProjectileHitBlock(a_Projectile, a_Face))
{
return true;
}
diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h
index 512bc1351..89a2170df 100644
--- a/src/Bindings/PluginManager.h
+++ b/src/Bindings/PluginManager.h
@@ -206,7 +206,7 @@ public: // tolua_export
bool CallHookPluginsLoaded (void);
bool CallHookPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe);
bool CallHookPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe);
- bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile);
+ bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face);
bool CallHookProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity);
bool CallHookSpawnedEntity (cWorld & a_World, cEntity & a_Entity);
bool CallHookSpawnedMonster (cWorld & a_World, cMonster & a_Monster);
diff --git a/src/Entities/ProjectileEntity.cpp b/src/Entities/ProjectileEntity.cpp
index a9735a53c..37964d102 100644
--- a/src/Entities/ProjectileEntity.cpp
+++ b/src/Entities/ProjectileEntity.cpp
@@ -67,7 +67,7 @@ protected:
eBlockFace Face;
if (bb.CalcLineIntersection(Line1, Line2, LineCoeff, Face))
{
- if (cPluginManager::Get()->CallHookProjectileHitBlock(*m_Projectile))
+ if (cPluginManager::Get()->CallHookProjectileHitBlock(*m_Projectile, Face))
{
return false;
}
--
cgit v1.2.3
From 66f1bb7b677324dd59265b7b0776490caa661bcc Mon Sep 17 00:00:00 2001
From: STRWarrior
Date: Sun, 30 Mar 2014 14:04:44 +0200
Subject: Added a BlockHitPos parameter to OnProjectileHitBlock
---
src/Bindings/Plugin.h | 2 +-
src/Bindings/PluginLua.cpp | 4 ++--
src/Bindings/PluginLua.h | 2 +-
src/Bindings/PluginManager.cpp | 4 ++--
src/Bindings/PluginManager.h | 2 +-
src/Entities/ProjectileEntity.cpp | 4 ++--
6 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/src/Bindings/Plugin.h b/src/Bindings/Plugin.h
index 4144bc734..9c2b59609 100644
--- a/src/Bindings/Plugin.h
+++ b/src/Bindings/Plugin.h
@@ -90,7 +90,7 @@ public:
virtual bool OnPluginsLoaded (void) = 0;
virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0;
virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0;
- virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face) = 0;
+ virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos) = 0;
virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) = 0;
virtual bool OnSpawnedEntity (cWorld & a_World, cEntity & a_Entity) = 0;
virtual bool OnSpawnedMonster (cWorld & a_World, cMonster & a_Monster) = 0;
diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp
index 9e989a9e1..a89cfc82c 100644
--- a/src/Bindings/PluginLua.cpp
+++ b/src/Bindings/PluginLua.cpp
@@ -1108,14 +1108,14 @@ bool cPluginLua::OnPreCrafting(const cPlayer * a_Player, const cCraftingGrid * a
-bool cPluginLua::OnProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face)
+bool cPluginLua::OnProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos)
{
cCSLock Lock(m_CriticalSection);
bool res = false;
cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_PROJECTILE_HIT_BLOCK];
for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr)
{
- m_LuaState.Call((int)(**itr), &a_Projectile, a_Face, cLuaState::Return, res);
+ m_LuaState.Call((int)(**itr), &a_Projectile, a_Face, a_BlockHitPos, cLuaState::Return, res);
if (res)
{
return true;
diff --git a/src/Bindings/PluginLua.h b/src/Bindings/PluginLua.h
index e89baaf53..2e757f9dd 100644
--- a/src/Bindings/PluginLua.h
+++ b/src/Bindings/PluginLua.h
@@ -113,7 +113,7 @@ public:
virtual bool OnPluginsLoaded (void) override;
virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override;
virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override;
- virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face) override;
+ virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos) override;
virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) override;
virtual bool OnSpawnedEntity (cWorld & a_World, cEntity & a_Entity) override;
virtual bool OnSpawnedMonster (cWorld & a_World, cMonster & a_Monster) override;
diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp
index 7116a5826..0aa52e97e 100644
--- a/src/Bindings/PluginManager.cpp
+++ b/src/Bindings/PluginManager.cpp
@@ -1154,7 +1154,7 @@ bool cPluginManager::CallHookPreCrafting(const cPlayer * a_Player, const cCrafti
-bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face)
+bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos)
{
HookMap::iterator Plugins = m_Hooks.find(HOOK_PROJECTILE_HIT_BLOCK);
if (Plugins == m_Hooks.end())
@@ -1163,7 +1163,7 @@ bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile
}
for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr)
{
- if ((*itr)->OnProjectileHitBlock(a_Projectile, a_Face))
+ if ((*itr)->OnProjectileHitBlock(a_Projectile, a_Face, a_BlockHitPos))
{
return true;
}
diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h
index 89a2170df..5fdbaac1c 100644
--- a/src/Bindings/PluginManager.h
+++ b/src/Bindings/PluginManager.h
@@ -206,7 +206,7 @@ public: // tolua_export
bool CallHookPluginsLoaded (void);
bool CallHookPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe);
bool CallHookPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe);
- bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face);
+ bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos);
bool CallHookProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity);
bool CallHookSpawnedEntity (cWorld & a_World, cEntity & a_Entity);
bool CallHookSpawnedMonster (cWorld & a_World, cMonster & a_Monster);
diff --git a/src/Entities/ProjectileEntity.cpp b/src/Entities/ProjectileEntity.cpp
index 37964d102..72ebf5775 100644
--- a/src/Entities/ProjectileEntity.cpp
+++ b/src/Entities/ProjectileEntity.cpp
@@ -67,12 +67,12 @@ protected:
eBlockFace Face;
if (bb.CalcLineIntersection(Line1, Line2, LineCoeff, Face))
{
- if (cPluginManager::Get()->CallHookProjectileHitBlock(*m_Projectile, Face))
+ Vector3d Intersection = Line1 + m_Projectile->GetSpeed() * LineCoeff;
+ if (cPluginManager::Get()->CallHookProjectileHitBlock(*m_Projectile, Face, &Intersection))
{
return false;
}
- Vector3d Intersection = Line1 + m_Projectile->GetSpeed() * LineCoeff;
m_Projectile->OnHitSolidBlock(Intersection, Face);
return true;
}
--
cgit v1.2.3
From 36e1e57d038eda0c183f616f2b45d2ae4733e27c Mon Sep 17 00:00:00 2001
From: STRWarrior
Date: Sun, 30 Mar 2014 17:21:13 +0200
Subject: Using recommendations (I think)
---
src/Bindings/Plugin.h | 2 +-
src/Bindings/PluginLua.cpp | 2 +-
src/Bindings/PluginLua.h | 2 +-
src/Bindings/PluginManager.cpp | 2 +-
src/Bindings/PluginManager.h | 2 +-
src/Entities/ProjectileEntity.cpp | 3 ++-
6 files changed, 7 insertions(+), 6 deletions(-)
diff --git a/src/Bindings/Plugin.h b/src/Bindings/Plugin.h
index 9c2b59609..a6f91382c 100644
--- a/src/Bindings/Plugin.h
+++ b/src/Bindings/Plugin.h
@@ -90,7 +90,7 @@ public:
virtual bool OnPluginsLoaded (void) = 0;
virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0;
virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0;
- virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos) = 0;
+ virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, const Vector3i * a_BlockHitPos) = 0;
virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) = 0;
virtual bool OnSpawnedEntity (cWorld & a_World, cEntity & a_Entity) = 0;
virtual bool OnSpawnedMonster (cWorld & a_World, cMonster & a_Monster) = 0;
diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp
index a89cfc82c..97f78351b 100644
--- a/src/Bindings/PluginLua.cpp
+++ b/src/Bindings/PluginLua.cpp
@@ -1108,7 +1108,7 @@ bool cPluginLua::OnPreCrafting(const cPlayer * a_Player, const cCraftingGrid * a
-bool cPluginLua::OnProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos)
+bool cPluginLua::OnProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face, const Vector3i * a_BlockHitPos)
{
cCSLock Lock(m_CriticalSection);
bool res = false;
diff --git a/src/Bindings/PluginLua.h b/src/Bindings/PluginLua.h
index 2e757f9dd..627aa3cc8 100644
--- a/src/Bindings/PluginLua.h
+++ b/src/Bindings/PluginLua.h
@@ -113,7 +113,7 @@ public:
virtual bool OnPluginsLoaded (void) override;
virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override;
virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override;
- virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos) override;
+ virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, const Vector3i * a_BlockHitPos) override;
virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) override;
virtual bool OnSpawnedEntity (cWorld & a_World, cEntity & a_Entity) override;
virtual bool OnSpawnedMonster (cWorld & a_World, cMonster & a_Monster) override;
diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp
index 0aa52e97e..a5c904a77 100644
--- a/src/Bindings/PluginManager.cpp
+++ b/src/Bindings/PluginManager.cpp
@@ -1154,7 +1154,7 @@ bool cPluginManager::CallHookPreCrafting(const cPlayer * a_Player, const cCrafti
-bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos)
+bool cPluginManager::CallHookProjectileHitBlock(cProjectileEntity & a_Projectile, eBlockFace a_Face, const Vector3i * a_BlockHitPos)
{
HookMap::iterator Plugins = m_Hooks.find(HOOK_PROJECTILE_HIT_BLOCK);
if (Plugins == m_Hooks.end())
diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h
index 5fdbaac1c..35755459a 100644
--- a/src/Bindings/PluginManager.h
+++ b/src/Bindings/PluginManager.h
@@ -206,7 +206,7 @@ public: // tolua_export
bool CallHookPluginsLoaded (void);
bool CallHookPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe);
bool CallHookPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe);
- bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, Vector3d * a_BlockHitPos);
+ bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile, eBlockFace a_Face, const Vector3i * a_BlockHitPos);
bool CallHookProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity);
bool CallHookSpawnedEntity (cWorld & a_World, cEntity & a_Entity);
bool CallHookSpawnedMonster (cWorld & a_World, cMonster & a_Monster);
diff --git a/src/Entities/ProjectileEntity.cpp b/src/Entities/ProjectileEntity.cpp
index 72ebf5775..7a869a957 100644
--- a/src/Entities/ProjectileEntity.cpp
+++ b/src/Entities/ProjectileEntity.cpp
@@ -68,7 +68,8 @@ protected:
if (bb.CalcLineIntersection(Line1, Line2, LineCoeff, Face))
{
Vector3d Intersection = Line1 + m_Projectile->GetSpeed() * LineCoeff;
- if (cPluginManager::Get()->CallHookProjectileHitBlock(*m_Projectile, Face, &Intersection))
+ const Vector3i BlockHitPos = Vector3i(Intersection);
+ if (cPluginManager::Get()->CallHookProjectileHitBlock(*m_Projectile, Face, &BlockHitPos))
{
return false;
}
--
cgit v1.2.3
From ca08a44c988ed7c295a43e9a0a9579b093e4abf4 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Thu, 3 Apr 2014 21:43:40 +0200
Subject: Grass now grows under up-side-down slabs
---
src/Blocks/BlockDirt.h | 15 ++++++++++++---
1 file changed, 12 insertions(+), 3 deletions(-)
diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h
index 91534c5e5..098494585 100644
--- a/src/Blocks/BlockDirt.h
+++ b/src/Blocks/BlockDirt.h
@@ -3,6 +3,7 @@
#include "BlockHandler.h"
#include "../MersenneTwister.h"
+#include "BlockSlab.h"
@@ -35,8 +36,10 @@ public:
// Grass becomes dirt if there is something on top of it:
if (a_RelY < cChunkDef::Height - 1)
{
- BLOCKTYPE Above = a_Chunk.GetBlock(a_RelX, a_RelY + 1, a_RelZ);
- if ((!g_BlockTransparent[Above] && !g_BlockOneHitDig[Above]) || IsBlockWater(Above))
+ BLOCKTYPE Above;
+ NIBBLETYPE AboveMeta;
+ a_Chunk.GetBlockTypeMeta(a_RelX, a_RelY + 1, a_RelZ, Above, AboveMeta);
+ if ((!g_BlockTransparent[Above] && !g_BlockOneHitDig[Above] && !(cBlockSlabHandler::IsAnySlabType(Above) && (AboveMeta & 0x8))) || IsBlockWater(Above))
{
a_Chunk.FastSetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_DIRT, E_META_DIRT_NORMAL);
return;
@@ -77,7 +80,7 @@ public:
BLOCKTYPE AboveDest;
NIBBLETYPE AboveMeta;
Chunk->GetBlockTypeMeta(BlockX, BlockY + 1, BlockZ, AboveDest, AboveMeta);
- if ((g_BlockOneHitDig[AboveDest] || g_BlockTransparent[AboveDest]) && !IsBlockWater(AboveDest))
+ if ((g_BlockOneHitDig[AboveDest] || g_BlockTransparent[AboveDest] || ((cBlockSlabHandler::IsAnySlabType(AboveDest)) && (AboveMeta & 0x8))) && !IsBlockWater(AboveDest))
{
Chunk->FastSetBlock(BlockX, BlockY, BlockZ, E_BLOCK_GRASS, 0);
}
@@ -85,6 +88,12 @@ public:
}
+ bool IsGrowAble(BLOCKTYPE a_Block, NIBBLETYPE a_Meta)
+ {
+
+ }
+
+
virtual const char * GetStepSound(void) override
{
return "step.gravel";
--
cgit v1.2.3
From cbb0352e51d1346b3ff7980f83696fedb0371a92 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Thu, 3 Apr 2014 21:44:23 +0200
Subject: Remove old function
---
src/Blocks/BlockDirt.h | 6 ------
1 file changed, 6 deletions(-)
diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h
index 098494585..2559f4839 100644
--- a/src/Blocks/BlockDirt.h
+++ b/src/Blocks/BlockDirt.h
@@ -88,12 +88,6 @@ public:
}
- bool IsGrowAble(BLOCKTYPE a_Block, NIBBLETYPE a_Meta)
- {
-
- }
-
-
virtual const char * GetStepSound(void) override
{
return "step.gravel";
--
cgit v1.2.3
From 039191499caec958d3d79773e4ed1c1c4e2916c2 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sun, 6 Apr 2014 21:41:01 +0200
Subject: Add CanChangeDirtToGrass function to Block Handlers.
---
src/BlockInfo.cpp | 10 ++++++++++
src/Blocks/BlockBed.h | 7 +++++++
src/Blocks/BlockDirt.h | 6 +++---
src/Blocks/BlockHandler.cpp | 9 +++++++++
src/Blocks/BlockHandler.h | 3 +++
src/Blocks/BlockSlab.h | 6 ++++++
src/Blocks/BlockStairs.h | 5 +++++
src/Items/ItemMinecart.h | 2 +-
src/Items/ItemPickaxe.h | 1 +
9 files changed, 45 insertions(+), 4 deletions(-)
diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp
index 6fb5aa5b3..64fce20bf 100644
--- a/src/BlockInfo.cpp
+++ b/src/BlockInfo.cpp
@@ -110,10 +110,13 @@ void cBlockInfo::Initialize(void)
// Transparent blocks
ms_Info[E_BLOCK_ACTIVATOR_RAIL ].m_Transparent = true;
ms_Info[E_BLOCK_AIR ].m_Transparent = true;
+ ms_Info[E_BLOCK_ANVIL ].m_Transparent = true;
ms_Info[E_BLOCK_BIG_FLOWER ].m_Transparent = true;
ms_Info[E_BLOCK_BROWN_MUSHROOM ].m_Transparent = true;
+ ms_Info[E_BLOCK_CAKE ].m_Transparent = true;
ms_Info[E_BLOCK_CARROTS ].m_Transparent = true;
ms_Info[E_BLOCK_CHEST ].m_Transparent = true;
+ ms_Info[E_BLOCK_COBBLESTONE_WALL ].m_Transparent = true;
ms_Info[E_BLOCK_COBWEB ].m_Transparent = true;
ms_Info[E_BLOCK_CROPS ].m_Transparent = true;
ms_Info[E_BLOCK_DANDELION ].m_Transparent = true;
@@ -126,6 +129,7 @@ void cBlockInfo::Initialize(void)
ms_Info[E_BLOCK_FLOWER_POT ].m_Transparent = true;
ms_Info[E_BLOCK_GLASS ].m_Transparent = true;
ms_Info[E_BLOCK_GLASS_PANE ].m_Transparent = true;
+ ms_Info[E_BLOCK_HEAD ].m_Transparent = true;
ms_Info[E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE].m_Transparent = true;
ms_Info[E_BLOCK_ICE ].m_Transparent = true;
ms_Info[E_BLOCK_IRON_DOOR ].m_Transparent = true;
@@ -195,12 +199,14 @@ void cBlockInfo::Initialize(void)
ms_Info[E_BLOCK_BED ].m_PistonBreakable = true;
ms_Info[E_BLOCK_BIG_FLOWER ].m_PistonBreakable = true;
ms_Info[E_BLOCK_BROWN_MUSHROOM ].m_PistonBreakable = true;
+ ms_Info[E_BLOCK_CAKE ].m_PistonBreakable = true;
ms_Info[E_BLOCK_COBWEB ].m_PistonBreakable = true;
ms_Info[E_BLOCK_CROPS ].m_PistonBreakable = true;
ms_Info[E_BLOCK_DANDELION ].m_PistonBreakable = true;
ms_Info[E_BLOCK_DEAD_BUSH ].m_PistonBreakable = true;
ms_Info[E_BLOCK_FIRE ].m_PistonBreakable = true;
ms_Info[E_BLOCK_FLOWER ].m_PistonBreakable = true;
+ ms_Info[E_BLOCK_HEAD ].m_PistonBreakable = true;
ms_Info[E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE].m_PistonBreakable = true;
ms_Info[E_BLOCK_INACTIVE_COMPARATOR ].m_PistonBreakable = true;
ms_Info[E_BLOCK_IRON_DOOR ].m_PistonBreakable = true;
@@ -242,6 +248,7 @@ void cBlockInfo::Initialize(void)
ms_Info[E_BLOCK_CACTUS ].m_IsSnowable = false;
ms_Info[E_BLOCK_CHEST ].m_IsSnowable = false;
ms_Info[E_BLOCK_CROPS ].m_IsSnowable = false;
+ ms_Info[E_BLOCK_COBBLESTONE_WALL ].m_IsSnowable = false;
ms_Info[E_BLOCK_DANDELION ].m_IsSnowable = false;
ms_Info[E_BLOCK_FIRE ].m_IsSnowable = false;
ms_Info[E_BLOCK_FLOWER ].m_IsSnowable = false;
@@ -275,6 +282,7 @@ void cBlockInfo::Initialize(void)
ms_Info[E_BLOCK_POWERED_RAIL ].m_IsSnowable = false;
ms_Info[E_BLOCK_DETECTOR_RAIL ].m_IsSnowable = false;
ms_Info[E_BLOCK_COBWEB ].m_IsSnowable = false;
+ ms_Info[E_BLOCK_HEAD ].m_IsSnowable = false;
// Blocks that don't drop without a special tool:
@@ -282,6 +290,7 @@ void cBlockInfo::Initialize(void)
ms_Info[E_BLOCK_CAULDRON ].m_RequiresSpecialTool = true;
ms_Info[E_BLOCK_COAL_ORE ].m_RequiresSpecialTool = true;
ms_Info[E_BLOCK_COBBLESTONE ].m_RequiresSpecialTool = true;
+ ms_Info[E_BLOCK_COBBLESTONE_WALL ].m_RequiresSpecialTool = true;
ms_Info[E_BLOCK_COBBLESTONE_STAIRS ].m_RequiresSpecialTool = true;
ms_Info[E_BLOCK_COBWEB ].m_RequiresSpecialTool = true;
ms_Info[E_BLOCK_DIAMOND_BLOCK ].m_RequiresSpecialTool = true;
@@ -324,6 +333,7 @@ void cBlockInfo::Initialize(void)
ms_Info[E_BLOCK_AIR ].m_IsSolid = false;
ms_Info[E_BLOCK_BIG_FLOWER ].m_IsSolid = false;
ms_Info[E_BLOCK_BROWN_MUSHROOM ].m_IsSolid = false;
+ ms_Info[E_BLOCK_CAKE ].m_IsSolid = false;
ms_Info[E_BLOCK_CARROTS ].m_IsSolid = false;
ms_Info[E_BLOCK_COBWEB ].m_IsSolid = false;
ms_Info[E_BLOCK_CROPS ].m_IsSolid = false;
diff --git a/src/Blocks/BlockBed.h b/src/Blocks/BlockBed.h
index 92804aaac..cfd732d38 100644
--- a/src/Blocks/BlockBed.h
+++ b/src/Blocks/BlockBed.h
@@ -39,6 +39,13 @@ public:
}
+ virtual bool CanChangeDirtToGrass(BLOCKTYPE a_Block, NIBBLETYPE a_Meta) override
+ {
+ return true;
+ }
+
+
+
// Bed specific helper functions
static NIBBLETYPE RotationToMetaData(double a_Rotation)
{
diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h
index bde8e4201..84c8461b5 100644
--- a/src/Blocks/BlockDirt.h
+++ b/src/Blocks/BlockDirt.h
@@ -39,7 +39,7 @@ public:
BLOCKTYPE Above;
NIBBLETYPE AboveMeta;
a_Chunk.GetBlockTypeMeta(a_RelX, a_RelY + 1, a_RelZ, Above, AboveMeta);
- if ((!cBlockInfo::IsTransparent(Above) && !cBlockInfo::IsOneHitDig(Above) && !(cBlockSlabHandler::IsAnySlabType(Above) && (AboveMeta & 0x8))) || IsBlockWater(Above))
+ if ((IsBlockWater(Above)) || !cBlockInfo::GetHandler(Above)->CanChangeDirtToGrass(Above, AboveMeta))
{
a_Chunk.FastSetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_DIRT, E_META_DIRT_NORMAL);
return;
@@ -67,7 +67,7 @@ public:
cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(BlockX, BlockZ);
if (Chunk == NULL)
{
- // Unloaded chunk
+ // Unloaded chunks
continue;
}
Chunk->GetBlockTypeMeta(BlockX, BlockY, BlockZ, DestBlock, DestMeta);
@@ -80,7 +80,7 @@ public:
BLOCKTYPE AboveDest;
NIBBLETYPE AboveMeta;
Chunk->GetBlockTypeMeta(BlockX, BlockY + 1, BlockZ, AboveDest, AboveMeta);
- if ((cBlockInfo::IsOneHitDig(AboveDest) || cBlockInfo::IsTransparent(AboveDest) || ((cBlockSlabHandler::IsAnySlabType(AboveDest)) && (AboveMeta & 0x8))) && !IsBlockWater(AboveDest))
+ if ((!IsBlockWater(AboveDest)) && (cBlockInfo::GetHandler(AboveDest)->CanChangeDirtToGrass(AboveDest, AboveMeta)))
{
if (!cRoot::Get()->GetPluginManager()->CallHookBlockSpread((cWorld*) &a_WorldInterface, BlockX * cChunkDef::Width, BlockY, BlockZ * cChunkDef::Width, ssGrassSpread))
{
diff --git a/src/Blocks/BlockHandler.cpp b/src/Blocks/BlockHandler.cpp
index 7fd8c183c..13cb67041 100644
--- a/src/Blocks/BlockHandler.cpp
+++ b/src/Blocks/BlockHandler.cpp
@@ -396,6 +396,15 @@ bool cBlockHandler::CanBeAt(cChunkInterface & a_ChunkInterface, int a_BlockX, in
+bool cBlockHandler::CanChangeDirtToGrass(BLOCKTYPE a_Block, NIBBLETYPE a_Meta)
+{
+ return ((cBlockInfo::IsTransparent(a_Block)) || (cBlockInfo::IsOneHitDig(a_Block)));
+}
+
+
+
+
+
bool cBlockHandler::IsUseable()
{
return false;
diff --git a/src/Blocks/BlockHandler.h b/src/Blocks/BlockHandler.h
index 3a3efb3cc..760db02fe 100644
--- a/src/Blocks/BlockHandler.h
+++ b/src/Blocks/BlockHandler.h
@@ -85,6 +85,9 @@ public:
/// Checks if the block can stay at the specified relative coords in the chunk
virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk);
+
+ /** Can spread the block under this block to grass? */
+ virtual bool CanChangeDirtToGrass(BLOCKTYPE a_Block, NIBBLETYPE a_Meta);
/** Checks if the block can be placed at this point.
Default: CanBeAt(...)
diff --git a/src/Blocks/BlockSlab.h b/src/Blocks/BlockSlab.h
index 76f5ed0e7..84580b062 100644
--- a/src/Blocks/BlockSlab.h
+++ b/src/Blocks/BlockSlab.h
@@ -97,6 +97,12 @@ public:
return "";
}
+
+ virtual bool CanChangeDirtToGrass(BLOCKTYPE a_Block, NIBBLETYPE a_Meta) override
+ {
+ return (a_Meta & 0x8);
+ }
+
/// Returns true if the specified blocktype is one of the slabs handled by this handler
static bool IsAnySlabType(BLOCKTYPE a_BlockType)
diff --git a/src/Blocks/BlockStairs.h b/src/Blocks/BlockStairs.h
index 09ff254a6..d6363fed9 100644
--- a/src/Blocks/BlockStairs.h
+++ b/src/Blocks/BlockStairs.h
@@ -77,6 +77,11 @@ public:
// Reset meta to 0
a_Pickups.push_back(cItem(m_BlockType, 1, 0));
}
+
+ virtual bool CanChangeDirtToGrass(BLOCKTYPE a_Block, NIBBLETYPE a_Meta) override
+ {
+ return true;
+ }
static NIBBLETYPE RotationToMetaData(double a_Rotation)
{
diff --git a/src/Items/ItemMinecart.h b/src/Items/ItemMinecart.h
index 25500aeb9..4e7d8fcff 100644
--- a/src/Items/ItemMinecart.h
+++ b/src/Items/ItemMinecart.h
@@ -78,7 +78,7 @@ public:
}
return true;
}
-
+
} ;
diff --git a/src/Items/ItemPickaxe.h b/src/Items/ItemPickaxe.h
index 2a8e40daa..4f8ef4eb1 100644
--- a/src/Items/ItemPickaxe.h
+++ b/src/Items/ItemPickaxe.h
@@ -76,6 +76,7 @@ public:
case E_BLOCK_STONE_PRESSURE_PLATE:
case E_BLOCK_BRICK:
case E_BLOCK_COBBLESTONE_STAIRS:
+ case E_BLOCK_COBBLESTONE_WALL:
case E_BLOCK_STONE_BRICK_STAIRS:
case E_BLOCK_NETHER_BRICK_STAIRS:
case E_BLOCK_CAULDRON:
--
cgit v1.2.3
From 4d7b250a509213fa7043b3670c6a393a3683fc69 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sun, 6 Apr 2014 21:45:55 +0200
Subject: Remove old import
---
src/Blocks/BlockDirt.h | 3 +--
src/Blocks/BlockHandler.h | 2 +-
2 files changed, 2 insertions(+), 3 deletions(-)
diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h
index 84c8461b5..0c550257e 100644
--- a/src/Blocks/BlockDirt.h
+++ b/src/Blocks/BlockDirt.h
@@ -2,7 +2,6 @@
#pragma once
#include "BlockHandler.h"
-#include "BlockSlab.h"
#include "../FastRandom.h"
@@ -67,7 +66,7 @@ public:
cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(BlockX, BlockZ);
if (Chunk == NULL)
{
- // Unloaded chunks
+ // Unloaded chunk
continue;
}
Chunk->GetBlockTypeMeta(BlockX, BlockY, BlockZ, DestBlock, DestMeta);
diff --git a/src/Blocks/BlockHandler.h b/src/Blocks/BlockHandler.h
index 760db02fe..4d6a2abb6 100644
--- a/src/Blocks/BlockHandler.h
+++ b/src/Blocks/BlockHandler.h
@@ -86,7 +86,7 @@ public:
/// Checks if the block can stay at the specified relative coords in the chunk
virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk);
- /** Can spread the block under this block to grass? */
+ /** Can change the block under this block to grass? */
virtual bool CanChangeDirtToGrass(BLOCKTYPE a_Block, NIBBLETYPE a_Meta);
/** Checks if the block can be placed at this point.
--
cgit v1.2.3
From 8bcb176a19297bca4f55f03a5244a507f8bf9174 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Sat, 12 Apr 2014 00:04:50 +0200
Subject: Lighting reads blocktypes only for blocks under heightmap.
This should theoretically speed it up, since less data is copied back and forth.
Also implemented a possibly more cache-friendly blocklight starter algorithm (PrepareBlockLight2()), is disabled by default, needs perf testing.
---
src/LightingThread.cpp | 92 ++++++++++++++++++++++++++++++++++++++++++--------
src/LightingThread.h | 11 ++++--
2 files changed, 87 insertions(+), 16 deletions(-)
diff --git a/src/LightingThread.cpp b/src/LightingThread.cpp
index 302473d71..f23f0c5f4 100644
--- a/src/LightingThread.cpp
+++ b/src/LightingThread.cpp
@@ -27,7 +27,8 @@ class cReader :
ROW * OutputRows = (ROW *)m_BlockTypes;
int InputIdx = 0;
int OutputIdx = m_ReadingChunkX + m_ReadingChunkZ * cChunkDef::Width * 3;
- for (int y = 0; y < cChunkDef::Height; y++)
+ int MaxHeight = std::min(cChunkDef::Height, m_MaxHeight + 16); // Need 16 blocks above the highest
+ for (int y = 0; y < MaxHeight; y++)
{
for (int z = 0; z < cChunkDef::Width; z++)
{
@@ -43,6 +44,7 @@ class cReader :
virtual void HeightMap(const cChunkDef::HeightMap * a_Heightmap) override
{
+ // Copy the entire heightmap, distribute it into the 3x3 chunk blob:
typedef struct {HEIGHTTYPE m_Row[16]; } ROW;
ROW * InputRows = (ROW *)a_Heightmap;
ROW * OutputRows = (ROW *)m_HeightMap;
@@ -53,13 +55,32 @@ class cReader :
OutputRows[OutputIdx] = InputRows[InputIdx++];
OutputIdx += 3;
} // for z
+
+ // Find the highest block in the entire chunk, use it as a base for m_MaxHeight:
+ HEIGHTTYPE MaxHeight = m_MaxHeight;
+ for (size_t i = 0; i < ARRAYCOUNT(*a_Heightmap); i++)
+ {
+ if ((*a_Heightmap)[i] > MaxHeight)
+ {
+ MaxHeight = (*a_Heightmap)[i];
+ }
+ }
+ m_MaxHeight = MaxHeight;
}
public:
int m_ReadingChunkX; // 0, 1 or 2; x-offset of the chunk we're reading from the BlockTypes start
int m_ReadingChunkZ; // 0, 1 or 2; z-offset of the chunk we're reading from the BlockTypes start
+ HEIGHTTYPE m_MaxHeight; // Maximum value in this chunk's heightmap
BLOCKTYPE * m_BlockTypes; // 3x3 chunks of block types, organized as a single XZY blob of data (instead of 3x3 XZY blobs)
HEIGHTTYPE * m_HeightMap; // 3x3 chunks of height map, organized as a single XZY blob of data (instead of 3x3 XZY blobs)
+
+ cReader(BLOCKTYPE * a_BlockTypes, HEIGHTTYPE * a_HeightMap) :
+ m_BlockTypes(a_BlockTypes),
+ m_HeightMap(a_HeightMap),
+ m_MaxHeight(0)
+ {
+ }
} ;
@@ -225,7 +246,7 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item)
// DEBUG: Save chunk data with highlighted seeds for visual inspection:
cFile f4;
if (
- f4.Open(Printf("Chunk_%d_%d_seeds.grab", a_Item.x, a_Item.z), cFile::fmWrite)
+ f4.Open(Printf("Chunk_%d_%d_seeds.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite)
)
{
for (int z = 0; z < cChunkDef::Width * 3; z++)
@@ -244,6 +265,7 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item)
f4.Write(Seeds, cChunkDef::Width * 3);
}
}
+ f4.Close();
}
//*/
@@ -253,9 +275,9 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item)
// DEBUG: Save XY slices of the chunk data and lighting for visual inspection:
cFile f1, f2, f3;
if (
- f1.Open(Printf("Chunk_%d_%d_data.grab", a_Item.x, a_Item.z), cFile::fmWrite) &&
- f2.Open(Printf("Chunk_%d_%d_sky.grab", a_Item.x, a_Item.z), cFile::fmWrite) &&
- f3.Open(Printf("Chunk_%d_%d_glow.grab", a_Item.x, a_Item.z), cFile::fmWrite)
+ f1.Open(Printf("Chunk_%d_%d_data.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite) &&
+ f2.Open(Printf("Chunk_%d_%d_sky.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite) &&
+ f3.Open(Printf("Chunk_%d_%d_glow.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite)
)
{
for (int z = 0; z < cChunkDef::Width * 3; z++)
@@ -274,6 +296,9 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item)
f3.Write(BlockLight, cChunkDef::Width * 3);
}
}
+ f1.Close();
+ f2.Close();
+ f3.Close();
}
//*/
@@ -293,11 +318,9 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item)
-bool cLightingThread::ReadChunks(int a_ChunkX, int a_ChunkZ)
+void cLightingThread::ReadChunks(int a_ChunkX, int a_ChunkZ)
{
- cReader Reader;
- Reader.m_BlockTypes = m_BlockTypes;
- Reader.m_HeightMap = m_HeightMap;
+ cReader Reader(m_BlockTypes, m_HeightMap);
for (int z = 0; z < 3; z++)
{
@@ -305,16 +328,13 @@ bool cLightingThread::ReadChunks(int a_ChunkX, int a_ChunkZ)
for (int x = 0; x < 3; x++)
{
Reader.m_ReadingChunkX = x;
- if (!m_World->GetChunkData(a_ChunkX + x - 1, a_ChunkZ + z - 1, Reader))
- {
- return false;
- }
+ VERIFY(m_World->GetChunkData(a_ChunkX + x - 1, a_ChunkZ + z - 1, Reader));
} // for z
} // for x
memset(m_BlockLight, 0, sizeof(m_BlockLight));
memset(m_SkyLight, 0, sizeof(m_SkyLight));
- return true;
+ m_MaxHeight = Reader.m_MaxHeight;
}
@@ -405,6 +425,50 @@ void cLightingThread::PrepareBlockLight(void)
+void cLightingThread::PrepareBlockLight2(void)
+{
+ // Clear seeds:
+ memset(m_IsSeed1, 0, sizeof(m_IsSeed1));
+ memset(m_IsSeed2, 0, sizeof(m_IsSeed2));
+ m_NumSeeds = 0;
+
+ // Add each emissive block into the seeds:
+ for (int y = 0; y < m_MaxHeight; y++)
+ {
+ int BaseY = y * BlocksPerYLayer; // Partial offset into m_BlockTypes for the Y coord
+ for (int z = 1; z < cChunkDef::Width * 3 - 1; z++)
+ {
+ int HBaseZ = z * cChunkDef::Width * 3; // Partial offset into m_Heightmap for the Z coord
+ int BaseZ = BaseY + HBaseZ; // Partial offset into m_BlockTypes for the Y and Z coords
+ for (int x = 1; x < cChunkDef::Width * 3 - 1; x++)
+ {
+ int idx = BaseZ + x;
+ if (y > m_HeightMap[HBaseZ + x])
+ {
+ // We're above the heightmap, ignore the block
+ continue;
+ }
+ if (cBlockInfo::GetLightValue(m_BlockTypes[idx]) == 0)
+ {
+ // Not a light-emissive block
+ continue;
+ }
+
+ // Add current block as a seed:
+ m_IsSeed1[idx] = true;
+ m_SeedIdx1[m_NumSeeds++] = idx;
+
+ // Light it up:
+ m_BlockLight[idx] = cBlockInfo::GetLightValue(m_BlockTypes[idx]);
+ }
+ }
+ }
+}
+
+
+
+
+
void cLightingThread::CalcLight(NIBBLETYPE * a_Light)
{
int NumSeeds2 = 0;
diff --git a/src/LightingThread.h b/src/LightingThread.h
index 770ae809f..a484fcbed 100644
--- a/src/LightingThread.h
+++ b/src/LightingThread.h
@@ -108,6 +108,9 @@ protected:
cEvent m_evtItemAdded; // Set when queue is appended, or to stop the thread
cEvent m_evtQueueEmpty; // Set when the queue gets empty
+ /** The highest block in the current 3x3 chunk data */
+ HEIGHTTYPE m_MaxHeight;
+
// Buffers for the 3x3 chunk data
// These buffers alone are 1.7 MiB in size, therefore they cannot be located on the stack safely - some architectures may have only 1 MiB for stack, or even less
@@ -136,8 +139,8 @@ protected:
/** Lights the entire chunk. If neighbor chunks don't exist, touches them and re-queues the chunk */
void LightChunk(cLightingChunkStay & a_Item);
- /** Prepares m_BlockTypes and m_HeightMap data; returns false if any of the chunks fail. Zeroes out the light arrays */
- bool ReadChunks(int a_ChunkX, int a_ChunkZ);
+ /** Prepares m_BlockTypes and m_HeightMap data; zeroes out the light arrays */
+ void ReadChunks(int a_ChunkX, int a_ChunkZ);
/** Uses m_HeightMap to initialize the m_SkyLight[] data; fills in seeds for the skylight */
void PrepareSkyLight(void);
@@ -145,6 +148,10 @@ protected:
/** Uses m_BlockTypes to initialize the m_BlockLight[] data; fills in seeds for the blocklight */
void PrepareBlockLight(void);
+ /** Same as PrepareBlockLight(), but uses a different traversal scheme; possibly better perf cache-wise.
+ To be compared in perf benchmarks. */
+ void PrepareBlockLight2(void);
+
/** Calculates light in the light array specified, using stored seeds */
void CalcLight(NIBBLETYPE * a_Light);
--
cgit v1.2.3
From 5bc5272a4ea5fc5685626627dff62a697415826b Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Sat, 12 Apr 2014 00:24:35 +0200
Subject: Fixed member construction order.
---
src/LightingThread.cpp | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/LightingThread.cpp b/src/LightingThread.cpp
index f23f0c5f4..f22e3933b 100644
--- a/src/LightingThread.cpp
+++ b/src/LightingThread.cpp
@@ -76,9 +76,9 @@ public:
HEIGHTTYPE * m_HeightMap; // 3x3 chunks of height map, organized as a single XZY blob of data (instead of 3x3 XZY blobs)
cReader(BLOCKTYPE * a_BlockTypes, HEIGHTTYPE * a_HeightMap) :
+ m_MaxHeight(0),
m_BlockTypes(a_BlockTypes),
- m_HeightMap(a_HeightMap),
- m_MaxHeight(0)
+ m_HeightMap(a_HeightMap)
{
}
} ;
--
cgit v1.2.3
From b0dd3dca3d4a8b794719f37fc34dcf6e56ecc5af Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sat, 12 Apr 2014 10:44:31 -0700
Subject: Fixed link errors
---
src/ChunkDef.cpp | 9 +++++++++
1 file changed, 9 insertions(+)
create mode 100644 src/ChunkDef.cpp
diff --git a/src/ChunkDef.cpp b/src/ChunkDef.cpp
new file mode 100644
index 000000000..367f66ccc
--- /dev/null
+++ b/src/ChunkDef.cpp
@@ -0,0 +1,9 @@
+
+#include "Globals.h"
+
+#include "ChunkDef.h"
+
+// It appears that failing to have this definition causes link errors as cChunkDef::Height is not
+// defined. It also appears that we can have the initalizer in the declaration so it can be inlined
+// if the declaration is in a class????
+const int cChunkDef::Height;
--
cgit v1.2.3
From f763242e5c5d8e6469685c4be95d3dc264ed6a67 Mon Sep 17 00:00:00 2001
From: Tiger Wang
Date: Wed, 23 Apr 2014 21:06:07 +0100
Subject: Small changes
---
src/CraftingRecipes.cpp | 4 ++--
src/Items/ItemLilypad.h | 14 ++++++--------
src/Items/ItemThrowable.h | 5 ++++-
src/World.h | 4 +++-
4 files changed, 15 insertions(+), 12 deletions(-)
diff --git a/src/CraftingRecipes.cpp b/src/CraftingRecipes.cpp
index 30e7a8733..157d634cd 100644
--- a/src/CraftingRecipes.cpp
+++ b/src/CraftingRecipes.cpp
@@ -800,7 +800,7 @@ void cCraftingRecipes::HandleFireworks(const cItem * a_CraftingGrid, cCraftingRe
break;
}
case E_ITEM_PAPER: break;
- default: LOG("Unexpected item in firework rocket a_Recipe, was the crafting file fireworks section changed?"); break;
+ default: LOG("Unexpected item in firework rocket recipe, was the crafting file's fireworks section changed?"); break;
}
}
}
@@ -835,7 +835,7 @@ void cCraftingRecipes::HandleFireworks(const cItem * a_CraftingGrid, cCraftingRe
case E_ITEM_GOLD_NUGGET: a_Recipe->m_Result.m_FireworkItem.m_Type = 2; break;
case E_ITEM_FEATHER: a_Recipe->m_Result.m_FireworkItem.m_Type = 4; break;
case E_ITEM_HEAD: a_Recipe->m_Result.m_FireworkItem.m_Type = 3; break;
- default: LOG("Unexpected item in firework star a_Recipe, was the crafting file fireworks section changed?"); break; // ermahgerd BARD ardmins
+ default: LOG("Unexpected item in firework star recipe, was the crafting file's fireworks section changed?"); break; // ermahgerd BARD ardmins
}
}
diff --git a/src/Items/ItemLilypad.h b/src/Items/ItemLilypad.h
index 8fc1d8543..bc650cdbd 100644
--- a/src/Items/ItemLilypad.h
+++ b/src/Items/ItemLilypad.h
@@ -47,9 +47,9 @@ public:
public cBlockTracer::cCallbacks
{
public:
- cCallbacks(cWorld * a_CBWorld) :
- m_HasHitFluid(false),
- m_World(a_CBWorld)
+
+ cCallbacks(void) :
+ m_HasHitFluid(false)
{
}
@@ -62,10 +62,9 @@ public:
return false;
}
AddFaceDirection(a_CBBlockX, a_CBBlockY, a_CBBlockZ, BLOCK_FACE_YP); // Always place pad at top of water block
- BLOCKTYPE Block = m_World->GetBlock(a_CBBlockX, a_CBBlockY, a_CBBlockZ);
if (
- !IsBlockWater(Block) &&
- cBlockInfo::FullyOccupiesVoxel(Block)
+ !IsBlockWater(a_CBBlockType) &&
+ cBlockInfo::FullyOccupiesVoxel(a_CBBlockType)
)
{
// Can't place lilypad on air/in another block!
@@ -80,11 +79,10 @@ public:
Vector3i m_Pos;
bool m_HasHitFluid;
- cWorld * m_World;
};
- cCallbacks Callbacks(a_World);
+ cCallbacks Callbacks;
cLineBlockTracer Tracer(*a_Player->GetWorld(), Callbacks);
Vector3d Start(a_Player->GetEyePosition() + a_Player->GetLookVector());
Vector3d End(a_Player->GetEyePosition() + a_Player->GetLookVector() * 5);
diff --git a/src/Items/ItemThrowable.h b/src/Items/ItemThrowable.h
index c6a4e714e..f90caf037 100644
--- a/src/Items/ItemThrowable.h
+++ b/src/Items/ItemThrowable.h
@@ -127,7 +127,10 @@ public:
return false;
}
- a_World->CreateProjectile(a_BlockX + 0.5, a_BlockY + 1, a_BlockZ + 0.5, m_ProjectileKind, a_Player, a_Player->GetEquippedItem());
+ if (a_World->CreateProjectile(a_BlockX + 0.5, a_BlockY + 1, a_BlockZ + 0.5, m_ProjectileKind, a_Player, a_Player->GetEquippedItem()) == -1)
+ {
+ return false;
+ }
if (!a_Player->IsGameModeCreative())
{
diff --git a/src/World.h b/src/World.h
index e08ef7f53..61733bca0 100644
--- a/src/World.h
+++ b/src/World.h
@@ -710,7 +710,9 @@ public:
virtual int SpawnMob(double a_PosX, double a_PosY, double a_PosZ, cMonster::eType a_MonsterType) override; // tolua_export
int SpawnMobFinalize(cMonster* a_Monster);
- /** Creates a projectile of the specified type. Returns the projectile's EntityID if successful, <0 otherwise */
+ /** Creates a projectile of the specified type. Returns the projectile's EntityID if successful, <0 otherwise
+ Item parameter used currently for Fireworks to correctly set entity metadata based on item metadata
+ */
int CreateProjectile(double a_PosX, double a_PosY, double a_PosZ, cProjectileEntity::eKind a_Kind, cEntity * a_Creator, const cItem a_Item, const Vector3d * a_Speed = NULL); // tolua_export
/** Returns a random number from the m_TickRand in range [0 .. a_Range]. To be used only in the tick thread! */
--
cgit v1.2.3
From 7f5cf417de5e83641e6aa0998cc9dc8b377346b6 Mon Sep 17 00:00:00 2001
From: Tiger Wang
Date: Wed, 23 Apr 2014 21:06:46 +0100
Subject: Some change to Entity.cpp
* Added comments to BroadcastMovementUpdate() and the collision tracer
---
src/Entities/Entity.cpp | 182 ++++++++++++++++++++++-----------------------
src/Entities/Entity.h | 11 +--
src/Entities/ExpOrb.cpp | 2 -
src/Entities/Player.cpp | 22 ++----
src/Entities/Player.h | 3 -
src/Entities/TNTEntity.cpp | 2 -
src/Tracer.cpp | 6 +-
7 files changed, 105 insertions(+), 123 deletions(-)
diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp
index 56ef36ef8..25ae4c7d8 100644
--- a/src/Entities/Entity.cpp
+++ b/src/Entities/Entity.cpp
@@ -10,7 +10,6 @@
#include "../Simulator/FluidSimulator.h"
#include "../Bindings/PluginManager.h"
#include "../Tracer.h"
-#include "Minecart.h"
#include "Player.h"
@@ -32,16 +31,10 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d
, m_Attachee(NULL)
, m_bDirtyHead(true)
, m_bDirtyOrientation(true)
- , m_bDirtyPosition(true)
- , m_bDirtySpeed(true)
- , m_bOnGround( false )
- , m_Gravity( -9.81f )
- , m_LastPosX( 0.0 )
- , m_LastPosY( 0.0 )
- , m_LastPosZ( 0.0 )
- , m_TimeLastTeleportPacket(0)
- , m_TimeLastMoveReltPacket(0)
- , m_TimeLastSpeedPacket(0)
+ , m_bHasSentNoSpeed(true)
+ , m_bOnGround(false)
+ , m_Gravity(-9.81f)
+ , m_LastPos(a_X, a_Y, a_Z)
, m_IsInitialized(false)
, m_EntityType(a_EntityType)
, m_World(NULL)
@@ -52,7 +45,7 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d
, m_TicksSinceLastVoidDamage(0)
, m_IsSwimming(false)
, m_IsSubmerged(false)
- , m_HeadYaw( 0.0 )
+ , m_HeadYaw(0.0)
, m_Rot(0.0, 0.0, 0.0)
, m_Pos(a_X, a_Y, a_Z)
, m_WaterSpeed(0, 0, 0)
@@ -725,30 +718,45 @@ void cEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk)
NextSpeed += m_WaterSpeed;
- if( NextSpeed.SqrLength() > 0.f )
+ if (NextSpeed.SqrLength() > 0.f)
{
- cTracer Tracer( GetWorld() );
- bool HasHit = Tracer.Trace( NextPos, NextSpeed, 2 );
- if (HasHit) // Oh noez! we hit something
+ cTracer Tracer(GetWorld());
+
+ bool HasHit = Tracer.Trace(NextPos, NextSpeed,
+ // Distance traced is an integer, so we round up from the distance we should go (Speed * Delta), else we will encounter collision detection failures
+ (int)(ceil((NextSpeed * a_Dt).SqrLength()) * 2)
+ );
+
+ if (HasHit)
{
- // Set to hit position
+ // Oh noez! We hit something: verify that the (hit position - current) was smaller or equal to the (position that we should travel without obstacles - current)
+ // This is because previously, we traced with a length that was rounded up (due to integer limitations), and in the case that something was hit, we don't want to overshoot our projected movement
if ((Tracer.RealHit - NextPos).SqrLength() <= (NextSpeed * a_Dt).SqrLength())
{
+ // Block hit was within our projected path
+ // Begin by stopping movement in the direction that we hit something. The Normal is the line perpendicular to a 2D face and in this case, stores what block face was hit through either -1 or 1.
+ // Por ejemplo: HitNormal.y = -1 : BLOCK_FACE_YM; HitNormal.y = 1 : BLOCK_FACE_YP
if (Tracer.HitNormal.x != 0.f) NextSpeed.x = 0.f;
if (Tracer.HitNormal.y != 0.f) NextSpeed.y = 0.f;
if (Tracer.HitNormal.z != 0.f) NextSpeed.z = 0.f;
- if (Tracer.HitNormal.y > 0) // means on ground
+ if (Tracer.HitNormal.y == 1) // Hit BLOCK_FACE_YP, we are on the ground
{
m_bOnGround = true;
}
- NextPos.Set(Tracer.RealHit.x,Tracer.RealHit.y,Tracer.RealHit.z);
- NextPos.x += Tracer.HitNormal.x * 0.3f;
- NextPos.y += Tracer.HitNormal.y * 0.05f; // Any larger produces entity vibration-upon-the-spot
- NextPos.z += Tracer.HitNormal.z * 0.3f;
+
+ // Now, set our position to the hit block (i.e. move part way along our intended trajectory)
+ NextPos.Set(Tracer.RealHit.x, Tracer.RealHit.y, Tracer.RealHit.z);
+ NextPos.x += Tracer.HitNormal.x * 0.1;
+ NextPos.y += Tracer.HitNormal.y * 0.05;
+ NextPos.z += Tracer.HitNormal.z * 0.1;
}
else
{
+ // We have hit a block but overshot our intended trajectory, move normally, safe in the warm cocoon of knowledge that we won't appear to teleport forwards on clients,
+ // and that this piece of software will come to be hailed as the epitome of performance and functionality in C++, never before seen, and of such a like that will never
+ // be henceforth seen again in the time of programmers and man alike
+ // &sensationalist>
NextPos += (NextSpeed * a_Dt);
}
}
@@ -934,8 +942,8 @@ void cEntity::SetSwimState(cChunk & a_Chunk)
{
// This sometimes happens on Linux machines
// Ref.: http://forum.mc-server.org/showthread.php?tid=1244
- LOGD("SetSwimState failure: RelX = %d, RelZ = %d, LastPos = {%.02f, %.02f}, Pos = %.02f, %.02f}",
- RelX, RelY, m_LastPosX, m_LastPosZ, GetPosX(), GetPosZ()
+ LOGD("SetSwimState failure: RelX = %d, RelZ = %d, Pos = %.02f, %.02f}",
+ RelX, RelY, GetPosX(), GetPosZ()
);
m_IsSwimming = false;
m_IsSubmerged = false;
@@ -1092,72 +1100,70 @@ void cEntity::TeleportToCoords(double a_PosX, double a_PosY, double a_PosZ)
void cEntity::BroadcastMovementUpdate(const cClientHandle * a_Exclude)
{
- // Send velocity packet every two ticks if: speed is not negligible or speed was set (as indicated by the DirtySpeed flag)
- if (((m_Speed.SqrLength() > 0.0004f) || m_bDirtySpeed) && ((m_World->GetWorldAge() - m_TimeLastSpeedPacket) >= 2))
+ // Process packet sending every two ticks
+ if (GetWorld()->GetWorldAge() % 2 == 0)
{
- m_World->BroadcastEntityVelocity(*this,a_Exclude);
- m_bDirtySpeed = false;
- m_TimeLastSpeedPacket = m_World->GetWorldAge();
- }
-
- // Have to process position related packets this every two ticks
- if (m_World->GetWorldAge() % 2 == 0)
- {
- int DiffX = (int) (floor(GetPosX() * 32.0) - floor(m_LastPosX * 32.0));
- int DiffY = (int) (floor(GetPosY() * 32.0) - floor(m_LastPosY * 32.0));
- int DiffZ = (int) (floor(GetPosZ() * 32.0) - floor(m_LastPosZ * 32.0));
- Int64 DiffTeleportPacket = m_World->GetWorldAge() - m_TimeLastTeleportPacket;
- // 4 blocks is max Relative So if the Diff is greater than 127 or. Send an absolute position every 20 seconds
- if (DiffTeleportPacket >= 400 ||
- ((DiffX > 127) || (DiffX < -128) ||
- (DiffY > 127) || (DiffY < -128) ||
- (DiffZ > 127) || (DiffZ < -128)))
+ double SpeedSqr = GetSpeed().SqrLength();
+ if (SpeedSqr == 0.0)
{
- //
- m_World->BroadcastTeleportEntity(*this,a_Exclude);
- m_TimeLastTeleportPacket = m_World->GetWorldAge();
- m_TimeLastMoveReltPacket = m_TimeLastTeleportPacket; //Must synchronize.
- m_LastPosX = GetPosX();
- m_LastPosY = GetPosY();
- m_LastPosZ = GetPosZ();
- m_bDirtyPosition = false;
- m_bDirtyOrientation = false;
+ // Speed is zero, send this to clients once only as well as an absolute position
+ if (!m_bHasSentNoSpeed)
+ {
+ m_World->BroadcastEntityVelocity(*this, a_Exclude);
+ m_World->BroadcastTeleportEntity(*this, a_Exclude);
+ m_bHasSentNoSpeed = true;
+ }
}
else
{
- Int64 DiffMoveRelPacket = m_World->GetWorldAge() - m_TimeLastMoveReltPacket;
- //if the change is big enough.
- if ((abs(DiffX) >= 4 || abs(DiffY) >= 4 || abs(DiffZ) >= 4 || DiffMoveRelPacket >= 60) && m_bDirtyPosition)
+ // Movin'
+ m_World->BroadcastEntityVelocity(*this, a_Exclude);
+ m_bHasSentNoSpeed = false;
+ }
+
+ // TODO: Pickups move disgracefully if relative move packets are sent as opposed to just velocity. Have a system to send relmove only when SetPosXXX() is called with a large difference in position
+ int DiffX = (int)(floor(GetPosX() * 32.0) - floor(m_LastPos.x * 32.0));
+ int DiffY = (int)(floor(GetPosY() * 32.0) - floor(m_LastPos.y * 32.0));
+ int DiffZ = (int)(floor(GetPosZ() * 32.0) - floor(m_LastPos.z * 32.0));
+
+ if ((abs(DiffX) >= 4) || (abs(DiffY) >= 4) || (abs(DiffZ) >= 4))
+ {
+ if ((abs(DiffX) <= 127) && (abs(DiffY) <= 127) && (abs(DiffZ) <= 127)) // Limitations of a Byte
{
+ // Difference within Byte limitations, use a relative move packet
if (m_bDirtyOrientation)
{
- m_World->BroadcastEntityRelMoveLook(*this, (char)DiffX, (char)DiffY, (char)DiffZ,a_Exclude);
+ m_World->BroadcastEntityRelMoveLook(*this, (char)DiffX, (char)DiffY, (char)DiffZ, a_Exclude);
m_bDirtyOrientation = false;
}
else
{
- m_World->BroadcastEntityRelMove(*this, (char)DiffX, (char)DiffY, (char)DiffZ,a_Exclude);
+ m_World->BroadcastEntityRelMove(*this, (char)DiffX, (char)DiffY, (char)DiffZ, a_Exclude);
}
- m_LastPosX = GetPosX();
- m_LastPosY = GetPosY();
- m_LastPosZ = GetPosZ();
- m_bDirtyPosition = false;
- m_TimeLastMoveReltPacket = m_World->GetWorldAge();
+ // Clients seem to store two positions, one for the velocity packet and one for the teleport/relmove packet
+ // The latter is only changed with a relmove/teleport, and m_LastPos stores this position
+ m_LastPos = GetPosition();
}
else
{
- if (m_bDirtyOrientation)
- {
- m_World->BroadcastEntityLook(*this,a_Exclude);
- m_bDirtyOrientation = false;
- }
- }
+ // Too big a movement, do a teleport
+ m_World->BroadcastTeleportEntity(*this, a_Exclude);
+ m_LastPos = GetPosition(); // See above
+ m_bDirtyOrientation = false;
+ }
}
+
if (m_bDirtyHead)
{
- m_World->BroadcastEntityHeadLook(*this,a_Exclude);
+ m_World->BroadcastEntityHeadLook(*this, a_Exclude);
m_bDirtyHead = false;
}
+ if (m_bDirtyOrientation)
+ {
+ // Send individual update in case above (sending with rel-move packet) wasn't done
+ GetWorld()->BroadcastEntityLook(*this, a_Exclude);
+ m_bDirtyOrientation = false;
+ }
}
}
@@ -1297,7 +1303,7 @@ void cEntity::SetRoll(double a_Roll)
void cEntity::SetSpeed(double a_SpeedX, double a_SpeedY, double a_SpeedZ)
{
m_Speed.Set(a_SpeedX, a_SpeedY, a_SpeedZ);
- m_bDirtySpeed = true;
+
WrapSpeed();
}
@@ -1307,7 +1313,7 @@ void cEntity::SetSpeed(double a_SpeedX, double a_SpeedY, double a_SpeedZ)
void cEntity::SetSpeedX(double a_SpeedX)
{
m_Speed.x = a_SpeedX;
- m_bDirtySpeed = true;
+
WrapSpeed();
}
@@ -1317,7 +1323,7 @@ void cEntity::SetSpeedX(double a_SpeedX)
void cEntity::SetSpeedY(double a_SpeedY)
{
m_Speed.y = a_SpeedY;
- m_bDirtySpeed = true;
+
WrapSpeed();
}
@@ -1327,7 +1333,7 @@ void cEntity::SetSpeedY(double a_SpeedY)
void cEntity::SetSpeedZ(double a_SpeedZ)
{
m_Speed.z = a_SpeedZ;
- m_bDirtySpeed = true;
+
WrapSpeed();
}
@@ -1347,7 +1353,7 @@ void cEntity::SetWidth(double a_Width)
void cEntity::AddPosX(double a_AddPosX)
{
m_Pos.x += a_AddPosX;
- m_bDirtyPosition = true;
+
}
@@ -1356,7 +1362,7 @@ void cEntity::AddPosX(double a_AddPosX)
void cEntity::AddPosY(double a_AddPosY)
{
m_Pos.y += a_AddPosY;
- m_bDirtyPosition = true;
+
}
@@ -1365,7 +1371,7 @@ void cEntity::AddPosY(double a_AddPosY)
void cEntity::AddPosZ(double a_AddPosZ)
{
m_Pos.z += a_AddPosZ;
- m_bDirtyPosition = true;
+
}
@@ -1376,7 +1382,7 @@ void cEntity::AddPosition(double a_AddPosX, double a_AddPosY, double a_AddPosZ)
m_Pos.x += a_AddPosX;
m_Pos.y += a_AddPosY;
m_Pos.z += a_AddPosZ;
- m_bDirtyPosition = true;
+
}
@@ -1386,8 +1392,7 @@ void cEntity::AddSpeed(double a_AddSpeedX, double a_AddSpeedY, double a_AddSpeed
{
m_Speed.x += a_AddSpeedX;
m_Speed.y += a_AddSpeedY;
- m_Speed.z += a_AddSpeedZ;
- m_bDirtySpeed = true;
+ m_Speed.z += a_AddSpeedZ;
WrapSpeed();
}
@@ -1397,8 +1402,7 @@ void cEntity::AddSpeed(double a_AddSpeedX, double a_AddSpeedY, double a_AddSpeed
void cEntity::AddSpeedX(double a_AddSpeedX)
{
- m_Speed.x += a_AddSpeedX;
- m_bDirtySpeed = true;
+ m_Speed.x += a_AddSpeedX;
WrapSpeed();
}
@@ -1408,8 +1412,7 @@ void cEntity::AddSpeedX(double a_AddSpeedX)
void cEntity::AddSpeedY(double a_AddSpeedY)
{
- m_Speed.y += a_AddSpeedY;
- m_bDirtySpeed = true;
+ m_Speed.y += a_AddSpeedY;
WrapSpeed();
}
@@ -1419,8 +1422,7 @@ void cEntity::AddSpeedY(double a_AddSpeedY)
void cEntity::AddSpeedZ(double a_AddSpeedZ)
{
- m_Speed.z += a_AddSpeedZ;
- m_bDirtySpeed = true;
+ m_Speed.z += a_AddSpeedZ;
WrapSpeed();
}
@@ -1475,8 +1477,7 @@ Vector3d cEntity::GetLookVector(void) const
// Set position
void cEntity::SetPosition(double a_PosX, double a_PosY, double a_PosZ)
{
- m_Pos.Set(a_PosX, a_PosY, a_PosZ);
- m_bDirtyPosition = true;
+ m_Pos.Set(a_PosX, a_PosY, a_PosZ);
}
@@ -1485,8 +1486,7 @@ void cEntity::SetPosition(double a_PosX, double a_PosY, double a_PosZ)
void cEntity::SetPosX(double a_PosX)
{
- m_Pos.x = a_PosX;
- m_bDirtyPosition = true;
+ m_Pos.x = a_PosX;
}
@@ -1495,8 +1495,7 @@ void cEntity::SetPosX(double a_PosX)
void cEntity::SetPosY(double a_PosY)
{
- m_Pos.y = a_PosY;
- m_bDirtyPosition = true;
+ m_Pos.y = a_PosY;
}
@@ -1506,7 +1505,6 @@ void cEntity::SetPosY(double a_PosY)
void cEntity::SetPosZ(double a_PosZ)
{
m_Pos.z = a_PosZ;
- m_bDirtyPosition = true;
}
diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h
index 8f3899e2f..354e324c9 100644
--- a/src/Entities/Entity.h
+++ b/src/Entities/Entity.h
@@ -417,17 +417,14 @@ protected:
// Flags that signal that we haven't updated the clients with the latest.
bool m_bDirtyHead;
bool m_bDirtyOrientation;
- bool m_bDirtyPosition;
- bool m_bDirtySpeed;
+ bool m_bHasSentNoSpeed;
bool m_bOnGround;
float m_Gravity;
- // Last Position.
- double m_LastPosX, m_LastPosY, m_LastPosZ;
-
- // This variables keep track of the last time a packet was sent
- Int64 m_TimeLastTeleportPacket, m_TimeLastMoveReltPacket, m_TimeLastSpeedPacket; // In ticks
+ /** Last position sent to client via the Relative Move or Teleport packets (not Velocity)
+ Only updated if cEntity::BroadcastMovementUpdate() is called! */
+ Vector3d m_LastPos;
bool m_IsInitialized; // Is set to true when it's initialized, until it's destroyed (Initialize() till Destroy() )
diff --git a/src/Entities/ExpOrb.cpp b/src/Entities/ExpOrb.cpp
index 3623c869a..10f79aedc 100644
--- a/src/Entities/ExpOrb.cpp
+++ b/src/Entities/ExpOrb.cpp
@@ -34,8 +34,6 @@ cExpOrb::cExpOrb(const Vector3d & a_Pos, int a_Reward)
void cExpOrb::SpawnOn(cClientHandle & a_Client)
{
a_Client.SendExperienceOrb(*this);
- m_bDirtyPosition = false;
- m_bDirtySpeed = false;
m_bDirtyOrientation = false;
m_bDirtyHead = false;
}
diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp
index 2df0711b4..ba4353478 100644
--- a/src/Entities/Player.cpp
+++ b/src/Entities/Player.cpp
@@ -76,11 +76,8 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName)
cTimer t1;
m_LastPlayerListTime = t1.GetNowTime();
-
- m_TimeLastTeleportPacket = 0;
m_PlayerName = a_PlayerName;
- m_bDirtyPosition = true; // So chunks are streamed to player at spawn
if (!LoadFromDisk())
{
@@ -208,25 +205,22 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk)
m_BowCharge += 1;
}
- //handle updating experience
+ // Handle updating experience
if (m_bDirtyExperience)
{
SendExperience();
}
- if (m_bDirtyPosition)
+ if ((GetPosition() - m_LastPos).SqrLength() != 0.0) // Change in position from last tick?
{
// Apply food exhaustion from movement:
ApplyFoodExhaustionFromMovement();
cRoot::Get()->GetPluginManager()->CallHookPlayerMoving(*this);
- BroadcastMovementUpdate(m_ClientHandle);
m_ClientHandle->StreamChunks();
}
- else
- {
- BroadcastMovementUpdate(m_ClientHandle);
- }
+
+ BroadcastMovementUpdate(m_ClientHandle);
if (m_Health > 0) // make sure player is alive
{
@@ -1592,10 +1586,7 @@ bool cPlayer::LoadFromDisk()
SetPosX(JSON_PlayerPosition[(unsigned int)0].asDouble());
SetPosY(JSON_PlayerPosition[(unsigned int)1].asDouble());
SetPosZ(JSON_PlayerPosition[(unsigned int)2].asDouble());
- m_LastPosX = GetPosX();
- m_LastPosY = GetPosY();
- m_LastPosZ = GetPosZ();
- m_LastFoodPos = GetPosition();
+ m_LastPos = GetPosition();
}
Json::Value & JSON_PlayerRotation = root["rotation"];
@@ -1858,9 +1849,8 @@ void cPlayer::ApplyFoodExhaustionFromMovement()
}
// Calculate the distance travelled, update the last pos:
- Vector3d Movement(GetPosition() - m_LastFoodPos);
+ Vector3d Movement(GetPosition() - m_LastPos);
Movement.y = 0; // Only take XZ movement into account
- m_LastFoodPos = GetPosition();
// If riding anything, apply no food exhaustion
if (m_AttachedTo != NULL)
diff --git a/src/Entities/Player.h b/src/Entities/Player.h
index 05377a117..7a6b46ae9 100644
--- a/src/Entities/Player.h
+++ b/src/Entities/Player.h
@@ -423,9 +423,6 @@ protected:
/** Number of ticks remaining for the foodpoisoning effect; zero if not foodpoisoned */
int m_FoodPoisonedTicksRemaining;
- /** Last position that has been recorded for food-related processing: */
- Vector3d m_LastFoodPos;
-
float m_LastJumpHeight;
float m_LastGroundHeight;
bool m_bTouchGround;
diff --git a/src/Entities/TNTEntity.cpp b/src/Entities/TNTEntity.cpp
index 02f31f5bb..fd9a4e7ac 100644
--- a/src/Entities/TNTEntity.cpp
+++ b/src/Entities/TNTEntity.cpp
@@ -30,8 +30,6 @@ cTNTEntity::cTNTEntity(const Vector3d & a_Pos, int a_FuseTicks) :
void cTNTEntity::SpawnOn(cClientHandle & a_ClientHandle)
{
a_ClientHandle.SendSpawnObject(*this, 50, 1, 0, 0); // 50 means TNT
- m_bDirtyPosition = false;
- m_bDirtySpeed = false;
m_bDirtyOrientation = false;
m_bDirtyHead = false;
}
diff --git a/src/Tracer.cpp b/src/Tracer.cpp
index 6da6b2ad7..be42430a5 100644
--- a/src/Tracer.cpp
+++ b/src/Tracer.cpp
@@ -219,6 +219,10 @@ bool cTracer::Trace( const Vector3f & a_Start, const Vector3f & a_Direction, int
return false;
}
+ if ((pos.y < 0) || (pos.y >= cChunkDef::Height))
+ {
+ return false;
+ }
BLOCKTYPE BlockID = m_World->GetBlock(pos.x, pos.y, pos.z);
// Block is counted as a collision if we are not doing a line of sight and it is solid,
// or if the block is not air and not water. That way mobs can still see underwater.
@@ -226,7 +230,7 @@ bool cTracer::Trace( const Vector3f & a_Start, const Vector3f & a_Direction, int
{
BlockHitPosition = pos;
int Normal = GetHitNormal(a_Start, End, pos );
- if(Normal > 0)
+ if (Normal > 0)
{
HitNormal = m_NormalTable[Normal-1];
}
--
cgit v1.2.3
From c701adbd241ea84d6f64842e8015c1009a41d786 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 24 Apr 2014 21:34:45 +0200
Subject: Initial C++ SSL classes.
---
src/Globals.h | 6 ++--
src/PolarSSL++/CtrDrbgContext.cpp | 49 ++++++++++++++++++++++++++++++++
src/PolarSSL++/CtrDrbgContext.h | 60 +++++++++++++++++++++++++++++++++++++++
src/PolarSSL++/EntropyContext.cpp | 29 +++++++++++++++++++
src/PolarSSL++/EntropyContext.h | 31 ++++++++++++++++++++
src/PolarSSL++/X509Cert.cpp | 38 +++++++++++++++++++++++++
src/PolarSSL++/X509Cert.h | 37 ++++++++++++++++++++++++
7 files changed, 248 insertions(+), 2 deletions(-)
create mode 100644 src/PolarSSL++/CtrDrbgContext.cpp
create mode 100644 src/PolarSSL++/CtrDrbgContext.h
create mode 100644 src/PolarSSL++/EntropyContext.cpp
create mode 100644 src/PolarSSL++/EntropyContext.h
create mode 100644 src/PolarSSL++/X509Cert.cpp
create mode 100644 src/PolarSSL++/X509Cert.h
diff --git a/src/Globals.h b/src/Globals.h
index 26a0d87a9..3d7c9707c 100644
--- a/src/Globals.h
+++ b/src/Globals.h
@@ -264,9 +264,11 @@ template class SizeChecker;
// Same as assert but in all Self test builds
#ifdef SELF_TEST
-#define assert_test(x) ( !!(x) || (assert(!#x), exit(1), 0))
+ #define assert_test(x) ( !!(x) || (assert(!#x), exit(1), 0))
#endif
+#define SharedPtr std::tr1::shared_ptr
+
@@ -296,7 +298,7 @@ T Clamp(T a_Value, T a_Min, T a_Max)
#ifndef TOLUA_TEMPLATE_BIND
-#define TOLUA_TEMPLATE_BIND(x)
+ #define TOLUA_TEMPLATE_BIND(x)
#endif
diff --git a/src/PolarSSL++/CtrDrbgContext.cpp b/src/PolarSSL++/CtrDrbgContext.cpp
new file mode 100644
index 000000000..86e6d1ca5
--- /dev/null
+++ b/src/PolarSSL++/CtrDrbgContext.cpp
@@ -0,0 +1,49 @@
+
+// CtrDrbgContext.cpp
+
+// Implements the cCtrDrbgContext class representing a wrapper over CTR-DRBG implementation in PolarSSL
+
+#include "Globals.h"
+#include "CtrDrbgContext.h"
+#include "EntropyContext.h"
+
+
+
+
+
+cCtrDrbgContext::cCtrDrbgContext(void) :
+ m_EntropyContext(new cEntropyContext),
+ m_IsValid(false)
+{
+}
+
+
+
+
+
+cCtrDrbgContext::cCtrDrbgContext(const SharedPtr & a_EntropyContext) :
+ m_EntropyContext(a_EntropyContext),
+ m_IsValid(false)
+{
+}
+
+
+
+
+
+int cCtrDrbgContext::Initialize(const void * a_Custom, size_t a_CustomSize)
+{
+ if (m_IsValid)
+ {
+ // Already initialized
+ return 0;
+ }
+
+ int res = ctr_drbg_init(&m_CtrDrbg, entropy_func, &(m_EntropyContext->m_Entropy), (const unsigned char *)a_Custom, a_CustomSize);
+ m_IsValid = (res == 0);
+ return res;
+}
+
+
+
+
diff --git a/src/PolarSSL++/CtrDrbgContext.h b/src/PolarSSL++/CtrDrbgContext.h
new file mode 100644
index 000000000..987f4dd72
--- /dev/null
+++ b/src/PolarSSL++/CtrDrbgContext.h
@@ -0,0 +1,60 @@
+
+// CtrDrbgContext.h
+
+// Declares the cCtrDrbgContext class representing a wrapper over CTR-DRBG implementation in PolarSSL
+
+
+
+
+
+#pragma once
+
+#include "polarssl/ctr_drbg.h"
+
+
+
+
+
+// fwd: EntropyContext.h
+class cEntropyContext;
+
+
+
+
+
+class cCtrDrbgContext
+{
+ friend class cSslContext;
+
+public:
+ /** Constructs the context with a new entropy context. */
+ cCtrDrbgContext(void);
+
+ /** Constructs the context with the specified entropy context. */
+ cCtrDrbgContext(const SharedPtr & a_EntropyContext);
+
+ /** Initializes the context.
+ a_Custom is optional additional data to use for entropy, nullptr is accepted.
+ Returns 0 if successful, PolarSSL error code on failure. */
+ int Initialize(const void * a_Custom, size_t a_CustomSize);
+
+ /** Returns true if the object is valid (has been initialized properly) */
+ bool IsValid(void) const { return m_IsValid; }
+
+ /** Returns the internal context ptr. Only use in PolarSSL API calls. */
+ __declspec(deprecated) ctr_drbg_context * Get(void) { return &m_CtrDrbg; }
+
+protected:
+ /** The entropy source used for generating the random */
+ SharedPtr m_EntropyContext;
+
+ /** The random generator context */
+ ctr_drbg_context m_CtrDrbg;
+
+ /** Set to true if the object is valid (has been initialized properly) */
+ bool m_IsValid;
+} ;
+
+
+
+
diff --git a/src/PolarSSL++/EntropyContext.cpp b/src/PolarSSL++/EntropyContext.cpp
new file mode 100644
index 000000000..9c59b3f11
--- /dev/null
+++ b/src/PolarSSL++/EntropyContext.cpp
@@ -0,0 +1,29 @@
+
+// EntropyContext.cpp
+
+// Implements the cEntropyContext class representing a wrapper over entropy contexts in PolarSSL
+
+#include "Globals.h"
+#include "EntropyContext.h"
+
+
+
+
+
+cEntropyContext::cEntropyContext(void)
+{
+ entropy_init(&m_Entropy);
+}
+
+
+
+
+
+cEntropyContext::~cEntropyContext()
+{
+ entropy_free(&m_Entropy);
+}
+
+
+
+
diff --git a/src/PolarSSL++/EntropyContext.h b/src/PolarSSL++/EntropyContext.h
new file mode 100644
index 000000000..bc7fff066
--- /dev/null
+++ b/src/PolarSSL++/EntropyContext.h
@@ -0,0 +1,31 @@
+
+// EntropyContext.h
+
+// Declares the cEntropyContext class representing a wrapper over entropy contexts in PolarSSL
+
+
+
+
+
+#pragma once
+
+#include "polarssl/entropy.h"
+
+
+
+
+
+class cEntropyContext
+{
+ friend class cCtrDrbgContext;
+public:
+ cEntropyContext(void);
+ ~cEntropyContext();
+
+protected:
+ entropy_context m_Entropy;
+} ;
+
+
+
+
diff --git a/src/PolarSSL++/X509Cert.cpp b/src/PolarSSL++/X509Cert.cpp
new file mode 100644
index 000000000..ecf664855
--- /dev/null
+++ b/src/PolarSSL++/X509Cert.cpp
@@ -0,0 +1,38 @@
+
+// X509Cert.cpp
+
+// Implements the cX509Cert class representing a wrapper over X509 certs in PolarSSL
+
+#include "Globals.h"
+#include "X509Cert.h"
+
+
+
+
+
+cX509Cert::cX509Cert(void)
+{
+ x509_crt_init(&m_Cert);
+}
+
+
+
+
+
+cX509Cert::~cX509Cert()
+{
+ x509_crt_free(&m_Cert);
+}
+
+
+
+
+
+int cX509Cert::Parse(const void * a_CertContents, size_t a_Size)
+{
+ return x509_crt_parse(&m_Cert, (const unsigned char *)a_CertContents, a_Size);
+}
+
+
+
+
diff --git a/src/PolarSSL++/X509Cert.h b/src/PolarSSL++/X509Cert.h
new file mode 100644
index 000000000..b0450510d
--- /dev/null
+++ b/src/PolarSSL++/X509Cert.h
@@ -0,0 +1,37 @@
+
+// X509Cert.h
+
+// Declares the cX509Cert class representing a wrapper over X509 certs in PolarSSL
+
+
+
+
+
+#pragma once
+
+#include "polarssl/x509_crt.h"
+
+
+
+
+
+class cX509Cert
+{
+public:
+ cX509Cert(void);
+ ~cX509Cert(void);
+
+ /** Parses the certificate chain data into the context.
+ Returns 0 on succes, or PolarSSL error code on failure. */
+ int Parse(const void * a_CertContents, size_t a_Size);
+
+ /** Returns the internal cert ptr. Only use in PolarSSL API calls. */
+ __declspec(deprecated) x509_crt * Get(void) { return &m_Cert; }
+
+protected:
+ x509_crt m_Cert;
+} ;
+
+
+
+
--
cgit v1.2.3
From c4b4447a3ada43d4333bba329e89700527870332 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 24 Apr 2014 21:51:19 +0200
Subject: Authenticator uses some C++ SSL objects.
---
src/Protocol/Authenticator.cpp | 59 ++++++++++++++++++++++++++++--------------
1 file changed, 40 insertions(+), 19 deletions(-)
diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp
index e0fcc0007..ccc994e36 100644
--- a/src/Protocol/Authenticator.cpp
+++ b/src/Protocol/Authenticator.cpp
@@ -13,10 +13,12 @@
#include "polarssl/config.h"
#include "polarssl/net.h"
#include "polarssl/ssl.h"
-#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/error.h"
-#include "polarssl/certs.h"
+
+#include "PolarSSL++/EntropyContext.h"
+#include "PolarSSL++/CtrDrbgContext.h"
+#include "PolarSSL++/X509Cert.h"
#include
#include
@@ -150,31 +152,52 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
int ret, server_fd = -1;
unsigned char buf[1024];
- const char *pers = "cAuthenticator";
+ const char pers[] = "cAuthenticator";
- entropy_context entropy;
- ctr_drbg_context ctr_drbg;
+ cCtrDrbgContext CtrDrbg;
ssl_context ssl;
- x509_crt cacert;
+ cX509Cert CACert;
/* Initialize the RNG and the session data */
memset(&ssl, 0, sizeof(ssl_context));
- x509_crt_init(&cacert);
- entropy_init(&entropy);
- if ((ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const unsigned char *)pers, strlen(pers))) != 0)
+ if ((ret = CtrDrbg.Initialize(pers, sizeof(pers))) != 0)
{
- LOGWARNING("cAuthenticator: ctr_drbg_init returned %d", ret);
+ LOGWARNING("cAuthenticator: CtrDrbg.Initialize() returned %d", ret);
return false;
}
/* Initialize certificates */
- // TODO: Grab the sessionserver's root CA and any intermediates and hard-code them here, instead of test_ca_list
- ret = x509_crt_parse(&cacert, (const unsigned char *)test_ca_list, strlen(test_ca_list));
-
+ // This is the root cert for Starfield Technologies, the CA that signed sessionserver.mojang.com's cert:
+ static const char StarfieldCACert[] =
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\n"
+ "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\n"
+ "HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\n"
+ "ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\n"
+ "MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\n"
+ "b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\n"
+ "aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\n"
+ "Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n"
+ "ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\n"
+ "nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\n"
+ "HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N\n"
+ "Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN\n"
+ "dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0\n"
+ "HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO\n"
+ "BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G\n"
+ "CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU\n"
+ "sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3\n"
+ "4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg\n"
+ "8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K\n"
+ "pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1\n"
+ "mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0\n"
+ "-----END CERTIFICATE-----";
+ // Parse the Starfield CA and add it to "trusted root certs"
+ ret = CACert.Parse(StarfieldCACert, sizeof(StarfieldCACert) - 1);
if (ret < 0)
{
- LOGWARNING("cAuthenticator: x509_crt_parse returned -0x%x", -ret);
+ LOGWARNING("cAuthenticator: CACert.Parse returned -0x%x", -ret);
return false;
}
@@ -193,8 +216,8 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
}
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
- ssl_set_ca_chain(&ssl, &cacert, NULL, "PolarSSL Server 1");
- ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg);
+ ssl_set_ca_chain(&ssl, CACert.Get(), NULL, "PolarSSL Server 1");
+ ssl_set_rng(&ssl, ctr_drbg_random, CtrDrbg.Get());
ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
/* Handshake */
@@ -253,13 +276,11 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
}
Response.append((const char *)buf, ret);
- }
+ }
ssl_close_notify(&ssl);
- x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
- entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
// Check the HTTP status line:
--
cgit v1.2.3
From e33573ab59fefb76c1d01910f49428d808992b2b Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 24 Apr 2014 21:51:39 +0200
Subject: Attempted CMake inclusion for PolarSSL++.
---
src/CMakeLists.txt | 4 ++--
src/PolarSSL++/CMakeLists.txt | 17 +++++++++++++++++
2 files changed, 19 insertions(+), 2 deletions(-)
create mode 100644 src/PolarSSL++/CMakeLists.txt
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 30e9dbfd4..67bb299db 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -5,7 +5,7 @@ include_directories (SYSTEM "${PROJECT_SOURCE_DIR}/../lib/")
include_directories (SYSTEM "${PROJECT_SOURCE_DIR}/../lib/jsoncpp/include")
include_directories (SYSTEM "${PROJECT_SOURCE_DIR}/../lib/polarssl/include")
-set(FOLDERS OSSupport HTTPServer Items Blocks Protocol Generating)
+set(FOLDERS OSSupport HTTPServer Items Blocks Protocol Generating PolarSSL++)
set(FOLDERS ${FOLDERS} WorldStorage Mobs Entities Simulator UI BlockEntities Generating/Prefabs)
@@ -233,7 +233,7 @@ endif ()
if (NOT MSVC)
target_link_libraries(${EXECUTABLE} OSSupport HTTPServer Bindings Items Blocks)
target_link_libraries(${EXECUTABLE} Protocol Generating Generating_Prefabs WorldStorage)
- target_link_libraries(${EXECUTABLE} Mobs Entities Simulator UI BlockEntities)
+ target_link_libraries(${EXECUTABLE} Mobs Entities Simulator UI BlockEntities PolarSSL++)
endif ()
if (WIN32)
target_link_libraries(${EXECUTABLE} expat tolualib ws2_32.lib Psapi.lib)
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
new file mode 100644
index 000000000..4f954a7e5
--- /dev/null
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -0,0 +1,17 @@
+
+cmake_minimum_required (VERSION 2.6)
+project (MCServer)
+
+include_directories ("${PROJECT_SOURCE_DIR}/../")
+
+set(SOURCES
+ "EntropyContext.cpp"
+ "CtrDrbgContext.cpp"
+ "x509Cert.cpp"
+)
+
+add_library(PolarSSL++ ${SOURCES})
+
+if (UNIX)
+ target_link_libraries(PolarSSL++ polarssl)
+endif()
--
cgit v1.2.3
From c7694687f5d921a354fa87ea47c36570e705b9ff Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 24 Apr 2014 22:15:21 +0200
Subject: Fixed filename case.
---
src/PolarSSL++/CMakeLists.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
index 4f954a7e5..c5b747980 100644
--- a/src/PolarSSL++/CMakeLists.txt
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -7,7 +7,7 @@ include_directories ("${PROJECT_SOURCE_DIR}/../")
set(SOURCES
"EntropyContext.cpp"
"CtrDrbgContext.cpp"
- "x509Cert.cpp"
+ "X509Cert.cpp"
)
add_library(PolarSSL++ ${SOURCES})
--
cgit v1.2.3
From a02e8e8021147783b011d9a2f99ba3f1128ae8e8 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 24 Apr 2014 22:30:19 +0200
Subject: Declared a SharedPtr that hopefully resolves on all platforms.
MSVC2008 has it in std::tr1, all the others in std.
---
src/Globals.h | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/src/Globals.h b/src/Globals.h
index 3d7c9707c..2e7e0c9cf 100644
--- a/src/Globals.h
+++ b/src/Globals.h
@@ -267,7 +267,15 @@ template class SizeChecker;
#define assert_test(x) ( !!(x) || (assert(!#x), exit(1), 0))
#endif
-#define SharedPtr std::tr1::shared_ptr
+// Allow both Older versions of MSVC and newer versions of everything use a shared_ptr:
+// Note that we cannot typedef, because C++ doesn't allow (partial) templates to be typedeffed.
+#if (defined(_MSC_VER) && (_MSC_VER < 1600))
+ // MSVC before 2010 doesn't have std::shared_ptr, but has std::tr1::shared_ptr
+ #define SharedPtr std::tr1::shared_ptr
+#else
+ // All others have std::shared ptr
+ #define SharedPtr std::shared_ptr
+#endif
--
cgit v1.2.3
From 616fb15508187d317a7ca4195667e204faf3749c Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 24 Apr 2014 22:42:33 +0200
Subject: cByteBuffer uses void * instead of char * in data interface.
This makes it compatible with any pointer type.
---
src/ByteBuffer.cpp | 9 +++++----
src/ByteBuffer.h | 2 +-
2 files changed, 6 insertions(+), 5 deletions(-)
diff --git a/src/ByteBuffer.cpp b/src/ByteBuffer.cpp
index c634dc308..ad753118b 100644
--- a/src/ByteBuffer.cpp
+++ b/src/ByteBuffer.cpp
@@ -171,7 +171,7 @@ cByteBuffer::~cByteBuffer()
-bool cByteBuffer::Write(const char * a_Bytes, size_t a_Count)
+bool cByteBuffer::Write(const void * a_Bytes, size_t a_Count)
{
CHECK_THREAD;
CheckValid();
@@ -187,13 +187,14 @@ bool cByteBuffer::Write(const char * a_Bytes, size_t a_Count)
}
ASSERT(m_BufferSize >= m_WritePos);
size_t TillEnd = m_BufferSize - m_WritePos;
+ const char * Bytes = (const char *)a_Bytes;
if (TillEnd <= a_Count)
{
// Need to wrap around the ringbuffer end
if (TillEnd > 0)
{
- memcpy(m_Buffer + m_WritePos, a_Bytes, TillEnd);
- a_Bytes += TillEnd;
+ memcpy(m_Buffer + m_WritePos, Bytes, TillEnd);
+ Bytes += TillEnd;
a_Count -= TillEnd;
WrittenBytes = TillEnd;
}
@@ -203,7 +204,7 @@ bool cByteBuffer::Write(const char * a_Bytes, size_t a_Count)
// We're guaranteed that we'll fit in a single write op
if (a_Count > 0)
{
- memcpy(m_Buffer + m_WritePos, a_Bytes, a_Count);
+ memcpy(m_Buffer + m_WritePos, Bytes, a_Count);
m_WritePos += a_Count;
WrittenBytes += a_Count;
}
diff --git a/src/ByteBuffer.h b/src/ByteBuffer.h
index 44f43e17f..7656a5b13 100644
--- a/src/ByteBuffer.h
+++ b/src/ByteBuffer.h
@@ -31,7 +31,7 @@ public:
~cByteBuffer();
/// Writes the bytes specified to the ringbuffer. Returns true if successful, false if not
- bool Write(const char * a_Bytes, size_t a_Count);
+ bool Write(const void * a_Bytes, size_t a_Count);
/// Returns the number of bytes that can be successfully written to the ringbuffer
size_t GetFreeSpace(void) const;
--
cgit v1.2.3
From 4f49c978cf6b130ede105e9a858831806e51d118 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 24 Apr 2014 22:43:20 +0200
Subject: Replaced MSVC-specific decorators with our universal ones.
---
src/PolarSSL++/CtrDrbgContext.h | 2 +-
src/PolarSSL++/X509Cert.h | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/PolarSSL++/CtrDrbgContext.h b/src/PolarSSL++/CtrDrbgContext.h
index 987f4dd72..e9a1e17e2 100644
--- a/src/PolarSSL++/CtrDrbgContext.h
+++ b/src/PolarSSL++/CtrDrbgContext.h
@@ -42,7 +42,7 @@ public:
bool IsValid(void) const { return m_IsValid; }
/** Returns the internal context ptr. Only use in PolarSSL API calls. */
- __declspec(deprecated) ctr_drbg_context * Get(void) { return &m_CtrDrbg; }
+ OBSOLETE ctr_drbg_context * Get(void) { return &m_CtrDrbg; }
protected:
/** The entropy source used for generating the random */
diff --git a/src/PolarSSL++/X509Cert.h b/src/PolarSSL++/X509Cert.h
index b0450510d..5ef19c324 100644
--- a/src/PolarSSL++/X509Cert.h
+++ b/src/PolarSSL++/X509Cert.h
@@ -26,7 +26,7 @@ public:
int Parse(const void * a_CertContents, size_t a_Size);
/** Returns the internal cert ptr. Only use in PolarSSL API calls. */
- __declspec(deprecated) x509_crt * Get(void) { return &m_Cert; }
+ OBSOLETE x509_crt * Get(void) { return &m_Cert; }
protected:
x509_crt m_Cert;
--
cgit v1.2.3
From c949c1e7550fda892957bccaa81c53e9c2215935 Mon Sep 17 00:00:00 2001
From: Tiger Wang
Date: Thu, 24 Apr 2014 22:03:47 +0100
Subject: Implemented suggestions
---
src/Entities/Entity.cpp | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp
index 5c7c9c95a..f535faac7 100644
--- a/src/Entities/Entity.cpp
+++ b/src/Entities/Entity.cpp
@@ -1,3 +1,4 @@
+
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Entity.h"
@@ -722,11 +723,9 @@ void cEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk)
if (NextSpeed.SqrLength() > 0.f)
{
cTracer Tracer(GetWorld());
-
- bool HasHit = Tracer.Trace(NextPos, NextSpeed,
- // Distance traced is an integer, so we round up from the distance we should go (Speed * Delta), else we will encounter collision detection failures
- (int)(ceil((NextSpeed * a_Dt).SqrLength()) * 2)
- );
+ // Distance traced is an integer, so we round up from the distance we should go (Speed * Delta), else we will encounter collision detection failurse
+ int DistanceToTrace = (int)(ceil((NextSpeed * a_Dt).SqrLength()) * 2);
+ bool HasHit = Tracer.Trace(NextPos, NextSpeed, DistanceToTrace);
if (HasHit)
{
@@ -736,7 +735,7 @@ void cEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk)
{
// Block hit was within our projected path
// Begin by stopping movement in the direction that we hit something. The Normal is the line perpendicular to a 2D face and in this case, stores what block face was hit through either -1 or 1.
- // Por ejemplo: HitNormal.y = -1 : BLOCK_FACE_YM; HitNormal.y = 1 : BLOCK_FACE_YP
+ // For example: HitNormal.y = -1 : BLOCK_FACE_YM; HitNormal.y = 1 : BLOCK_FACE_YP
if (Tracer.HitNormal.x != 0.f) NextSpeed.x = 0.f;
if (Tracer.HitNormal.y != 0.f) NextSpeed.y = 0.f;
if (Tracer.HitNormal.z != 0.f) NextSpeed.z = 0.f;
@@ -954,7 +953,7 @@ void cEntity::SetSwimState(cChunk & a_Chunk)
// Ref.: http://forum.mc-server.org/showthread.php?tid=1244
LOGD("SetSwimState failure: RelX = %d, RelZ = %d, Pos = %.02f, %.02f}",
RelX, RelY, GetPosX(), GetPosZ()
- );
+ );
m_IsSwimming = false;
m_IsSubmerged = false;
return;
--
cgit v1.2.3
From f3dfc0349d7008efa50855c739d86918bdbf4a88 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Fri, 25 Apr 2014 09:48:52 +0200
Subject: Added shared_ptr handling for C++03 mode.
---
src/Globals.h | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/src/Globals.h b/src/Globals.h
index 2e7e0c9cf..93baf69ea 100644
--- a/src/Globals.h
+++ b/src/Globals.h
@@ -270,11 +270,15 @@ template class SizeChecker;
// Allow both Older versions of MSVC and newer versions of everything use a shared_ptr:
// Note that we cannot typedef, because C++ doesn't allow (partial) templates to be typedeffed.
#if (defined(_MSC_VER) && (_MSC_VER < 1600))
- // MSVC before 2010 doesn't have std::shared_ptr, but has std::tr1::shared_ptr
+ // MSVC before 2010 doesn't have std::shared_ptr, but has std::tr1::shared_ptr, defined in included earlier
#define SharedPtr std::tr1::shared_ptr
-#else
- // All others have std::shared ptr
+#elif (__cplusplus > 201103L)
+ // C++11 has std::shared_ptr in , included earlier
#define SharedPtr std::shared_ptr
+#else
+ // C++03 has std::tr1::shared_ptr in
+ #include
+ #define SharedPtr std::tr1::shared_ptr
#endif
--
cgit v1.2.3
From 6d167b370e409d77eb2b9e02bc95b80463670823 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Fri, 25 Apr 2014 16:05:24 +0200
Subject: Fixed C++11 check for SharedPtr.
---
src/Globals.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Globals.h b/src/Globals.h
index 93baf69ea..a09819ce9 100644
--- a/src/Globals.h
+++ b/src/Globals.h
@@ -272,7 +272,7 @@ template class SizeChecker;
#if (defined(_MSC_VER) && (_MSC_VER < 1600))
// MSVC before 2010 doesn't have std::shared_ptr, but has std::tr1::shared_ptr, defined in included earlier
#define SharedPtr std::tr1::shared_ptr
-#elif (__cplusplus > 201103L)
+#elif (__cplusplus >= 201103L)
// C++11 has std::shared_ptr in , included earlier
#define SharedPtr std::shared_ptr
#else
--
cgit v1.2.3
From 7e76f030aa2e6d39ac7fe9fb6a8a3db44bf3dd5f Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sat, 26 Apr 2014 00:32:30 +0200
Subject: Add entity invulnerable
---
src/Entities/Boat.cpp | 8 ++++++--
src/Entities/Boat.h | 2 +-
src/Entities/Entity.cpp | 21 ++++++++++++++++++---
src/Entities/Entity.h | 17 +++++++++++++----
src/Entities/Minecart.cpp | 14 +++++++++-----
src/Entities/Minecart.h | 2 +-
src/Entities/Player.cpp | 21 ++++++++++++---------
src/Entities/Player.h | 2 +-
src/Mobs/Creeper.cpp | 8 ++++++--
src/Mobs/Creeper.h | 2 +-
src/Mobs/Monster.cpp | 8 ++++++--
src/Mobs/Monster.h | 2 +-
src/Mobs/PassiveAggressiveMonster.cpp | 8 ++++++--
src/Mobs/PassiveAggressiveMonster.h | 2 +-
src/Mobs/PassiveMonster.cpp | 8 ++++++--
src/Mobs/PassiveMonster.h | 2 +-
src/Mobs/Villager.cpp | 9 +++++++--
src/Mobs/Villager.h | 2 +-
src/Mobs/Wither.cpp | 10 +++++-----
src/Mobs/Wither.h | 2 +-
src/Mobs/Wolf.cpp | 9 +++++++--
src/Mobs/Wolf.h | 2 +-
22 files changed, 111 insertions(+), 50 deletions(-)
diff --git a/src/Entities/Boat.cpp b/src/Entities/Boat.cpp
index 921252253..31bfe3dc3 100644
--- a/src/Entities/Boat.cpp
+++ b/src/Entities/Boat.cpp
@@ -33,9 +33,12 @@ void cBoat::SpawnOn(cClientHandle & a_ClientHandle)
-void cBoat::DoTakeDamage(TakeDamageInfo & TDI)
+bool cBoat::DoTakeDamage(TakeDamageInfo & TDI)
{
- super::DoTakeDamage(TDI);
+ if (!super::DoTakeDamage(TDI))
+ {
+ return false;
+ }
if (GetHealth() == 0)
{
@@ -50,6 +53,7 @@ void cBoat::DoTakeDamage(TakeDamageInfo & TDI)
}
Destroy(true);
}
+ return true;
}
diff --git a/src/Entities/Boat.h b/src/Entities/Boat.h
index c4c9afe7a..0fcfbd602 100644
--- a/src/Entities/Boat.h
+++ b/src/Entities/Boat.h
@@ -26,7 +26,7 @@ public:
// cEntity overrides:
virtual void SpawnOn(cClientHandle & a_ClientHandle) override;
virtual void OnRightClicked(cPlayer & a_Player) override;
- virtual void DoTakeDamage(TakeDamageInfo & TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & TDI) override;
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
virtual void HandleSpeedFromAttachee(float a_Forward, float a_Sideways) override;
diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp
index 6da6da54e..4403ab161 100644
--- a/src/Entities/Entity.cpp
+++ b/src/Entities/Entity.cpp
@@ -60,6 +60,7 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d
, m_Mass (0.001) // Default 1g
, m_Width(a_Width)
, m_Height(a_Height)
+ , m_InvulnerableTicks(20)
{
cCSLock Lock(m_CSCount);
m_EntityCount++;
@@ -294,17 +295,23 @@ void cEntity::SetPitchFromSpeed(void)
-void cEntity::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI)
{
if (cRoot::Get()->GetPluginManager()->CallHookTakeDamage(*this, a_TDI))
{
- return;
+ return false;
}
if (m_Health <= 0)
{
// Can't take damage if already dead
- return;
+ return false;
+ }
+
+ if (m_InvulnerableTicks > 0)
+ {
+ // Entity is invulnerable
+ return false;
}
if ((a_TDI.Attacker != NULL) && (a_TDI.Attacker->IsPlayer()))
@@ -333,10 +340,13 @@ void cEntity::DoTakeDamage(TakeDamageInfo & a_TDI)
m_World->BroadcastEntityStatus(*this, esGenericHurt);
+ m_InvulnerableTicks = 10;
+
if (m_Health <= 0)
{
KilledBy(a_TDI.Attacker);
}
+ return true;
}
@@ -511,6 +521,11 @@ void cEntity::SetHealth(int a_Health)
void cEntity::Tick(float a_Dt, cChunk & a_Chunk)
{
+ if (m_InvulnerableTicks > 0)
+ {
+ m_InvulnerableTicks--;
+ }
+
if (m_AttachedTo != NULL)
{
if ((m_Pos - m_AttachedTo->GetPosition()).Length() > 0.5)
diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h
index 86efc5a98..fc4186afc 100644
--- a/src/Entities/Entity.h
+++ b/src/Entities/Entity.h
@@ -262,8 +262,8 @@ public:
// tolua_end
- /// Makes this entity take damage specified in the a_TDI. The TDI is sent through plugins first, then applied
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI);
+ /** Makes this entity take damage specified in the a_TDI. The TDI is sent through plugins first, then applied. If it returns false, the entity hasn't become any damage. */
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI);
// tolua_begin
@@ -391,6 +391,12 @@ public:
virtual bool IsSubmerged(void) const{ return m_IsSubmerged; }
/** Gets remaining air of a monster */
int GetAirLevel(void) const { return m_AirLevel; }
+
+ /** Gets the invulnerable ticks from the entity */
+ int GetInvulnerableTicks(void) const { return m_InvulnerableTicks; }
+
+ /** Set the invulnerable ticks from the entity */
+ void SetInvulnerableTicks(int a_InvulnerableTicks) { m_InvulnerableTicks = a_InvulnerableTicks; }
// tolua_end
@@ -493,11 +499,14 @@ private:
// Measured in Kilograms (Kg)
double m_Mass;
- /// Width of the entity, in the XZ plane. Since entities are represented as cylinders, this is more of a diameter.
+ // Width of the entity, in the XZ plane. Since entities are represented as cylinders, this is more of a diameter.
double m_Width;
- /// Height of the entity (Y axis)
+ // Height of the entity (Y axis)
double m_Height;
+
+ // If a player hunt a entity, the entity become a invulnerable of 20 ticks
+ int m_InvulnerableTicks;
} ; // tolua_export
typedef std::list cEntityList;
diff --git a/src/Entities/Minecart.cpp b/src/Entities/Minecart.cpp
index db55eb058..7bd440d6d 100644
--- a/src/Entities/Minecart.cpp
+++ b/src/Entities/Minecart.cpp
@@ -902,18 +902,21 @@ bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta)
-void cMinecart::DoTakeDamage(TakeDamageInfo & TDI)
+bool cMinecart::DoTakeDamage(TakeDamageInfo & TDI)
{
if ((TDI.Attacker != NULL) && TDI.Attacker->IsPlayer() && ((cPlayer *)TDI.Attacker)->IsGameModeCreative())
{
Destroy();
TDI.FinalDamage = GetMaxHealth(); // Instant hit for creative
- super::DoTakeDamage(TDI);
- return; // No drops for creative
+ SetInvulnerableTicks(0);
+ return super::DoTakeDamage(TDI); // No drops for creative
}
m_LastDamage = TDI.FinalDamage;
- super::DoTakeDamage(TDI);
+ if (!super::DoTakeDamage(TDI))
+ {
+ return false;
+ }
m_World->BroadcastEntityMetadata(*this);
@@ -952,12 +955,13 @@ void cMinecart::DoTakeDamage(TakeDamageInfo & TDI)
default:
{
ASSERT(!"Unhandled minecart type when spawning pickup!");
- return;
+ return true;
}
}
m_World->SpawnItemPickups(Drops, GetPosX(), GetPosY(), GetPosZ());
}
+ return true;
}
diff --git a/src/Entities/Minecart.h b/src/Entities/Minecart.h
index ebdb576e0..1e60f091c 100644
--- a/src/Entities/Minecart.h
+++ b/src/Entities/Minecart.h
@@ -36,7 +36,7 @@ public:
// cEntity overrides:
virtual void SpawnOn(cClientHandle & a_ClientHandle) override;
virtual void HandlePhysics(float a_Dt, cChunk & a_Chunk) override;
- virtual void DoTakeDamage(TakeDamageInfo & TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & TDI) override;
virtual void Destroyed() override;
int LastDamage(void) const { return m_LastDamage; }
diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp
index fedb62527..08b7d3984 100644
--- a/src/Entities/Player.cpp
+++ b/src/Entities/Player.cpp
@@ -808,14 +808,14 @@ void cPlayer::SetFlying(bool a_IsFlying)
-void cPlayer::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cPlayer::DoTakeDamage(TakeDamageInfo & a_TDI)
{
if ((a_TDI.DamageType != dtInVoid) && (a_TDI.DamageType != dtPlugin))
{
if (IsGameModeCreative())
{
// No damage / health in creative mode if not void or plugin damage
- return;
+ return false;
}
}
@@ -828,17 +828,19 @@ void cPlayer::DoTakeDamage(TakeDamageInfo & a_TDI)
if (!m_Team->AllowsFriendlyFire())
{
// Friendly fire is disabled
- return;
+ return false;
}
}
}
- super::DoTakeDamage(a_TDI);
-
- // Any kind of damage adds food exhaustion
- AddFoodExhaustion(0.3f);
-
- SendHealth();
+ if (super::DoTakeDamage(a_TDI))
+ {
+ // Any kind of damage adds food exhaustion
+ AddFoodExhaustion(0.3f);
+ SendHealth();
+ return true;
+ }
+ return false;
}
@@ -897,6 +899,7 @@ void cPlayer::KilledBy(cEntity * a_Killer)
void cPlayer::Respawn(void)
{
m_Health = GetMaxHealth();
+ SetInvulnerableTicks(20);
// Reset food level:
m_FoodLevel = MAX_FOOD_LEVEL;
diff --git a/src/Entities/Player.h b/src/Entities/Player.h
index 78d661015..3029abfe0 100644
--- a/src/Entities/Player.h
+++ b/src/Entities/Player.h
@@ -498,7 +498,7 @@ protected:
virtual void Destroyed(void);
/** Filters out damage for creative mode/friendly fire */
- virtual void DoTakeDamage(TakeDamageInfo & TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & TDI) override;
/** Stops players from burning in creative mode */
virtual void TickBurning(cChunk & a_Chunk) override;
diff --git a/src/Mobs/Creeper.cpp b/src/Mobs/Creeper.cpp
index 3471b4cf1..9cf539427 100644
--- a/src/Mobs/Creeper.cpp
+++ b/src/Mobs/Creeper.cpp
@@ -75,9 +75,12 @@ void cCreeper::GetDrops(cItems & a_Drops, cEntity * a_Killer)
-void cCreeper::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cCreeper::DoTakeDamage(TakeDamageInfo & a_TDI)
{
- super::DoTakeDamage(a_TDI);
+ if (!super::DoTakeDamage(a_TDI))
+ {
+ return false;
+ }
if (a_TDI.DamageType == dtLightning)
{
@@ -85,6 +88,7 @@ void cCreeper::DoTakeDamage(TakeDamageInfo & a_TDI)
}
m_World->BroadcastEntityMetadata(*this);
+ return true;
}
diff --git a/src/Mobs/Creeper.h b/src/Mobs/Creeper.h
index 9abca369b..fc7db6716 100644
--- a/src/Mobs/Creeper.h
+++ b/src/Mobs/Creeper.h
@@ -18,7 +18,7 @@ public:
CLASS_PROTODEF(cCreeper);
virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override;
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override;
virtual void Attack(float a_Dt) override;
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
virtual void OnRightClicked(cPlayer & a_Player) override;
diff --git a/src/Mobs/Monster.cpp b/src/Mobs/Monster.cpp
index eb8480268..9e4c2ba25 100644
--- a/src/Mobs/Monster.cpp
+++ b/src/Mobs/Monster.cpp
@@ -457,9 +457,12 @@ int cMonster::FindFirstNonAirBlockPosition(double a_PosX, double a_PosZ)
-void cMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
{
- super::DoTakeDamage(a_TDI);
+ if (!super::DoTakeDamage(a_TDI))
+ {
+ return false;
+ }
if((m_SoundHurt != "") && (m_Health > 0))
m_World->BroadcastSoundEffect(m_SoundHurt, (int)(GetPosX() * 8), (int)(GetPosY() * 8), (int)(GetPosZ() * 8), 1.0f, 0.8f);
@@ -468,6 +471,7 @@ void cMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
{
m_Target = a_TDI.Attacker;
}
+ return true;
}
diff --git a/src/Mobs/Monster.h b/src/Mobs/Monster.h
index 70b3783fc..5a925dfc6 100644
--- a/src/Mobs/Monster.h
+++ b/src/Mobs/Monster.h
@@ -87,7 +87,7 @@ public:
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override;
virtual void KilledBy(cEntity * a_Killer) override;
diff --git a/src/Mobs/PassiveAggressiveMonster.cpp b/src/Mobs/PassiveAggressiveMonster.cpp
index 4b45f9a2a..24501b1ba 100644
--- a/src/Mobs/PassiveAggressiveMonster.cpp
+++ b/src/Mobs/PassiveAggressiveMonster.cpp
@@ -19,9 +19,12 @@ cPassiveAggressiveMonster::cPassiveAggressiveMonster(const AString & a_ConfigNam
-void cPassiveAggressiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cPassiveAggressiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
{
- super::DoTakeDamage(a_TDI);
+ if (!super::DoTakeDamage(a_TDI))
+ {
+ return false;
+ }
if ((m_Target != NULL) && (m_Target->IsPlayer()))
{
@@ -30,6 +33,7 @@ void cPassiveAggressiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
m_EMState = CHASING;
}
}
+ return true;
}
diff --git a/src/Mobs/PassiveAggressiveMonster.h b/src/Mobs/PassiveAggressiveMonster.h
index 2c5ef30b1..a0da50e8e 100644
--- a/src/Mobs/PassiveAggressiveMonster.h
+++ b/src/Mobs/PassiveAggressiveMonster.h
@@ -15,7 +15,7 @@ class cPassiveAggressiveMonster :
public:
cPassiveAggressiveMonster(const AString & a_ConfigName, eType a_MobType, const AString & a_SoundHurt, const AString & a_SoundDeath, double a_Width, double a_Height);
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override;
} ;
diff --git a/src/Mobs/PassiveMonster.cpp b/src/Mobs/PassiveMonster.cpp
index 904cd63cc..2861d7314 100644
--- a/src/Mobs/PassiveMonster.cpp
+++ b/src/Mobs/PassiveMonster.cpp
@@ -18,13 +18,17 @@ cPassiveMonster::cPassiveMonster(const AString & a_ConfigName, eType a_MobType,
-void cPassiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cPassiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
{
- super::DoTakeDamage(a_TDI);
+ if (!super::DoTakeDamage(a_TDI))
+ {
+ return false;
+ }
if ((a_TDI.Attacker != this) && (a_TDI.Attacker != NULL))
{
m_EMState = ESCAPING;
}
+ return true;
}
diff --git a/src/Mobs/PassiveMonster.h b/src/Mobs/PassiveMonster.h
index 0b3c155da..70574585a 100644
--- a/src/Mobs/PassiveMonster.h
+++ b/src/Mobs/PassiveMonster.h
@@ -18,7 +18,7 @@ public:
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
/// When hit by someone, run away
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override;
/** Returns the item that the animal of this class follows when a player holds it in hand
Return an empty item not to follow (default). */
virtual const cItem GetFollowedItem(void) const { return cItem(); }
diff --git a/src/Mobs/Villager.cpp b/src/Mobs/Villager.cpp
index d049acc1e..41283acf4 100644
--- a/src/Mobs/Villager.cpp
+++ b/src/Mobs/Villager.cpp
@@ -23,9 +23,13 @@ cVillager::cVillager(eVillagerType VillagerType) :
-void cVillager::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cVillager::DoTakeDamage(TakeDamageInfo & a_TDI)
{
- super::DoTakeDamage(a_TDI);
+ if (!super::DoTakeDamage(a_TDI))
+ {
+ return false;
+ }
+
if ((a_TDI.Attacker != NULL) && a_TDI.Attacker->IsPlayer())
{
if (m_World->GetTickRandomNumber(5) == 3)
@@ -33,6 +37,7 @@ void cVillager::DoTakeDamage(TakeDamageInfo & a_TDI)
m_World->BroadcastEntityStatus(*this, esVillagerAngry);
}
}
+ return true;
}
diff --git a/src/Mobs/Villager.h b/src/Mobs/Villager.h
index 5bba4d4ba..abde48407 100644
--- a/src/Mobs/Villager.h
+++ b/src/Mobs/Villager.h
@@ -30,7 +30,7 @@ public:
CLASS_PROTODEF(cVillager);
// cEntity overrides
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override;
virtual void Tick (float a_Dt, cChunk & a_Chunk) override;
// cVillager functions
diff --git a/src/Mobs/Wither.cpp b/src/Mobs/Wither.cpp
index 8f5d28b68..144f89658 100644
--- a/src/Mobs/Wither.cpp
+++ b/src/Mobs/Wither.cpp
@@ -40,24 +40,24 @@ bool cWither::Initialize(cWorld * a_World)
-void cWither::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cWither::DoTakeDamage(TakeDamageInfo & a_TDI)
{
if (a_TDI.DamageType == dtDrowning)
{
- return;
+ return false;
}
if (m_InvulnerableTicks > 0)
{
- return;
+ return false;
}
if (IsArmored() && (a_TDI.DamageType == dtRangedAttack))
{
- return;
+ return false;
}
- super::DoTakeDamage(a_TDI);
+ return super::DoTakeDamage(a_TDI);
}
diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h
index bc78bfaad..3b22ba4a5 100644
--- a/src/Mobs/Wither.h
+++ b/src/Mobs/Wither.h
@@ -27,7 +27,7 @@ public:
// cEntity overrides
virtual bool Initialize(cWorld * a_World) override;
virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override;
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override;
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
private:
diff --git a/src/Mobs/Wolf.cpp b/src/Mobs/Wolf.cpp
index f02b8a4fc..e6268abc7 100644
--- a/src/Mobs/Wolf.cpp
+++ b/src/Mobs/Wolf.cpp
@@ -25,14 +25,19 @@ cWolf::cWolf(void) :
-void cWolf::DoTakeDamage(TakeDamageInfo & a_TDI)
+bool cWolf::DoTakeDamage(TakeDamageInfo & a_TDI)
{
- super::DoTakeDamage(a_TDI);
+ if (super::DoTakeDamage(a_TDI))
+ {
+ return false;
+ }
+
if (!m_IsTame)
{
m_IsAngry = true;
}
m_World->BroadcastEntityMetadata(*this); // Broadcast health and possibly angry face
+ return true;
}
diff --git a/src/Mobs/Wolf.h b/src/Mobs/Wolf.h
index 5925373e1..fb8a7c995 100644
--- a/src/Mobs/Wolf.h
+++ b/src/Mobs/Wolf.h
@@ -18,7 +18,7 @@ public:
CLASS_PROTODEF(cWolf);
- virtual void DoTakeDamage(TakeDamageInfo & a_TDI) override;
+ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override;
virtual void OnRightClicked(cPlayer & a_Player) override;
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
virtual void TickFollowPlayer();
--
cgit v1.2.3
From ad1410f46e5deccc9f9a38e360fa65d6e33b82b4 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sat, 26 Apr 2014 00:37:09 +0200
Subject: Change m_InvulnerableTicks description
---
src/Entities/Entity.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h
index fc4186afc..ac9cf8b32 100644
--- a/src/Entities/Entity.h
+++ b/src/Entities/Entity.h
@@ -505,7 +505,7 @@ private:
// Height of the entity (Y axis)
double m_Height;
- // If a player hunt a entity, the entity become a invulnerable of 20 ticks
+ // If a player hit a entity, the entity become a invulnerable of 20 ticks
int m_InvulnerableTicks;
} ; // tolua_export
--
cgit v1.2.3
From ed1aa02d0c0efbffbaf46c8f17dc4c52c9e6f34d Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sat, 26 Apr 2014 00:37:40 +0200
Subject: Change m_InvulnerableTicks description again.
---
src/Entities/Entity.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h
index ac9cf8b32..ba74a38a9 100644
--- a/src/Entities/Entity.h
+++ b/src/Entities/Entity.h
@@ -505,7 +505,7 @@ private:
// Height of the entity (Y axis)
double m_Height;
- // If a player hit a entity, the entity become a invulnerable of 20 ticks
+ // If a player hit a entity, the entity become a invulnerable of 10 ticks
int m_InvulnerableTicks;
} ; // tolua_export
--
cgit v1.2.3
From e5683ede63572fe8b40703d449adf784b7d80ea7 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sat, 26 Apr 2014 00:41:00 +0200
Subject: Change m_InvulnerableTicks description again again :D
---
src/Entities/Entity.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h
index ba74a38a9..e76279c28 100644
--- a/src/Entities/Entity.h
+++ b/src/Entities/Entity.h
@@ -505,7 +505,7 @@ private:
// Height of the entity (Y axis)
double m_Height;
- // If a player hit a entity, the entity become a invulnerable of 10 ticks
+ // If a player hit a entity, the entity become a invulnerable of 10 ticks. While this ticks, a player can't hit this entity.
int m_InvulnerableTicks;
} ; // tolua_export
--
cgit v1.2.3
From 49f6819829b437f776ea08f50c92cc506ee9ddcb Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sat, 26 Apr 2014 16:44:15 +0200
Subject: Fixes
---
src/Entities/Entity.cpp | 2 +-
src/Entities/Entity.h | 23 +++++++++++++----------
src/Mobs/Wither.cpp | 10 +++++-----
src/Mobs/Wither.h | 6 +++---
src/Protocol/Protocol125.cpp | 2 +-
src/Protocol/Protocol17x.cpp | 2 +-
src/WorldStorage/NBTChunkSerializer.cpp | 2 +-
src/WorldStorage/WSSAnvil.cpp | 2 +-
8 files changed, 26 insertions(+), 23 deletions(-)
diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp
index 0af4eafde..db657909c 100644
--- a/src/Entities/Entity.cpp
+++ b/src/Entities/Entity.cpp
@@ -60,7 +60,7 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d
, m_Mass (0.001) // Default 1g
, m_Width(a_Width)
, m_Height(a_Height)
- , m_InvulnerableTicks(20)
+ , m_InvulnerableTicks(0)
{
cCSLock Lock(m_CSCount);
m_EntityCount++;
diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h
index e76279c28..26edf8dca 100644
--- a/src/Entities/Entity.h
+++ b/src/Entities/Entity.h
@@ -262,7 +262,9 @@ public:
// tolua_end
- /** Makes this entity take damage specified in the a_TDI. The TDI is sent through plugins first, then applied. If it returns false, the entity hasn't become any damage. */
+ /** Makes this entity take damage specified in the a_TDI.
+ The TDI is sent through plugins first, then applied.
+ If it returns false, the entity hasn't receive any damage. */
virtual bool DoTakeDamage(TakeDamageInfo & a_TDI);
// tolua_begin
@@ -481,31 +483,32 @@ protected:
int m_AirTickTimer;
private:
- // Measured in degrees, [-180, +180)
+ /** Measured in degrees, [-180, +180) */
double m_HeadYaw;
- // Measured in meter/second (m/s)
+ /** Measured in meter/second (m/s) */
Vector3d m_Speed;
- // Measured in degrees, [-180, +180)
+ /** Measured in degrees, [-180, +180) */
Vector3d m_Rot;
- /// Position of the entity's XZ center and Y bottom
+ /** Position of the entity's XZ center and Y bottom */
Vector3d m_Pos;
- // Measured in meter / second
+ /** Measured in meter / second */
Vector3d m_WaterSpeed;
- // Measured in Kilograms (Kg)
+ /** Measured in Kilograms (Kg) */
double m_Mass;
- // Width of the entity, in the XZ plane. Since entities are represented as cylinders, this is more of a diameter.
+ /** Width of the entity, in the XZ plane. Since entities are represented as cylinders, this is more of a diameter. */
double m_Width;
- // Height of the entity (Y axis)
+ /** Height of the entity (Y axis) */
double m_Height;
- // If a player hit a entity, the entity become a invulnerable of 10 ticks. While this ticks, a player can't hit this entity.
+ /** If a player hit a entity, the entity receive a invulnerable of 10 ticks.
+ While this ticks, a player can't hit this entity. */
int m_InvulnerableTicks;
} ; // tolua_export
diff --git a/src/Mobs/Wither.cpp b/src/Mobs/Wither.cpp
index 144f89658..5b6e895e1 100644
--- a/src/Mobs/Wither.cpp
+++ b/src/Mobs/Wither.cpp
@@ -10,7 +10,7 @@
cWither::cWither(void) :
super("Wither", mtWither, "mob.wither.hurt", "mob.wither.death", 0.9, 4.0),
- m_InvulnerableTicks(220)
+ m_WitherInvulnerableTicks(220)
{
SetMaxHealth(300);
}
@@ -47,7 +47,7 @@ bool cWither::DoTakeDamage(TakeDamageInfo & a_TDI)
return false;
}
- if (m_InvulnerableTicks > 0)
+ if (m_WitherInvulnerableTicks > 0)
{
return false;
}
@@ -68,16 +68,16 @@ void cWither::Tick(float a_Dt, cChunk & a_Chunk)
{
super::Tick(a_Dt, a_Chunk);
- if (m_InvulnerableTicks > 0)
+ if (m_WitherInvulnerableTicks > 0)
{
- unsigned int NewTicks = m_InvulnerableTicks - 1;
+ unsigned int NewTicks = m_WitherInvulnerableTicks - 1;
if (NewTicks == 0)
{
m_World->DoExplosionAt(7.0, GetPosX(), GetPosY(), GetPosZ(), false, esWitherBirth, this);
}
- m_InvulnerableTicks = NewTicks;
+ m_WitherInvulnerableTicks = NewTicks;
if ((NewTicks % 10) == 0)
{
diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h
index 3b22ba4a5..08b460009 100644
--- a/src/Mobs/Wither.h
+++ b/src/Mobs/Wither.h
@@ -17,9 +17,9 @@ public:
CLASS_PROTODEF(cWither);
- unsigned int GetNumInvulnerableTicks(void) const { return m_InvulnerableTicks; }
+ unsigned int GetWitherInvulnerableTicks(void) const { return m_WitherInvulnerableTicks; }
- void SetNumInvulnerableTicks(unsigned int a_Ticks) { m_InvulnerableTicks = a_Ticks; }
+ void SetWitherInvulnerableTicks(unsigned int a_Ticks) { m_WitherInvulnerableTicks = a_Ticks; }
/** Returns whether the wither is invulnerable to arrows. */
bool IsArmored(void) const;
@@ -33,7 +33,7 @@ public:
private:
/** The number of ticks of invulnerability left after being initially created. Zero once invulnerability has expired. */
- unsigned int m_InvulnerableTicks;
+ unsigned int m_WitherInvulnerableTicks;
} ;
diff --git a/src/Protocol/Protocol125.cpp b/src/Protocol/Protocol125.cpp
index 3282a827f..a23afb29a 100644
--- a/src/Protocol/Protocol125.cpp
+++ b/src/Protocol/Protocol125.cpp
@@ -2013,7 +2013,7 @@ void cProtocol125::WriteMobMetadata(const cMonster & a_Mob)
case cMonster::mtWither:
{
WriteByte(0x54); // Int at index 20
- WriteInt((Int32)((const cWither &)a_Mob).GetNumInvulnerableTicks());
+ WriteInt((Int32)((const cWither &)a_Mob).GetWitherInvulnerableTicks());
WriteByte(0x66); // Float at index 6
WriteFloat((float)(a_Mob.GetHealth()));
break;
diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp
index e57b551cb..80b161e3e 100644
--- a/src/Protocol/Protocol17x.cpp
+++ b/src/Protocol/Protocol17x.cpp
@@ -2820,7 +2820,7 @@ void cProtocol172::cPacketizer::WriteMobMetadata(const cMonster & a_Mob)
case cMonster::mtWither:
{
WriteByte(0x54); // Int at index 20
- WriteInt(((const cWither &)a_Mob).GetNumInvulnerableTicks());
+ WriteInt(((const cWither &)a_Mob).GetWitherInvulnerableTicks());
WriteByte(0x66); // Float at index 6
WriteFloat((float)(a_Mob.GetHealth()));
break;
diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp
index b6c14db9c..46c6b8e92 100644
--- a/src/WorldStorage/NBTChunkSerializer.cpp
+++ b/src/WorldStorage/NBTChunkSerializer.cpp
@@ -516,7 +516,7 @@ void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster)
}
case cMonster::mtWither:
{
- m_Writer.AddInt("Invul", ((const cWither *)a_Monster)->GetNumInvulnerableTicks());
+ m_Writer.AddInt("Invul", ((const cWither *)a_Monster)->GetWitherInvulnerableTicks());
break;
}
case cMonster::mtWolf:
diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp
index 66144dbd5..4532a925a 100644
--- a/src/WorldStorage/WSSAnvil.cpp
+++ b/src/WorldStorage/WSSAnvil.cpp
@@ -2272,7 +2272,7 @@ void cWSSAnvil::LoadWitherFromNBT(cEntityList & a_Entities, const cParsedNBT & a
int CurrLine = a_NBT.FindChildByName(a_TagIdx, "Invul");
if (CurrLine > 0)
{
- Monster->SetNumInvulnerableTicks(a_NBT.GetInt(CurrLine));
+ Monster->SetWitherInvulnerableTicks(a_NBT.GetInt(CurrLine));
}
a_Entities.push_back(Monster.release());
--
cgit v1.2.3
From 619592b5a0ab651e714d55932bc7909e4204cee9 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sat, 26 Apr 2014 17:37:35 +0200
Subject: Withers now use the new invulnerable.
---
src/Mobs/Wither.cpp | 29 +++++++++--------------------
src/Mobs/Wither.h | 7 +------
2 files changed, 10 insertions(+), 26 deletions(-)
diff --git a/src/Mobs/Wither.cpp b/src/Mobs/Wither.cpp
index 5b6e895e1..fe4dbb28b 100644
--- a/src/Mobs/Wither.cpp
+++ b/src/Mobs/Wither.cpp
@@ -10,9 +10,10 @@
cWither::cWither(void) :
super("Wither", mtWither, "mob.wither.hurt", "mob.wither.death", 0.9, 4.0),
- m_WitherInvulnerableTicks(220)
+ m_IsSpawnInvulnerable(true)
{
SetMaxHealth(300);
+ SetInvulnerableTicks(220);
}
@@ -47,11 +48,6 @@ bool cWither::DoTakeDamage(TakeDamageInfo & a_TDI)
return false;
}
- if (m_WitherInvulnerableTicks > 0)
- {
- return false;
- }
-
if (IsArmored() && (a_TDI.DamageType == dtRangedAttack))
{
return false;
@@ -68,21 +64,14 @@ void cWither::Tick(float a_Dt, cChunk & a_Chunk)
{
super::Tick(a_Dt, a_Chunk);
- if (m_WitherInvulnerableTicks > 0)
+ if (GetInvulnerableTicks() <= 0 && m_IsSpawnInvulnerable)
{
- unsigned int NewTicks = m_WitherInvulnerableTicks - 1;
-
- if (NewTicks == 0)
- {
- m_World->DoExplosionAt(7.0, GetPosX(), GetPosY(), GetPosZ(), false, esWitherBirth, this);
- }
-
- m_WitherInvulnerableTicks = NewTicks;
-
- if ((NewTicks % 10) == 0)
- {
- Heal(10);
- }
+ m_World->DoExplosionAt(7.0, GetPosX(), GetPosY(), GetPosZ(), false, esWitherBirth, this);
+ m_IsSpawnInvulnerable = false;
+ }
+ else if (((GetInvulnerableTicks() % 10) == 0) && (GetInvulnerableTicks() > 10))
+ {
+ Heal(10);
}
m_World->BroadcastEntityMetadata(*this);
diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h
index 08b460009..81c9df1b1 100644
--- a/src/Mobs/Wither.h
+++ b/src/Mobs/Wither.h
@@ -17,10 +17,6 @@ public:
CLASS_PROTODEF(cWither);
- unsigned int GetWitherInvulnerableTicks(void) const { return m_WitherInvulnerableTicks; }
-
- void SetWitherInvulnerableTicks(unsigned int a_Ticks) { m_WitherInvulnerableTicks = a_Ticks; }
-
/** Returns whether the wither is invulnerable to arrows. */
bool IsArmored(void) const;
@@ -32,8 +28,7 @@ public:
private:
- /** The number of ticks of invulnerability left after being initially created. Zero once invulnerability has expired. */
- unsigned int m_WitherInvulnerableTicks;
+ bool m_IsSpawnInvulnerable;
} ;
--
cgit v1.2.3
From d50f8f6f11f69e7e1e56be92fb2d72a5014a3e34 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Sat, 26 Apr 2014 17:47:25 +0200
Subject: Changed the old invulnerable methods from the wither to the new.
---
src/Mobs/Wither.h | 3 +++
src/Protocol/Protocol125.cpp | 9 ++++++++-
src/Protocol/Protocol17x.cpp | 9 ++++++++-
src/WorldStorage/NBTChunkSerializer.cpp | 9 ++++++++-
src/WorldStorage/WSSAnvil.cpp | 2 +-
5 files changed, 28 insertions(+), 4 deletions(-)
diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h
index 81c9df1b1..fbea331d3 100644
--- a/src/Mobs/Wither.h
+++ b/src/Mobs/Wither.h
@@ -19,6 +19,9 @@ public:
/** Returns whether the wither is invulnerable to arrows. */
bool IsArmored(void) const;
+
+ /** Use the wither the invulnerable from the spawn? */
+ bool IsSpawnInvulnerable(void) const { return m_IsSpawnInvulnerable; }
// cEntity overrides
virtual bool Initialize(cWorld * a_World) override;
diff --git a/src/Protocol/Protocol125.cpp b/src/Protocol/Protocol125.cpp
index a23afb29a..3951eb3e4 100644
--- a/src/Protocol/Protocol125.cpp
+++ b/src/Protocol/Protocol125.cpp
@@ -2013,7 +2013,14 @@ void cProtocol125::WriteMobMetadata(const cMonster & a_Mob)
case cMonster::mtWither:
{
WriteByte(0x54); // Int at index 20
- WriteInt((Int32)((const cWither &)a_Mob).GetWitherInvulnerableTicks());
+ if (((const cWither &)a_Mob).IsSpawnInvulnerable())
+ {
+ WriteInt((Int32)((const cWither &)a_Mob).GetInvulnerableTicks());
+ }
+ else
+ {
+ WriteInt((Int32)0);
+ }
WriteByte(0x66); // Float at index 6
WriteFloat((float)(a_Mob.GetHealth()));
break;
diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp
index 80b161e3e..311e770f9 100644
--- a/src/Protocol/Protocol17x.cpp
+++ b/src/Protocol/Protocol17x.cpp
@@ -2820,7 +2820,14 @@ void cProtocol172::cPacketizer::WriteMobMetadata(const cMonster & a_Mob)
case cMonster::mtWither:
{
WriteByte(0x54); // Int at index 20
- WriteInt(((const cWither &)a_Mob).GetWitherInvulnerableTicks());
+ if (((const cWither &)a_Mob).IsSpawnInvulnerable())
+ {
+ WriteInt(((const cWither &)a_Mob).GetInvulnerableTicks());
+ }
+ else
+ {
+ WriteInt(0);
+ }
WriteByte(0x66); // Float at index 6
WriteFloat((float)(a_Mob.GetHealth()));
break;
diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp
index 46c6b8e92..0c4a1a430 100644
--- a/src/WorldStorage/NBTChunkSerializer.cpp
+++ b/src/WorldStorage/NBTChunkSerializer.cpp
@@ -516,7 +516,14 @@ void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster)
}
case cMonster::mtWither:
{
- m_Writer.AddInt("Invul", ((const cWither *)a_Monster)->GetWitherInvulnerableTicks());
+ if (((const cWither *)a_Monster)->IsSpawnInvulnerable())
+ {
+ m_Writer.AddInt("Invul", ((const cWither *)a_Monster)->GetInvulnerableTicks());
+ }
+ else
+ {
+ m_Writer.AddInt("Invul", 0);
+ }
break;
}
case cMonster::mtWolf:
diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp
index 4532a925a..c21809270 100644
--- a/src/WorldStorage/WSSAnvil.cpp
+++ b/src/WorldStorage/WSSAnvil.cpp
@@ -2272,7 +2272,7 @@ void cWSSAnvil::LoadWitherFromNBT(cEntityList & a_Entities, const cParsedNBT & a
int CurrLine = a_NBT.FindChildByName(a_TagIdx, "Invul");
if (CurrLine > 0)
{
- Monster->SetWitherInvulnerableTicks(a_NBT.GetInt(CurrLine));
+ Monster->SetInvulnerableTicks(a_NBT.GetInt(CurrLine));
}
a_Entities.push_back(Monster.release());
--
cgit v1.2.3
From e40f9d6e5b93e840e3d67e79f5ba49da1fbb75f0 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sat, 26 Apr 2014 10:50:23 -0700
Subject: Implemented Chunk Sparsing with segments
---
src/BlockArea.cpp | 166 +++++++----------
src/BlockArea.h | 5 +-
src/Chunk.cpp | 186 ++++---------------
src/Chunk.h | 32 ++--
src/ChunkBuffer.cpp | 146 +++++++++++++++
src/ChunkBuffer.h | 310 ++++++++++++++++++++++++++++++++
src/ChunkDef.h | 100 +----------
src/ChunkMap.cpp | 16 +-
src/ChunkSender.h | 1 +
src/Entities/FallingBlock.cpp | 5 +-
src/LightingThread.cpp | 11 +-
src/MobProximityCounter.cpp | 3 +-
src/Simulator/FireSimulator.cpp | 10 +-
src/WorldStorage/NBTChunkSerializer.cpp | 3 +-
src/WorldStorage/NBTChunkSerializer.h | 4 +-
src/WorldStorage/WSSCompact.cpp | 10 +-
src/WorldStorage/WSSCompact.h | 3 +-
17 files changed, 610 insertions(+), 401 deletions(-)
create mode 100644 src/ChunkBuffer.cpp
create mode 100644 src/ChunkBuffer.h
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index 40cca8882..b4b519bc7 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -9,7 +9,7 @@
#include "OSSupport/GZipFile.h"
#include "Blocks/BlockHandler.h"
#include "Cuboid.h"
-
+#include "ChunkBuffer.h"
@@ -1909,116 +1909,88 @@ bool cBlockArea::cChunkReader::Coords(int a_ChunkX, int a_ChunkZ)
-void cBlockArea::cChunkReader::BlockTypes(const BLOCKTYPE * a_BlockTypes)
+void cBlockArea::cChunkReader::ChunkBuffer(const cChunkBuffer & a_BlockBuffer)
{
- if (m_Area.m_BlockTypes == NULL)
- {
- // Don't want BlockTypes
- return;
- }
-
- int SizeY = m_Area.m_Size.y;
- int MinY = m_Origin.y;
-
- // SizeX, SizeZ are the dmensions of the block data to copy from the current chunk (size of the geometric union)
- // OffX, OffZ are the offsets of the current chunk data from the area origin
- // BaseX, BaseZ are the offsets of the area data within the current chunk from the chunk borders
- int SizeX = cChunkDef::Width;
- int SizeZ = cChunkDef::Width;
- int OffX, OffZ;
- int BaseX, BaseZ;
- OffX = m_CurrentChunkX * cChunkDef::Width - m_Origin.x;
- if (OffX < 0)
- {
- BaseX = -OffX;
- SizeX += OffX; // SizeX is decreased, OffX is negative
- OffX = 0;
- }
- else
- {
- BaseX = 0;
- }
- OffZ = m_CurrentChunkZ * cChunkDef::Width - m_Origin.z;
- if (OffZ < 0)
- {
- BaseZ = -OffZ;
- SizeZ += OffZ; // SizeZ is decreased, OffZ is negative
- OffZ = 0;
- }
- else
- {
- BaseZ = 0;
- }
- // If the chunk extends beyond the area in the X or Z axis, cut off the Size:
- if ((m_CurrentChunkX + 1) * cChunkDef::Width > m_Origin.x + m_Area.m_Size.x)
- {
- SizeX -= (m_CurrentChunkX + 1) * cChunkDef::Width - (m_Origin.x + m_Area.m_Size.x);
- }
- if ((m_CurrentChunkZ + 1) * cChunkDef::Width > m_Origin.z + m_Area.m_Size.z)
- {
- SizeZ -= (m_CurrentChunkZ + 1) * cChunkDef::Width - (m_Origin.z + m_Area.m_Size.z);
- }
-
- for (int y = 0; y < SizeY; y++)
- {
- int ChunkY = MinY + y;
- int AreaY = y;
- for (int z = 0; z < SizeZ; z++)
+ { // BlockTypes
+ if (!(m_Area.m_BlockTypes == NULL))
{
- int ChunkZ = BaseZ + z;
- int AreaZ = OffZ + z;
- for (int x = 0; x < SizeX; x++)
+ int SizeY = m_Area.m_Size.y;
+ int MinY = m_Origin.y;
+
+ // SizeX, SizeZ are the dmensions of the block data to copy from the current chunk (size of the geometric union)
+ // OffX, OffZ are the offsets of the current chunk data from the area origin
+ // BaseX, BaseZ are the offsets of the area data within the current chunk from the chunk borders
+ int SizeX = cChunkDef::Width;
+ int SizeZ = cChunkDef::Width;
+ int OffX, OffZ;
+ int BaseX, BaseZ;
+ OffX = m_CurrentChunkX * cChunkDef::Width - m_Origin.x;
+ if (OffX < 0)
{
- int ChunkX = BaseX + x;
- int AreaX = OffX + x;
- m_Area.m_BlockTypes[m_Area.MakeIndex(AreaX, AreaY, AreaZ)] = cChunkDef::GetBlock(a_BlockTypes, ChunkX, ChunkY, ChunkZ);
- } // for x
- } // for z
- } // for y
-}
-
-
-
+ BaseX = -OffX;
+ SizeX += OffX; // SizeX is decreased, OffX is negative
+ OffX = 0;
+ }
+ else
+ {
+ BaseX = 0;
+ }
+ OffZ = m_CurrentChunkZ * cChunkDef::Width - m_Origin.z;
+ if (OffZ < 0)
+ {
+ BaseZ = -OffZ;
+ SizeZ += OffZ; // SizeZ is decreased, OffZ is negative
+ OffZ = 0;
+ }
+ else
+ {
+ BaseZ = 0;
+ }
+ // If the chunk extends beyond the area in the X or Z axis, cut off the Size:
+ if ((m_CurrentChunkX + 1) * cChunkDef::Width > m_Origin.x + m_Area.m_Size.x)
+ {
+ SizeX -= (m_CurrentChunkX + 1) * cChunkDef::Width - (m_Origin.x + m_Area.m_Size.x);
+ }
+ if ((m_CurrentChunkZ + 1) * cChunkDef::Width > m_Origin.z + m_Area.m_Size.z)
+ {
+ SizeZ -= (m_CurrentChunkZ + 1) * cChunkDef::Width - (m_Origin.z + m_Area.m_Size.z);
+ }
+ for (int y = 0; y < SizeY; y++)
+ {
+ int ChunkY = MinY + y;
+ int AreaY = y;
+ for (int z = 0; z < SizeZ; z++)
+ {
+ int ChunkZ = BaseZ + z;
+ int AreaZ = OffZ + z;
+ for (int x = 0; x < SizeX; x++)
+ {
+ int ChunkX = BaseX + x;
+ int AreaX = OffX + x;
+ m_Area.m_BlockTypes[m_Area.MakeIndex(AreaX, AreaY, AreaZ)] = a_BlockBuffer.GetBlock(ChunkX, ChunkY, ChunkZ);
+ } // for x
+ } // for z
+ } // for y
+ }
+ }
-void cBlockArea::cChunkReader::BlockMeta(const NIBBLETYPE * a_BlockMetas)
-{
- if (m_Area.m_BlockMetas == NULL)
+ if (m_Area.m_BlockMetas)
{
- // Don't want metas
- return;
+ a_BlockBuffer.CopyMeta(m_Area.m_BlockMetas);
}
- CopyNibbles(m_Area.m_BlockMetas, a_BlockMetas);
-}
-
-
-
-
-void cBlockArea::cChunkReader::BlockLight(const NIBBLETYPE * a_BlockLight)
-{
- if (m_Area.m_BlockLight == NULL)
+ if (m_Area.m_BlockLight)
{
- // Don't want light
- return;
+ a_BlockBuffer.CopyLight(m_Area.m_BlockLight);
}
- CopyNibbles(m_Area.m_BlockLight, a_BlockLight);
-}
-
-
-
-
-void cBlockArea::cChunkReader::BlockSkyLight(const NIBBLETYPE * a_BlockSkyLight)
-{
- if (m_Area.m_BlockSkyLight == NULL)
+ if (m_Area.m_BlockSkyLight)
{
- // Don't want skylight
- return;
+ a_BlockBuffer.CopySkyLight(m_Area.m_BlockSkyLight);
}
- CopyNibbles(m_Area.m_BlockSkyLight, a_BlockSkyLight);
-}
+}
diff --git a/src/BlockArea.h b/src/BlockArea.h
index c48175b8c..d17a68fbb 100644
--- a/src/BlockArea.h
+++ b/src/BlockArea.h
@@ -317,10 +317,7 @@ protected:
// cChunkDataCallback overrides:
virtual bool Coords (int a_ChunkX, int a_ChunkZ) override;
- virtual void BlockTypes (const BLOCKTYPE * a_BlockTypes) override;
- virtual void BlockMeta (const NIBBLETYPE * a_BlockMetas) override;
- virtual void BlockLight (const NIBBLETYPE * a_BlockLight) override;
- virtual void BlockSkyLight(const NIBBLETYPE * a_BlockSkyLight) override;
+ virtual void ChunkBuffer (const cChunkBuffer & a_BlockTypes) override;
} ;
typedef NIBBLETYPE * NIBBLEARRAY;
diff --git a/src/Chunk.cpp b/src/Chunk.cpp
index ee1531b5c..171f329fb 100644
--- a/src/Chunk.cpp
+++ b/src/Chunk.cpp
@@ -241,23 +241,9 @@ void cChunk::GetAllData(cChunkDataCallback & a_Callback)
a_Callback.HeightMap (&m_HeightMap);
a_Callback.BiomeData (&m_BiomeMap);
- std::vector Blocks = m_BlockTypes;
- Blocks.resize(NumBlocks);
- a_Callback.BlockTypes (&Blocks[0]);
-
- std::vector Metas = m_BlockMeta;
- Metas.resize(NumBlocks / 2);
- a_Callback.BlockMeta (&Metas[0]);
-
a_Callback.LightIsValid (m_IsLightValid);
- std::vector BlockLights = m_BlockLight;
- BlockLights.resize(NumBlocks / 2);
- a_Callback.BlockLight (&BlockLights[0]);
-
- std::vector BlockSkyLights = m_BlockSkyLight;
- BlockSkyLights.resize(NumBlocks / 2, 0xff);
- a_Callback.BlockSkyLight(&BlockSkyLights[0]);
+ a_Callback.ChunkBuffer (m_ChunkBuffer);
for (cEntityList::iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr)
{
@@ -296,48 +282,10 @@ void cChunk::SetAllData(
CalculateHeightmap(a_BlockTypes);
}
- int IdxWhereNonEmptyStarts = 0;
- { // Blocktype compression
- unsigned char Highest = 0;
- int X = 0, Z = 0;
- m_BlockTypes.clear();
-
- for (int x = 0; x < Width; x++)
- {
- for (int z = 0; z < Width; z++)
- {
- unsigned char Height = m_HeightMap[x + z * Width];
- if (Height > Highest)
- {
- Highest = Height;
- X = x; Z = z;
- }
- }
- }
-
- IdxWhereNonEmptyStarts = MakeIndexNoCheck(X, Highest + 1, Z);
-
- m_BlockTypes.insert(m_BlockTypes.end(), &a_BlockTypes[0], &a_BlockTypes[IdxWhereNonEmptyStarts]);
- }
-
- { // Blockmeta compression
- m_BlockMeta.clear();
- m_BlockMeta.insert(m_BlockMeta.end(), &a_BlockMeta[0], &a_BlockMeta[IdxWhereNonEmptyStarts / 2]);
- }
-
- if (a_BlockLight != NULL)
- {
- // Compress blocklight
- m_BlockLight.clear();
- m_BlockLight.insert(m_BlockLight.end(), &a_BlockLight[0], &a_BlockLight[IdxWhereNonEmptyStarts / 2]);
- }
-
- if (a_BlockSkyLight != NULL)
- {
- // Compress skylight
- m_BlockSkyLight.clear();
- m_BlockSkyLight.insert(m_BlockSkyLight.end(), &a_BlockSkyLight[0], &a_BlockSkyLight[IdxWhereNonEmptyStarts / 2]);
- }
+ m_ChunkBuffer.SetBlocks (a_BlockTypes);
+ m_ChunkBuffer.SetMeta (a_BlockMeta);
+ m_ChunkBuffer.SetLight (a_BlockLight);
+ m_ChunkBuffer.SetSkyLight (a_BlockSkyLight);
m_IsLightValid = (a_BlockLight != NULL) && (a_BlockSkyLight != NULL);
@@ -378,39 +326,9 @@ void cChunk::SetLight(
// TODO: We might get cases of wrong lighting when a chunk changes in the middle of a lighting calculation.
// Postponing until we see how bad it is :)
- { // Compress blocklight
- bool FoundNonEmpty = false;
- int IdxWhereNonEmptyStarts = 0;
- m_BlockLight.clear();
-
- for (int Idx = (NumBlocks / 2) - 1; Idx >= 0; Idx--)
- {
- if (a_BlockLight[Idx] != 0)
- {
- FoundNonEmpty = true;
- IdxWhereNonEmptyStarts = Idx;
- break;
- }
- }
- m_BlockLight.insert(m_BlockLight.end(), &a_BlockLight[0], &a_BlockLight[IdxWhereNonEmptyStarts + 1]);
- }
-
- { // Compress skylight
- bool FoundNonEmpty = false;
- int IdxWhereNonEmptyStarts = 0;
- m_BlockSkyLight.clear();
+ m_ChunkBuffer.SetLight (a_BlockLight);
- for (int Idx = (NumBlocks / 2) - 1; Idx >= 0; Idx--)
- {
- if (a_SkyLight[Idx] != 0xff)
- {
- FoundNonEmpty = true;
- IdxWhereNonEmptyStarts = Idx;
- break;
- }
- }
- m_BlockSkyLight.insert(m_BlockSkyLight.end(), &a_SkyLight[0], &a_SkyLight[IdxWhereNonEmptyStarts + 1]);
- }
+ m_ChunkBuffer.SetSkyLight (a_SkyLight);
m_IsLightValid = true;
}
@@ -421,10 +339,7 @@ void cChunk::SetLight(
void cChunk::GetBlockTypes(BLOCKTYPE * a_BlockTypes)
{
- std::vector Blocks = m_BlockTypes;
- Blocks.resize(NumBlocks);
-
- memcpy(a_BlockTypes, &Blocks[0], NumBlocks);
+ m_ChunkBuffer.CopyBlocks(a_BlockTypes);
}
@@ -710,8 +625,7 @@ void cChunk::Tick(float a_Dt)
void cChunk::TickBlock(int a_RelX, int a_RelY, int a_RelZ)
{
- unsigned Index = MakeIndex(a_RelX, a_RelY, a_RelZ);
- cBlockHandler * Handler = BlockHandler(GetBlock(Index));
+ cBlockHandler * Handler = BlockHandler(GetBlock(a_RelX, a_RelY, a_RelZ));
ASSERT(Handler != NULL); // Happenned on server restart, FS #243
cChunkInterface ChunkInterface(this->GetWorld()->GetChunkMap());
cBlockInServerPluginInterface PluginInterface(*this->GetWorld());
@@ -836,19 +750,18 @@ void cChunk::CheckBlocks()
{
return;
}
- std::vector ToTickBlocks;
+ std::vector ToTickBlocks;
std::swap(m_ToTickBlocks, ToTickBlocks);
cChunkInterface ChunkInterface(m_World->GetChunkMap());
cBlockInServerPluginInterface PluginInterface(*m_World);
- for (std::vector::const_iterator itr = ToTickBlocks.begin(), end = ToTickBlocks.end(); itr != end; ++itr)
+ for (std::vector::const_iterator itr = ToTickBlocks.begin(), end = ToTickBlocks.end(); itr != end; ++itr)
{
- unsigned int index = (*itr);
- Vector3i BlockPos = IndexToCoordinate(index);
+ Vector3i Pos = (*itr);
- cBlockHandler * Handler = BlockHandler(GetBlock(index));
- Handler->Check(ChunkInterface, PluginInterface, BlockPos.x, BlockPos.y, BlockPos.z, *this);
+ cBlockHandler * Handler = BlockHandler(GetBlock(Pos));
+ Handler->Check(ChunkInterface, PluginInterface, Pos.x, Pos.y, Pos.z, *this);
} // for itr - ToTickBlocks[]
}
@@ -891,8 +804,7 @@ void cChunk::TickBlocks(void)
continue; // It's all air up here
}
- unsigned int Index = MakeIndexNoCheck(m_BlockTickX, m_BlockTickY, m_BlockTickZ);
- cBlockHandler * Handler = BlockHandler(GetBlock(Index));
+ cBlockHandler * Handler = BlockHandler(GetBlock(m_BlockTickX, m_BlockTickY, m_BlockTickZ));
ASSERT(Handler != NULL); // Happenned on server restart, FS #243
Handler->OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, m_BlockTickX, m_BlockTickY, m_BlockTickZ);
} // for i - tickblocks
@@ -1284,9 +1196,8 @@ bool cChunk::UnboundedRelGetBlockLights(int a_RelX, int a_RelY, int a_RelZ, NIBB
// The chunk is not available, bail out
return false;
}
- int idx = Chunk->MakeIndex(a_RelX, a_RelY, a_RelZ);
- a_BlockLight = Chunk->GetBlockLight(idx);
- a_SkyLight = Chunk->GetSkyLight(idx);
+ a_BlockLight = Chunk->GetBlockLight(a_RelX, a_RelY, a_RelZ);
+ a_SkyLight = Chunk->GetSkyLight(a_RelX, a_RelY, a_RelZ);
return true;
}
@@ -1490,11 +1401,9 @@ void cChunk::CalculateHeightmap(const BLOCKTYPE * a_BlockTypes)
void cChunk::SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta)
{
FastSetBlock(a_RelX, a_RelY, a_RelZ, a_BlockType, a_BlockMeta);
-
- const int index = MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
// Tick this block and its neighbors:
- m_ToTickBlocks.push_back(index);
+ m_ToTickBlocks.push_back(Vector3i(a_RelX, a_RelY, a_RelZ));
QueueTickBlockNeighbors(a_RelX, a_RelY, a_RelZ);
// If there was a block entity, remove it:
@@ -1557,7 +1466,7 @@ void cChunk::QueueTickBlock(int a_RelX, int a_RelY, int a_RelZ)
return;
}
- m_ToTickBlocks.push_back(MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ));
+ m_ToTickBlocks.push_back(Vector3i(a_RelX, a_RelY, a_RelZ));
}
@@ -1595,9 +1504,8 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
ASSERT(IsValid());
- const int index = MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
- const BLOCKTYPE OldBlockType = GetBlock(index);
- const BLOCKTYPE OldBlockMeta = GetNibble(m_BlockMeta, index);
+ const BLOCKTYPE OldBlockType = GetBlock(a_RelX, a_RelY, a_RelZ);
+ const BLOCKTYPE OldBlockMeta = m_ChunkBuffer.GetMeta(a_RelX, a_RelY, a_RelZ);
if ((OldBlockType == a_BlockType) && (OldBlockMeta == a_BlockMeta))
{
return;
@@ -1605,11 +1513,7 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
MarkDirty();
- if (m_BlockTypes.empty() || ((size_t)index > m_BlockTypes.size() - 1) /* Vector starts from zero, .size() starts from 1 */)
- {
- m_BlockTypes.resize(index + 1);
- }
- m_BlockTypes[index] = a_BlockType;
+ m_ChunkBuffer.SetBlock(a_RelX, a_RelY, a_RelZ, a_BlockType);
// The client doesn't need to distinguish between stationary and nonstationary fluids:
if (
@@ -1625,7 +1529,7 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, a_BlockType, a_BlockMeta));
}
- SetNibble(m_BlockMeta, index, a_BlockMeta);
+ m_ChunkBuffer.SetMeta(a_RelX, a_RelY, a_RelZ, a_BlockMeta);
// ONLY recalculate lighting if it's necessary!
if (
@@ -1648,7 +1552,7 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
{
for (int y = a_RelY - 1; y > 0; --y)
{
- if (GetBlock(MakeIndexNoCheck(a_RelX, y, a_RelZ)) != E_BLOCK_AIR)
+ if (GetBlock(a_RelX, y, a_RelZ) != E_BLOCK_AIR)
{
m_HeightMap[a_RelX + a_RelZ * Width] = (unsigned char)y;
break;
@@ -1665,18 +1569,16 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
void cChunk::SendBlockTo(int a_RelX, int a_RelY, int a_RelZ, cClientHandle * a_Client)
{
// The coords must be valid, because the upper level already does chunk lookup. No need to check them again.
- // There's an debug-time assert in MakeIndexNoCheck anyway
- unsigned int index = MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
if (a_Client == NULL)
{
// Queue the block for all clients in the chunk (will be sent in Tick())
- m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, GetBlock(index), GetMeta(index)));
+ m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, GetBlock(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ)));
return;
}
Vector3i wp = PositionToWorldPosition(a_RelX, a_RelY, a_RelZ);
- a_Client->SendBlockChange(wp.x, wp.y, wp.z, GetBlock(index), GetMeta(index));
+ a_Client->SendBlockChange(wp.x, wp.y, wp.z, GetBlock(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ));
// FS #268 - if a BlockEntity digging is cancelled by a plugin, the entire block entity must be re-sent to the client:
for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), end = m_BlockEntities.end(); itr != end; ++itr)
@@ -2535,27 +2437,7 @@ BLOCKTYPE cChunk::GetBlock(int a_RelX, int a_RelY, int a_RelZ) const
return 0; // Clip
}
- return GetBlock(MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ));
-}
-
-
-
-
-
-BLOCKTYPE cChunk::GetBlock(int a_BlockIdx) const
-{
- if ((a_BlockIdx < 0) || (a_BlockIdx >= NumBlocks))
- {
- ASSERT(!"GetBlock(idx) out of bounds!");
- return 0;
- }
-
- if (m_BlockTypes.empty() || ((size_t)a_BlockIdx > m_BlockTypes.size() - 1) /* Vector starts from zero, .size() starts from 1 */)
- {
- return E_BLOCK_AIR;
- }
-
- return m_BlockTypes[a_BlockIdx];
+ return m_ChunkBuffer.GetBlock(a_RelX, a_RelY, a_RelZ);
}
@@ -2564,9 +2446,8 @@ BLOCKTYPE cChunk::GetBlock(int a_BlockIdx) const
void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta)
{
- int Idx = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
- a_BlockType = GetBlock(Idx);
- a_BlockMeta = cChunkDef::GetNibble(m_BlockMeta, Idx);
+ a_BlockType = GetBlock(a_RelX, a_RelY, a_RelZ);
+ a_BlockMeta = m_ChunkBuffer.GetMeta(a_RelX, a_RelY, a_RelZ);
}
@@ -2575,11 +2456,10 @@ void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_
void cChunk::GetBlockInfo(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight)
{
- int Idx = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
- a_BlockType = GetBlock(Idx);
- a_Meta = cChunkDef::GetNibble(m_BlockMeta, Idx);
- a_SkyLight = cChunkDef::GetNibble(m_BlockSkyLight, Idx);
- a_BlockLight = cChunkDef::GetNibble(m_BlockLight, Idx);
+ a_BlockType = GetBlock(a_RelX, a_RelY, a_RelZ);
+ a_Meta = m_ChunkBuffer.GetMeta(a_RelX, a_RelY, a_RelZ);
+ a_SkyLight = m_ChunkBuffer.GetSkyLight(a_RelX, a_RelY, a_RelZ);
+ a_BlockLight = m_ChunkBuffer.GetBlockLight(a_RelX, a_RelY, a_RelZ);
}
diff --git a/src/Chunk.h b/src/Chunk.h
index 9100eec58..ea3e035ad 100644
--- a/src/Chunk.h
+++ b/src/Chunk.h
@@ -3,6 +3,7 @@
#include "Entities/Entity.h"
#include "ChunkDef.h"
+#include "ChunkBuffer.h"
#include "Simulator/FireSimulator.h"
#include "Simulator/SandSimulator.h"
@@ -66,6 +67,7 @@ public:
cChunkMap * a_ChunkMap, cWorld * a_World, // Parent objects
cChunk * a_NeighborXM, cChunk * a_NeighborXP, cChunk * a_NeighborZM, cChunk * a_NeighborZP // Neighbor chunks
);
+ cChunk(cChunk& other);
~cChunk();
bool IsValid(void) const {return m_IsValid; } // Returns true if the chunk block data is valid (loaded / generated)
@@ -154,7 +156,7 @@ public:
void FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, BLOCKTYPE a_BlockMeta ); // Doesn't force block updates on neighbors, use for simple changes such as grass growing etc.
BLOCKTYPE GetBlock(int a_RelX, int a_RelY, int a_RelZ) const;
- BLOCKTYPE GetBlock(int a_BlockIdx) const;
+ BLOCKTYPE GetBlock(Vector3i a_cords) const { return GetBlock(a_cords.x,a_cords.y,a_cords.z);}
void GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta);
void GetBlockInfo (int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight);
@@ -320,15 +322,17 @@ public:
m_BlockTickZ = a_RelZ;
}
- inline NIBBLETYPE GetMeta(int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockMeta, a_RelX, a_RelY, a_RelZ); }
- inline NIBBLETYPE GetMeta(int a_BlockIdx) const {return cChunkDef::GetNibble(m_BlockMeta, a_BlockIdx); }
- inline void SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Meta) { cChunkDef::SetNibble(m_BlockMeta, a_RelX, a_RelY, a_RelZ, a_Meta); }
- inline void SetMeta(int a_BlockIdx, NIBBLETYPE a_Meta) { cChunkDef::SetNibble(m_BlockMeta, a_BlockIdx, a_Meta); }
+ inline NIBBLETYPE GetMeta(int a_RelX, int a_RelY, int a_RelZ) const
+ {
+ return m_ChunkBuffer.GetMeta(a_RelX, a_RelY, a_RelZ);
+ }
+ inline void SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Meta)
+ {
+ m_ChunkBuffer.SetMeta(a_RelX, a_RelY, a_RelZ, a_Meta);
+ }
- inline NIBBLETYPE GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockLight, a_RelX, a_RelY, a_RelZ); }
- inline NIBBLETYPE GetSkyLight (int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockSkyLight, a_RelX, a_RelY, a_RelZ, true); }
- inline NIBBLETYPE GetBlockLight(int a_Idx) const {return cChunkDef::GetNibble(m_BlockLight, a_Idx); }
- inline NIBBLETYPE GetSkyLight (int a_Idx) const {return cChunkDef::GetNibble(m_BlockSkyLight, a_Idx, true); }
+ inline NIBBLETYPE GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const {return m_ChunkBuffer.GetBlockLight(a_RelX, a_RelY, a_RelZ); }
+ inline NIBBLETYPE GetSkyLight (int a_RelX, int a_RelY, int a_RelZ) const {return m_ChunkBuffer.GetSkyLight(a_RelX, a_RelY, a_RelZ); }
/** Same as GetBlock(), but relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success */
bool UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const;
@@ -403,8 +407,8 @@ private:
bool m_IsSaving; // True if the chunk is being saved
bool m_HasLoadFailed; // True if chunk failed to load and hasn't been generated yet since then
- std::vector m_ToTickBlocks;
- sSetBlockVector m_PendingSendBlocks; ///< Blocks that have changed and need to be sent to all clients
+ std::vector m_ToTickBlocks;
+ sSetBlockVector m_PendingSendBlocks; ///< Blocks that have changed and need to be sent to all clients
sSetBlockQueueVector m_SetBlockQueue; ///< Block changes that are queued to a specific tick
@@ -420,11 +424,7 @@ private:
cWorld * m_World;
cChunkMap * m_ChunkMap;
- // TODO: Make these pointers and don't allocate what isn't needed
- std::vector m_BlockTypes;
- std::vector m_BlockMeta;
- std::vector m_BlockLight;
- std::vector m_BlockSkyLight;
+ cChunkBuffer m_ChunkBuffer;
cChunkDef::HeightMap m_HeightMap;
cChunkDef::BiomeMap m_BiomeMap;
diff --git a/src/ChunkBuffer.cpp b/src/ChunkBuffer.cpp
new file mode 100644
index 000000000..8e87d3049
--- /dev/null
+++ b/src/ChunkBuffer.cpp
@@ -0,0 +1,146 @@
+
+#include "Globals.h"
+#include "ChunkBuffer.h"
+
+cChunkBuffer cChunkBuffer::Copy() const
+{
+ cChunkBuffer copy;
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ if(m_Sections[i])
+ {
+ copy.m_Sections[i] = Allocate();
+ *copy.m_Sections[i] = *m_Sections[i];
+ }
+ }
+ return copy;
+}
+
+
+
+
+
+void cChunkBuffer::CopyBlocks (BLOCKTYPE * a_dest, size_t a_Idx, size_t length) const
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16;
+ if (a_Idx > 0) a_Idx = a_Idx > length ? a_Idx - length : 0;
+ if (a_Idx == 0)
+ {
+ size_t tocopy = length > segment_length ? segment_length : length;
+ length -= tocopy;
+ memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockTypes, sizeof(BLOCKTYPE) * length);
+ }
+ }
+}
+
+
+
+
+
+void cChunkBuffer::CopyMeta(NIBBLETYPE * a_dest) const
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
+ memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockMeta, sizeof(NIBBLETYPE) * segment_length);
+ }
+}
+
+
+
+
+
+void cChunkBuffer::CopyLight(NIBBLETYPE * a_dest) const
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
+ memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockLight, sizeof(NIBBLETYPE) * segment_length);
+ }
+}
+
+
+
+
+
+void cChunkBuffer::CopySkyLight(NIBBLETYPE * a_dest) const
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
+ memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockSkyLight, sizeof(NIBBLETYPE) * segment_length);
+ }
+}
+
+
+
+
+
+void cChunkBuffer::SetBlocks(const BLOCKTYPE * a_src)
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
+ if (m_Sections[i])
+ {
+ memcpy(&m_Sections[i]->m_BlockTypes, &a_src[i * segment_length], sizeof(BLOCKTYPE) * segment_length);
+ }
+ }
+}
+
+
+
+
+void cChunkBuffer::SetMeta(const NIBBLETYPE * a_src)
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
+ if (m_Sections[i])
+ {
+ memcpy(&m_Sections[i]->m_BlockMeta, &a_src[i * segment_length], sizeof(NIBBLETYPE) * segment_length);
+ }
+ }
+}
+
+
+
+
+void cChunkBuffer::SetLight(const NIBBLETYPE * a_src)
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
+ if (m_Sections[i])
+ {
+ memcpy(&m_Sections[i]->m_BlockLight, &a_src[i * segment_length], sizeof(NIBBLETYPE) * segment_length);
+ }
+ }
+}
+
+
+
+
+void cChunkBuffer::SetSkyLight (const NIBBLETYPE * a_src)
+{
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
+ if (m_Sections[i])
+ {
+ memcpy(&m_Sections[i]->m_BlockSkyLight, &a_src[i * segment_length], sizeof(NIBBLETYPE) * segment_length);
+ }
+ }
+}
+
+
+
+
+
+cChunkBuffer::sChunkSection * cChunkBuffer::Allocate() const
+{
+ // TODO: use a allocation pool
+ return new cChunkBuffer::sChunkSection;
+}
diff --git a/src/ChunkBuffer.h b/src/ChunkBuffer.h
new file mode 100644
index 000000000..44e447c82
--- /dev/null
+++ b/src/ChunkBuffer.h
@@ -0,0 +1,310 @@
+
+#pragma once
+
+#define CHUNK_SECTION_HEIGHT 16
+#define CHUNK_SECTION_NUM (256 / CHUNK_SECTION_HEIGHT)
+
+#if __cplusplus < 201103L
+// auto_ptr style interface for memory management
+#else
+// unique_ptr style interface for memory management
+#endif
+
+class cChunkBuffer
+{
+public:
+
+ cChunkBuffer()
+ #if __cplusplus < 201103L
+ // auto_ptr style interface for memory management
+ : IsOwner(true)
+ #endif
+ {
+ memset(m_Sections, 0, sizeof(m_Sections));
+ }
+ ~cChunkBuffer()
+ {
+ #if __cplusplus < 201103L
+ // auto_ptr style interface for memory management
+ if(!IsOwner) return;
+ #endif
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ if(m_Sections[i]) delete m_Sections[i];
+ }
+ }
+
+ #if __cplusplus < 201103L
+ // auto_ptr style interface for memory management
+ cChunkBuffer(cChunkBuffer& other) :
+ IsOwner(true);
+ {
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ m_Sections[i] = other.m_Sections[i];
+ }
+ other.IsOwner = false;
+ }
+ void operator=(cChunkBuffer& other)
+ {
+ if(IsOwner)
+ {
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ if(m_Sections[i]) delete m_Sections[i];
+ }
+ }
+ IsOwner = true;
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ m_Sections[i] = other.m_Sections[i];
+ }
+ other.IsOwner = false;
+ }
+ #else
+ // unique_ptr style interface for memory management
+ cChunkBuffer(cChunkBuffer&& other)
+ {
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ m_Sections[i] = other.m_Sections[i];
+ }
+ }
+
+ void operator=(cChunkBuffer&& other)
+ {
+ for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ {
+ if(m_Sections[i]) delete m_Sections[i];
+ m_Sections[i] = other.m_Sections[i];
+ }
+ }
+ #endif
+
+ BLOCKTYPE GetBlock(int a_X, int a_Y, int a_Z) const
+ {
+ ASSERT((a_X >= 0) && (a_X < cChunkDef::Width));
+ ASSERT((a_Y >= 0) && (a_Y < cChunkDef::Height));
+ ASSERT((a_Z >= 0) && (a_Z < cChunkDef::Width));
+ int Section = a_Y / CHUNK_SECTION_HEIGHT;
+ if(m_Sections[Section])
+ {
+ int Index = cChunkDef::MakeIndexNoCheck(a_X, a_Y - (Section * CHUNK_SECTION_HEIGHT), a_Z);
+ return m_Sections[Section]->m_BlockTypes[Index];
+ }
+ else
+ {
+ return 0;
+ }
+ }
+
+ void SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_Block)
+ {
+ if (
+ (a_RelX >= cChunkDef::Width) || (a_RelX < 0) ||
+ (a_RelY >= cChunkDef::Height) || (a_RelY < 0) ||
+ (a_RelZ >= cChunkDef::Width) || (a_RelZ < 0)
+ )
+ {
+ ASSERT(!"cChunkBuffer::SetMeta(): index out of range!");
+ return;
+ }
+
+ int Section = a_RelY / CHUNK_SECTION_HEIGHT;
+ if(!m_Sections[Section])
+ {
+ m_Sections[Section] = Allocate();
+ if(!m_Sections[Section])
+ {
+ ASSERT("Failed to allocate a new section in Chunkbuffer");
+ return;
+ }
+ }
+ int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * CHUNK_SECTION_HEIGHT), a_RelZ);
+ m_Sections[Section]->m_BlockTypes[Index] = a_Block;
+ }
+
+ NIBBLETYPE GetMeta(int a_RelX, int a_RelY, int a_RelZ) const
+ {
+ if ((a_RelX < cChunkDef::Width) && (a_RelX > -1) && (a_RelY < cChunkDef::Height) && (a_RelY > -1) && (a_RelZ < cChunkDef::Width) && (a_RelZ > -1))
+ {
+ int Section = a_RelY / CHUNK_SECTION_HEIGHT;
+ if(m_Sections[Section])
+ {
+ int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * CHUNK_SECTION_HEIGHT), a_RelZ);
+ return (m_Sections[Section]->m_BlockMeta[Index / 2] >> ((Index & 1) * 4)) & 0x0f;
+ }
+ else
+ {
+ return 0;
+ }
+ }
+ ASSERT(!"cChunkBuffer::GetMeta(): coords out of chunk range!");
+ return 0;
+ }
+
+ void SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Nibble)
+ {
+ if (
+ (a_RelX >= cChunkDef::Width) || (a_RelX < 0) ||
+ (a_RelY >= cChunkDef::Height) || (a_RelY < 0) ||
+ (a_RelZ >= cChunkDef::Width) || (a_RelZ < 0)
+ )
+ {
+ ASSERT(!"cChunkBuffer::SetMeta(): index out of range!");
+ return;
+ }
+
+ int Section = a_RelY / CHUNK_SECTION_HEIGHT;
+ if(!m_Sections[Section])
+ {
+ m_Sections[Section] = Allocate();
+ if(!m_Sections[Section])
+ {
+ ASSERT("Failed to allocate a new section in Chunkbuffer");
+ return;
+ }
+ }
+ int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * CHUNK_SECTION_HEIGHT), a_RelZ);
+ m_Sections[Section]->m_BlockMeta[Index / 2] = static_cast(
+ (m_Sections[Section]->m_BlockMeta[Index / 2] & (0xf0 >> ((Index & 1) * 4))) | // The untouched nibble
+ ((a_Nibble & 0x0f) << ((Index & 1) * 4)) // The nibble being set
+ );
+ }
+
+ NIBBLETYPE GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const
+ {
+ if ((a_RelX < cChunkDef::Width) && (a_RelX > -1) && (a_RelY < cChunkDef::Height) && (a_RelY > -1) && (a_RelZ < cChunkDef::Width) && (a_RelZ > -1))
+ {
+ int Section = a_RelY / CHUNK_SECTION_HEIGHT;
+ if(m_Sections[Section])
+ {
+ int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * CHUNK_SECTION_HEIGHT), a_RelZ);
+ return (m_Sections[Section]->m_BlockLight[Index / 2] >> ((Index & 1) * 4)) & 0x0f;
+ }
+ else
+ {
+ return 0;
+ }
+ }
+ ASSERT(!"cChunkBuffer::GetMeta(): coords out of chunk range!");
+ return 0;
+ }
+
+ NIBBLETYPE GetSkyLight(int a_RelX, int a_RelY, int a_RelZ) const
+ {
+ if ((a_RelX < cChunkDef::Width) && (a_RelX > -1) && (a_RelY < cChunkDef::Height) && (a_RelY > -1) && (a_RelZ < cChunkDef::Width) && (a_RelZ > -1))
+ {
+ int Section = a_RelY / CHUNK_SECTION_HEIGHT;
+ if(m_Sections[Section])
+ {
+ int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * CHUNK_SECTION_HEIGHT), a_RelZ);
+ return (m_Sections[Section]->m_BlockLight[Index / 2] >> ((Index & 1) * 4)) & 0x0f;
+ }
+ else
+ {
+ return 0xFF;
+ }
+ }
+ ASSERT(!"cChunkBuffer::GetMeta(): coords out of chunk range!");
+ return 0;
+ }
+
+ cChunkBuffer Copy() const;
+ void CopyBlocks (BLOCKTYPE * a_dest, size_t a_Idx = 0, size_t length = cChunkDef::NumBlocks) const;
+ void CopyMeta (NIBBLETYPE * a_dest) const;
+ void CopyLight (NIBBLETYPE * a_dest) const;
+ void CopySkyLight (NIBBLETYPE * a_dest) const;
+
+ void SetBlocks (const BLOCKTYPE * a_src);
+ void SetMeta (const NIBBLETYPE * a_src);
+ void SetLight (const NIBBLETYPE * a_src);
+ void SetSkyLight (const NIBBLETYPE * a_src);
+
+private:
+
+ #if __cplusplus < 201103L
+ // auto_ptr style interface for memory management
+ bool IsOwner;
+ #endif
+
+ struct sChunkSection {
+ BLOCKTYPE m_BlockTypes [CHUNK_SECTION_HEIGHT * 16 * 16] ;
+ NIBBLETYPE m_BlockMeta [CHUNK_SECTION_HEIGHT * 16 * 16 / 2];
+ NIBBLETYPE m_BlockLight [CHUNK_SECTION_HEIGHT * 16 * 16 / 2];
+ NIBBLETYPE m_BlockSkyLight[CHUNK_SECTION_HEIGHT * 16 * 16 / 2];
+ };
+
+ sChunkSection *m_Sections[CHUNK_SECTION_NUM];
+
+ sChunkSection * Allocate() const;
+};
+
+
+
+
+/** A simple implementation of the cChunkDataCallback interface that collects all block data into a buffer
+*/
+class cChunkBufferCollector :
+ public cChunkDataCallback
+{
+public:
+
+ cChunkBuffer m_BlockData;
+
+protected:
+
+ virtual void ChunkBuffer(const cChunkBuffer & a_BlockData) override
+ {
+ m_BlockData = a_BlockData.Copy();
+ }
+};
+
+
+/** A simple implementation of the cChunkDataCallback interface that collects all block data into a single buffer
+*/
+class cChunkDataCollector :
+public cChunkDataCallback
+{
+public:
+
+ // Must be unsigned char instead of BLOCKTYPE or NIBBLETYPE, because it houses both.
+ unsigned char m_BlockData[cChunkDef::BlockDataSize];
+
+protected:
+
+ virtual void ChunkBuffer(const cChunkBuffer & a_ChunkBuffer) override
+ {
+ a_ChunkBuffer.CopyBlocks(m_BlockData);
+ a_ChunkBuffer.CopyMeta(m_BlockData + cChunkDef::NumBlocks);
+ a_ChunkBuffer.CopyLight(m_BlockData + 3 * cChunkDef::NumBlocks / 2);
+ a_ChunkBuffer.CopySkyLight(m_BlockData + 2 * cChunkDef::NumBlocks);
+ }
+};
+
+/** A simple implementation of the cChunkDataCallback interface that collects all block data into a separate buffers
+*/
+class cChunkDataSeparateCollector :
+public cChunkDataCallback
+{
+public:
+
+ cChunkDef::BlockTypes m_BlockTypes;
+ cChunkDef::BlockNibbles m_BlockMetas;
+ cChunkDef::BlockNibbles m_BlockLight;
+ cChunkDef::BlockNibbles m_BlockSkyLight;
+
+protected:
+
+ virtual void ChunkBuffer(const cChunkBuffer & a_ChunkBuffer) override
+ {
+ a_ChunkBuffer.CopyBlocks(m_BlockTypes);
+ a_ChunkBuffer.CopyMeta(m_BlockMetas);
+ a_ChunkBuffer.CopyLight(m_BlockLight);
+ a_ChunkBuffer.CopySkyLight(m_BlockSkyLight);
+ }
+} ;
+
+
+
+
diff --git a/src/ChunkDef.h b/src/ChunkDef.h
index bb9f14bbe..a5eccc9d6 100644
--- a/src/ChunkDef.h
+++ b/src/ChunkDef.h
@@ -366,6 +366,7 @@ public:
+class cChunkBuffer;
/** Interface class used for getting data out of a chunk using the GetAllData() function.
@@ -390,20 +391,11 @@ public:
/// Called once to provide biome data
virtual void BiomeData (const cChunkDef::BiomeMap * a_BiomeMap) {UNUSED(a_BiomeMap); };
- /// Called once to export block types
- virtual void BlockTypes (const BLOCKTYPE * a_Type) {UNUSED(a_Type); };
+ /// Called once to let know if the chunk lighting is valid. Return value is ignored
+ virtual void LightIsValid(bool a_IsLightValid) {UNUSED(a_IsLightValid); };
- /// Called once to export block meta
- virtual void BlockMeta (const NIBBLETYPE * a_Meta) {UNUSED(a_Meta); };
-
- /// Called once to let know if the chunk lighting is valid. Return value is used to control if BlockLight() and BlockSkyLight() are called next (if true)
- virtual bool LightIsValid(bool a_IsLightValid) {UNUSED(a_IsLightValid); return true; };
-
- /// Called once to export block light
- virtual void BlockLight (const NIBBLETYPE * a_BlockLight) {UNUSED(a_BlockLight); };
-
- /// Called once to export sky light
- virtual void BlockSkyLight(const NIBBLETYPE * a_SkyLight) {UNUSED(a_SkyLight); };
+ /// Called once to export block info
+ virtual void ChunkBuffer (const cChunkBuffer & a_Buffer) {UNUSED(a_Buffer); };
/// Called for each entity in the chunk
virtual void Entity(cEntity * a_Entity) {UNUSED(a_Entity); };
@@ -416,88 +408,6 @@ public:
-/** A simple implementation of the cChunkDataCallback interface that collects all block data into a single buffer
-*/
-class cChunkDataCollector :
- public cChunkDataCallback
-{
-public:
-
- // Must be unsigned char instead of BLOCKTYPE or NIBBLETYPE, because it houses both.
- unsigned char m_BlockData[cChunkDef::BlockDataSize];
-
-protected:
-
- virtual void BlockTypes(const BLOCKTYPE * a_BlockTypes) override
- {
- memcpy(m_BlockData, a_BlockTypes, sizeof(cChunkDef::BlockTypes));
- }
-
-
- virtual void BlockMeta(const NIBBLETYPE * a_BlockMeta) override
- {
- memcpy(m_BlockData + cChunkDef::NumBlocks, a_BlockMeta, cChunkDef::NumBlocks / 2);
- }
-
-
- virtual void BlockLight(const NIBBLETYPE * a_BlockLight) override
- {
- memcpy(m_BlockData + 3 * cChunkDef::NumBlocks / 2, a_BlockLight, cChunkDef::NumBlocks / 2);
- }
-
-
- virtual void BlockSkyLight(const NIBBLETYPE * a_BlockSkyLight) override
- {
- memcpy(m_BlockData + 2 * cChunkDef::NumBlocks, a_BlockSkyLight, cChunkDef::NumBlocks / 2);
- }
-} ;
-
-
-
-
-
-/** A simple implementation of the cChunkDataCallback interface that collects all block data into a separate buffers
-*/
-class cChunkDataSeparateCollector :
- public cChunkDataCallback
-{
-public:
-
- cChunkDef::BlockTypes m_BlockTypes;
- cChunkDef::BlockNibbles m_BlockMetas;
- cChunkDef::BlockNibbles m_BlockLight;
- cChunkDef::BlockNibbles m_BlockSkyLight;
-
-protected:
-
- virtual void BlockTypes(const BLOCKTYPE * a_BlockTypes) override
- {
- memcpy(m_BlockTypes, a_BlockTypes, sizeof(m_BlockTypes));
- }
-
-
- virtual void BlockMeta(const NIBBLETYPE * a_BlockMeta) override
- {
- memcpy(m_BlockMetas, a_BlockMeta, sizeof(m_BlockMetas));
- }
-
-
- virtual void BlockLight(const NIBBLETYPE * a_BlockLight) override
- {
- memcpy(m_BlockLight, a_BlockLight, sizeof(m_BlockLight));
- }
-
-
- virtual void BlockSkyLight(const NIBBLETYPE * a_BlockSkyLight) override
- {
- memcpy(m_BlockSkyLight, a_BlockSkyLight, sizeof(m_BlockSkyLight));
- }
-} ;
-
-
-
-
-
/** Interface class used for comparing clients of two chunks.
Used primarily for entity moving while both chunks are locked.
*/
diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp
index e695f0ab2..2b47f25f8 100644
--- a/src/ChunkMap.cpp
+++ b/src/ChunkMap.cpp
@@ -219,9 +219,8 @@ bool cChunkMap::LockedGetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY
return false;
}
- int Index = cChunkDef::MakeIndexNoCheck(a_BlockX, a_BlockY, a_BlockZ);
- a_BlockType = Chunk->GetBlock(Index);
- a_BlockMeta = Chunk->GetMeta(Index);
+ a_BlockType = Chunk->GetBlock(a_BlockX, a_BlockY, a_BlockZ);
+ a_BlockMeta = Chunk->GetMeta(a_BlockX, a_BlockY, a_BlockZ);
return true;
}
@@ -242,8 +241,7 @@ bool cChunkMap::LockedGetBlockType(int a_BlockX, int a_BlockY, int a_BlockZ, BLO
return false;
}
- int Index = cChunkDef::MakeIndexNoCheck(a_BlockX, a_BlockY, a_BlockZ);
- a_BlockType = Chunk->GetBlock(Index);
+ a_BlockType = Chunk->GetBlock(a_BlockX, a_BlockY, a_BlockZ);
return true;
}
@@ -264,8 +262,7 @@ bool cChunkMap::LockedGetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ, NIB
return false;
}
- int Index = cChunkDef::MakeIndexNoCheck(a_BlockX, a_BlockY, a_BlockZ);
- a_BlockMeta = Chunk->GetMeta(Index);
+ a_BlockMeta = Chunk->GetMeta(a_BlockX, a_BlockY, a_BlockZ);
return true;
}
@@ -1486,9 +1483,8 @@ bool cChunkMap::GetBlocks(sSetBlockVector & a_Blocks, bool a_ContinueOnFailure)
res = false;
continue;
}
- int idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z);
- itr->BlockType = Chunk->GetBlock(idx);
- itr->BlockMeta = Chunk->GetMeta(idx);
+ itr->BlockType = Chunk->GetBlock(itr->x, itr->y, itr->z);
+ itr->BlockMeta = Chunk->GetMeta(itr->x, itr->y, itr->z);
}
return res;
}
diff --git a/src/ChunkSender.h b/src/ChunkSender.h
index a26f764a7..81b298a55 100644
--- a/src/ChunkSender.h
+++ b/src/ChunkSender.h
@@ -27,6 +27,7 @@ Note that it may be called by world's BroadcastToChunk() if the client is still
#include "OSSupport/IsThread.h"
#include "ChunkDef.h"
+#include "ChunkBuffer.h"
diff --git a/src/Entities/FallingBlock.cpp b/src/Entities/FallingBlock.cpp
index a66c7e4ae..e57c45eaf 100644
--- a/src/Entities/FallingBlock.cpp
+++ b/src/Entities/FallingBlock.cpp
@@ -55,9 +55,8 @@ void cFallingBlock::Tick(float a_Dt, cChunk & a_Chunk)
return;
}
- int idx = a_Chunk.MakeIndexNoCheck(BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width);
- BLOCKTYPE BlockBelow = a_Chunk.GetBlock(idx);
- NIBBLETYPE BelowMeta = a_Chunk.GetMeta(idx);
+ BLOCKTYPE BlockBelow = a_Chunk.GetBlock(BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width);
+ NIBBLETYPE BelowMeta = a_Chunk.GetMeta(BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width);
if (cSandSimulator::DoesBreakFallingThrough(BlockBelow, BelowMeta))
{
// Fallen onto a block that breaks this into pickups (e. g. half-slab)
diff --git a/src/LightingThread.cpp b/src/LightingThread.cpp
index 302473d71..56d5dba22 100644
--- a/src/LightingThread.cpp
+++ b/src/LightingThread.cpp
@@ -18,20 +18,17 @@
class cReader :
public cChunkDataCallback
{
- virtual void BlockTypes(const BLOCKTYPE * a_Type) override
+ virtual void ChunkBuffer(const cChunkBuffer & a_ChunkBuffer) override
{
- // ROW is a block of 16 Blocks, one whole row is copied at a time (hopefully the compiler will optimize that)
- // C++ doesn't permit copying arrays, but arrays as a part of a struct is ok :)
- typedef struct {BLOCKTYPE m_Row[16]; } ROW;
- ROW * InputRows = (ROW *)a_Type;
- ROW * OutputRows = (ROW *)m_BlockTypes;
+ BLOCKTYPE * OutputRows = m_BlockTypes;
int InputIdx = 0;
int OutputIdx = m_ReadingChunkX + m_ReadingChunkZ * cChunkDef::Width * 3;
for (int y = 0; y < cChunkDef::Height; y++)
{
for (int z = 0; z < cChunkDef::Width; z++)
{
- OutputRows[OutputIdx] = InputRows[InputIdx++];
+ a_ChunkBuffer.CopyBlocks(OutputRows + OutputIdx * 16, InputIdx * 16, 16);
+ InputIdx++;
OutputIdx += 3;
} // for z
// Skip into the next y-level in the 3x3 chunk blob; each level has cChunkDef::Width * 9 rows
diff --git a/src/MobProximityCounter.cpp b/src/MobProximityCounter.cpp
index 6c44ea458..e7493dd0f 100644
--- a/src/MobProximityCounter.cpp
+++ b/src/MobProximityCounter.cpp
@@ -24,7 +24,8 @@ void cMobProximityCounter::CollectMob(cEntity& a_Monster, cChunk& a_Chunk, doubl
if (a_Distance < it->second.m_Distance)
{
it->second.m_Distance = a_Distance;
- it->second.m_Chunk = a_Chunk;
+ ASSERT(false);
+ //it->second.m_Chunk = a_Chunk;
}
}
diff --git a/src/Simulator/FireSimulator.cpp b/src/Simulator/FireSimulator.cpp
index 470dfc791..4c1008897 100644
--- a/src/Simulator/FireSimulator.cpp
+++ b/src/Simulator/FireSimulator.cpp
@@ -95,8 +95,10 @@ void cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChun
int NumMSecs = (int)a_Dt;
for (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();)
{
- int idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z);
- BLOCKTYPE BlockType = a_Chunk->GetBlock(idx);
+ int x = itr->x;
+ int y = itr->y;
+ int z = itr->z;
+ BLOCKTYPE BlockType = a_Chunk->GetBlock(x,y,z);
if (!IsAllowedBlock(BlockType))
{
@@ -125,7 +127,7 @@ void cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChun
itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width
);
*/
- NIBBLETYPE BlockMeta = a_Chunk->GetMeta(idx);
+ NIBBLETYPE BlockMeta = a_Chunk->GetMeta(x, y, z);
if (BlockMeta == 0x0f)
{
// The fire burnt out completely
@@ -140,7 +142,7 @@ void cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChun
if((itr->y > 0) && (!DoesBurnForever(a_Chunk->GetBlock(itr->x, itr->y - 1, itr->z))))
{
- a_Chunk->SetMeta(idx, BlockMeta + 1);
+ a_Chunk->SetMeta(x, y, z, BlockMeta + 1);
}
itr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z); // TODO: Add some randomness into this
} // for itr - Data[]
diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp
index 415693ae2..10acfb537 100644
--- a/src/WorldStorage/NBTChunkSerializer.cpp
+++ b/src/WorldStorage/NBTChunkSerializer.cpp
@@ -692,10 +692,9 @@ void cNBTChunkSerializer::AddMinecartChestContents(cMinecartWithChest * a_Mineca
-bool cNBTChunkSerializer::LightIsValid(bool a_IsLightValid)
+void cNBTChunkSerializer::LightIsValid(bool a_IsLightValid)
{
m_IsLightValid = a_IsLightValid;
- return a_IsLightValid; // We want lighting only if it's valid, otherwise don't bother
}
diff --git a/src/WorldStorage/NBTChunkSerializer.h b/src/WorldStorage/NBTChunkSerializer.h
index 51d104970..6da2bc6dd 100644
--- a/src/WorldStorage/NBTChunkSerializer.h
+++ b/src/WorldStorage/NBTChunkSerializer.h
@@ -9,7 +9,7 @@
#pragma once
-#include "../ChunkDef.h"
+#include "../ChunkBuffer.h"
@@ -121,7 +121,7 @@ protected:
void AddMinecartChestContents(cMinecartWithChest * a_Minecart);
// cChunkDataSeparateCollector overrides:
- virtual bool LightIsValid(bool a_IsLightValid) override;
+ virtual void LightIsValid(bool a_IsLightValid) override;
virtual void BiomeData(const cChunkDef::BiomeMap * a_BiomeMap) override;
virtual void Entity(cEntity * a_Entity) override;
virtual void BlockEntity(cBlockEntity * a_Entity) override;
diff --git a/src/WorldStorage/WSSCompact.cpp b/src/WorldStorage/WSSCompact.cpp
index bb9d4b9e6..b44dd02c5 100644
--- a/src/WorldStorage/WSSCompact.cpp
+++ b/src/WorldStorage/WSSCompact.cpp
@@ -107,15 +107,13 @@ void cJsonChunkSerializer::BlockEntity(cBlockEntity * a_BlockEntity)
-bool cJsonChunkSerializer::LightIsValid(bool a_IsLightValid)
+void cJsonChunkSerializer::LightIsValid(bool a_IsLightValid)
{
- if (!a_IsLightValid)
+ if (a_IsLightValid)
{
- return false;
+ m_Root["IsLightValid"] = true;
+ m_HasJsonData = true;
}
- m_Root["IsLightValid"] = true;
- m_HasJsonData = true;
- return true;
}
diff --git a/src/WorldStorage/WSSCompact.h b/src/WorldStorage/WSSCompact.h
index 4df146ec3..49a897984 100644
--- a/src/WorldStorage/WSSCompact.h
+++ b/src/WorldStorage/WSSCompact.h
@@ -14,6 +14,7 @@
#include "WorldStorage.h"
#include "../Vector3.h"
#include "json/json.h"
+#include "ChunkBuffer.h"
@@ -42,7 +43,7 @@ protected:
// cChunkDataCollector overrides:
virtual void Entity (cEntity * a_Entity) override;
virtual void BlockEntity (cBlockEntity * a_Entity) override;
- virtual bool LightIsValid (bool a_IsLightValid) override;
+ virtual void LightIsValid (bool a_IsLightValid) override;
} ;
--
cgit v1.2.3
From b4b3b5ce6480419bb18bafa6650dd09ea5544441 Mon Sep 17 00:00:00 2001
From: Tiger Wang
Date: Sat, 26 Apr 2014 23:50:24 +0100
Subject: More comments!
* Also fixed a potential issue with position sending - if someone moved
slowly enough, their position would never be updated.
---
src/Entities/Entity.cpp | 2 +-
src/Entities/Entity.h | 11 +++++++++--
2 files changed, 10 insertions(+), 3 deletions(-)
diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp
index f535faac7..921457b2d 100644
--- a/src/Entities/Entity.cpp
+++ b/src/Entities/Entity.cpp
@@ -1145,7 +1145,7 @@ void cEntity::BroadcastMovementUpdate(const cClientHandle * a_Exclude)
int DiffY = (int)(floor(GetPosY() * 32.0) - floor(m_LastPos.y * 32.0));
int DiffZ = (int)(floor(GetPosZ() * 32.0) - floor(m_LastPos.z * 32.0));
- if ((abs(DiffX) >= 4) || (abs(DiffY) >= 4) || (abs(DiffZ) >= 4))
+ if ((abs(DiffX) != 0) || (abs(DiffY) != 0) || (abs(DiffZ) != 0)) // Have we moved?
{
if ((abs(DiffX) <= 127) && (abs(DiffY) <= 127) && (abs(DiffZ) <= 127)) // Limitations of a Byte
{
diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h
index 0785b5609..22b133fb7 100644
--- a/src/Entities/Entity.h
+++ b/src/Entities/Entity.h
@@ -419,19 +419,26 @@ protected:
/// The entity which is attached to this entity (rider), NULL if none
cEntity * m_Attachee;
- // Flags that signal that we haven't updated the clients with the latest.
+ /** Stores whether head yaw has been set manually */
bool m_bDirtyHead;
+ /** Stores whether our yaw/pitch/roll (body orientation) has been set manually */
bool m_bDirtyOrientation;
+ /** Stores whether we have sent a Velocity packet with a speed of zero (no speed) to the client
+ Ensures that said packet is sent only once */
bool m_bHasSentNoSpeed;
+ /** Stores if the entity is on the ground */
bool m_bOnGround;
+ /** Stores gravity that is applied to an entity every tick
+ For realistic effects, this should be negative. For spaaaaaaace, this can be zero or even positive */
float m_Gravity;
/** Last position sent to client via the Relative Move or Teleport packets (not Velocity)
Only updated if cEntity::BroadcastMovementUpdate() is called! */
Vector3d m_LastPos;
- bool m_IsInitialized; // Is set to true when it's initialized, until it's destroyed (Initialize() till Destroy() )
+ /** True when entity is initialised (Initialize()) and false when destroyed pending deletion (Destroy()) */
+ bool m_IsInitialized;
eEntityType m_EntityType;
--
cgit v1.2.3
From 15767badac8f1832dad93afa39b4678f611ce697 Mon Sep 17 00:00:00 2001
From: Tiger Wang
Date: Sat, 26 Apr 2014 23:52:18 +0100
Subject: A tiny speed improvement in ApplyFoodExhaustion()
---
src/Entities/Player.cpp | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp
index a7b1dd74e..b43205226 100644
--- a/src/Entities/Player.cpp
+++ b/src/Entities/Player.cpp
@@ -1848,16 +1848,16 @@ void cPlayer::ApplyFoodExhaustionFromMovement()
{
return;
}
-
- // Calculate the distance travelled, update the last pos:
- Vector3d Movement(GetPosition() - m_LastPos);
- Movement.y = 0; // Only take XZ movement into account
-
+
// If riding anything, apply no food exhaustion
if (m_AttachedTo != NULL)
{
return;
}
+
+ // Calculate the distance travelled, update the last pos:
+ Vector3d Movement(GetPosition() - m_LastPos);
+ Movement.y = 0; // Only take XZ movement into account
// Apply the exhaustion based on distance travelled:
double BaseExhaustion = Movement.Length();
--
cgit v1.2.3
From dcb2a590e364301aa1919546ad33a33e5dc34042 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 06:45:33 -0700
Subject: Fixed bad merge
---
src/Chunk.cpp | 22 +++++++++-------------
1 file changed, 9 insertions(+), 13 deletions(-)
diff --git a/src/Chunk.cpp b/src/Chunk.cpp
index 5a82ca66a..6b0058303 100644
--- a/src/Chunk.cpp
+++ b/src/Chunk.cpp
@@ -1468,7 +1468,7 @@ void cChunk::QueueTickBlock(int a_RelX, int a_RelY, int a_RelZ)
return;
}
- m_ToTickBlocks.push_back(MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ));
+ m_ToTickBlocks.push_back(Vector3i(a_RelX, a_RelY, a_RelZ));
}
@@ -1531,7 +1531,7 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, a_BlockType, a_BlockMeta));
}
- SetNibble(m_BlockMeta, index, a_BlockMeta);
+ m_ChunkBuffer.SetMeta(a_RelX, a_RelY, a_RelZ, a_BlockMeta);
// ONLY recalculate lighting if it's necessary!
if (
@@ -1554,7 +1554,7 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
{
for (int y = a_RelY - 1; y > 0; --y)
{
- if (GetBlock(MakeIndexNoCheck(a_RelX, y, a_RelZ)) != E_BLOCK_AIR)
+ if (GetBlock(a_RelX, y, a_RelZ) != E_BLOCK_AIR)
{
m_HeightMap[a_RelX + a_RelZ * Width] = (unsigned char)y;
break;
@@ -1570,19 +1570,16 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
void cChunk::SendBlockTo(int a_RelX, int a_RelY, int a_RelZ, cClientHandle * a_Client)
{
- // The coords must be valid, because the upper level already does chunk lookup. No need to check them again.
- // There's an debug-time assert in MakeIndexNoCheck anyway
- unsigned int index = MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
if (a_Client == NULL)
{
// Queue the block for all clients in the chunk (will be sent in Tick())
- m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, GetBlock(index), GetMeta(index)));
+ m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, GetBlock(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ)));
return;
}
Vector3i wp = PositionToWorldPosition(a_RelX, a_RelY, a_RelZ);
- a_Client->SendBlockChange(wp.x, wp.y, wp.z, GetBlock(index), GetMeta(index));
+ a_Client->SendBlockChange(wp.x, wp.y, wp.z, GetBlock(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ));
// FS #268 - if a BlockEntity digging is cancelled by a plugin, the entire block entity must be re-sent to the client:
for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), end = m_BlockEntities.end(); itr != end; ++itr)
@@ -2460,11 +2457,10 @@ void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_
void cChunk::GetBlockInfo(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight)
{
- int Idx = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
- a_BlockType = GetBlock(Idx);
- a_Meta = cChunkDef::GetNibble(m_BlockMeta, Idx);
- a_SkyLight = cChunkDef::GetNibble(m_BlockSkyLight, Idx);
- a_BlockLight = cChunkDef::GetNibble(m_BlockLight, Idx);
+ a_BlockType = GetBlock(a_RelX, a_RelY, a_RelZ);
+ a_Meta = m_ChunkBuffer.GetMeta(a_RelX, a_RelY, a_RelZ);
+ a_SkyLight = m_ChunkBuffer.GetSkyLight(a_RelX, a_RelY, a_RelZ);
+ a_BlockLight = m_ChunkBuffer.GetBlockLight(a_RelX, a_RelY, a_RelZ);
}
--
cgit v1.2.3
From e3bdc81ca04fbad284eb0c3b53678f0fb357eb64 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 06:46:13 -0700
Subject: Fixed MobProximity Counter to remove chunk copys
---
src/MobProximityCounter.cpp | 5 ++---
src/MobProximityCounter.h | 4 ++--
2 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/src/MobProximityCounter.cpp b/src/MobProximityCounter.cpp
index c7e91e18b..ce20bf56b 100644
--- a/src/MobProximityCounter.cpp
+++ b/src/MobProximityCounter.cpp
@@ -24,8 +24,7 @@ void cMobProximityCounter::CollectMob(cEntity& a_Monster, cChunk& a_Chunk, doubl
if (a_Distance < it->second.m_Distance)
{
it->second.m_Distance = a_Distance;
- ASSERT(false);
- //it->second.m_Chunk = a_Chunk;
+ it->second.m_Chunk = &a_Chunk;
}
}
@@ -37,7 +36,7 @@ void cMobProximityCounter::convertMaps()
{
for(tMonsterToDistance::const_iterator itr = m_MonsterToDistance.begin(); itr != m_MonsterToDistance.end(); ++itr)
{
- m_DistanceToMonster.insert(tDistanceToMonster::value_type(itr->second.m_Distance,sMonsterAndChunk(*itr->first,itr->second.m_Chunk)));
+ m_DistanceToMonster.insert(tDistanceToMonster::value_type(itr->second.m_Distance,sMonsterAndChunk(*itr->first,*itr->second.m_Chunk)));
}
}
diff --git a/src/MobProximityCounter.h b/src/MobProximityCounter.h
index 8a67139aa..79429eb60 100644
--- a/src/MobProximityCounter.h
+++ b/src/MobProximityCounter.h
@@ -16,9 +16,9 @@ protected :
// structs used for later maps (see m_MonsterToDistance and m_DistanceToMonster)
struct sDistanceAndChunk
{
- sDistanceAndChunk(double a_Distance, cChunk& a_Chunk) : m_Distance(a_Distance), m_Chunk(a_Chunk) {}
+ sDistanceAndChunk(double a_Distance, cChunk& a_Chunk) : m_Distance(a_Distance), m_Chunk(&a_Chunk) {}
double m_Distance;
- cChunk& m_Chunk;
+ cChunk* m_Chunk;
};
struct sMonsterAndChunk
{
--
cgit v1.2.3
From 2730a41946b5236894d65ec9cc001ed41b6a5589 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 07:10:30 -0700
Subject: Fixed issues with gcc
---
src/ChunkBuffer.h | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)
diff --git a/src/ChunkBuffer.h b/src/ChunkBuffer.h
index 44e447c82..a6a6da013 100644
--- a/src/ChunkBuffer.h
+++ b/src/ChunkBuffer.h
@@ -36,8 +36,8 @@ public:
#if __cplusplus < 201103L
// auto_ptr style interface for memory management
- cChunkBuffer(cChunkBuffer& other) :
- IsOwner(true);
+ cChunkBuffer(const cChunkBuffer& other) :
+ IsOwner(true)
{
for (int i = 0; i < CHUNK_SECTION_NUM; i++)
{
@@ -45,7 +45,8 @@ public:
}
other.IsOwner = false;
}
- void operator=(cChunkBuffer& other)
+
+ void operator=(const cChunkBuffer& other)
{
if(IsOwner)
{
@@ -63,7 +64,7 @@ public:
}
#else
// unique_ptr style interface for memory management
- cChunkBuffer(cChunkBuffer&& other)
+ cChunkBuffer(const cChunkBuffer&& other)
{
for (int i = 0; i < CHUNK_SECTION_NUM; i++)
{
@@ -71,7 +72,7 @@ public:
}
}
- void operator=(cChunkBuffer&& other)
+ void operator=(const cChunkBuffer&& other)
{
for (int i = 0; i < CHUNK_SECTION_NUM; i++)
{
@@ -225,7 +226,7 @@ private:
#if __cplusplus < 201103L
// auto_ptr style interface for memory management
- bool IsOwner;
+ mutable bool IsOwner;
#endif
struct sChunkSection {
--
cgit v1.2.3
From 48a2488477023b5427381863585fd1448743d32e Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 07:38:16 -0700
Subject: Added other half of implementation
---
src/ChunkBuffer.cpp | 147 +++++++++++++++++++++++++++++++++++++++++++++++-----
1 file changed, 133 insertions(+), 14 deletions(-)
diff --git a/src/ChunkBuffer.cpp b/src/ChunkBuffer.cpp
index 8e87d3049..7946fba1e 100644
--- a/src/ChunkBuffer.cpp
+++ b/src/ChunkBuffer.cpp
@@ -22,7 +22,7 @@ cChunkBuffer cChunkBuffer::Copy() const
void cChunkBuffer::CopyBlocks (BLOCKTYPE * a_dest, size_t a_Idx, size_t length) const
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16;
if (a_Idx > 0) a_Idx = a_Idx > length ? a_Idx - length : 0;
@@ -30,7 +30,22 @@ void cChunkBuffer::CopyBlocks (BLOCKTYPE * a_dest, size_t a_Idx, size_t length
{
size_t tocopy = length > segment_length ? segment_length : length;
length -= tocopy;
- memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockTypes, sizeof(BLOCKTYPE) * length);
+ if(m_Sections[i])
+ {
+ memcpy(
+ &a_dest[i * segment_length],
+ &m_Sections[i]->m_BlockTypes,
+ sizeof(BLOCKTYPE) * length
+ );
+ }
+ else
+ {
+ memset(
+ &a_dest[i * segment_length],
+ 0,
+ sizeof(BLOCKTYPE) * length
+ );
+ }
}
}
}
@@ -41,10 +56,24 @@ void cChunkBuffer::CopyBlocks (BLOCKTYPE * a_dest, size_t a_Idx, size_t length
void cChunkBuffer::CopyMeta(NIBBLETYPE * a_dest) const
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
- memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockMeta, sizeof(NIBBLETYPE) * segment_length);
+ if(m_Sections[i])
+ {
+ memcpy(
+ &a_dest[i * segment_length],
+ &m_Sections[i]->m_BlockMeta,
+ sizeof(NIBBLETYPE) * segment_length);
+ }
+ else
+ {
+ memset(
+ &a_dest[i * segment_length],
+ 0,
+ sizeof(BLOCKTYPE) * segment_length
+ );
+ }
}
}
@@ -54,10 +83,25 @@ void cChunkBuffer::CopyMeta(NIBBLETYPE * a_dest) const
void cChunkBuffer::CopyLight(NIBBLETYPE * a_dest) const
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
- memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockLight, sizeof(NIBBLETYPE) * segment_length);
+ if(m_Sections[i])
+ {
+ memcpy(
+ &a_dest[i * segment_length],
+ &m_Sections[i]->m_BlockLight,
+ sizeof(NIBBLETYPE) * segment_length
+ );
+ }
+ else
+ {
+ memset(
+ &a_dest[i * segment_length],
+ 0,
+ sizeof(BLOCKTYPE) * segment_length
+ );
+ }
}
}
@@ -67,10 +111,25 @@ void cChunkBuffer::CopyLight(NIBBLETYPE * a_dest) const
void cChunkBuffer::CopySkyLight(NIBBLETYPE * a_dest) const
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
- memcpy(&a_dest[i * segment_length], &m_Sections[i]->m_BlockSkyLight, sizeof(NIBBLETYPE) * segment_length);
+ if(m_Sections[i])
+ {
+ memcpy(
+ &a_dest[i * segment_length],
+ &m_Sections[i]->m_BlockSkyLight,
+ sizeof(NIBBLETYPE) * segment_length
+ );
+ }
+ else
+ {
+ memset(
+ &a_dest[i * segment_length],
+ 0xFF,
+ sizeof(BLOCKTYPE) * segment_length
+ );
+ }
}
}
@@ -80,13 +139,28 @@ void cChunkBuffer::CopySkyLight(NIBBLETYPE * a_dest) const
void cChunkBuffer::SetBlocks(const BLOCKTYPE * a_src)
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
if (m_Sections[i])
{
memcpy(&m_Sections[i]->m_BlockTypes, &a_src[i * segment_length], sizeof(BLOCKTYPE) * segment_length);
}
+ else
+ {
+ size_t j = 0;
+ // do nothing whilst 0
+ for (; j < segment_length && a_src[i * segment_length + j] == 0; j++);
+ if (j != segment_length)
+ {
+ m_Sections[i] = Allocate();
+ memcpy(
+ &m_Sections[i]->m_BlockTypes,
+ &a_src[i * segment_length],
+ sizeof(BLOCKTYPE) * segment_length
+ );
+ }
+ }
}
}
@@ -95,13 +169,28 @@ void cChunkBuffer::SetBlocks(const BLOCKTYPE * a_src)
void cChunkBuffer::SetMeta(const NIBBLETYPE * a_src)
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
if (m_Sections[i])
{
memcpy(&m_Sections[i]->m_BlockMeta, &a_src[i * segment_length], sizeof(NIBBLETYPE) * segment_length);
}
+ else
+ {
+ size_t j = 0;
+ // do nothing whilst 0
+ for (; j < segment_length && a_src[i * segment_length + j] == 0; j++);
+ if (j != segment_length)
+ {
+ m_Sections[i] = Allocate();
+ memcpy(
+ &m_Sections[i]->m_BlockTypes,
+ &a_src[i * segment_length],
+ sizeof(BLOCKTYPE) * segment_length
+ );
+ }
+ }
}
}
@@ -110,14 +199,29 @@ void cChunkBuffer::SetMeta(const NIBBLETYPE * a_src)
void cChunkBuffer::SetLight(const NIBBLETYPE * a_src)
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
if (m_Sections[i])
{
memcpy(&m_Sections[i]->m_BlockLight, &a_src[i * segment_length], sizeof(NIBBLETYPE) * segment_length);
}
- }
+ else
+ {
+ size_t j = 0;
+ // do nothing whilst 0
+ for (; j < segment_length && a_src[i * segment_length + j] == 0; j++);
+ if (j != segment_length)
+ {
+ m_Sections[i] = Allocate();
+ memcpy(
+ &m_Sections[i]->m_BlockTypes,
+ &a_src[i * segment_length],
+ sizeof(BLOCKTYPE) * segment_length
+ );
+ }
+ }
+ }
}
@@ -125,14 +229,29 @@ void cChunkBuffer::SetLight(const NIBBLETYPE * a_src)
void cChunkBuffer::SetSkyLight (const NIBBLETYPE * a_src)
{
- for (int i = 0; i < CHUNK_SECTION_NUM; i++)
+ for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
if (m_Sections[i])
{
memcpy(&m_Sections[i]->m_BlockSkyLight, &a_src[i * segment_length], sizeof(NIBBLETYPE) * segment_length);
}
- }
+ else
+ {
+ size_t j = 0;
+ // do nothing whilst 0
+ for (; j < segment_length && a_src[i * segment_length + j] == 0xFF; j++);
+ if (j != segment_length)
+ {
+ m_Sections[i] = Allocate();
+ memcpy(
+ &m_Sections[i]->m_BlockTypes,
+ &a_src[i * segment_length],
+ sizeof(BLOCKTYPE) * segment_length
+ );
+ }
+ }
+ }
}
--
cgit v1.2.3
From d412630904c1de6c0d9ef00fbc75b5558f931e8b Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 08:11:56 -0700
Subject: Fixed a couple of segfaults and made Free a seperate function
---
src/ChunkBuffer.cpp | 38 +++++++++++++++++++++++++++++++++++---
src/ChunkBuffer.h | 7 ++++---
2 files changed, 39 insertions(+), 6 deletions(-)
diff --git a/src/ChunkBuffer.cpp b/src/ChunkBuffer.cpp
index 7946fba1e..a41b8f61a 100644
--- a/src/ChunkBuffer.cpp
+++ b/src/ChunkBuffer.cpp
@@ -160,6 +160,11 @@ void cChunkBuffer::SetBlocks(const BLOCKTYPE * a_src)
sizeof(BLOCKTYPE) * segment_length
);
}
+ else
+ {
+ Free(m_Sections[i]);
+ m_Sections[i] = 0;
+ }
}
}
}
@@ -185,11 +190,16 @@ void cChunkBuffer::SetMeta(const NIBBLETYPE * a_src)
{
m_Sections[i] = Allocate();
memcpy(
- &m_Sections[i]->m_BlockTypes,
+ &m_Sections[i]->m_BlockMeta,
&a_src[i * segment_length],
sizeof(BLOCKTYPE) * segment_length
);
}
+ else
+ {
+ Free(m_Sections[i]);
+ m_Sections[i] = 0;
+ }
}
}
}
@@ -199,6 +209,7 @@ void cChunkBuffer::SetMeta(const NIBBLETYPE * a_src)
void cChunkBuffer::SetLight(const NIBBLETYPE * a_src)
{
+ if (!a_src) return;
for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
@@ -215,11 +226,16 @@ void cChunkBuffer::SetLight(const NIBBLETYPE * a_src)
{
m_Sections[i] = Allocate();
memcpy(
- &m_Sections[i]->m_BlockTypes,
+ &m_Sections[i]->m_BlockLight,
&a_src[i * segment_length],
sizeof(BLOCKTYPE) * segment_length
);
}
+ else
+ {
+ Free(m_Sections[i]);
+ m_Sections[i] = 0;
+ }
}
}
}
@@ -229,6 +245,7 @@ void cChunkBuffer::SetLight(const NIBBLETYPE * a_src)
void cChunkBuffer::SetSkyLight (const NIBBLETYPE * a_src)
{
+ if (!a_src) return;
for (size_t i = 0; i < CHUNK_SECTION_NUM; i++)
{
const size_t segment_length = CHUNK_SECTION_HEIGHT * 16 * 16 / 2;
@@ -245,11 +262,16 @@ void cChunkBuffer::SetSkyLight (const NIBBLETYPE * a_src)
{
m_Sections[i] = Allocate();
memcpy(
- &m_Sections[i]->m_BlockTypes,
+ &m_Sections[i]->m_BlockSkyLight,
&a_src[i * segment_length],
sizeof(BLOCKTYPE) * segment_length
);
}
+ else
+ {
+ Free(m_Sections[i]);
+ m_Sections[i] = 0;
+ }
}
}
}
@@ -263,3 +285,13 @@ cChunkBuffer::sChunkSection * cChunkBuffer::Allocate() const
// TODO: use a allocation pool
return new cChunkBuffer::sChunkSection;
}
+
+
+
+void cChunkBuffer::Free(cChunkBuffer::sChunkSection * ptr) const
+{
+ delete ptr;
+}
+
+
+
diff --git a/src/ChunkBuffer.h b/src/ChunkBuffer.h
index a6a6da013..c23f8971d 100644
--- a/src/ChunkBuffer.h
+++ b/src/ChunkBuffer.h
@@ -30,7 +30,7 @@ public:
#endif
for (int i = 0; i < CHUNK_SECTION_NUM; i++)
{
- if(m_Sections[i]) delete m_Sections[i];
+ if(m_Sections[i]) Free(m_Sections[i]);;
}
}
@@ -52,7 +52,7 @@ public:
{
for (int i = 0; i < CHUNK_SECTION_NUM; i++)
{
- if(m_Sections[i]) delete m_Sections[i];
+ if(m_Sections[i]) Free(m_Sections[i]);;
}
}
IsOwner = true;
@@ -76,7 +76,7 @@ public:
{
for (int i = 0; i < CHUNK_SECTION_NUM; i++)
{
- if(m_Sections[i]) delete m_Sections[i];
+ if(m_Sections[i]) Free(m_Sections[i]);;
m_Sections[i] = other.m_Sections[i];
}
}
@@ -239,6 +239,7 @@ private:
sChunkSection *m_Sections[CHUNK_SECTION_NUM];
sChunkSection * Allocate() const;
+ void Free(sChunkSection * ptr) const;
};
--
cgit v1.2.3
From 6f1fea759e3595d5538330ecf8f05b8edcf0882e Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 08:14:56 -0700
Subject: Fixed bad comment
---
src/BlockArea.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index b4b519bc7..68976ab7a 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -1911,7 +1911,7 @@ bool cBlockArea::cChunkReader::Coords(int a_ChunkX, int a_ChunkZ)
void cBlockArea::cChunkReader::ChunkBuffer(const cChunkBuffer & a_BlockBuffer)
{
- { // BlockTypes
+ {
if (!(m_Area.m_BlockTypes == NULL))
{
int SizeY = m_Area.m_Size.y;
--
cgit v1.2.3
From bbc5faa723b7dd63250949f7b28601ffd748e2f5 Mon Sep 17 00:00:00 2001
From: Tiger Wang
Date: Sun, 27 Apr 2014 17:35:41 +0100
Subject: Redstone simulator now directly accesses cChunk
* Redstone simulator performance improvements
* Added return values to some functions
* Minor fixes
---
src/Chunk.cpp | 20 +-
src/Chunk.h | 9 +-
src/ChunkMap.cpp | 2 -
src/ClientHandle.cpp | 3 +-
src/Entities/Entity.cpp | 1 +
src/Entities/FallingBlock.cpp | 3 +-
src/Mobs/AggressiveMonster.cpp | 5 +-
src/Simulator/IncrementalRedstoneSimulator.cpp | 926 ++++++++++++++-----------
src/Simulator/IncrementalRedstoneSimulator.h | 68 +-
src/World.h | 2 +-
10 files changed, 586 insertions(+), 453 deletions(-)
diff --git a/src/Chunk.cpp b/src/Chunk.cpp
index cd3bceda2..053648262 100644
--- a/src/Chunk.cpp
+++ b/src/Chunk.cpp
@@ -749,7 +749,7 @@ void cChunk::ProcessQueuedSetBlocks(void)
{
if (itr->m_Tick <= CurrTick)
{
- if (itr->m_PreviousType != E_BLOCK_AIR) // PreviousType defaults to -1 if not specified
+ if (itr->m_PreviousType != E_BLOCK_AIR) // PreviousType defaults to 0 if not specified
{
if (GetBlock(itr->m_RelX, itr->m_RelY, itr->m_RelZ) == itr->m_PreviousType)
{
@@ -1638,6 +1638,24 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT
+void cChunk::SetMeta(int a_BlockIdx, NIBBLETYPE a_Meta)
+{
+ if (GetNibble(m_BlockMeta, a_BlockIdx) == a_Meta)
+ {
+ return;
+ }
+
+ MarkDirty();
+ SetNibble(m_BlockMeta, a_BlockIdx, a_Meta);
+ Vector3i Coords(IndexToCoordinate(a_BlockIdx));
+
+ m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, Coords.x, Coords.y, Coords.z, GetBlock(a_BlockIdx), a_Meta));
+}
+
+
+
+
+
void cChunk::SendBlockTo(int a_RelX, int a_RelY, int a_RelZ, cClientHandle * a_Client)
{
// The coords must be valid, because the upper level already does chunk lookup. No need to check them again.
diff --git a/src/Chunk.h b/src/Chunk.h
index a15d43e00..84ec35496 100644
--- a/src/Chunk.h
+++ b/src/Chunk.h
@@ -320,10 +320,10 @@ public:
m_BlockTickZ = a_RelZ;
}
- inline NIBBLETYPE GetMeta(int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockMeta, a_RelX, a_RelY, a_RelZ); }
- inline NIBBLETYPE GetMeta(int a_BlockIdx) const {return cChunkDef::GetNibble(m_BlockMeta, a_BlockIdx); }
- inline void SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Meta) { cChunkDef::SetNibble(m_BlockMeta, a_RelX, a_RelY, a_RelZ, a_Meta); }
- inline void SetMeta(int a_BlockIdx, NIBBLETYPE a_Meta) { cChunkDef::SetNibble(m_BlockMeta, a_BlockIdx, a_Meta); }
+ inline NIBBLETYPE GetMeta(int a_RelX, int a_RelY, int a_RelZ) const { return cChunkDef::GetNibble(m_BlockMeta, a_RelX, a_RelY, a_RelZ); }
+ inline NIBBLETYPE GetMeta(int a_BlockIdx) const { return cChunkDef::GetNibble(m_BlockMeta, a_BlockIdx); }
+ inline void SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Meta) { SetMeta(MakeIndex(a_RelX, a_RelY, a_RelZ), a_Meta); }
+ void SetMeta(int a_BlockIdx, NIBBLETYPE a_Meta);
inline NIBBLETYPE GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockLight, a_RelX, a_RelY, a_RelZ); }
inline NIBBLETYPE GetSkyLight (int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockSkyLight, a_RelX, a_RelY, a_RelZ, true); }
@@ -420,7 +420,6 @@ private:
cWorld * m_World;
cChunkMap * m_ChunkMap;
- // TODO: Make these pointers and don't allocate what isn't needed
COMPRESSED_BLOCKTYPE m_BlockTypes;
COMPRESSED_NIBBLETYPE m_BlockMeta;
COMPRESSED_NIBBLETYPE m_BlockLight;
diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp
index 0fb6988b5..193937278 100644
--- a/src/ChunkMap.cpp
+++ b/src/ChunkMap.cpp
@@ -1248,8 +1248,6 @@ void cChunkMap::SetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYP
if ((Chunk != NULL) && Chunk->IsValid())
{
Chunk->SetMeta(a_BlockX, a_BlockY, a_BlockZ, a_BlockMeta);
- Chunk->MarkDirty();
- Chunk->SendBlockTo(a_BlockX, a_BlockY, a_BlockZ, NULL);
}
}
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index fc3f98aaf..8dddef7f8 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -202,7 +202,7 @@ AString cClientHandle::FormatMessageType(bool ShouldAppendChatPrefixes, eMessage
{
switch (a_ChatPrefix)
{
- case mtCustom: return AString();
+ case mtCustom: return "";
case mtFailure: return FormatChatPrefix(ShouldAppendChatPrefixes, "INFO", cChatColor::Rose, cChatColor::White);
case mtInformation: return FormatChatPrefix(ShouldAppendChatPrefixes, "INFO", cChatColor::Yellow, cChatColor::White);
case mtSuccess: return FormatChatPrefix(ShouldAppendChatPrefixes, "INFO", cChatColor::Green, cChatColor::White);
@@ -220,6 +220,7 @@ AString cClientHandle::FormatMessageType(bool ShouldAppendChatPrefixes, eMessage
}
}
ASSERT(!"Unhandled chat prefix type!");
+ return "";
}
diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp
index 7c8e18b51..7a301a5b7 100644
--- a/src/Entities/Entity.cpp
+++ b/src/Entities/Entity.cpp
@@ -441,6 +441,7 @@ bool cEntity::ArmorCoversAgainst(eDamageType a_DamageType)
}
}
ASSERT(!"Invalid damage type!");
+ return false;
}
diff --git a/src/Entities/FallingBlock.cpp b/src/Entities/FallingBlock.cpp
index bcdac0291..86720ac94 100644
--- a/src/Entities/FallingBlock.cpp
+++ b/src/Entities/FallingBlock.cpp
@@ -88,8 +88,7 @@ void cFallingBlock::Tick(float a_Dt, cChunk & a_Chunk)
AddPosition(GetSpeed() * MilliDt);
// If not static (One billionth precision) broadcast movement.
- static const float epsilon = 0.000000001;
- if ((fabs(GetSpeedX()) > epsilon) || (fabs(GetSpeedZ()) > epsilon))
+ if ((fabs(GetSpeedX()) > std::numeric_limits::epsilon()) || (fabs(GetSpeedZ()) > std::numeric_limits::epsilon()))
{
BroadcastMovementUpdate();
}
diff --git a/src/Mobs/AggressiveMonster.cpp b/src/Mobs/AggressiveMonster.cpp
index 3e5f72dbf..85b122034 100644
--- a/src/Mobs/AggressiveMonster.cpp
+++ b/src/Mobs/AggressiveMonster.cpp
@@ -108,14 +108,13 @@ void cAggressiveMonster::Attack(float a_Dt)
bool cAggressiveMonster::IsMovingToTargetPosition()
{
- float epsilon = 0.000000000001;
// Difference between destination x and target x is negligible (to 10^-12 precision)
- if (fabsf((float)m_FinalDestination.x - (float)m_Target->GetPosX()) < epsilon)
+ if (fabsf((float)m_FinalDestination.x - (float)m_Target->GetPosX()) < std::numeric_limits::epsilon())
{
return false;
}
// Difference between destination z and target z is negligible (to 10^-12 precision)
- else if (fabsf(m_FinalDestination.z - (float)m_Target->GetPosZ()) > epsilon)
+ else if (fabsf((float)m_FinalDestination.z - (float)m_Target->GetPosZ()) > std::numeric_limits::epsilon())
{
return false;
}
diff --git a/src/Simulator/IncrementalRedstoneSimulator.cpp b/src/Simulator/IncrementalRedstoneSimulator.cpp
index d37d2eecf..5ac48d328 100644
--- a/src/Simulator/IncrementalRedstoneSimulator.cpp
+++ b/src/Simulator/IncrementalRedstoneSimulator.cpp
@@ -139,14 +139,14 @@ void cIncrementalRedstoneSimulator::RedstoneAddBlock(int a_BlockX, int a_BlockY,
SimulatedPlayerToggleableList * SimulatedPlayerToggleableBlocks = a_Chunk->GetRedstoneSimulatorSimulatedPlayerToggleableList();
for (SimulatedPlayerToggleableList::iterator itr = SimulatedPlayerToggleableBlocks->begin(); itr != SimulatedPlayerToggleableBlocks->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_RelBlockPos.Equals(Vector3i(RelX, a_BlockY, RelZ)))
{
continue;
}
if (!IsAllowedBlock(Block))
{
- LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from toggleable simulated list as it is no longer redstone", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z);
+ LOGD("cIncrementalRedstoneSimulator: Erased block @ {%i, %i, %i} from toggleable simulated list as it is no longer redstone", itr->a_RelBlockPos.x, itr->a_RelBlockPos.y, itr->a_RelBlockPos.z);
SimulatedPlayerToggleableBlocks->erase(itr);
break;
}
@@ -155,7 +155,7 @@ void cIncrementalRedstoneSimulator::RedstoneAddBlock(int a_BlockX, int a_BlockY,
RepeatersDelayList * RepeatersDelayList = a_Chunk->GetRedstoneSimulatorRepeatersDelayList();
for (RepeatersDelayList::iterator itr = RepeatersDelayList->begin(); itr != RepeatersDelayList->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_RelBlockPos.Equals(Vector3i(RelX, a_BlockY, RelZ)))
{
continue;
}
@@ -221,9 +221,6 @@ void cIncrementalRedstoneSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int
m_LinkedPoweredBlocks = a_Chunk->GetRedstoneSimulatorLinkedBlocksList();
m_Chunk = a_Chunk;
- int BaseX = a_Chunk->GetPosX() * cChunkDef::Width;
- int BaseZ = a_Chunk->GetPosZ() * cChunkDef::Width;
-
for (cRedstoneSimulatorChunkData::iterator dataitr = m_RedstoneSimulatorChunkData->begin(); dataitr != m_RedstoneSimulatorChunkData->end();)
{
if (dataitr->DataTwo)
@@ -232,67 +229,65 @@ void cIncrementalRedstoneSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int
continue;
}
- int a_X = BaseX + dataitr->x;
- int a_Z = BaseZ + dataitr->z;
switch (dataitr->Data)
{
- case E_BLOCK_BLOCK_OF_REDSTONE: HandleRedstoneBlock(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_LEVER: HandleRedstoneLever(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_FENCE_GATE: HandleFenceGate(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_TNT: HandleTNT(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_TRAPDOOR: HandleTrapdoor(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_REDSTONE_WIRE: HandleRedstoneWire(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_NOTE_BLOCK: HandleNoteBlock(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_DAYLIGHT_SENSOR: HandleDaylightSensor(a_X, dataitr->y, a_Z); break;
- case E_BLOCK_COMMAND_BLOCK: HandleCommandBlock(a_X, dataitr->y, a_Z); break;
+ case E_BLOCK_BLOCK_OF_REDSTONE: HandleRedstoneBlock(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_LEVER: HandleRedstoneLever(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_FENCE_GATE: HandleFenceGate(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_TNT: HandleTNT(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_TRAPDOOR: HandleTrapdoor(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_REDSTONE_WIRE: HandleRedstoneWire(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_NOTE_BLOCK: HandleNoteBlock(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_DAYLIGHT_SENSOR: HandleDaylightSensor(dataitr->x, dataitr->y, dataitr->z); break;
+ case E_BLOCK_COMMAND_BLOCK: HandleCommandBlock(dataitr->x, dataitr->y, dataitr->z); break;
case E_BLOCK_REDSTONE_TORCH_OFF:
case E_BLOCK_REDSTONE_TORCH_ON:
{
- HandleRedstoneTorch(a_X, dataitr->y, a_Z, dataitr->Data);
+ HandleRedstoneTorch(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_STONE_BUTTON:
case E_BLOCK_WOODEN_BUTTON:
{
- HandleRedstoneButton(a_X, dataitr->y, a_Z, dataitr->Data);
+ HandleRedstoneButton(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_REDSTONE_REPEATER_OFF:
case E_BLOCK_REDSTONE_REPEATER_ON:
{
- HandleRedstoneRepeater(a_X, dataitr->y, a_Z, dataitr->Data);
+ HandleRedstoneRepeater(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_PISTON:
case E_BLOCK_STICKY_PISTON:
{
- HandlePiston(a_X, dataitr->y, a_Z);
+ HandlePiston(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_REDSTONE_LAMP_OFF:
case E_BLOCK_REDSTONE_LAMP_ON:
{
- HandleRedstoneLamp(a_X, dataitr->y, a_Z, dataitr->Data);
+ HandleRedstoneLamp(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_DISPENSER:
case E_BLOCK_DROPPER:
{
- HandleDropSpenser(a_X, dataitr->y, a_Z);
+ HandleDropSpenser(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_WOODEN_DOOR:
case E_BLOCK_IRON_DOOR:
{
- HandleDoor(a_X, dataitr->y, a_Z);
+ HandleDoor(dataitr->x, dataitr->y, dataitr->z);
break;
}
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_DETECTOR_RAIL:
case E_BLOCK_POWERED_RAIL:
{
- HandleRail(a_X, dataitr->y, a_Z, dataitr->Data);
+ HandleRail(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
case E_BLOCK_WOODEN_PRESSURE_PLATE:
@@ -300,7 +295,7 @@ void cIncrementalRedstoneSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int
case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE:
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
{
- HandlePressurePlate(a_X, dataitr->y, a_Z, dataitr->Data);
+ HandlePressurePlate(dataitr->x, dataitr->y, dataitr->z, dataitr->Data);
break;
}
default: LOGD("Unhandled block (!) or unimplemented redstone block: %s", ItemToString(dataitr->Data).c_str()); break;
@@ -342,7 +337,7 @@ void cIncrementalRedstoneSimulator::WakeUp(int a_BlockX, int a_BlockY, int a_Blo
-void cIncrementalRedstoneSimulator::HandleRedstoneTorch(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyState)
+void cIncrementalRedstoneSimulator::HandleRedstoneTorch(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
static const struct // Define which directions the torch can power
{
@@ -359,54 +354,58 @@ void cIncrementalRedstoneSimulator::HandleRedstoneTorch(int a_BlockX, int a_Bloc
if (a_MyState == E_BLOCK_REDSTONE_TORCH_ON)
{
// Check if the block the torch is on is powered
- int X = a_BlockX; int Y = a_BlockY; int Z = a_BlockZ;
- AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ)), true); // Inverse true to get the block torch is on
+ int X = a_RelBlockX; int Y = a_RelBlockY; int Z = a_RelBlockZ;
+ AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)), true); // Inverse true to get the block torch is on
if (AreCoordsDirectlyPowered(X, Y, Z))
{
// There was a match, torch goes off
- m_World.SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_TORCH_OFF, m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ));
+ m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_TORCH_OFF, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
return;
}
// Torch still on, make all 4(X, Z) + 1(Y) sides powered
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++)
{
- BLOCKTYPE Type = m_World.GetBlock(a_BlockX + gCrossCoords[i].x, a_BlockY + gCrossCoords[i].y, a_BlockZ + gCrossCoords[i].z);
+ BLOCKTYPE Type = 0;
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, Type))
+ {
+ continue;
+ }
if (i + 1 < ARRAYCOUNT(gCrossCoords)) // Sides of torch, not top (top is last)
{
if (
((IsMechanism(Type)) || (Type == E_BLOCK_REDSTONE_WIRE)) && // Is it a mechanism or wire? Not block/other torch etc.
- (!Vector3i(a_BlockX + gCrossCoords[i].x, a_BlockY + gCrossCoords[i].y, a_BlockZ + gCrossCoords[i].z).Equals(Vector3i(X, Y, Z))) // CAN'T power block is that it is on
+ (!Vector3i(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z).Equals(Vector3i(X, Y, Z))) // CAN'T power block is that it is on
)
{
- SetBlockPowered(a_BlockX + gCrossCoords[i].x, a_BlockY + gCrossCoords[i].y, a_BlockZ + gCrossCoords[i].z, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_TORCH_ON);
+ SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
}
else
{
// Top side, power whatever is there, including blocks
- SetBlockPowered(a_BlockX + gCrossCoords[i].x, a_BlockY + gCrossCoords[i].y, a_BlockZ + gCrossCoords[i].z, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_TORCH_ON);
+ SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
// Power all blocks surrounding block above torch
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_YP, E_BLOCK_REDSTONE_TORCH_ON);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YP);
}
}
- if (m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) != 0x5) // Is torch standing on ground? If NOT (i.e. on wall), power block beneath
+ if (m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) != 0x5) // Is torch standing on ground? If NOT (i.e. on wall), power block beneath
{
- BLOCKTYPE Type = m_World.GetBlock(a_BlockX, a_BlockY - 1, a_BlockZ);
+ BLOCKTYPE Type = m_Chunk->GetBlock(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ);
if ((IsMechanism(Type)) || (Type == E_BLOCK_REDSTONE_WIRE)) // Still can't make a normal block powered though!
{
- SetBlockPowered(a_BlockX, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_TORCH_ON);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
}
}
else
{
// Check if the block the torch is on is powered
- int X = a_BlockX; int Y = a_BlockY; int Z = a_BlockZ;
- AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ)), true); // Inverse true to get the block torch is on
+ int X = a_RelBlockX; int Y = a_RelBlockY; int Z = a_RelBlockZ;
+ AddFaceDirection(X, Y, Z, cBlockTorchHandler::MetaDataToDirection(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)), true); // Inverse true to get the block torch is on
// See if off state torch can be turned on again
if (AreCoordsDirectlyPowered(X, Y, Z))
@@ -415,7 +414,7 @@ void cIncrementalRedstoneSimulator::HandleRedstoneTorch(int a_BlockX, int a_Bloc
}
// Block torch on not powered, can be turned on again!
- m_World.SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_TORCH_ON, m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ));
+ m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_TORCH_ON, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
}
}
@@ -423,28 +422,28 @@ void cIncrementalRedstoneSimulator::HandleRedstoneTorch(int a_BlockX, int a_Bloc
-void cIncrementalRedstoneSimulator::HandleRedstoneBlock(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleRedstoneBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_BLOCK_OF_REDSTONE);
- SetBlockPowered(a_BlockX, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_BLOCK_OF_REDSTONE); // Set self as powered
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ); // Set self as powered
}
-void cIncrementalRedstoneSimulator::HandleRedstoneLever(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleRedstoneLever(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- if (IsLeverOn(m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ)))
+ if (IsLeverOn(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_LEVER);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XM, E_BLOCK_LEVER);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XP, E_BLOCK_LEVER);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_YM, E_BLOCK_LEVER);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_YP, E_BLOCK_LEVER);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZM, E_BLOCK_LEVER);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZP, E_BLOCK_LEVER);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YP);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP);
}
}
@@ -452,27 +451,29 @@ void cIncrementalRedstoneSimulator::HandleRedstoneLever(int a_BlockX, int a_Bloc
-void cIncrementalRedstoneSimulator::HandleFenceGate(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleFenceGate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
cChunkInterface ChunkInterface(m_World.GetChunkMap());
- NIBBLETYPE MetaData = ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
+ NIBBLETYPE MetaData = ChunkInterface.GetBlockMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
- if (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ))
+ if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, true))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, MetaData | 0x4);
- m_World.BroadcastSoundParticleEffect(1003, a_BlockX, a_BlockY, a_BlockZ, 0);
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, true);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MetaData | 0x4);
+ m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, false))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, MetaData & 0xFFFFFFFB);
- m_World.BroadcastSoundParticleEffect(1003, a_BlockX, a_BlockY, a_BlockZ, 0);
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, false);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MetaData & 0xFFFFFFFB);
+ m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
@@ -481,18 +482,18 @@ void cIncrementalRedstoneSimulator::HandleFenceGate(int a_BlockX, int a_BlockY,
-void cIncrementalRedstoneSimulator::HandleRedstoneButton(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType)
+void cIncrementalRedstoneSimulator::HandleRedstoneButton(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- if (IsButtonOn(m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ)))
+ if (IsButtonOn(m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, a_BlockType);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XM, a_BlockType);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XP, a_BlockType);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_YM, a_BlockType);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_YP, a_BlockType);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZM, a_BlockType);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZP, a_BlockType);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YP);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP);
}
}
@@ -500,7 +501,7 @@ void cIncrementalRedstoneSimulator::HandleRedstoneButton(int a_BlockX, int a_Blo
-void cIncrementalRedstoneSimulator::HandleRedstoneWire(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleRedstoneWire(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
static const struct // Define which directions the wire can receive power from
{
@@ -535,14 +536,16 @@ void cIncrementalRedstoneSimulator::HandleRedstoneWire(int a_BlockX, int a_Block
// Check to see if directly beside a power source
unsigned char MyPower;
- if (!IsWirePowered(a_BlockX, a_BlockY, a_BlockZ, MyPower))
+ if (!IsWirePowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower))
{
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, 0);
- m_World.WakeUpSimulators(a_BlockX, a_BlockY, a_BlockZ);
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0);
+ m_World.WakeUpSimulators(BlockX, a_RelBlockY, BlockZ);
return;
}
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, MyPower);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
if (MyPower < 1)
{
@@ -555,74 +558,102 @@ void cIncrementalRedstoneSimulator::HandleRedstoneWire(int a_BlockX, int a_Block
{
if ((i >= 4) && (i <= 7)) // If we are currently checking for wire surrounding ourself one block above...
{
- if (cBlockInfo::IsSolid(m_World.GetBlock(a_BlockX, a_BlockY + 1, a_BlockZ))) // If there is something solid above us (wire cut off)...
+ BLOCKTYPE Type = 0;
+ if (a_RelBlockY + 1 >= cChunkDef::Height)
+ {
+ continue;
+ }
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, Type))
+ {
+ continue;
+ }
+ if (cBlockInfo::IsSolid(Type)) // If there is something solid above us (wire cut off)...
{
continue; // We don't receive power from that wire
}
}
else if ((i >= 8) && (i <= 11)) // See above, but this is for wire below us
{
- if (cBlockInfo::IsSolid(m_World.GetBlock(a_BlockX, a_BlockY - 1, a_BlockZ)))
+ BLOCKTYPE Type = 0;
+ if (a_RelBlockY - 1 < 0)
+ {
+ continue;
+ }
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, Type))
+ {
+ continue;
+ }
+ if (cBlockInfo::IsSolid(Type))
{
continue;
}
}
- if (m_World.GetBlock(a_BlockX + gCrossCoords[i].x, a_BlockY + gCrossCoords[i].y, a_BlockZ + gCrossCoords[i].z) == E_BLOCK_REDSTONE_WIRE)
+ BLOCKTYPE Type = 0;
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, Type))
{
- SetBlockPowered(a_BlockX + gCrossCoords[i].x, a_BlockY + gCrossCoords[i].y, a_BlockZ + gCrossCoords[i].z, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
+ continue;
+ }
+ if (Type == E_BLOCK_REDSTONE_WIRE)
+ {
+ SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
}
}
for (size_t i = 0; i < ARRAYCOUNT(gSideCoords); i++) // Look for repeaters immediately surrounding self and try to power them
{
- if (m_World.GetBlock(a_BlockX + gSideCoords[i].x, a_BlockY + gSideCoords[i].y, a_BlockZ + gSideCoords[i].z) == E_BLOCK_REDSTONE_REPEATER_OFF)
+ BLOCKTYPE Type = 0;
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + gSideCoords[i].x, a_RelBlockY + gSideCoords[i].y, a_RelBlockZ + gSideCoords[i].z, Type))
{
- SetBlockPowered(a_BlockX + gSideCoords[i].x, a_BlockY + gSideCoords[i].y, a_BlockZ + gSideCoords[i].z, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
+ continue;
+ }
+ if (Type == E_BLOCK_REDSTONE_REPEATER_OFF)
+ {
+ SetBlockPowered(a_RelBlockX + gSideCoords[i].x, a_RelBlockY + gSideCoords[i].y, a_RelBlockZ + gSideCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
}
}
// Wire still powered, power blocks beneath
- SetBlockPowered(a_BlockX, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_YM, E_BLOCK_REDSTONE_WIRE, MyPower);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_YM, MyPower);
- switch (GetWireDirection(a_BlockX, a_BlockY, a_BlockZ))
+ switch (GetWireDirection(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
case REDSTONE_NONE:
{
- SetBlockPowered(a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetBlockPowered(a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetBlockPowered(a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetBlockPowered(a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
+ SetBlockPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetBlockPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XM, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XP, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZM, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZP, E_BLOCK_REDSTONE_WIRE, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP, MyPower);
break;
}
case REDSTONE_X_POS:
{
- SetBlockPowered(a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XP, E_BLOCK_REDSTONE_WIRE, MyPower);
+ SetBlockPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP, MyPower);
break;
}
case REDSTONE_X_NEG:
{
- SetBlockPowered(a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XM, E_BLOCK_REDSTONE_WIRE, MyPower);
+ SetBlockPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM, MyPower);
break;
}
case REDSTONE_Z_POS:
{
- SetBlockPowered(a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZP, E_BLOCK_REDSTONE_WIRE, MyPower);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP, MyPower);
break;
}
case REDSTONE_Z_NEG:
{
- SetBlockPowered(a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_WIRE, MyPower);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZM, E_BLOCK_REDSTONE_WIRE, MyPower);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MyPower);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM, MyPower);
break;
}
}
@@ -632,7 +663,7 @@ void cIncrementalRedstoneSimulator::HandleRedstoneWire(int a_BlockX, int a_Block
-void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyState)
+void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
/* Repeater Orientation Mini Guide:
===================================
@@ -643,7 +674,7 @@ void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_BlockX, int a_B
X Axis ---->
- Repeater directions, values from a cWorld::GetBlockMeta(a_BlockX , a_BlockY, a_BlockZ) lookup:
+ Repeater directions, values from a cWorld::GetBlockMeta(a_RelBlockX , a_RelBlockY, a_RelBlockZ) lookup:
East (Right) (X+): 0x1
West (Left) (X-): 0x3
@@ -656,25 +687,25 @@ void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_BlockX, int a_B
*/
// Create a variable holding my meta to avoid multiple lookups.
- NIBBLETYPE a_Meta = m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
+ NIBBLETYPE a_Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
bool IsOn = (a_MyState == E_BLOCK_REDSTONE_REPEATER_ON);
- if (!IsRepeaterLocked(a_BlockX, a_BlockY, a_BlockZ, a_Meta)) // If we're locked, change nothing. Otherwise:
+ if (!IsRepeaterLocked(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta)) // If we're locked, change nothing. Otherwise:
{
- bool IsSelfPowered = IsRepeaterPowered(a_BlockX, a_BlockY, a_BlockZ, a_Meta);
+ bool IsSelfPowered = IsRepeaterPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta);
if (IsSelfPowered && !IsOn) // Queue a power change if powered, but not on and not locked.
{
- QueueRepeaterPowerChange(a_BlockX, a_BlockY, a_BlockZ, a_Meta, true);
+ QueueRepeaterPowerChange(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta, true);
}
else if (!IsSelfPowered && IsOn) // Queue a power change if unpowered, on, and not locked.
{
- QueueRepeaterPowerChange(a_BlockX, a_BlockY, a_BlockZ, a_Meta, false);
+ QueueRepeaterPowerChange(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_Meta, false);
}
}
for (RepeatersDelayList::iterator itr = m_RepeatersDelayList->begin(); itr != m_RepeatersDelayList->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
continue;
}
@@ -685,33 +716,33 @@ void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_BlockX, int a_B
{
if (!IsOn)
{
- m_World.SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_REPEATER_ON, a_Meta); // For performance
+ m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_REPEATER_ON, a_Meta); // For performance
}
switch (a_Meta & 0x3) // We only want the direction (bottom) bits
{
case 0x0:
{
- SetBlockPowered(a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_REPEATER_ON);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZM, E_BLOCK_REDSTONE_REPEATER_ON);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZM);
break;
}
case 0x1:
{
- SetBlockPowered(a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_REPEATER_ON);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XP, E_BLOCK_REDSTONE_REPEATER_ON);
+ SetBlockPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XP);
break;
}
case 0x2:
{
- SetBlockPowered(a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_REPEATER_ON);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_ZP, E_BLOCK_REDSTONE_REPEATER_ON);
+ SetBlockPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_ZP);
break;
}
case 0x3:
{
- SetBlockPowered(a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_REPEATER_ON);
- SetDirectionLinkedPowered(a_BlockX, a_BlockY, a_BlockZ, BLOCK_FACE_XM, E_BLOCK_REDSTONE_REPEATER_ON);
+ SetBlockPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ SetDirectionLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, BLOCK_FACE_XM);
break;
}
}
@@ -724,7 +755,7 @@ void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_BlockX, int a_B
{
if (IsOn)
{
- m_World.SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_REPEATER_OFF, a_Meta);
+ m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_REPEATER_OFF, a_Meta);
}
m_RepeatersDelayList->erase(itr); // We can remove off repeaters which don't need further updating
return;
@@ -735,7 +766,7 @@ void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_BlockX, int a_B
// Apparently, incrementing ticks only works reliably here, and not in SimChunk;
// With a world with lots of redstone, the repeaters simply do not delay
// I am confounded to say why. Perhaps optimisation failure.
- LOGD("Incremented a repeater @ {%i %i %i} | Elapsed ticks: %i | Target delay: %i", itr->a_BlockPos.x, itr->a_BlockPos.y, itr->a_BlockPos.z, itr->a_ElapsedTicks, itr->a_DelayTicks);
+ LOGD("Incremented a repeater @ {%i %i %i} | Elapsed ticks: %i | Target delay: %i", itr->a_RelBlockPos.x, itr->a_RelBlockPos.y, itr->a_RelBlockPos.z, itr->a_ElapsedTicks, itr->a_DelayTicks);
itr->a_ElapsedTicks++;
}
}
@@ -745,16 +776,19 @@ void cIncrementalRedstoneSimulator::HandleRedstoneRepeater(int a_BlockX, int a_B
-void cIncrementalRedstoneSimulator::HandlePiston(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandlePiston(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
cPiston Piston(&m_World);
- if (IsPistonPowered(a_BlockX, a_BlockY, a_BlockZ, m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) & 0x7)) // We only want the bottom three bits (4th controls extended-ness)
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+
+ if (IsPistonPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x7)) // We only want the bottom three bits (4th controls extended-ness)
{
- Piston.ExtendPiston(a_BlockX, a_BlockY, a_BlockZ);
+ Piston.ExtendPiston(BlockX, a_RelBlockY, BlockZ);
}
else
{
- Piston.RetractPiston(a_BlockX, a_BlockY, a_BlockZ);
+ Piston.RetractPiston(BlockX, a_RelBlockY, BlockZ);
}
}
@@ -762,7 +796,7 @@ void cIncrementalRedstoneSimulator::HandlePiston(int a_BlockX, int a_BlockY, int
-void cIncrementalRedstoneSimulator::HandleDropSpenser(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleDropSpenser(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cSetPowerToDropSpenser :
public cDropSpenserCallback
@@ -776,29 +810,31 @@ void cIncrementalRedstoneSimulator::HandleDropSpenser(int a_BlockX, int a_BlockY
a_DropSpenser->SetRedstonePower(m_IsPowered);
return false;
}
- } DrSpSP (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ));
+ } DrSpSP (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
- m_World.DoWithDropSpenserAt(a_BlockX, a_BlockY, a_BlockZ, DrSpSP);
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+ m_Chunk->DoWithDropSpenserAt(BlockX, a_RelBlockY, BlockZ, DrSpSP);
}
-void cIncrementalRedstoneSimulator::HandleRedstoneLamp(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyState)
+void cIncrementalRedstoneSimulator::HandleRedstoneLamp(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState)
{
if (a_MyState == E_BLOCK_REDSTONE_LAMP_OFF)
{
- if (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ))
+ if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
- m_World.SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_LAMP_ON, 0);
+ m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_LAMP_ON, 0);
}
}
else
{
- if (!AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ))
+ if (!AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
- m_World.SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_REDSTONE_LAMP_OFF, 0);
+ m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_REDSTONE_LAMP_OFF, 0);
}
}
}
@@ -807,13 +843,16 @@ void cIncrementalRedstoneSimulator::HandleRedstoneLamp(int a_BlockX, int a_Block
-void cIncrementalRedstoneSimulator::HandleTNT(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleTNT(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- if (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ))
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+
+ if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
- m_World.BroadcastSoundEffect("game.tnt.primed", a_BlockX * 8, a_BlockY * 8, a_BlockZ * 8, 0.5f, 0.6f);
- m_World.SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_AIR, 0);
- m_World.SpawnPrimedTNT(a_BlockX + 0.5, a_BlockY + 0.5, a_BlockZ + 0.5); // 80 ticks to boom
+ m_Chunk->BroadcastSoundEffect("game.tnt.primed", BlockX * 8, a_RelBlockY * 8, BlockZ * 8, 0.5f, 0.6f);
+ m_Chunk->SetBlock(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_BLOCK_AIR, 0);
+ m_World.SpawnPrimedTNT(BlockX + 0.5, a_RelBlockY + 0.5, BlockZ + 0.5); // 80 ticks to boom
}
}
@@ -821,26 +860,29 @@ void cIncrementalRedstoneSimulator::HandleTNT(int a_BlockX, int a_BlockY, int a_
-void cIncrementalRedstoneSimulator::HandleDoor(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleDoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- if (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ))
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+
+ if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, true))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
cChunkInterface ChunkInterface(m_World.GetChunkMap());
- cBlockDoorHandler::ChangeDoor(ChunkInterface, a_BlockX, a_BlockY, a_BlockZ);
- m_World.BroadcastSoundParticleEffect(1003, a_BlockX, a_BlockY, a_BlockZ, 0);
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, true);
+ cBlockDoorHandler::ChangeDoor(ChunkInterface, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, false))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
cChunkInterface ChunkInterface(m_World.GetChunkMap());
- cBlockDoorHandler::ChangeDoor(ChunkInterface, a_BlockX, a_BlockY, a_BlockZ);
- m_World.BroadcastSoundParticleEffect(1003, a_BlockX, a_BlockY, a_BlockZ, 0);
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, false);
+ cBlockDoorHandler::ChangeDoor(ChunkInterface, a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ m_Chunk->BroadcastSoundParticleEffect(1003, BlockX, a_RelBlockY, BlockZ, 0);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
@@ -849,7 +891,7 @@ void cIncrementalRedstoneSimulator::HandleDoor(int a_BlockX, int a_BlockY, int a
-void cIncrementalRedstoneSimulator::HandleCommandBlock(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleCommandBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
class cSetPowerToCommandBlock :
public cCommandBlockCallback
@@ -863,37 +905,39 @@ void cIncrementalRedstoneSimulator::HandleCommandBlock(int a_BlockX, int a_Block
a_CommandBlock->SetRedstonePower(m_IsPowered);
return false;
}
- } CmdBlockSP (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ));
+ } CmdBlockSP (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ));
- m_World.DoWithCommandBlockAt(a_BlockX, a_BlockY, a_BlockZ, CmdBlockSP);
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+ m_Chunk->DoWithCommandBlockAt(BlockX, a_RelBlockY, BlockZ, CmdBlockSP);
}
-void cIncrementalRedstoneSimulator::HandleRail(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyType)
+void cIncrementalRedstoneSimulator::HandleRail(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType)
{
switch (a_MyType)
{
case E_BLOCK_DETECTOR_RAIL:
{
- if ((m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) & 0x08) == 0x08)
+ if ((m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x08) == 0x08)
{
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, a_MyType);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_MyType);
}
break;
}
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_POWERED_RAIL:
{
- if (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ))
+ if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) | 0x08);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) | 0x08);
}
else
{
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) & 0x07);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ) & 0x07);
}
break;
}
@@ -905,22 +949,25 @@ void cIncrementalRedstoneSimulator::HandleRail(int a_BlockX, int a_BlockY, int a
-void cIncrementalRedstoneSimulator::HandleTrapdoor(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleTrapdoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- if (AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ))
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+
+ if (AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ))
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, true))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
- m_World.SetTrapdoorOpen(a_BlockX, a_BlockY, a_BlockZ, true);
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, true);
+ m_World.SetTrapdoorOpen(BlockX, a_RelBlockY, BlockZ, true);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, false))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
- m_World.SetTrapdoorOpen(a_BlockX, a_BlockY, a_BlockZ, false);
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, false);
+ m_World.SetTrapdoorOpen(BlockX, a_RelBlockY, BlockZ, false);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
@@ -929,13 +976,13 @@ void cIncrementalRedstoneSimulator::HandleTrapdoor(int a_BlockX, int a_BlockY, i
-void cIncrementalRedstoneSimulator::HandleNoteBlock(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleNoteBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- bool m_bAreCoordsPowered = AreCoordsPowered(a_BlockX, a_BlockY, a_BlockZ);
+ bool m_bAreCoordsPowered = AreCoordsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (m_bAreCoordsPowered)
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, true))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true))
{
class cSetPowerToNoteBlock :
public cNoteBlockCallback
@@ -954,15 +1001,17 @@ void cIncrementalRedstoneSimulator::HandleNoteBlock(int a_BlockX, int a_BlockY,
}
} NoteBlockSP(m_bAreCoordsPowered);
- m_World.DoWithNoteBlockAt(a_BlockX, a_BlockY, a_BlockZ, NoteBlockSP);
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, true);
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+ m_Chunk->DoWithNoteBlockAt(BlockX, a_RelBlockY, BlockZ, NoteBlockSP);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, true);
}
}
else
{
- if (!AreCoordsSimulated(a_BlockX, a_BlockY, a_BlockZ, false))
+ if (!AreCoordsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false))
{
- SetPlayerToggleableBlockAsSimulated(a_BlockX, a_BlockY, a_BlockZ, false);
+ SetPlayerToggleableBlockAsSimulated(a_RelBlockX, a_RelBlockY, a_RelBlockZ, false);
}
}
}
@@ -971,10 +1020,10 @@ void cIncrementalRedstoneSimulator::HandleNoteBlock(int a_BlockX, int a_BlockY,
-void cIncrementalRedstoneSimulator::HandleDaylightSensor(int a_BlockX, int a_BlockY, int a_BlockZ)
+void cIncrementalRedstoneSimulator::HandleDaylightSensor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int a_ChunkX, a_ChunkZ;
- cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, a_ChunkX, a_ChunkZ);
+ cChunkDef::BlockToChunk(a_RelBlockX, a_RelBlockZ, a_ChunkX, a_ChunkZ);
if (!m_World.IsChunkLighted(a_ChunkX, a_ChunkZ))
{
@@ -982,10 +1031,12 @@ void cIncrementalRedstoneSimulator::HandleDaylightSensor(int a_BlockX, int a_Blo
}
else
{
- NIBBLETYPE SkyLight = m_World.GetBlockSkyLight(a_BlockX, a_BlockY + 1, a_BlockZ) - m_World.GetSkyDarkness();
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+ NIBBLETYPE SkyLight = m_Chunk->GetTimeAlteredLight(m_World.GetBlockSkyLight(BlockX, a_RelBlockY + 1, BlockZ));
if (SkyLight > 8)
{
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_DAYLIGHT_SENSOR);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
}
}
@@ -994,24 +1045,27 @@ void cIncrementalRedstoneSimulator::HandleDaylightSensor(int a_BlockX, int a_Blo
-void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyType)
+void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType)
{
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+
switch (a_MyType)
{
case E_BLOCK_STONE_PRESSURE_PLATE:
{
// MCS feature - stone pressure plates can only be triggered by players :D
- cPlayer * a_Player = m_World.FindClosestPlayer(Vector3f(a_BlockX + 0.5f, (float)a_BlockY, a_BlockZ + 0.5f), 0.5f, false);
+ cPlayer * a_Player = m_World.FindClosestPlayer(Vector3f(BlockX + 0.5f, (float)a_RelBlockY, BlockZ + 0.5f), 0.5f, false);
if (a_Player != NULL)
{
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, 0x1);
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_STONE_PRESSURE_PLATE);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x1);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
else
{
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, 0x0);
- m_World.WakeUpSimulators(a_BlockX, a_BlockY, a_BlockZ);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, 0x0);
+ m_World.WakeUpSimulators(BlockX, a_RelBlockY, BlockZ);
}
break;
}
@@ -1056,95 +1110,96 @@ void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_BlockX, int a_Bloc
int m_Z;
};
- cPressurePlateCallback PressurePlateCallback(a_BlockX, a_BlockY, a_BlockZ);
+ cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntity(PressurePlateCallback);
unsigned char Power;
- NIBBLETYPE Meta = m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
+ NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.GetPowerLevel(Power))
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
- m_World.BroadcastSoundEffect("random.click", (int)((a_BlockX + 0.5) * 8.0), (int)((a_BlockY + 0.1) * 8.0), (int)((a_BlockZ + 0.5) * 8.0), 0.3F, 0.5F);
+ m_Chunk->BroadcastSoundEffect("random.click", (int)((BlockX + 0.5) * 8.0), (int)((a_RelBlockY + 0.1) * 8.0), (int)((BlockZ + 0.5) * 8.0), 0.3F, 0.5F);
}
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, a_MyType, Power);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Power);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
- m_World.BroadcastSoundEffect("random.click", (int)((a_BlockX + 0.5) * 8.0), (int)((a_BlockY + 0.1) * 8.0), (int)((a_BlockZ + 0.5) * 8.0), 0.3F, 0.6F);
+ m_Chunk->BroadcastSoundEffect("random.click", (int)((BlockX + 0.5) * 8.0), (int)((a_RelBlockY + 0.1) * 8.0), (int)((BlockZ + 0.5) * 8.0), 0.3F, 0.6F);
}
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, E_META_PRESSURE_PLATE_RAISED);
- m_World.WakeUpSimulators(a_BlockX, a_BlockY, a_BlockZ);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
+ m_World.WakeUpSimulators(BlockX, a_RelBlockY, BlockZ);
}
break;
}
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
- {class cPressurePlateCallback :
- public cEntityCallback
{
- public:
- cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
- m_NumberOfEntities(0),
- m_X(a_BlockX),
- m_Y(a_BlockY),
- m_Z(a_BlockZ)
- {
- }
-
- virtual bool Item(cEntity * a_Entity) override
+ class cPressurePlateCallback :
+ public cEntityCallback
{
- Vector3f EntityPos = a_Entity->GetPosition();
- Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
- double Distance = (EntityPos - BlockPos).Length();
+ public:
+ cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
+ m_NumberOfEntities(0),
+ m_X(a_BlockX),
+ m_Y(a_BlockY),
+ m_Z(a_BlockZ)
+ {
+ }
- if (Distance <= 0.7)
+ virtual bool Item(cEntity * a_Entity) override
{
- m_NumberOfEntities++;
+ Vector3f EntityPos = a_Entity->GetPosition();
+ Vector3f BlockPos(m_X + 0.5f, (float)m_Y, m_Z + 0.5f);
+ double Distance = (EntityPos - BlockPos).Length();
+
+ if (Distance <= 0.7)
+ {
+ m_NumberOfEntities++;
+ }
+ return false;
}
- return false;
- }
- bool GetPowerLevel(unsigned char & a_PowerLevel) const
- {
- a_PowerLevel = std::min((int)ceil(m_NumberOfEntities / (float)10), MAX_POWER_LEVEL);
- return (a_PowerLevel > 0);
- }
+ bool GetPowerLevel(unsigned char & a_PowerLevel) const
+ {
+ a_PowerLevel = std::min((int)ceil(m_NumberOfEntities / (float)10), MAX_POWER_LEVEL);
+ return (a_PowerLevel > 0);
+ }
- protected:
- int m_NumberOfEntities;
+ protected:
+ int m_NumberOfEntities;
- int m_X;
- int m_Y;
- int m_Z;
- };
+ int m_X;
+ int m_Y;
+ int m_Z;
+ };
- cPressurePlateCallback PressurePlateCallback(a_BlockX, a_BlockY, a_BlockZ);
- m_World.ForEachEntity(PressurePlateCallback);
+ cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
+ m_World.ForEachEntity(PressurePlateCallback);
- unsigned char Power;
- NIBBLETYPE Meta = m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
- if (PressurePlateCallback.GetPowerLevel(Power))
- {
- if (Meta == E_META_PRESSURE_PLATE_RAISED)
+ unsigned char Power;
+ NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
+ if (PressurePlateCallback.GetPowerLevel(Power))
{
- m_World.BroadcastSoundEffect("random.click", (int)((a_BlockX + 0.5) * 8.0), (int)((a_BlockY + 0.1) * 8.0), (int)((a_BlockZ + 0.5) * 8.0), 0.3F, 0.5F);
+ if (Meta == E_META_PRESSURE_PLATE_RAISED)
+ {
+ m_Chunk->BroadcastSoundEffect("random.click", (int)((BlockX + 0.5) * 8.0), (int)((a_RelBlockY + 0.1) * 8.0), (int)((BlockZ + 0.5) * 8.0), 0.3F, 0.5F);
+ }
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Power);
}
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, a_MyType, Power);
- }
- else
- {
- if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
+ else
{
- m_World.BroadcastSoundEffect("random.click", (int)((a_BlockX + 0.5) * 8.0), (int)((a_BlockY + 0.1) * 8.0), (int)((a_BlockZ + 0.5) * 8.0), 0.3F, 0.6F);
+ if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
+ {
+ m_Chunk->BroadcastSoundEffect("random.click", (int)((BlockX + 0.5) * 8.0), (int)((a_RelBlockY + 0.1) * 8.0), (int)((BlockZ + 0.5) * 8.0), 0.3F, 0.6F);
+ }
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
+ m_World.WakeUpSimulators(BlockX, a_RelBlockY, BlockZ);
}
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, E_META_PRESSURE_PLATE_RAISED);
- m_World.WakeUpSimulators(a_BlockX, a_BlockY, a_BlockZ);
- }
break;
}
@@ -1155,7 +1210,6 @@ void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_BlockX, int a_Bloc
{
public:
cPressurePlateCallback(int a_BlockX, int a_BlockY, int a_BlockZ) :
- m_FoundEntity(false),
m_X(a_BlockX),
m_Y(a_BlockY),
m_Z(a_BlockZ)
@@ -1189,27 +1243,27 @@ void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_BlockX, int a_Bloc
int m_Z;
} ;
- cPressurePlateCallback PressurePlateCallback(a_BlockX, a_BlockY, a_BlockZ);
+ cPressurePlateCallback PressurePlateCallback(BlockX, a_RelBlockY, BlockZ);
m_World.ForEachEntity(PressurePlateCallback);
- NIBBLETYPE Meta = m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
+ NIBBLETYPE Meta = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
if (PressurePlateCallback.FoundEntity())
{
if (Meta == E_META_PRESSURE_PLATE_RAISED)
{
- m_World.BroadcastSoundEffect("random.click", (int) ((a_BlockX + 0.5) * 8.0), (int) ((a_BlockY + 0.1) * 8.0), (int) ((a_BlockZ + 0.5) * 8.0), 0.3F, 0.5F);
+ m_Chunk->BroadcastSoundEffect("random.click", (int)((BlockX + 0.5) * 8.0), (int)((a_RelBlockY + 0.1) * 8.0), (int)((BlockZ + 0.5) * 8.0), 0.3F, 0.5F);
}
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
- SetAllDirsAsPowered(a_BlockX, a_BlockY, a_BlockZ, a_MyType);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_DEPRESSED);
+ SetAllDirsAsPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
}
else
{
if (Meta == E_META_PRESSURE_PLATE_DEPRESSED)
{
- m_World.BroadcastSoundEffect("random.click", (int) ((a_BlockX + 0.5) * 8.0), (int) ((a_BlockY + 0.1) * 8.0), (int) ((a_BlockZ + 0.5) * 8.0), 0.3F, 0.6F);
+ m_Chunk->BroadcastSoundEffect("random.click", (int)((BlockX + 0.5) * 8.0), (int)((a_RelBlockY + 0.1) * 8.0), (int)((BlockZ + 0.5) * 8.0), 0.3F, 0.6F);
}
- m_World.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, E_META_PRESSURE_PLATE_RAISED);
- m_World.WakeUpSimulators(a_BlockX, a_BlockY, a_BlockZ);
+ m_Chunk->SetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ, E_META_PRESSURE_PLATE_RAISED);
+ m_World.WakeUpSimulators(BlockX, a_RelBlockY, BlockZ);
}
break;
}
@@ -1225,11 +1279,15 @@ void cIncrementalRedstoneSimulator::HandlePressurePlate(int a_BlockX, int a_Bloc
-bool cIncrementalRedstoneSimulator::AreCoordsDirectlyPowered(int a_BlockX, int a_BlockY, int a_BlockZ)
+bool cIncrementalRedstoneSimulator::AreCoordsDirectlyPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
- for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr) // Check powered list
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+
+ PoweredBlocksList * Powered = m_Chunk->GetNeighborChunk(BlockX, BlockZ)->GetRedstoneSimulatorPoweredBlocksList(); // Torches want to access neighbour's data when on a wall
+ for (PoweredBlocksList::const_iterator itr = Powered->begin(); itr != Powered->end(); ++itr) // Check powered list
{
- if (itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
@@ -1241,11 +1299,14 @@ bool cIncrementalRedstoneSimulator::AreCoordsDirectlyPowered(int a_BlockX, int a
-bool cIncrementalRedstoneSimulator::AreCoordsLinkedPowered(int a_BlockX, int a_BlockY, int a_BlockZ)
+bool cIncrementalRedstoneSimulator::AreCoordsLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr) // Check linked powered list
{
- if (itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
@@ -1258,35 +1319,37 @@ bool cIncrementalRedstoneSimulator::AreCoordsLinkedPowered(int a_BlockX, int a_B
// IsRepeaterPowered tests if a repeater should be powered by testing for power sources behind the repeater.
// It takes the coordinates of the repeater the the meta value.
-bool cIncrementalRedstoneSimulator::IsRepeaterPowered(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta)
+bool cIncrementalRedstoneSimulator::IsRepeaterPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
// Repeaters cannot be powered by any face except their back; verify that this is true for a source
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) { continue; }
+ if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
switch (a_Meta & 0x3)
{
case 0x0:
{
// Flip the coords to check the back of the repeater
- if (itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ + 1))) { return true; }
+ if (itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ + 1))) { return true; }
break;
}
case 0x1:
{
- if (itr->a_SourcePos.Equals(Vector3i(a_BlockX - 1, a_BlockY, a_BlockZ))) { return true; }
+ if (itr->a_SourcePos.Equals(Vector3i(BlockX - 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
case 0x2:
{
- if (itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ - 1))) { return true; }
+ if (itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ - 1))) { return true; }
break;
}
case 0x3:
{
- if (itr->a_SourcePos.Equals(Vector3i(a_BlockX + 1, a_BlockY, a_BlockZ))) { return true; }
+ if (itr->a_SourcePos.Equals(Vector3i(BlockX + 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
}
@@ -1294,28 +1357,28 @@ bool cIncrementalRedstoneSimulator::IsRepeaterPowered(int a_BlockX, int a_BlockY
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) { continue; }
+ if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
switch (a_Meta & 0x3)
{
case 0x0:
{
- if (itr->a_MiddlePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ + 1))) { return true; }
+ if (itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ + 1))) { return true; }
break;
}
case 0x1:
{
- if (itr->a_MiddlePos.Equals(Vector3i(a_BlockX - 1, a_BlockY, a_BlockZ))) { return true; }
+ if (itr->a_MiddlePos.Equals(Vector3i(BlockX - 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
case 0x2:
{
- if (itr->a_MiddlePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ - 1))) { return true; }
+ if (itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ - 1))) { return true; }
break;
}
case 0x3:
{
- if (itr->a_MiddlePos.Equals(Vector3i(a_BlockX + 1, a_BlockY, a_BlockZ))) { return true; }
+ if (itr->a_MiddlePos.Equals(Vector3i(BlockX + 1, a_RelBlockY, BlockZ))) { return true; }
break;
}
}
@@ -1327,7 +1390,7 @@ bool cIncrementalRedstoneSimulator::IsRepeaterPowered(int a_BlockX, int a_BlockY
-bool cIncrementalRedstoneSimulator::IsRepeaterLocked(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta)
+bool cIncrementalRedstoneSimulator::IsRepeaterLocked(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
switch (a_Meta & 0x3) // We only want the 'direction' part of our metadata
{
@@ -1336,16 +1399,17 @@ bool cIncrementalRedstoneSimulator::IsRepeaterLocked(int a_BlockX, int a_BlockY,
case 0x2:
{
// Check if eastern(right) neighbor is a powered on repeater who is facing us.
- if (m_World.GetBlock(a_BlockX + 1, a_BlockY, a_BlockZ) == E_BLOCK_REDSTONE_REPEATER_ON) // Is right neighbor a powered repeater?
+ BLOCKTYPE Block = 0;
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON)) // Is right neighbor a powered repeater?
{
- NIBBLETYPE OtherRepeaterDir = m_World.GetBlockMeta(a_BlockX + 1, a_BlockY, a_BlockZ) & 0x3;
+ NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ) & 0x3;
if (OtherRepeaterDir == 0x3) { return true; } // If so, I am latched/locked.
}
// Check if western(left) neighbor is a powered on repeater who is facing us.
- if (m_World.GetBlock(a_BlockX - 1, a_BlockY, a_BlockZ) == E_BLOCK_REDSTONE_REPEATER_ON)
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
- NIBBLETYPE OtherRepeaterDir = m_World.GetBlockMeta(a_BlockX -1, a_BlockY, a_BlockZ) & 0x3;
+ NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX -1, a_RelBlockY, a_RelBlockZ) & 0x3;
if (OtherRepeaterDir == 0x1) { return true; } // If so, I am latched/locked.
}
@@ -1357,16 +1421,17 @@ bool cIncrementalRedstoneSimulator::IsRepeaterLocked(int a_BlockX, int a_BlockY,
case 0x3:
{
// Check if southern(down) neighbor is a powered on repeater who is facing us.
- if (m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ + 1) == E_BLOCK_REDSTONE_REPEATER_ON)
+ BLOCKTYPE Block = 0;
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
- NIBBLETYPE OtherRepeaterDir = m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ + 1) & 0x3;
+ NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1) & 0x3;
if (OtherRepeaterDir == 0x0) { return true; } // If so, am latched/locked.
}
// Check if northern(up) neighbor is a powered on repeater who is facing us.
- if (m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ -1) == E_BLOCK_REDSTONE_REPEATER_ON)
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, Block) && (Block == E_BLOCK_REDSTONE_REPEATER_ON))
{
- NIBBLETYPE OtherRepeaterDir = m_World.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ - 1) & 0x3;
+ NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1) & 0x3;
if (OtherRepeaterDir == 0x2) { return true; } // If so, I am latched/locked.
}
@@ -1380,43 +1445,45 @@ bool cIncrementalRedstoneSimulator::IsRepeaterLocked(int a_BlockX, int a_BlockY,
-bool cIncrementalRedstoneSimulator::IsPistonPowered(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta)
+bool cIncrementalRedstoneSimulator::IsPistonPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta)
{
// Pistons cannot be powered through their front face; this function verifies that a source meets this requirement
- int OldX = a_BlockX, OldY = a_BlockY, OldZ = a_BlockZ;
+ int OldX = a_RelBlockX, OldY = a_RelBlockY, OldZ = a_RelBlockZ;
eBlockFace Face = cPiston::MetaDataToDirection(a_Meta);
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) { continue; }
+ if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
- AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, Face);
+ AddFaceDirection(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Face);
- if (!itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
- a_BlockX = OldX;
- a_BlockY = OldY;
- a_BlockZ = OldZ;
+ a_RelBlockX = OldX;
+ a_RelBlockY = OldY;
+ a_RelBlockZ = OldZ;
}
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) { continue; }
+ if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))) { continue; }
- AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, Face);
+ AddFaceDirection(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Face);
- if (!itr->a_MiddlePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_MiddlePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
return true;
}
- a_BlockX = OldX;
- a_BlockY = OldY;
- a_BlockZ = OldZ;
+ a_RelBlockX = OldX;
+ a_RelBlockY = OldY;
+ a_RelBlockZ = OldZ;
}
return false; // Source was in front of the piston's front face
}
@@ -1424,13 +1491,15 @@ bool cIncrementalRedstoneSimulator::IsPistonPowered(int a_BlockX, int a_BlockY,
-bool cIncrementalRedstoneSimulator::IsWirePowered(int a_BlockX, int a_BlockY, int a_BlockZ, unsigned char & a_PowerLevel)
+bool cIncrementalRedstoneSimulator::IsWirePowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char & a_PowerLevel)
{
a_PowerLevel = 0;
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
for (PoweredBlocksList::const_iterator itr = m_PoweredBlocks->begin(); itr != m_PoweredBlocks->end(); ++itr) // Check powered list
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
continue;
}
@@ -1439,7 +1508,7 @@ bool cIncrementalRedstoneSimulator::IsWirePowered(int a_BlockX, int a_BlockY, in
for (LinkedBlocksList::const_iterator itr = m_LinkedPoweredBlocks->begin(); itr != m_LinkedPoweredBlocks->end(); ++itr) // Check linked powered list
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)))
{
continue;
}
@@ -1453,11 +1522,11 @@ bool cIncrementalRedstoneSimulator::IsWirePowered(int a_BlockX, int a_BlockY, in
-bool cIncrementalRedstoneSimulator::AreCoordsSimulated(int a_BlockX, int a_BlockY, int a_BlockZ, bool IsCurrentStatePowered)
+bool cIncrementalRedstoneSimulator::AreCoordsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool IsCurrentStatePowered)
{
for (SimulatedPlayerToggleableList::const_iterator itr = m_SimulatedPlayerToggleableBlocks->begin(); itr != m_SimulatedPlayerToggleableBlocks->end(); ++itr)
{
- if (itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
if (itr->WasLastStatePowered != IsCurrentStatePowered) // Was the last power state different to the current?
{
@@ -1476,79 +1545,98 @@ bool cIncrementalRedstoneSimulator::AreCoordsSimulated(int a_BlockX, int a_Block
-void cIncrementalRedstoneSimulator::SetDirectionLinkedPowered(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Direction, BLOCKTYPE a_SourceType, unsigned char a_PowerLevel)
+void cIncrementalRedstoneSimulator::SetDirectionLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, char a_Direction, unsigned char a_PowerLevel)
{
+ BLOCKTYPE MiddleBlock = 0;
switch (a_Direction)
{
case BLOCK_FACE_XM:
{
- BLOCKTYPE MiddleBlock = m_World.GetBlock(a_BlockX - 1, a_BlockY, a_BlockZ);
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, MiddleBlock))
+ {
+ return;
+ }
- SetBlockLinkedPowered(a_BlockX - 2, a_BlockY, a_BlockZ, a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY + 1, a_BlockZ, a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY - 1, a_BlockZ, a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY, a_BlockZ + 1, a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY, a_BlockZ - 1, a_BlockX - 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 2, a_RelBlockY, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_XP:
{
- BLOCKTYPE MiddleBlock = m_World.GetBlock(a_BlockX + 1, a_BlockY, a_BlockZ);
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, MiddleBlock))
+ {
+ return;
+ }
- SetBlockLinkedPowered(a_BlockX + 2, a_BlockY, a_BlockZ, a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY + 1, a_BlockZ, a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY - 1, a_BlockZ, a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY, a_BlockZ + 1, a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY, a_BlockZ - 1, a_BlockX + 1, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 2, a_RelBlockY, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_YM:
{
- BLOCKTYPE MiddleBlock = m_World.GetBlock(a_BlockX, a_BlockY - 1, a_BlockZ);
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, MiddleBlock))
+ {
+ return;
+ }
- SetBlockLinkedPowered(a_BlockX, a_BlockY - 2, a_BlockZ, a_BlockX, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY - 1, a_BlockZ + 1, a_BlockX, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY - 1, a_BlockZ - 1, a_BlockX, a_BlockY - 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 2, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_YP:
{
- BLOCKTYPE MiddleBlock = m_World.GetBlock(a_BlockX, a_BlockY + 1, a_BlockZ);
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, MiddleBlock))
+ {
+ return;
+ }
- SetBlockLinkedPowered(a_BlockX, a_BlockY + 2, a_BlockZ, a_BlockX, a_BlockY + 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY + 1, a_BlockZ, a_BlockX, a_BlockY + 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY + 1, a_BlockZ, a_BlockX, a_BlockY + 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY + 1, a_BlockZ + 1, a_BlockX, a_BlockY + 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY + 1, a_BlockZ - 1, a_BlockX, a_BlockY + 1, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 2, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_ZM:
{
- BLOCKTYPE MiddleBlock = m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ - 1);
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, MiddleBlock))
+ {
+ return;
+ }
- SetBlockLinkedPowered(a_BlockX, a_BlockY, a_BlockZ - 2, a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY + 1, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY - 1, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ - 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 2, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
case BLOCK_FACE_ZP:
{
- BLOCKTYPE MiddleBlock = m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ + 1);
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, MiddleBlock))
+ {
+ return;
+ }
- SetBlockLinkedPowered(a_BlockX, a_BlockY, a_BlockZ + 2, a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX + 1, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX - 1, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY + 1, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
- SetBlockLinkedPowered(a_BlockX, a_BlockY - 1, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ + 1, a_BlockX, a_BlockY, a_BlockZ, a_SourceType, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 2, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY + 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
+ SetBlockLinkedPowered(a_RelBlockX, a_RelBlockY - 1, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, a_RelBlockX, a_RelBlockY, a_RelBlockZ, MiddleBlock, a_PowerLevel);
break;
}
@@ -1564,7 +1652,7 @@ void cIncrementalRedstoneSimulator::SetDirectionLinkedPowered(int a_BlockX, int
-void cIncrementalRedstoneSimulator::SetAllDirsAsPowered(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_SourceBlock, unsigned char a_PowerLevel)
+void cIncrementalRedstoneSimulator::SetAllDirsAsPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char a_PowerLevel)
{
static const struct
{
@@ -1572,16 +1660,16 @@ void cIncrementalRedstoneSimulator::SetAllDirsAsPowered(int a_BlockX, int a_Bloc
} gCrossCoords[] =
{
{ 1, 0, 0 },
- {-1, 0, 0 },
+ { -1, 0, 0 },
{ 0, 0, 1 },
- { 0, 0,-1 },
+ { 0, 0, -1 },
{ 0, 1, 0 },
- { 0,-1, 0 }
+ { 0, -1, 0 }
};
for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++) // Loop through struct to power all directions
{
- SetBlockPowered(a_BlockX + gCrossCoords[i].x, a_BlockY + gCrossCoords[i].y, a_BlockZ + gCrossCoords[i].z, a_BlockX, a_BlockY, a_BlockZ, a_SourceBlock, a_PowerLevel);
+ SetBlockPowered(a_RelBlockX + gCrossCoords[i].x, a_RelBlockY + gCrossCoords[i].y, a_RelBlockZ + gCrossCoords[i].z, a_RelBlockX, a_RelBlockY, a_RelBlockZ, a_PowerLevel);
}
}
@@ -1589,39 +1677,45 @@ void cIncrementalRedstoneSimulator::SetAllDirsAsPowered(int a_BlockX, int a_Bloc
-void cIncrementalRedstoneSimulator::SetBlockPowered(int a_BlockX, int a_BlockY, int a_BlockZ, int a_SourceX, int a_SourceY, int a_SourceZ, BLOCKTYPE a_SourceBlock, unsigned char a_PowerLevel)
+void cIncrementalRedstoneSimulator::SetBlockPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ, unsigned char a_PowerLevel)
{
- BLOCKTYPE Block = m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ);
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+ int SourceX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelSourceX;
+ int SourceZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelSourceZ;
+
+ BLOCKTYPE Block = 0;
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ, Block))
+ {
+ return;
+ }
if (Block == E_BLOCK_AIR)
{
// Don't set air, fixes some bugs (wires powering themselves)
return;
}
- PoweredBlocksList * Powered = m_Chunk->GetNeighborChunk(a_BlockX, a_BlockZ)->GetRedstoneSimulatorPoweredBlocksList();
+ PoweredBlocksList * Powered = m_Chunk->GetNeighborChunk(BlockX, BlockZ)->GetRedstoneSimulatorPoweredBlocksList();
for (PoweredBlocksList::iterator itr = Powered->begin(); itr != Powered->end(); ++itr) // Check powered list
{
if (
- itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)) &&
- itr->a_SourcePos.Equals(Vector3i(a_SourceX, a_SourceY, a_SourceZ))
- )
+ itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
+ itr->a_SourcePos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ))
+ )
{
- // Check for duplicates, update power level if everything else the same but either way, don't add a new listing
- if (itr->a_PowerLevel != a_PowerLevel)
- {
- itr->a_PowerLevel = a_PowerLevel;
- }
+ // Check for duplicates, update power level, don't add a new listing
+ itr->a_PowerLevel = a_PowerLevel;
return;
}
}
- PoweredBlocksList * OtherPowered = m_Chunk->GetNeighborChunk(a_SourceX, a_SourceZ)->GetRedstoneSimulatorPoweredBlocksList();
+ PoweredBlocksList * OtherPowered = m_Chunk->GetNeighborChunk(SourceX, SourceZ)->GetRedstoneSimulatorPoweredBlocksList();
for (PoweredBlocksList::const_iterator itr = OtherPowered->begin(); itr != OtherPowered->end(); ++itr) // Check powered list
{
if (
- itr->a_BlockPos.Equals(Vector3i(a_SourceX, a_SourceY, a_SourceZ)) &&
- itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))
- )
+ itr->a_BlockPos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ)) &&
+ itr->a_SourcePos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ))
+ )
{
// Powered wires try to power their source - don't let them!
return;
@@ -1629,8 +1723,8 @@ void cIncrementalRedstoneSimulator::SetBlockPowered(int a_BlockX, int a_BlockY,
}
sPoweredBlocks RC;
- RC.a_BlockPos = Vector3i(a_BlockX, a_BlockY, a_BlockZ);
- RC.a_SourcePos = Vector3i(a_SourceX, a_SourceY, a_SourceZ);
+ RC.a_BlockPos = Vector3i(BlockX, a_RelBlockY, BlockZ);
+ RC.a_SourcePos = Vector3i(SourceX, a_RelSourceY, SourceZ);
RC.a_PowerLevel = a_PowerLevel;
Powered->push_back(RC);
}
@@ -1640,45 +1734,57 @@ void cIncrementalRedstoneSimulator::SetBlockPowered(int a_BlockX, int a_BlockY,
void cIncrementalRedstoneSimulator::SetBlockLinkedPowered(
- int a_BlockX, int a_BlockY, int a_BlockZ,
- int a_MiddleX, int a_MiddleY, int a_MiddleZ,
- int a_SourceX, int a_SourceY, int a_SourceZ,
- BLOCKTYPE a_SourceBlock, BLOCKTYPE a_MiddleBlock, unsigned char a_PowerLevel
-)
+ int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ,
+ int a_RelMiddleX, int a_RelMiddleY, int a_RelMiddleZ,
+ int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ,
+ BLOCKTYPE a_MiddleBlock, unsigned char a_PowerLevel
+ )
{
- BLOCKTYPE DestBlock = m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ);
+ int BlockX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelBlockX;
+ int BlockZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelBlockZ;
+ int MiddleX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelMiddleX;
+ int MiddleZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelMiddleZ;
+ int SourceX = (m_Chunk->GetPosX() * cChunkDef::Width) + a_RelSourceX;
+ int SourceZ = (m_Chunk->GetPosZ() * cChunkDef::Width) + a_RelSourceZ;
+
+ BLOCKTYPE DestBlock = 0;
+ if (!m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ, DestBlock))
+ {
+ return;
+ }
if (DestBlock == E_BLOCK_AIR)
{
// Don't set air, fixes some bugs (wires powering themselves)
return;
}
+ if ((DestBlock == E_BLOCK_REDSTONE_WIRE) && (m_Chunk->GetBlock(a_RelSourceX, a_RelSourceY, a_RelSourceZ) == E_BLOCK_REDSTONE_WIRE))
+ {
+ return;
+ }
if (!IsViableMiddleBlock(a_MiddleBlock))
{
return;
}
- LinkedBlocksList * Linked = m_Chunk->GetNeighborChunk(a_BlockX, a_BlockZ)->GetRedstoneSimulatorLinkedBlocksList();
+ LinkedBlocksList * Linked = m_Chunk->GetNeighborChunk(BlockX, BlockZ)->GetRedstoneSimulatorLinkedBlocksList();
for (LinkedBlocksList::iterator itr = Linked->begin(); itr != Linked->end(); ++itr) // Check linked powered list
{
if (
- itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)) &&
- itr->a_MiddlePos.Equals(Vector3i(a_MiddleX, a_MiddleY, a_MiddleZ)) &&
- itr->a_SourcePos.Equals(Vector3i(a_SourceX, a_SourceY, a_SourceZ))
+ itr->a_BlockPos.Equals(Vector3i(BlockX, a_RelBlockY, BlockZ)) &&
+ itr->a_MiddlePos.Equals(Vector3i(MiddleX, a_RelMiddleY, MiddleZ)) &&
+ itr->a_SourcePos.Equals(Vector3i(SourceX, a_RelSourceY, SourceZ))
)
{
- // Check for duplicates, update power level if everything else the same but either way, don't add a new listing
- if (itr->a_PowerLevel != a_PowerLevel)
- {
- itr->a_PowerLevel = a_PowerLevel;
- }
+ // Check for duplicates, update power level, don't add a new listing
+ itr->a_PowerLevel = a_PowerLevel;
return;
}
}
sLinkedPoweredBlocks RC;
- RC.a_BlockPos = Vector3i(a_BlockX, a_BlockY, a_BlockZ);
- RC.a_MiddlePos = Vector3i(a_MiddleX, a_MiddleY, a_MiddleZ);
- RC.a_SourcePos = Vector3i(a_SourceX, a_SourceY, a_SourceZ);
+ RC.a_BlockPos = Vector3i(BlockX, a_RelBlockY, BlockZ);
+ RC.a_MiddlePos = Vector3i(MiddleX, a_RelMiddleY, MiddleZ);
+ RC.a_SourcePos = Vector3i(SourceX, a_RelSourceY, SourceZ);
RC.a_PowerLevel = a_PowerLevel;
Linked->push_back(RC);
}
@@ -1687,11 +1793,11 @@ void cIncrementalRedstoneSimulator::SetBlockLinkedPowered(
-void cIncrementalRedstoneSimulator::SetPlayerToggleableBlockAsSimulated(int a_BlockX, int a_BlockY, int a_BlockZ, bool WasLastStatePowered)
+void cIncrementalRedstoneSimulator::SetPlayerToggleableBlockAsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool WasLastStatePowered)
{
for (SimulatedPlayerToggleableList::iterator itr = m_SimulatedPlayerToggleableBlocks->begin(); itr != m_SimulatedPlayerToggleableBlocks->end(); ++itr)
{
- if (!itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (!itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
continue;
}
@@ -1711,7 +1817,7 @@ void cIncrementalRedstoneSimulator::SetPlayerToggleableBlockAsSimulated(int a_Bl
// We have arrive here; no block must be in list - add one
sSimulatedPlayerToggleableList RC;
- RC.a_BlockPos = Vector3i(a_BlockX, a_BlockY, a_BlockZ);
+ RC.a_RelBlockPos = Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
RC.WasLastStatePowered = WasLastStatePowered;
m_SimulatedPlayerToggleableBlocks->push_back(RC);
}
@@ -1720,11 +1826,11 @@ void cIncrementalRedstoneSimulator::SetPlayerToggleableBlockAsSimulated(int a_Bl
-void cIncrementalRedstoneSimulator::QueueRepeaterPowerChange(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta, bool ShouldPowerOn)
+void cIncrementalRedstoneSimulator::QueueRepeaterPowerChange(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta, bool ShouldPowerOn)
{
for (RepeatersDelayList::iterator itr = m_RepeatersDelayList->begin(); itr != m_RepeatersDelayList->end(); ++itr)
{
- if (itr->a_BlockPos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ)))
+ if (itr->a_RelBlockPos.Equals(Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ)))
{
if (ShouldPowerOn == itr->ShouldPowerOn) // We are queued already for the same thing, don't replace entry
{
@@ -1741,7 +1847,7 @@ void cIncrementalRedstoneSimulator::QueueRepeaterPowerChange(int a_BlockX, int a
// Self not in list, add self to list
sRepeatersDelayList RC;
- RC.a_BlockPos = Vector3i(a_BlockX, a_BlockY, a_BlockZ);
+ RC.a_RelBlockPos = Vector3i(a_RelBlockX, a_RelBlockY, a_RelBlockZ);
// Gets the top two bits (delay time), shifts them into the lower two bits, and adds one (meta 0 = 1 tick; 1 = 2 etc.)
// * 2 because in MCS, 1 redstone tick = 1 world tick, but in Vanilla, 1 redstone tick = 2 world ticks, and we need to maintain compatibility
@@ -1757,52 +1863,64 @@ void cIncrementalRedstoneSimulator::QueueRepeaterPowerChange(int a_BlockX, int a
-cIncrementalRedstoneSimulator::eRedstoneDirection cIncrementalRedstoneSimulator::GetWireDirection(int a_BlockX, int a_BlockY, int a_BlockZ)
+cIncrementalRedstoneSimulator::eRedstoneDirection cIncrementalRedstoneSimulator::GetWireDirection(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ)
{
int Dir = REDSTONE_NONE;
- BLOCKTYPE NegX = m_World.GetBlock(a_BlockX - 1, a_BlockY, a_BlockZ);
- if (IsPotentialSource(NegX))
+ BLOCKTYPE NegX = 0;
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, NegX))
{
- Dir |= (REDSTONE_X_POS);
+ if (IsPotentialSource(NegX))
+ {
+ Dir |= (REDSTONE_X_POS);
+ }
}
- BLOCKTYPE PosX = m_World.GetBlock(a_BlockX + 1, a_BlockY, a_BlockZ);
- if (IsPotentialSource(PosX))
+ BLOCKTYPE PosX = 0;
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX + 1, a_RelBlockY, a_RelBlockZ, PosX))
{
- Dir |= (REDSTONE_X_NEG);
+ if (IsPotentialSource(PosX))
+ {
+ Dir |= (REDSTONE_X_NEG);
+ }
}
- BLOCKTYPE NegZ = m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ - 1);
- if (IsPotentialSource(NegZ))
+ BLOCKTYPE NegZ = 0;
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ - 1, NegZ))
{
- if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
+ if (IsPotentialSource(NegZ))
{
- Dir ^= REDSTONE_X_POS;
- Dir |= REDSTONE_X_NEG;
- }
- if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
- {
- Dir ^= REDSTONE_X_NEG;
- Dir |= REDSTONE_X_POS;
+ if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
+ {
+ Dir ^= REDSTONE_X_POS;
+ Dir |= REDSTONE_X_NEG;
+ }
+ if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
+ {
+ Dir ^= REDSTONE_X_NEG;
+ Dir |= REDSTONE_X_POS;
+ }
+ Dir |= REDSTONE_Z_POS;
}
- Dir |= REDSTONE_Z_POS;
}
- BLOCKTYPE PosZ = m_World.GetBlock(a_BlockX, a_BlockY, a_BlockZ + 1);
- if (IsPotentialSource(PosZ))
+ BLOCKTYPE PosZ = 0;
+ if (m_Chunk->UnboundedRelGetBlockType(a_RelBlockX, a_RelBlockY, a_RelBlockZ + 1, PosZ))
{
- if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
- {
- Dir ^= REDSTONE_X_POS;
- Dir |= REDSTONE_X_NEG;
- }
- if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
+ if (IsPotentialSource(PosZ))
{
- Dir ^= REDSTONE_X_NEG;
- Dir |= REDSTONE_X_POS;
+ if ((Dir & REDSTONE_X_POS) && !(Dir & REDSTONE_X_NEG)) // corner
+ {
+ Dir ^= REDSTONE_X_POS;
+ Dir |= REDSTONE_X_NEG;
+ }
+ if ((Dir & REDSTONE_X_NEG) && !(Dir & REDSTONE_X_POS)) // corner
+ {
+ Dir ^= REDSTONE_X_NEG;
+ Dir |= REDSTONE_X_POS;
+ }
+ Dir |= REDSTONE_Z_NEG;
}
- Dir |= REDSTONE_Z_NEG;
}
return (eRedstoneDirection)Dir;
}
diff --git a/src/Simulator/IncrementalRedstoneSimulator.h b/src/Simulator/IncrementalRedstoneSimulator.h
index a42cce79a..233a3d408 100644
--- a/src/Simulator/IncrementalRedstoneSimulator.h
+++ b/src/Simulator/IncrementalRedstoneSimulator.h
@@ -55,13 +55,13 @@ private:
struct sSimulatedPlayerToggleableList // Define structure of the list containing simulate-on-update blocks (such as trapdoors that respond once to a block update, and can be toggled by a player)
{
- Vector3i a_BlockPos;
+ Vector3i a_RelBlockPos;
bool WasLastStatePowered; // Was the last state powered or not? Determines whether a source update has happened and if I should resimulate
};
struct sRepeatersDelayList // Define structure of list containing repeaters' delay states
{
- Vector3i a_BlockPos;
+ Vector3i a_RelBlockPos;
unsigned char a_DelayTicks; // For how many ticks should the repeater delay
unsigned char a_ElapsedTicks; // How much of the previous has been elapsed?
bool ShouldPowerOn; // What happens when the delay time is fulfilled?
@@ -91,80 +91,80 @@ private:
/* ====== SOURCES ====== */
/** Handles the redstone torch */
- void HandleRedstoneTorch(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyState);
+ void HandleRedstoneTorch(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState);
/** Handles the redstone block */
- void HandleRedstoneBlock(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleRedstoneBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles levers */
- void HandleRedstoneLever(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleRedstoneLever(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles buttons */
- void HandleRedstoneButton(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType);
+ void HandleRedstoneButton(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles daylight sensors */
- void HandleDaylightSensor(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleDaylightSensor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles pressure plates */
- void HandlePressurePlate(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyType);
+ void HandlePressurePlate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType);
/* ==================== */
/* ====== CARRIERS ====== */
/** Handles redstone wire */
- void HandleRedstoneWire(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleRedstoneWire(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles repeaters */
- void HandleRedstoneRepeater(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyState);
+ void HandleRedstoneRepeater(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState);
/* ====================== */
/* ====== DEVICES ====== */
/** Handles pistons */
- void HandlePiston(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandlePiston(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles dispensers and droppers */
- void HandleDropSpenser(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleDropSpenser(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles TNT (exploding) */
- void HandleTNT(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleTNT(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles redstone lamps */
- void HandleRedstoneLamp(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyState);
+ void HandleRedstoneLamp(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyState);
/** Handles doords */
- void HandleDoor(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleDoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles command blocks */
- void HandleCommandBlock(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleCommandBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles activator, detector, and powered rails */
- void HandleRail(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_MyType);
+ void HandleRail(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, BLOCKTYPE a_MyType);
/** Handles trapdoors */
- void HandleTrapdoor(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleTrapdoor(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles fence gates */
- void HandleFenceGate(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleFenceGate(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Handles noteblocks */
- void HandleNoteBlock(int a_BlockX, int a_BlockY, int a_BlockZ);
+ void HandleNoteBlock(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/* ===================== */
/* ====== Helper functions ====== */
/** Marks a block as powered */
- void SetBlockPowered(int a_BlockX, int a_BlockY, int a_BlockZ, int a_SourceX, int a_SourceY, int a_SourceZ, BLOCKTYPE a_SourceBlock, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
+ void SetBlockPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
/** Marks a block as being powered through another block */
- void SetBlockLinkedPowered(int a_BlockX, int a_BlockY, int a_BlockZ, int a_MiddleX, int a_MiddleY, int a_MiddleZ, int a_SourceX, int a_SourceY, int a_SourceZ, BLOCKTYPE a_SourceBlock, BLOCKTYPE a_MiddeBlock, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
+ void SetBlockLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, int a_RelMiddleX, int a_RelMiddleY, int a_RelMiddleZ, int a_RelSourceX, int a_RelSourceY, int a_RelSourceZ, BLOCKTYPE a_MiddeBlock, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
/** Marks a block as simulated, who should not be simulated further unless their power state changes, to accomodate a player manually toggling the block without triggering the simulator toggling it back */
- void SetPlayerToggleableBlockAsSimulated(int a_BlockX, int a_BlockY, int a_BlockZ, bool WasLastStatePowered);
+ void SetPlayerToggleableBlockAsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool WasLastStatePowered);
/** Marks the second block in a direction as linked powered */
- void SetDirectionLinkedPowered(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Direction, BLOCKTYPE a_SourceBlock, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
+ void SetDirectionLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, char a_Direction, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
/** Marks all blocks immediately surrounding a coordinate as powered */
- void SetAllDirsAsPowered(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_SourceBlock, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
+ void SetAllDirsAsPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char a_PowerLevel = MAX_POWER_LEVEL);
/** Queues a repeater to be powered or unpowered */
- void QueueRepeaterPowerChange(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta, bool ShouldPowerOn);
+ void QueueRepeaterPowerChange(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta, bool ShouldPowerOn);
/** Returns if a coordinate is powered or linked powered */
- bool AreCoordsPowered(int a_BlockX, int a_BlockY, int a_BlockZ) { return AreCoordsDirectlyPowered(a_BlockX, a_BlockY, a_BlockZ) || AreCoordsLinkedPowered(a_BlockX, a_BlockY, a_BlockZ); }
+ bool AreCoordsPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ) { return AreCoordsDirectlyPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ) || AreCoordsLinkedPowered(a_RelBlockX, a_RelBlockY, a_RelBlockZ); }
/** Returns if a coordinate is in the directly powered blocks list */
- bool AreCoordsDirectlyPowered(int a_BlockX, int a_BlockY, int a_BlockZ);
+ bool AreCoordsDirectlyPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Returns if a coordinate is in the indirectly powered blocks list */
- bool AreCoordsLinkedPowered(int a_BlockX, int a_BlockY, int a_BlockZ);
+ bool AreCoordsLinkedPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ);
/** Returns if a coordinate was marked as simulated (for blocks toggleable by players) */
- bool AreCoordsSimulated(int a_BlockX, int a_BlockY, int a_BlockZ, bool IsCurrentStatePowered);
+ bool AreCoordsSimulated(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, bool IsCurrentStatePowered);
/** Returns if a repeater is powered */
- bool IsRepeaterPowered(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta);
+ bool IsRepeaterPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta);
/** Returns if a repeater is locked */
- bool IsRepeaterLocked(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta);
+ bool IsRepeaterLocked(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta);
/** Returns if a piston is powered */
- bool IsPistonPowered(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Meta);
+ bool IsPistonPowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, NIBBLETYPE a_Meta);
/** Returns if a wire is powered
The only diffence between this and a normal AreCoordsPowered is that this function checks for a wire powering another wire */
- bool IsWirePowered(int a_BlockX, int a_BlockY, int a_BlockZ, unsigned char & a_PowerLevel);
+ bool IsWirePowered(int a_RelBlockX, int a_RelBlockY, int a_RelBlockZ, unsigned char & a_PowerLevel);
/** Returns if lever metadata marks it as emitting power */
diff --git a/src/World.h b/src/World.h
index f789916df..de0a257f9 100644
--- a/src/World.h
+++ b/src/World.h
@@ -351,7 +351,7 @@ public:
/** Is the trapdoor open? Returns false if there is no trapdoor at the specified coords. */
bool IsTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_export
- /** Set the state of a trapdoor. Returns true if the trapdoor was update, false if there was no trapdoor at those coords. */
+ /** Set the state of a trapdoor. Returns true if the trapdoor was updated, false if there was no trapdoor at those coords. */
bool SetTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ, bool a_Open); // tolua_export
/** Regenerate the given chunk: */
--
cgit v1.2.3
From 1d3ad6faa22a040bc6bb15727b9783ae2f547a02 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 12:25:03 -0700
Subject: Added Testing capability
---
CMakeLists.txt | 7 ++++++-
lib/polarssl.cmake | 6 +++++-
tests/CMakeLists.txt | 5 +++++
tests/ChunkBuffer/CMakeLists.txt | 10 ++++++++++
tests/ChunkBuffer/creatable.cpp | 4 ++++
5 files changed, 30 insertions(+), 2 deletions(-)
create mode 100644 tests/CMakeLists.txt
create mode 100644 tests/ChunkBuffer/CMakeLists.txt
create mode 100644 tests/ChunkBuffer/creatable.cpp
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9a860920c..45fc8c37a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required (VERSION 2.6)
+cmake_minimum_required (VERSION 2.8.2)
# Without this, the MSVC variable isn't defined for MSVC builds ( http://www.cmake.org/pipermail/cmake/2011-November/047130.html )
enable_language(CXX C)
@@ -69,3 +69,8 @@ set_exe_flags()
add_subdirectory (src)
+if(${SELF_TEST})
+ enable_testing()
+ add_subdirectory (tests)
+endif()
+
diff --git a/lib/polarssl.cmake b/lib/polarssl.cmake
index d57cc9220..2a58e54c5 100644
--- a/lib/polarssl.cmake
+++ b/lib/polarssl.cmake
@@ -1,5 +1,9 @@
if(NOT TARGET polarssl)
message("including polarssl")
- add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl EXCLUDE_FROM_ALL )
+ if (SELF_TEST)
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl)
+ else()
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl EXCLUDE_FROM_ALL)
+ endif()
endif()
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
new file mode 100644
index 000000000..c2f9ceb5a
--- /dev/null
+++ b/tests/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required (VERSION 2.6)
+
+enable_testing()
+
+add_subdirectory(ChunkBuffer)
diff --git a/tests/ChunkBuffer/CMakeLists.txt b/tests/ChunkBuffer/CMakeLists.txt
new file mode 100644
index 000000000..33722f785
--- /dev/null
+++ b/tests/ChunkBuffer/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required (VERSION 2.6)
+
+enable_testing()
+
+add_library(ChunkBuffer ${CMAKE_SOURCE_DIR}/src/ChunkBuffer.cpp)
+
+
+add_executable(creatable-exe creatable.cpp)
+target_link_libraries(creatable-exe ChunkBuffer)
+add_test(NAME creatable-test COMMAND creatable-exe)
diff --git a/tests/ChunkBuffer/creatable.cpp b/tests/ChunkBuffer/creatable.cpp
new file mode 100644
index 000000000..573f09de9
--- /dev/null
+++ b/tests/ChunkBuffer/creatable.cpp
@@ -0,0 +1,4 @@
+int main(int argc, char** argv)
+{
+return 0;
+}
--
cgit v1.2.3
From 25d933883a24c97b67f90ae6839ce3d6b8d630d5 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 13:07:21 -0700
Subject: Removed unneeded assert Fixed CID 43610
---
src/Generating/Prefab.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Generating/Prefab.cpp b/src/Generating/Prefab.cpp
index c0c9e8a13..44d5097de 100644
--- a/src/Generating/Prefab.cpp
+++ b/src/Generating/Prefab.cpp
@@ -283,7 +283,7 @@ void cPrefab::ParseCharMap(CharMap & a_CharMapOut, const char * a_CharMapDef)
if ((NumElements >= 3) && !CharDef[2].empty())
{
BlockMeta = (NIBBLETYPE)atoi(CharDef[2].c_str());
- ASSERT((BlockMeta >= 0) && (BlockMeta <= 15));
+ ASSERT((BlockMeta <= 15));
}
a_CharMapOut[Src].m_BlockMeta = BlockMeta;
} // for itr - Lines[]
--
cgit v1.2.3
From a2b1fa6520355e9f073fcb44897c6ee21a69df75 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 13:12:36 -0700
Subject: Initialised MetaArrays in BlockArea Fixes CID 43621
---
src/BlockArea.cpp | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index 40cca8882..49c564ca5 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -663,8 +663,12 @@ void cBlockArea::Merge(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_R
if (IsDummyMetas)
{
- SrcMetas = new NIBBLETYPE[a_Src.GetBlockCount()];
- DstMetas = new NIBBLETYPE[GetBlockCount()];
+ size_t SrcCount = a_Src.GetBlockCount();
+ size_t DestCount = GetBlockCount();
+ SrcMetas = new NIBBLETYPE[SrcCount];
+ DstMetas = new NIBBLETYPE[DestCount];
+ memset(SrcMetas, 0, SrcCount);
+ memset(DstMetas, 0, DestCount);
}
switch (a_Strategy)
--
cgit v1.2.3
From 71c51783f3fc73d7370714ebbb0cdd4c8206843c Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 13:15:19 -0700
Subject: Initalize counter in fastrandom Fixes CID 43622
---
src/FastRandom.cpp | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/FastRandom.cpp b/src/FastRandom.cpp
index c45261947..42bf5f3f9 100644
--- a/src/FastRandom.cpp
+++ b/src/FastRandom.cpp
@@ -91,7 +91,8 @@ int cFastRandom::m_SeedCounter = 0;
cFastRandom::cFastRandom(void) :
- m_Seed(m_SeedCounter++)
+ m_Seed(m_SeedCounter++),
+ m_Counter(0)
{
}
--
cgit v1.2.3
From 077179277c5f3db46c5b805ae61506b99de7e851 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 13:20:00 -0700
Subject: Fixes to uninitallsed array access in Noise.cpp CID 43634, 43634
---
src/Noise.cpp | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/Noise.cpp b/src/Noise.cpp
index 95a022ea3..13a194938 100644
--- a/src/Noise.cpp
+++ b/src/Noise.cpp
@@ -608,6 +608,8 @@ void cCubicNoise::Generate2D(
NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY ///< Noise-space coords of the array in the Y direction
) const
{
+ ASSERT(a_SizeX > 0);
+ ASSERT(a_SizeY > 0);
ASSERT(a_SizeX < MAX_SIZE);
ASSERT(a_SizeY < MAX_SIZE);
ASSERT(a_StartX < a_EndX);
--
cgit v1.2.3
From f301d052cfa70d00f76c31fcad4f961040736a80 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Sun, 27 Apr 2014 22:20:49 +0200
Subject: cSocket creates the socket in Connect if no socket is present yet.
---
src/OSSupport/Socket.cpp | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/src/OSSupport/Socket.cpp b/src/OSSupport/Socket.cpp
index c29e495c3..98f694a79 100644
--- a/src/OSSupport/Socket.cpp
+++ b/src/OSSupport/Socket.cpp
@@ -295,7 +295,7 @@ bool cSocket::ConnectToLocalhostIPv4(unsigned short a_Port)
bool cSocket::ConnectIPv4(const AString & a_HostNameOrAddr, unsigned short a_Port)
{
- // First try IP Address string to hostent conversion, because it's faster
+ // First try IP Address string to hostent conversion, because it's faster and local:
unsigned long addr = inet_addr(a_HostNameOrAddr.c_str());
if (addr == INADDR_NONE)
{
@@ -307,10 +307,16 @@ bool cSocket::ConnectIPv4(const AString & a_HostNameOrAddr, unsigned short a_Por
CloseSocket();
return false;
}
- // Should be optimised to a single word copy
memcpy(&addr, hp->h_addr, hp->h_length);
}
+ // If the socket is not created yet, create one:
+ if (!IsValid())
+ {
+ m_Socket = socket((int)IPv4, SOCK_STREAM, 0);
+ }
+
+ // Connect the socket:
sockaddr_in server;
server.sin_addr.s_addr = addr;
server.sin_family = AF_INET;
--
cgit v1.2.3
From 0bdc49221b325feb3a09988737559361fe916be2 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Sun, 27 Apr 2014 22:27:53 +0200
Subject: PolarSSL wrappers for the SSL context.
---
src/PolarSSL++/BlockingSslClientSocket.cpp | 195 +++++++++++++++++++++++++++++
src/PolarSSL++/BlockingSslClientSocket.h | 80 ++++++++++++
src/PolarSSL++/BufferedSslContext.cpp | 62 +++++++++
src/PolarSSL++/BufferedSslContext.h | 52 ++++++++
src/PolarSSL++/CMakeLists.txt | 18 ++-
src/PolarSSL++/CallbackSslContext.cpp | 59 +++++++++
src/PolarSSL++/CallbackSslContext.h | 61 +++++++++
src/PolarSSL++/SslContext.cpp | 181 ++++++++++++++++++++++++++
src/PolarSSL++/SslContext.h | 134 ++++++++++++++++++++
src/PolarSSL++/X509Cert.h | 10 +-
10 files changed, 847 insertions(+), 5 deletions(-)
create mode 100644 src/PolarSSL++/BlockingSslClientSocket.cpp
create mode 100644 src/PolarSSL++/BlockingSslClientSocket.h
create mode 100644 src/PolarSSL++/BufferedSslContext.cpp
create mode 100644 src/PolarSSL++/BufferedSslContext.h
create mode 100644 src/PolarSSL++/CallbackSslContext.cpp
create mode 100644 src/PolarSSL++/CallbackSslContext.h
create mode 100644 src/PolarSSL++/SslContext.cpp
create mode 100644 src/PolarSSL++/SslContext.h
diff --git a/src/PolarSSL++/BlockingSslClientSocket.cpp b/src/PolarSSL++/BlockingSslClientSocket.cpp
new file mode 100644
index 000000000..20b2df1e7
--- /dev/null
+++ b/src/PolarSSL++/BlockingSslClientSocket.cpp
@@ -0,0 +1,195 @@
+
+// BlockingSslClientSocket.cpp
+
+// Implements the cBlockingSslClientSocket class representing a blocking TCP socket with client SSL encryption over it
+
+#include "Globals.h"
+#include "BlockingSslClientSocket.h"
+
+
+
+
+
+cBlockingSslClientSocket::cBlockingSslClientSocket(void) :
+ m_IsConnected(false),
+ m_Ssl(*this)
+{
+ // Nothing needed yet
+}
+
+
+
+
+
+bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Port)
+{
+ // If already connected, report an error:
+ if (m_IsConnected)
+ {
+ // TODO: Handle this better - if connected to the same server and port, and the socket is alive, return success
+ m_LastErrorText = "Already connected";
+ return false;
+ }
+
+ // Connect the underlying socket:
+ m_Socket.CreateSocket(cSocket::IPv4);
+ if (!m_Socket.ConnectIPv4(a_ServerName.c_str(), a_Port))
+ {
+ Printf(m_LastErrorText, "Socket connect failed: %s", m_Socket.GetLastErrorString().c_str());
+ return false;
+ }
+
+ // Initialize the SSL:
+ int ret = m_Ssl.Initialize(true);
+ if (ret != 0)
+ {
+ Printf(m_LastErrorText, "SSL initialization failed: -0x%x", -ret);
+ return false;
+ }
+
+ // If we have been assigned a trusted CA root cert store, push it into the SSL context:
+ if (m_CACerts.get() != NULL)
+ {
+ m_Ssl.SetCACerts(m_CACerts, m_ExpectedPeerName);
+ }
+
+ ret = m_Ssl.Handshake();
+ if (ret != 0)
+ {
+ Printf(m_LastErrorText, "SSL handshake failed: -0x%x", -ret);
+ return false;
+ }
+
+ m_IsConnected = true;
+ return true;
+}
+
+
+
+
+
+
+bool cBlockingSslClientSocket::SetTrustedRootCertsFromString(const AString & a_CACerts, const AString & a_ExpectedPeerName)
+{
+ // Warn if used multiple times, but don't signal an error:
+ if (m_CACerts.get() != NULL)
+ {
+ LOGWARNING(
+ "SSL: Trying to set multiple trusted CA root cert stores, only the last one will be used. Name: %s",
+ a_ExpectedPeerName.c_str()
+ );
+ }
+
+ // Parse the cert:
+ m_CACerts.reset(new cX509Cert);
+ int ret = m_CACerts->Parse(a_CACerts.data(), a_CACerts.size());
+ if (ret < 0)
+ {
+ Printf(m_LastErrorText, "CA cert parsing failed: -0x%x", -ret);
+ return false;
+ }
+ m_ExpectedPeerName = a_ExpectedPeerName;
+
+ return true;
+}
+
+
+
+
+
+bool cBlockingSslClientSocket::Send(const void * a_Data, size_t a_NumBytes)
+{
+ ASSERT(m_IsConnected);
+
+ // Keep sending the data until all of it is sent:
+ const char * Data = (const char *)a_Data;
+ size_t NumBytes = a_NumBytes;
+ for (;;)
+ {
+ int res = m_Ssl.WritePlain(a_Data, a_NumBytes);
+ if (res < 0)
+ {
+ ASSERT(res != POLARSSL_ERR_NET_WANT_READ); // This should never happen with callback-based SSL
+ ASSERT(res != POLARSSL_ERR_NET_WANT_WRITE); // This should never happen with callback-based SSL
+ Printf(m_LastErrorText, "Data cannot be written to SSL context: -0x%x", -res);
+ return false;
+ }
+ else
+ {
+ Data += res;
+ NumBytes -= res;
+ if (NumBytes == 0)
+ {
+ return true;
+ }
+ }
+ }
+}
+
+
+
+
+
+
+int cBlockingSslClientSocket::Receive(void * a_Data, size_t a_MaxBytes)
+{
+ ASSERT(m_IsConnected);
+
+ int res = m_Ssl.ReadPlain(a_Data, a_MaxBytes);
+ if (res < 0)
+ {
+ Printf(m_LastErrorText, "Data cannot be read form SSL context: -0x%x", -res);
+ }
+ return res;
+}
+
+
+
+
+
+void cBlockingSslClientSocket::Disconnect(void)
+{
+ // Ignore if not connected
+ if (!m_IsConnected)
+ {
+ return;
+ }
+
+ m_Ssl.NotifyClose();
+ m_Socket.CloseSocket();
+ m_IsConnected = false;
+}
+
+
+
+
+
+int cBlockingSslClientSocket::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes)
+{
+ int res = m_Socket.Receive((char *)a_Buffer, a_NumBytes, 0);
+ if (res < 0)
+ {
+ // PolarSSL's net routines distinguish between connection reset and general failure, we don't need to
+ return POLARSSL_ERR_NET_RECV_FAILED;
+ }
+ return res;
+}
+
+
+
+
+
+int cBlockingSslClientSocket::SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes)
+{
+ int res = m_Socket.Send((const char *)a_Buffer, a_NumBytes);
+ if (res < 0)
+ {
+ // PolarSSL's net routines distinguish between connection reset and general failure, we don't need to
+ return POLARSSL_ERR_NET_SEND_FAILED;
+ }
+ return res;
+}
+
+
+
+
diff --git a/src/PolarSSL++/BlockingSslClientSocket.h b/src/PolarSSL++/BlockingSslClientSocket.h
new file mode 100644
index 000000000..7af897582
--- /dev/null
+++ b/src/PolarSSL++/BlockingSslClientSocket.h
@@ -0,0 +1,80 @@
+
+// BlockingSslClientSocket.h
+
+// Declares the cBlockingSslClientSocket class representing a blocking TCP socket with client SSL encryption over it
+
+
+
+
+
+#pragma once
+
+#include "CallbackSslContext.h"
+#include "../OSSupport/Socket.h"
+
+
+
+
+
+class cBlockingSslClientSocket :
+ protected cCallbackSslContext::cDataCallbacks
+{
+public:
+ cBlockingSslClientSocket(void);
+
+ /** Connects to the specified server and performs SSL handshake.
+ Returns true if successful, false on failure. Sets internal error text on failure. */
+ bool Connect(const AString & a_ServerName, UInt16 a_Port);
+
+ /** Sends the specified data over the connection.
+ Returns true if successful, false on failure. Sets the internal error text on failure. */
+ bool Send(const void * a_Data, size_t a_NumBytes);
+
+ /** Receives data from the connection.
+ Blocks until there is any data available, then returns as much as possible.
+ Returns the number of bytes actually received, negative number on failure.
+ Sets the internal error text on failure. */
+ int Receive(void * a_Data, size_t a_MaxBytes);
+
+ /** Disconnects the connection gracefully, if possible.
+ Note that this also frees the internal SSL context, so all the certificates etc. are lost. */
+ void Disconnect(void);
+
+ /** Sets the root certificates that are to be trusted. Forces the connection to use strict cert
+ verification. Needs to be used before calling Connect().
+ a_ExpectedPeerName is the name that we expect to receive in the SSL peer's cert; verification will fail if
+ the presented name is different (possible MITM).
+ Returns true on success, false on failure. Sets internal error text on failure. */
+ bool SetTrustedRootCertsFromString(const AString & a_CACerts, const AString & a_ExpectedPeerName);
+
+ /** Returns the text of the last error that has occurred in this instance. */
+ const AString & GetLastErrorText(void) const { return m_LastErrorText; }
+
+protected:
+ /** The SSL context used for the socket */
+ cCallbackSslContext m_Ssl;
+
+ /** The underlying socket to the SSL server */
+ cSocket m_Socket;
+
+ /** The trusted CA root cert store, if we are to verify the cert strictly. Set by SetTrustedRootCertsFromString(). */
+ cX509CertPtr m_CACerts;
+
+ /** The expected SSL peer's name, if we are to verify the cert strictly. Set by SetTrustedRootCertsFromString(). */
+ AString m_ExpectedPeerName;
+
+ /** Text of the last error that has occurred. */
+ AString m_LastErrorText;
+
+ /** Set to true if the connection established successfully. */
+ bool m_IsConnected;
+
+
+ // cCallbackSslContext::cDataCallbacks overrides:
+ virtual int ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes) override;
+ virtual int SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes) override;
+} ;
+
+
+
+
diff --git a/src/PolarSSL++/BufferedSslContext.cpp b/src/PolarSSL++/BufferedSslContext.cpp
new file mode 100644
index 000000000..885b30c68
--- /dev/null
+++ b/src/PolarSSL++/BufferedSslContext.cpp
@@ -0,0 +1,62 @@
+
+// BufferedSslContext.cpp
+
+// Implements the cBufferedSslContext class representing a SSL context with the SSL peer data backed by a cByteBuffer
+
+#include "Globals.h"
+#include "BufferedSslContext.h"
+
+
+
+
+
+cBufferedSslContext::cBufferedSslContext(size_t a_BufferSize):
+ m_OutgoingData(a_BufferSize),
+ m_IncomingData(a_BufferSize)
+{
+}
+
+
+
+
+
+int cBufferedSslContext::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes)
+{
+ // Called when PolarSSL wants to read encrypted data from the SSL peer
+ // Read the data from the buffer inside this object, where the owner has stored them using WriteIncoming():
+ size_t NumBytes = std::min(a_NumBytes, m_IncomingData.GetReadableSpace());
+ if (NumBytes == 0)
+ {
+ return POLARSSL_ERR_NET_WANT_READ;
+ }
+ if (!m_IncomingData.ReadBuf(a_Buffer, NumBytes))
+ {
+ m_IncomingData.ResetRead();
+ return POLARSSL_ERR_NET_RECV_FAILED;
+ }
+ m_IncomingData.CommitRead();
+ return (int)NumBytes;
+}
+
+
+
+
+
+int cBufferedSslContext::SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes)
+{
+ // Called when PolarSSL wants to write encrypted data to the SSL peer
+ // Write the data into the buffer inside this object, where the owner can later read them using ReadOutgoing():
+ if (!m_OutgoingData.CanWriteBytes(a_NumBytes))
+ {
+ return POLARSSL_ERR_NET_WANT_WRITE;
+ }
+ if (!m_OutgoingData.Write((const char *)a_Buffer, a_NumBytes))
+ {
+ return POLARSSL_ERR_NET_SEND_FAILED;
+ }
+ return (int)a_NumBytes;
+}
+
+
+
+
diff --git a/src/PolarSSL++/BufferedSslContext.h b/src/PolarSSL++/BufferedSslContext.h
new file mode 100644
index 000000000..1b7e1af46
--- /dev/null
+++ b/src/PolarSSL++/BufferedSslContext.h
@@ -0,0 +1,52 @@
+
+// BufferedSslContext.h
+
+// Declares the cBufferedSslContext class representing a SSL context with the SSL peer data backed by a cByteBuffer
+
+
+
+
+
+#pragma once
+
+#include "SslContext.h"
+
+
+
+
+
+class cBufferedSslContext :
+ public cSslContext
+{
+ typedef cSslContext super;
+
+public:
+ /** Creates a new context with the buffers of specified size for the encrypted / decrypted data. */
+ cBufferedSslContext(size_t a_BufferSize = 64000);
+
+ /** Stores the specified data in the "incoming" buffer, to be process by the SSL decryptor.
+ This is the data received from the SSL peer.
+ Returns the number of bytes actually stored. If 0 is returned, owner should check the error state. */
+ size_t WriteIncoming(const void * a_Data, size_t a_NumBytes);
+
+ /** Retrieves data from the "outgoing" buffer, after being processed by the SSL encryptor.
+ This is the data to be sent to the SSL peer.
+ Returns the number of bytes actually retrieved. */
+ size_t ReadOutgoing(void * a_Data, size_t a_DataMaxSize);
+
+protected:
+ /** Buffer for the data that has been encrypted into the SSL stream and should be sent out. */
+ cByteBuffer m_OutgoingData;
+
+ /** Buffer for the data that has come in and needs to be decrypted from the SSL stream. */
+ cByteBuffer m_IncomingData;
+
+
+ // cSslContext overrides:
+ virtual int ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes) override;
+ virtual int SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes) override;
+} ;
+
+
+
+
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
index c5b747980..14a6dc537 100644
--- a/src/PolarSSL++/CMakeLists.txt
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -5,12 +5,26 @@ project (MCServer)
include_directories ("${PROJECT_SOURCE_DIR}/../")
set(SOURCES
- "EntropyContext.cpp"
+ "BlockingSslClientSocket.cpp"
+ "BufferedSslSocket.cpp"
+ "CallbackSslContext.cpp"
"CtrDrbgContext.cpp"
+ "EntropyContext.cpp"
+ "SslContext.cpp"
"X509Cert.cpp"
)
-add_library(PolarSSL++ ${SOURCES})
+set(HEADERS
+ "BlockingSslClientSocket.h"
+ "BufferedSslSocket.h"
+ "CallbackSslContext.h"
+ "CtrDrbgContext.h"
+ "EntropyContext.h"
+ "SslContext.h"
+ "X509Cert.h"
+)
+
+add_library(PolarSSL++ ${SOURCES} ${HEADERS})
if (UNIX)
target_link_libraries(PolarSSL++ polarssl)
diff --git a/src/PolarSSL++/CallbackSslContext.cpp b/src/PolarSSL++/CallbackSslContext.cpp
new file mode 100644
index 000000000..0cc88a14a
--- /dev/null
+++ b/src/PolarSSL++/CallbackSslContext.cpp
@@ -0,0 +1,59 @@
+
+// CallbackSslContext.cpp
+
+// Declares the cCallbackSslContext class representing a SSL context wrapper that uses callbacks to read and write SSL peer data
+
+#include "Globals.h"
+#include "CallbackSslContext.h"
+
+
+
+
+
+
+cCallbackSslContext::cCallbackSslContext(void)
+{
+ // Nothing needed, but the constructor needs to exist so
+}
+
+
+
+
+
+cCallbackSslContext::cCallbackSslContext(cCallbackSslContext::cDataCallbacks & a_Callbacks) :
+ m_Callbacks(&a_Callbacks)
+{
+}
+
+
+
+
+
+int cCallbackSslContext::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes)
+{
+ if (m_Callbacks == NULL)
+ {
+ LOGWARNING("SSL: Trying to receive data with no callbacks, aborting.");
+ return POLARSSL_ERR_NET_RECV_FAILED;
+ }
+ return m_Callbacks->ReceiveEncrypted(a_Buffer, a_NumBytes);
+}
+
+
+
+
+
+int cCallbackSslContext::SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes)
+{
+ if (m_Callbacks == NULL)
+ {
+ LOGWARNING("SSL: Trying to send data with no callbacks, aborting.");
+ return POLARSSL_ERR_NET_SEND_FAILED;
+ }
+ return m_Callbacks->SendEncrypted(a_Buffer, a_NumBytes);
+}
+
+
+
+
+
diff --git a/src/PolarSSL++/CallbackSslContext.h b/src/PolarSSL++/CallbackSslContext.h
new file mode 100644
index 000000000..4e4c1ed7f
--- /dev/null
+++ b/src/PolarSSL++/CallbackSslContext.h
@@ -0,0 +1,61 @@
+
+// CallbackSslContext.h
+
+// Declares the cCallbackSslContext class representing a SSL context wrapper that uses callbacks to read and write SSL peer data
+
+
+
+
+
+#pragma once
+
+#include "SslContext.h"
+
+
+
+
+
+class cCallbackSslContext :
+ public cSslContext
+{
+public:
+ /** Interface used as a data sink for the SSL peer data. */
+ class cDataCallbacks
+ {
+ public:
+ /** Called when PolarSSL wants to read encrypted data from the SSL peer.
+ The returned value is the number of bytes received, or a PolarSSL error on failure.
+ The implementation can return POLARSSL_ERR_NET_WANT_READ or POLARSSL_ERR_NET_WANT_WRITE to indicate
+ that there's currently no more data and that there might be more data in the future. In such cases the
+ SSL operation that invoked this call will terminate with the same return value, so that the owner is
+ notified of this condition and can potentially restart the operation later on. */
+ virtual int ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes) = 0;
+
+ /** Called when PolarSSL wants to write encrypted data to the SSL peer.
+ The returned value is the number of bytes sent, or a PolarSSL error on failure.
+ The implementation can return POLARSSL_ERR_NET_WANT_READ or POLARSSL_ERR_NET_WANT_WRITE to indicate
+ that there's currently no more data and that there might be more data in the future. In such cases the
+ SSL operation that invoked this call will terminate with the same return value, so that the owner is
+ notified of this condition and can potentially restart the operation later on. */
+ virtual int SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes) = 0;
+ } ;
+
+
+ /** Creates a new SSL context with no callbacks assigned */
+ cCallbackSslContext(void);
+
+ /** Creates a new SSL context with the specified callbacks */
+ cCallbackSslContext(cDataCallbacks & a_Callbacks);
+
+protected:
+ /** The callbacks to use to send and receive SSL peer data */
+ cDataCallbacks * m_Callbacks;
+
+ // cSslContext overrides:
+ virtual int ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes) override;
+ virtual int SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes) override;
+};
+
+
+
+
diff --git a/src/PolarSSL++/SslContext.cpp b/src/PolarSSL++/SslContext.cpp
new file mode 100644
index 000000000..e7fa11c75
--- /dev/null
+++ b/src/PolarSSL++/SslContext.cpp
@@ -0,0 +1,181 @@
+
+// SslContext.cpp
+
+// Implements the cSslContext class that holds everything a single SSL context needs to function
+
+#include "Globals.h"
+#include "SslContext.h"
+#include "EntropyContext.h"
+#include "CtrDrbgContext.h"
+
+
+
+
+
+cSslContext::cSslContext(void) :
+ m_IsValid(false),
+ m_HasHandshaken(false)
+{
+}
+
+
+
+
+
+cSslContext::~cSslContext()
+{
+ if (m_IsValid)
+ {
+ ssl_free(&m_Ssl);
+ }
+}
+
+
+
+
+
+int cSslContext::Initialize(bool a_IsClient, const SharedPtr & a_CtrDrbg)
+{
+ // Check double-initialization:
+ if (m_IsValid)
+ {
+ LOGWARNING("SSL: Double initialization is not supported.");
+ return POLARSSL_ERR_SSL_MALLOC_FAILED; // There is no return value well-suited for this, reuse this one.
+ }
+
+ // Set the CtrDrbg context, create a new one if needed:
+ m_CtrDrbg = a_CtrDrbg;
+ if (m_CtrDrbg.get() == NULL)
+ {
+ m_CtrDrbg.reset(new cCtrDrbgContext);
+ m_CtrDrbg->Initialize("MCServer", 8);
+ }
+
+ // Initialize PolarSSL's structures:
+ memset(&m_Ssl, 0, sizeof(m_Ssl));
+ int res = ssl_init(&m_Ssl);
+ if (res != 0)
+ {
+ return res;
+ }
+ ssl_set_endpoint(&m_Ssl, a_IsClient ? SSL_IS_CLIENT : SSL_IS_SERVER);
+ ssl_set_authmode(&m_Ssl, SSL_VERIFY_OPTIONAL);
+ ssl_set_rng(&m_Ssl, ctr_drbg_random, &m_CtrDrbg->m_CtrDrbg);
+ ssl_set_bio(&m_Ssl, ReceiveEncrypted, this, SendEncrypted, this);
+
+ #ifdef _DEBUG
+ ssl_set_dbg(&m_Ssl, &SSLDebugMessage, this);
+ #endif
+
+ m_IsValid = true;
+ return 0;
+}
+
+
+
+
+
+void cSslContext::SetCACerts(const cX509CertPtr & a_CACert, const AString & a_ExpectedPeerName)
+{
+ // Store the data in our internal buffers, to avoid losing the pointers later on
+ // PolarSSL will need these after this call returns, and the caller may move / delete the data before that:
+ m_ExpectedPeerName = a_ExpectedPeerName;
+ m_CACerts = a_CACert;
+
+ // Set the trusted CA root cert store:
+ ssl_set_authmode(&m_Ssl, SSL_VERIFY_REQUIRED);
+ ssl_set_ca_chain(&m_Ssl, m_CACerts->GetInternal(), NULL, m_ExpectedPeerName.empty() ? NULL : m_ExpectedPeerName.c_str());
+}
+
+
+
+
+
+int cSslContext::WritePlain(const void * a_Data, size_t a_NumBytes)
+{
+ ASSERT(m_IsValid); // Need to call Initialize() first
+ if (!m_HasHandshaken)
+ {
+ int res = Handshake();
+ if (res != 0)
+ {
+ return res;
+ }
+ }
+
+ return ssl_write(&m_Ssl, (const unsigned char *)a_Data, a_NumBytes);
+}
+
+
+
+
+
+int cSslContext::ReadPlain(void * a_Data, size_t a_MaxBytes)
+{
+ ASSERT(m_IsValid); // Need to call Initialize() first
+ if (!m_HasHandshaken)
+ {
+ int res = Handshake();
+ if (res != 0)
+ {
+ return res;
+ }
+ }
+
+ return ssl_read(&m_Ssl, (unsigned char *)a_Data, a_MaxBytes);
+}
+
+
+
+
+
+int cSslContext::Handshake(void)
+{
+ ASSERT(m_IsValid); // Need to call Initialize() first
+ ASSERT(!m_HasHandshaken); // Must not call twice
+
+ int res = ssl_handshake(&m_Ssl);
+ if (res == 0)
+ {
+ m_HasHandshaken = true;
+ }
+ return res;
+}
+
+
+
+
+
+int cSslContext::NotifyClose(void)
+{
+ return ssl_close_notify(&m_Ssl);
+}
+
+
+
+
+
+#ifdef _DEBUG
+ void cSslContext::SSLDebugMessage(void * a_UserParam, int a_Level, const char * a_Text)
+ {
+ if (a_Level > 3)
+ {
+ // Don't want the trace messages
+ return;
+ }
+
+ // Remove the terminating LF:
+ size_t len = strlen(a_Text) - 1;
+ while ((len > 0) && (a_Text[len] <= 32))
+ {
+ len--;
+ }
+ AString Text(a_Text, len + 1);
+
+ LOGD("SSL (%d): %s", a_Level, Text.c_str());
+ }
+#endif // _DEBUG
+
+
+
+
diff --git a/src/PolarSSL++/SslContext.h b/src/PolarSSL++/SslContext.h
new file mode 100644
index 000000000..6effdcaea
--- /dev/null
+++ b/src/PolarSSL++/SslContext.h
@@ -0,0 +1,134 @@
+
+// SslContext.h
+
+// Declares the cSslContext class that holds everything a single SSL context needs to function
+
+
+
+
+
+#pragma once
+
+#include "polarssl/ssl.h"
+#include "../ByteBuffer.h"
+#include "X509Cert.h"
+
+
+
+
+
+// fwd:
+class cCtrDrbgContext;
+
+
+
+
+
+/**
+Acts as a generic SSL encryptor / decryptor between the two endpoints. The "owner" of this class is expected
+to create it, initialize it and then provide the means of reading and writing data through the SSL link.
+This is an abstract base class, there are descendants that handle the specific aspects of how the SSL peer
+data comes into the system:
+ - cBufferedSslContext uses a cByteBuffer to read and write the data
+ - cCallbackSslContext uses callbacks to provide the data
+*/
+class cSslContext abstract
+{
+public:
+ /** Creates a new uninitialized context */
+ cSslContext(void);
+
+ ~cSslContext();
+
+ /** Initializes the context for use as a server or client.
+ Returns 0 on success, PolarSSL error on failure. */
+ int Initialize(bool a_IsClient, const SharedPtr & a_CtrDrbg = SharedPtr());
+
+ /** Returns true if the object has been initialized properly. */
+ bool IsValid(void) const { return m_IsValid; }
+
+ /** Sets a cert chain as the trusted cert store for this context.
+ Calling this will switch the context into strict cert verification mode.
+ a_ExpectedPeerName is the CommonName that we expect the SSL peer to have in its cert,
+ if it is different, the verification will fail. An empty string will disable the CN check. */
+ void SetCACerts(const cX509CertPtr & a_CACert, const AString & a_ExpectedPeerName);
+
+ /** Writes data to be encrypted and sent to the SSL peer. Will perform SSL handshake, if needed.
+ Returns the number of bytes actually written, or PolarSSL error code.
+ If the return value is POLARSSL_ERR_NET_WANT_READ or POLARSSL_ERR_NET_WANT_WRITE, the owner should send any
+ cached outgoing data to the SSL peer and write any incoming data received from the SSL peer and then call
+ this function again with the same parameters. Note that this may repeat a few times before the data is
+ actually written, mainly due to initial handshake. */
+ int WritePlain(const void * a_Data, size_t a_NumBytes);
+
+ /** Reads data decrypted from the SSL stream. Will perform SSL handshake, if needed.
+ Returns the number of bytes actually read, or PolarSSL error code.
+ If the return value is POLARSSL_ERR_NET_WANT_READ or POLARSSL_ERR_NET_WANT_WRITE, the owner should send any
+ cached outgoing data to the SSL peer and write any incoming data received from the SSL peer and then call
+ this function again with the same parameters. Note that this may repeat a few times before the data is
+ actually read, mainly due to initial handshake. */
+ int ReadPlain(void * a_Data, size_t a_MaxBytes);
+
+ /** Performs the SSL handshake.
+ Returns zero on success, PoladSSL error code on failure.
+ If the return value is POLARSSL_ERR_NET_WANT_READ or POLARSSL_ERR_NET_WANT_WRITE, the owner should send any
+ cached outgoing data to the SSL peer and write any incoming data received from the SSL peer and then call
+ this function again. Note that this may repeat a few times before the handshake is completed. */
+ int Handshake(void);
+
+ /** Returns true if the SSL handshake has been completed. */
+ bool HasHandshaken(void) const { return m_HasHandshaken; }
+
+ /** Notifies the SSL peer that the connection is being closed.
+ Returns 0 on success, PolarSSL error code on failure. */
+ int NotifyClose(void);
+
+protected:
+ /** True if the object has been initialized properly. */
+ bool m_IsValid;
+
+ /** The random generator to use */
+ SharedPtr m_CtrDrbg;
+
+ /** The SSL context that PolarSSL uses. */
+ ssl_context m_Ssl;
+
+ /** True if the SSL handshake has been completed. */
+ bool m_HasHandshaken;
+
+ /** A copy of the trusted CA root cert store that is passed to us in SetCACerts(), so that the pointer
+ stays valid even after the call, when PolarSSL finally uses it. */
+ cX509CertPtr m_CACerts;
+
+ /** Buffer for the expected peer name. We need to buffer it because the caller may free the string they
+ give us before PolarSSL consumes the raw pointer it gets to the CN. */
+ AString m_ExpectedPeerName;
+
+
+ /** The callback used by PolarSSL when it wants to read encrypted data. */
+ static int ReceiveEncrypted(void * a_This, unsigned char * a_Buffer, size_t a_NumBytes)
+ {
+ return ((cSslContext *)a_This)->ReceiveEncrypted(a_Buffer, a_NumBytes);
+ }
+
+ /** The callback used by PolarSSL when it wants to write encrypted data. */
+ static int SendEncrypted(void * a_This, const unsigned char * a_Buffer, size_t a_NumBytes)
+ {
+ return ((cSslContext *)a_This)->SendEncrypted(a_Buffer, a_NumBytes);
+ }
+
+ #ifdef _DEBUG
+ /** The callback used by PolarSSL to output debug messages */
+ static void SSLDebugMessage(void * a_UserParam, int a_Level, const char * a_Text);
+ #endif // _DEBUG
+
+ /** Called when PolarSSL wants to read encrypted data. */
+ virtual int ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes) = 0;
+
+ /** Called when PolarSSL wants to write encrypted data. */
+ virtual int SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes) = 0;
+} ;
+
+
+
+
diff --git a/src/PolarSSL++/X509Cert.h b/src/PolarSSL++/X509Cert.h
index 5ef19c324..991617d24 100644
--- a/src/PolarSSL++/X509Cert.h
+++ b/src/PolarSSL++/X509Cert.h
@@ -17,6 +17,8 @@
class cX509Cert
{
+ friend class cSslContext;
+
public:
cX509Cert(void);
~cX509Cert(void);
@@ -25,13 +27,15 @@ public:
Returns 0 on succes, or PolarSSL error code on failure. */
int Parse(const void * a_CertContents, size_t a_Size);
- /** Returns the internal cert ptr. Only use in PolarSSL API calls. */
- OBSOLETE x509_crt * Get(void) { return &m_Cert; }
-
protected:
x509_crt m_Cert;
+
+ /** Returns the internal cert ptr. Only use in PolarSSL API calls. */
+ x509_crt * GetInternal(void) { return &m_Cert; }
} ;
+typedef SharedPtr cX509CertPtr;
+
--
cgit v1.2.3
From dd52719c2d34aa251e90fafb87448af7086e2658 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Sun, 27 Apr 2014 22:28:14 +0200
Subject: Rewritten cAuthenticator to use the new PolarSSL++ wrapper classes.
---
src/Protocol/Authenticator.cpp | 136 ++++++++++++++---------------------------
1 file changed, 45 insertions(+), 91 deletions(-)
diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp
index ccc994e36..efeb6c41c 100644
--- a/src/Protocol/Authenticator.cpp
+++ b/src/Protocol/Authenticator.cpp
@@ -16,9 +16,7 @@
#include "polarssl/ctr_drbg.h"
#include "polarssl/error.h"
-#include "PolarSSL++/EntropyContext.h"
-#include "PolarSSL++/CtrDrbgContext.h"
-#include "PolarSSL++/X509Cert.h"
+#include "PolarSSL++/BlockingSslClientSocket.h"
#include
#include
@@ -150,87 +148,47 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
{
LOGD("Trying to auth user %s", a_UserName.c_str());
- int ret, server_fd = -1;
+ int ret;
unsigned char buf[1024];
- const char pers[] = "cAuthenticator";
-
- cCtrDrbgContext CtrDrbg;
- ssl_context ssl;
- cX509Cert CACert;
-
- /* Initialize the RNG and the session data */
- memset(&ssl, 0, sizeof(ssl_context));
-
- if ((ret = CtrDrbg.Initialize(pers, sizeof(pers))) != 0)
- {
- LOGWARNING("cAuthenticator: CtrDrbg.Initialize() returned %d", ret);
- return false;
- }
/* Initialize certificates */
// This is the root cert for Starfield Technologies, the CA that signed sessionserver.mojang.com's cert:
- static const char StarfieldCACert[] =
- "-----BEGIN CERTIFICATE-----\n"
- "MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\n"
- "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\n"
- "HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\n"
- "ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\n"
- "MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\n"
- "b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\n"
- "aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\n"
- "Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n"
- "ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\n"
- "nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\n"
- "HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N\n"
- "Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN\n"
- "dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0\n"
- "HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO\n"
- "BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G\n"
- "CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU\n"
- "sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3\n"
- "4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg\n"
- "8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K\n"
- "pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1\n"
- "mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0\n"
- "-----END CERTIFICATE-----";
- // Parse the Starfield CA and add it to "trusted root certs"
- ret = CACert.Parse(StarfieldCACert, sizeof(StarfieldCACert) - 1);
- if (ret < 0)
- {
- LOGWARNING("cAuthenticator: CACert.Parse returned -0x%x", -ret);
- return false;
- }
-
- /* Connect */
- if ((ret = net_connect(&server_fd, m_Server.c_str(), 443)) != 0)
- {
- LOGWARNING("cAuthenticator: Can't connect to %s: %d", m_Server.c_str(), ret);
- return false;
- }
-
- /* Setup */
- if ((ret = ssl_init(&ssl)) != 0)
+ static const AString StarfieldCACert(
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\n"
+ "EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\n"
+ "HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\n"
+ "ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\n"
+ "MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\n"
+ "b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\n"
+ "aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\n"
+ "Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n"
+ "ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\n"
+ "nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\n"
+ "HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N\n"
+ "Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN\n"
+ "dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0\n"
+ "HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO\n"
+ "BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G\n"
+ "CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU\n"
+ "sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3\n"
+ "4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg\n"
+ "8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K\n"
+ "pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1\n"
+ "mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0\n"
+ "-----END CERTIFICATE-----"
+ );
+
+ // Connect the socket:
+ cBlockingSslClientSocket Socket;
+ Socket.SetTrustedRootCertsFromString(StarfieldCACert, m_Server);
+ if (!Socket.Connect(m_Server, 443))
{
- LOGWARNING("cAuthenticator: ssl_init returned %d", ret);
+ LOGWARNING("cAuthenticator: Can't connect to %s: %s", m_Server.c_str(), Socket.GetLastErrorText().c_str());
return false;
}
- ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
- ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
- ssl_set_ca_chain(&ssl, CACert.Get(), NULL, "PolarSSL Server 1");
- ssl_set_rng(&ssl, ctr_drbg_random, CtrDrbg.Get());
- ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
-
- /* Handshake */
- while ((ret = ssl_handshake(&ssl)) != 0)
- {
- if ((ret != POLARSSL_ERR_NET_WANT_READ) && (ret != POLARSSL_ERR_NET_WANT_WRITE))
- {
- LOGWARNING("cAuthenticator: ssl_handshake returned -0x%x", -ret);
- return false;
- }
- }
- /* Write the GET request */
+ // Create the GET request:
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", a_UserName);
ReplaceString(ActualAddress, "%SERVERID%", a_ServerId);
@@ -242,23 +200,23 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
Request += "Connection: close\r\n";
Request += "\r\n";
- ret = ssl_write(&ssl, (const unsigned char *)Request.c_str(), Request.size());
- if (ret <= 0)
+ if (!Socket.Send(Request.c_str(), Request.size()))
{
- LOGWARNING("cAuthenticator: ssl_write returned %d", ret);
+ LOGWARNING("cAuthenticator: Writing SSL data failed: %s", Socket.GetLastErrorText().c_str());
return false;
}
- /* Read the HTTP response */
+ // Read the HTTP response:
std::string Response;
for (;;)
{
- memset(buf, 0, sizeof(buf));
- ret = ssl_read(&ssl, buf, sizeof(buf));
+ ret = Socket.Receive(buf, sizeof(buf));
if ((ret == POLARSSL_ERR_NET_WANT_READ) || (ret == POLARSSL_ERR_NET_WANT_WRITE))
{
- continue;
+ // This value should never be returned, it is handled internally by cBlockingSslClientSocket
+ LOGWARNING("cAuthenticator: SSL reading failed internally.");
+ return false;
}
if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
{
@@ -266,22 +224,18 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
}
if (ret < 0)
{
- LOGWARNING("cAuthenticator: ssl_read returned %d", ret);
- break;
+ LOGWARNING("cAuthenticator: SSL reading failed: -0x%x", -ret);
+ return false;
}
if (ret == 0)
{
- LOGWARNING("cAuthenticator: EOF");
break;
}
- Response.append((const char *)buf, ret);
+ Response.append((const char *)buf, (size_t)ret);
}
- ssl_close_notify(&ssl);
- net_close(server_fd);
- ssl_free(&ssl);
- memset(&ssl, 0, sizeof(ssl));
+ Socket.Disconnect();
// Check the HTTP status line:
AString prefix("HTTP/1.1 200 OK");
--
cgit v1.2.3
From 744e00c904ebde6c89aa4763f06118635694d396 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Sun, 27 Apr 2014 13:43:59 -0700
Subject: Worked around const pointer
---
src/BlockArea.cpp | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index 49c564ca5..e4b122fa2 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -665,9 +665,10 @@ void cBlockArea::Merge(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_R
{
size_t SrcCount = a_Src.GetBlockCount();
size_t DestCount = GetBlockCount();
- SrcMetas = new NIBBLETYPE[SrcCount];
+ NIBBLETYPE * tempSrcMetas = new NIBBLETYPE[SrcCount];
+ memset(tempSrcMetas, 0, SrcCount);
+ SrcMetas = tempSrcMetas;
DstMetas = new NIBBLETYPE[DestCount];
- memset(SrcMetas, 0, SrcCount);
memset(DstMetas, 0, DestCount);
}
--
cgit v1.2.3
From bb73af68432b56d0c52c23448e4092d753521057 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Sun, 27 Apr 2014 23:31:26 +0200
Subject: Fixed a late-night typo.
---
src/PolarSSL++/CMakeLists.txt | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
index 14a6dc537..0493baba4 100644
--- a/src/PolarSSL++/CMakeLists.txt
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -6,7 +6,7 @@ include_directories ("${PROJECT_SOURCE_DIR}/../")
set(SOURCES
"BlockingSslClientSocket.cpp"
- "BufferedSslSocket.cpp"
+ "BufferedSslContext.cpp"
"CallbackSslContext.cpp"
"CtrDrbgContext.cpp"
"EntropyContext.cpp"
@@ -16,7 +16,7 @@ set(SOURCES
set(HEADERS
"BlockingSslClientSocket.h"
- "BufferedSslSocket.h"
+ "BufferedSslContext.h"
"CallbackSslContext.h"
"CtrDrbgContext.h"
"EntropyContext.h"
--
cgit v1.2.3
From ef57133f9b457430d2717825b91b747b378e6233 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Sun, 27 Apr 2014 23:35:17 +0200
Subject: Reordered constructors.
---
src/PolarSSL++/BlockingSslClientSocket.cpp | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/PolarSSL++/BlockingSslClientSocket.cpp b/src/PolarSSL++/BlockingSslClientSocket.cpp
index 20b2df1e7..699bc57ee 100644
--- a/src/PolarSSL++/BlockingSslClientSocket.cpp
+++ b/src/PolarSSL++/BlockingSslClientSocket.cpp
@@ -11,8 +11,8 @@
cBlockingSslClientSocket::cBlockingSslClientSocket(void) :
- m_IsConnected(false),
- m_Ssl(*this)
+ m_Ssl(*this),
+ m_IsConnected(false)
{
// Nothing needed yet
}
--
cgit v1.2.3
From 26e935cb2028e041623424d474ccf1b127d55e97 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Mon, 28 Apr 2014 13:51:22 +0200
Subject: Revert "Changed the old invulnerable methods from the wither to the
new."
This reverts commit d50f8f6f11f69e7e1e56be92fb2d72a5014a3e34.
---
src/Mobs/Wither.h | 3 ---
src/Protocol/Protocol125.cpp | 9 +--------
src/Protocol/Protocol17x.cpp | 9 +--------
src/WorldStorage/NBTChunkSerializer.cpp | 9 +--------
src/WorldStorage/WSSAnvil.cpp | 2 +-
5 files changed, 4 insertions(+), 28 deletions(-)
diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h
index fbea331d3..81c9df1b1 100644
--- a/src/Mobs/Wither.h
+++ b/src/Mobs/Wither.h
@@ -19,9 +19,6 @@ public:
/** Returns whether the wither is invulnerable to arrows. */
bool IsArmored(void) const;
-
- /** Use the wither the invulnerable from the spawn? */
- bool IsSpawnInvulnerable(void) const { return m_IsSpawnInvulnerable; }
// cEntity overrides
virtual bool Initialize(cWorld * a_World) override;
diff --git a/src/Protocol/Protocol125.cpp b/src/Protocol/Protocol125.cpp
index 3951eb3e4..a23afb29a 100644
--- a/src/Protocol/Protocol125.cpp
+++ b/src/Protocol/Protocol125.cpp
@@ -2013,14 +2013,7 @@ void cProtocol125::WriteMobMetadata(const cMonster & a_Mob)
case cMonster::mtWither:
{
WriteByte(0x54); // Int at index 20
- if (((const cWither &)a_Mob).IsSpawnInvulnerable())
- {
- WriteInt((Int32)((const cWither &)a_Mob).GetInvulnerableTicks());
- }
- else
- {
- WriteInt((Int32)0);
- }
+ WriteInt((Int32)((const cWither &)a_Mob).GetWitherInvulnerableTicks());
WriteByte(0x66); // Float at index 6
WriteFloat((float)(a_Mob.GetHealth()));
break;
diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp
index 311e770f9..80b161e3e 100644
--- a/src/Protocol/Protocol17x.cpp
+++ b/src/Protocol/Protocol17x.cpp
@@ -2820,14 +2820,7 @@ void cProtocol172::cPacketizer::WriteMobMetadata(const cMonster & a_Mob)
case cMonster::mtWither:
{
WriteByte(0x54); // Int at index 20
- if (((const cWither &)a_Mob).IsSpawnInvulnerable())
- {
- WriteInt(((const cWither &)a_Mob).GetInvulnerableTicks());
- }
- else
- {
- WriteInt(0);
- }
+ WriteInt(((const cWither &)a_Mob).GetWitherInvulnerableTicks());
WriteByte(0x66); // Float at index 6
WriteFloat((float)(a_Mob.GetHealth()));
break;
diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp
index 0c4a1a430..46c6b8e92 100644
--- a/src/WorldStorage/NBTChunkSerializer.cpp
+++ b/src/WorldStorage/NBTChunkSerializer.cpp
@@ -516,14 +516,7 @@ void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster)
}
case cMonster::mtWither:
{
- if (((const cWither *)a_Monster)->IsSpawnInvulnerable())
- {
- m_Writer.AddInt("Invul", ((const cWither *)a_Monster)->GetInvulnerableTicks());
- }
- else
- {
- m_Writer.AddInt("Invul", 0);
- }
+ m_Writer.AddInt("Invul", ((const cWither *)a_Monster)->GetWitherInvulnerableTicks());
break;
}
case cMonster::mtWolf:
diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp
index c21809270..4532a925a 100644
--- a/src/WorldStorage/WSSAnvil.cpp
+++ b/src/WorldStorage/WSSAnvil.cpp
@@ -2272,7 +2272,7 @@ void cWSSAnvil::LoadWitherFromNBT(cEntityList & a_Entities, const cParsedNBT & a
int CurrLine = a_NBT.FindChildByName(a_TagIdx, "Invul");
if (CurrLine > 0)
{
- Monster->SetInvulnerableTicks(a_NBT.GetInt(CurrLine));
+ Monster->SetWitherInvulnerableTicks(a_NBT.GetInt(CurrLine));
}
a_Entities.push_back(Monster.release());
--
cgit v1.2.3
From acd2804f316114a50b7103158a6bff5d3d14f673 Mon Sep 17 00:00:00 2001
From: Howaner
Date: Mon, 28 Apr 2014 13:51:40 +0200
Subject: Revert "Withers now use the new invulnerable."
This reverts commit 619592b5a0ab651e714d55932bc7909e4204cee9.
---
src/Mobs/Wither.cpp | 29 ++++++++++++++++++++---------
src/Mobs/Wither.h | 7 ++++++-
2 files changed, 26 insertions(+), 10 deletions(-)
diff --git a/src/Mobs/Wither.cpp b/src/Mobs/Wither.cpp
index fe4dbb28b..5b6e895e1 100644
--- a/src/Mobs/Wither.cpp
+++ b/src/Mobs/Wither.cpp
@@ -10,10 +10,9 @@
cWither::cWither(void) :
super("Wither", mtWither, "mob.wither.hurt", "mob.wither.death", 0.9, 4.0),
- m_IsSpawnInvulnerable(true)
+ m_WitherInvulnerableTicks(220)
{
SetMaxHealth(300);
- SetInvulnerableTicks(220);
}
@@ -48,6 +47,11 @@ bool cWither::DoTakeDamage(TakeDamageInfo & a_TDI)
return false;
}
+ if (m_WitherInvulnerableTicks > 0)
+ {
+ return false;
+ }
+
if (IsArmored() && (a_TDI.DamageType == dtRangedAttack))
{
return false;
@@ -64,14 +68,21 @@ void cWither::Tick(float a_Dt, cChunk & a_Chunk)
{
super::Tick(a_Dt, a_Chunk);
- if (GetInvulnerableTicks() <= 0 && m_IsSpawnInvulnerable)
+ if (m_WitherInvulnerableTicks > 0)
{
- m_World->DoExplosionAt(7.0, GetPosX(), GetPosY(), GetPosZ(), false, esWitherBirth, this);
- m_IsSpawnInvulnerable = false;
- }
- else if (((GetInvulnerableTicks() % 10) == 0) && (GetInvulnerableTicks() > 10))
- {
- Heal(10);
+ unsigned int NewTicks = m_WitherInvulnerableTicks - 1;
+
+ if (NewTicks == 0)
+ {
+ m_World->DoExplosionAt(7.0, GetPosX(), GetPosY(), GetPosZ(), false, esWitherBirth, this);
+ }
+
+ m_WitherInvulnerableTicks = NewTicks;
+
+ if ((NewTicks % 10) == 0)
+ {
+ Heal(10);
+ }
}
m_World->BroadcastEntityMetadata(*this);
diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h
index 81c9df1b1..08b460009 100644
--- a/src/Mobs/Wither.h
+++ b/src/Mobs/Wither.h
@@ -17,6 +17,10 @@ public:
CLASS_PROTODEF(cWither);
+ unsigned int GetWitherInvulnerableTicks(void) const { return m_WitherInvulnerableTicks; }
+
+ void SetWitherInvulnerableTicks(unsigned int a_Ticks) { m_WitherInvulnerableTicks = a_Ticks; }
+
/** Returns whether the wither is invulnerable to arrows. */
bool IsArmored(void) const;
@@ -28,7 +32,8 @@ public:
private:
- bool m_IsSpawnInvulnerable;
+ /** The number of ticks of invulnerability left after being initially created. Zero once invulnerability has expired. */
+ unsigned int m_WitherInvulnerableTicks;
} ;
--
cgit v1.2.3
From a42480cf8266a1e066209823aab42c9a3829adbc Mon Sep 17 00:00:00 2001
From: Tycho
Date: Mon, 28 Apr 2014 10:31:07 -0700
Subject: Template Magic
Removed need to allocate a fake meta block by using templates to provide a version
of the code that does not use metas. Also changed the function to a template
argument to make sure that the compilier is able to inline it.
---
src/BlockArea.cpp | 343 +++++++++++++++++++++++++------------------------
src/BlockArea.h | 5 +-
src/OSSupport/File.cpp | 4 +-
src/OSSupport/File.h | 4 +-
4 files changed, 183 insertions(+), 173 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index e4b122fa2..359f5cb81 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -13,18 +13,20 @@
-
// This wild construct allows us to pass a function argument and still have it inlined by the compiler :)
/// Merges two blocktypes and blockmetas of the specified sizes and offsets using the specified combinator function
-template void InternalMergeBlocks(
+
+typedef void (CombinatorFunc)(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta);
+
+template
+void InternalMergeBlocks(
BLOCKTYPE * a_DstTypes, const BLOCKTYPE * a_SrcTypes,
NIBBLETYPE * a_DstMetas, const NIBBLETYPE * a_SrcMetas,
int a_SizeX, int a_SizeY, int a_SizeZ,
int a_SrcOffX, int a_SrcOffY, int a_SrcOffZ,
int a_DstOffX, int a_DstOffY, int a_DstOffZ,
int a_SrcSizeX, int a_SrcSizeY, int a_SrcSizeZ,
- int a_DstSizeX, int a_DstSizeY, int a_DstSizeZ,
- Combinator a_Combinator
+ int a_DstSizeX, int a_DstSizeY, int a_DstSizeZ
)
{
UNUSED(a_SrcSizeY);
@@ -41,7 +43,15 @@ template void InternalMergeBlocks(
int DstIdx = DstBaseZ + a_DstOffX;
for (int x = 0; x < a_SizeX; x++)
{
- a_Combinator(a_DstTypes[DstIdx], a_SrcTypes[SrcIdx], a_DstMetas[DstIdx], a_SrcMetas[SrcIdx]);
+ if (MetasValid)
+ {
+ Combinator(a_DstTypes[DstIdx], a_SrcTypes[SrcIdx], a_DstMetas[DstIdx], a_SrcMetas[SrcIdx]);
+ }
+ else
+ {
+ BLOCKTYPE FakeDestMeta = 0;
+ Combinator(a_DstTypes[DstIdx], a_SrcTypes[SrcIdx], FakeDestMeta, (NIBBLETYPE)0);
+ }
++DstIdx;
++SrcIdx;
} // for x
@@ -51,13 +61,12 @@ template void InternalMergeBlocks(
-
-
/// Combinator used for cBlockArea::msOverwrite merging
+template
static inline void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
a_DstType = a_SrcType;
- a_DstMeta = a_SrcMeta;
+ if (MetaValid) a_DstMeta = a_SrcMeta;
}
@@ -65,12 +74,13 @@ static inline void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_S
/// Combinator used for cBlockArea::msFillAir merging
+template
static inline void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if (a_DstType == E_BLOCK_AIR)
{
a_DstType = a_SrcType;
- a_DstMeta = a_SrcMeta;
+ if (MetaValid) a_DstMeta = a_SrcMeta;
}
// "else" is the default, already in place
}
@@ -80,12 +90,13 @@ static inline void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_Src
/// Combinator used for cBlockArea::msImprint merging
+template
static inline void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if (a_SrcType != E_BLOCK_AIR)
{
a_DstType = a_SrcType;
- a_DstMeta = a_SrcMeta;
+ if (MetaValid) a_DstMeta = a_SrcMeta;
}
// "else" is the default, already in place
}
@@ -95,6 +106,7 @@ static inline void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_Src
/// Combinator used for cBlockArea::msLake merging
+template
static inline void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// Sponge is the NOP block
@@ -107,7 +119,7 @@ static inline void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcTyp
if (a_SrcType == E_BLOCK_AIR)
{
a_DstType = E_BLOCK_AIR;
- a_DstMeta = 0;
+ if (MetaValid) a_DstMeta = 0;
return;
}
@@ -132,7 +144,7 @@ static inline void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcTyp
case E_BLOCK_STATIONARY_LAVA:
{
a_DstType = a_SrcType;
- a_DstMeta = a_SrcMeta;
+ if (MetaValid) a_DstMeta = a_SrcMeta;
return;
}
}
@@ -146,7 +158,7 @@ static inline void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcTyp
case E_BLOCK_MYCELIUM:
{
a_DstType = E_BLOCK_STONE;
- a_DstMeta = 0;
+ if (MetaValid) a_DstMeta = 0;
return;
}
}
@@ -159,13 +171,14 @@ static inline void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcTyp
/** Combinator used for cBlockArea::msSpongePrint merging */
+template
static inline void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// Sponge overwrites nothing, everything else overwrites anything
if (a_SrcType != E_BLOCK_SPONGE)
{
a_DstType = a_SrcType;
- a_DstMeta = a_SrcMeta;
+ if (MetaValid) a_DstMeta = a_SrcMeta;
}
}
@@ -174,17 +187,18 @@ static inline void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a
/** Combinator used for cBlockArea::msDifference merging */
+template
static inline void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
- if ((a_DstType == a_SrcType) && (a_DstMeta == a_SrcMeta))
+ if ((a_DstType == a_SrcType) && (!MetaValid || (a_DstMeta == a_SrcMeta)))
{
a_DstType = E_BLOCK_AIR;
- a_DstMeta = 0;
+ if (MetaValid) a_DstMeta = 0;
}
else
{
a_DstType = a_SrcType;
- a_DstMeta = a_SrcMeta;
+ if (MetaValid) a_DstMeta = a_SrcMeta;
}
}
@@ -193,13 +207,14 @@ static inline void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_
/** Combinator used for cBlockArea::msMask merging */
+template
static inline void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// If the blocks are the same, keep the dest; otherwise replace with air
- if ((a_SrcType != a_DstType) || (a_SrcMeta != a_DstMeta))
+ if ((a_SrcType != a_DstType) || !MetaValid || (a_SrcMeta != a_DstMeta))
{
a_DstType = E_BLOCK_AIR;
- a_DstMeta = 0;
+ if (MetaValid) a_DstMeta = 0;
}
}
@@ -484,7 +499,7 @@ void cBlockArea::CopyTo(cBlockArea & a_Into) const
a_Into.Clear();
a_Into.SetSize(m_Size.x, m_Size.y, m_Size.z, GetDataTypes());
a_Into.m_Origin = m_Origin;
- int BlockCount = GetBlockCount();
+ size_t BlockCount = GetBlockCount();
if (HasBlockTypes())
{
memcpy(a_Into.m_BlockTypes, m_BlockTypes, BlockCount * sizeof(BLOCKTYPE));
@@ -532,7 +547,7 @@ void cBlockArea::DumpToRawFile(const AString & a_FileName)
f.Write(&SizeZ, 4);
unsigned char DataTypes = (unsigned char)GetDataTypes();
f.Write(&DataTypes, 1);
- int NumBlocks = GetBlockCount();
+ size_t NumBlocks = GetBlockCount();
if (HasBlockTypes())
{
f.Write(m_BlockTypes, NumBlocks * sizeof(BLOCKTYPE));
@@ -637,160 +652,19 @@ void cBlockArea::Expand(int a_SubMinX, int a_AddMaxX, int a_SubMinY, int a_AddMa
void cBlockArea::Merge(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_RelZ, eMergeStrategy a_Strategy)
{
- // Block types are compulsory, block metas are voluntary
- if (!HasBlockTypes() || !a_Src.HasBlockTypes())
- {
- LOGWARNING("%s: cannot merge because one of the areas doesn't have blocktypes.", __FUNCTION__);
- return;
- }
-
- // Dst is *this, Src is a_Src
- int SrcOffX = std::max(0, -a_RelX); // Offset in Src where to start reading
- int DstOffX = std::max(0, a_RelX); // Offset in Dst where to start writing
- int SizeX = std::min(a_Src.GetSizeX() - SrcOffX, GetSizeX() - DstOffX); // How many blocks to copy
-
- int SrcOffY = std::max(0, -a_RelY); // Offset in Src where to start reading
- int DstOffY = std::max(0, a_RelY); // Offset in Dst where to start writing
- int SizeY = std::min(a_Src.GetSizeY() - SrcOffY, GetSizeY() - DstOffY); // How many blocks to copy
-
- int SrcOffZ = std::max(0, -a_RelZ); // Offset in Src where to start reading
- int DstOffZ = std::max(0, a_RelZ); // Offset in Dst where to start writing
- int SizeZ = std::min(a_Src.GetSizeZ() - SrcOffZ, GetSizeZ() - DstOffZ); // How many blocks to copy
const NIBBLETYPE * SrcMetas = a_Src.GetBlockMetas();
NIBBLETYPE * DstMetas = m_BlockMetas;
+
bool IsDummyMetas = ((SrcMetas == NULL) || (DstMetas == NULL));
if (IsDummyMetas)
{
- size_t SrcCount = a_Src.GetBlockCount();
- size_t DestCount = GetBlockCount();
- NIBBLETYPE * tempSrcMetas = new NIBBLETYPE[SrcCount];
- memset(tempSrcMetas, 0, SrcCount);
- SrcMetas = tempSrcMetas;
- DstMetas = new NIBBLETYPE[DestCount];
- memset(DstMetas, 0, DestCount);
+ MergeByStrategy(a_Src, a_RelX, a_RelY, a_RelZ, a_Strategy, SrcMetas, DstMetas);
}
-
- switch (a_Strategy)
- {
- case msOverwrite:
- {
- InternalMergeBlocks(
- m_BlockTypes, a_Src.GetBlockTypes(),
- DstMetas, SrcMetas,
- SizeX, SizeY, SizeZ,
- SrcOffX, SrcOffY, SrcOffZ,
- DstOffX, DstOffY, DstOffZ,
- a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
- m_Size.x, m_Size.y, m_Size.z,
- MergeCombinatorOverwrite
- );
- break;
- } // case msOverwrite
-
- case msFillAir:
- {
- InternalMergeBlocks(
- m_BlockTypes, a_Src.GetBlockTypes(),
- DstMetas, SrcMetas,
- SizeX, SizeY, SizeZ,
- SrcOffX, SrcOffY, SrcOffZ,
- DstOffX, DstOffY, DstOffZ,
- a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
- m_Size.x, m_Size.y, m_Size.z,
- MergeCombinatorFillAir
- );
- break;
- } // case msFillAir
-
- case msImprint:
- {
- InternalMergeBlocks(
- m_BlockTypes, a_Src.GetBlockTypes(),
- DstMetas, SrcMetas,
- SizeX, SizeY, SizeZ,
- SrcOffX, SrcOffY, SrcOffZ,
- DstOffX, DstOffY, DstOffZ,
- a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
- m_Size.x, m_Size.y, m_Size.z,
- MergeCombinatorImprint
- );
- break;
- } // case msImprint
-
- case msLake:
- {
- InternalMergeBlocks(
- m_BlockTypes, a_Src.GetBlockTypes(),
- DstMetas, SrcMetas,
- SizeX, SizeY, SizeZ,
- SrcOffX, SrcOffY, SrcOffZ,
- DstOffX, DstOffY, DstOffZ,
- a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
- m_Size.x, m_Size.y, m_Size.z,
- MergeCombinatorLake
- );
- break;
- } // case msLake
-
- case msSpongePrint:
- {
- InternalMergeBlocks(
- m_BlockTypes, a_Src.GetBlockTypes(),
- DstMetas, SrcMetas,
- SizeX, SizeY, SizeZ,
- SrcOffX, SrcOffY, SrcOffZ,
- DstOffX, DstOffY, DstOffZ,
- a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
- m_Size.x, m_Size.y, m_Size.z,
- MergeCombinatorSpongePrint
- );
- break;
- } // case msSpongePrint
-
- case msDifference:
- {
- InternalMergeBlocks(
- m_BlockTypes, a_Src.GetBlockTypes(),
- DstMetas, SrcMetas,
- SizeX, SizeY, SizeZ,
- SrcOffX, SrcOffY, SrcOffZ,
- DstOffX, DstOffY, DstOffZ,
- a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
- m_Size.x, m_Size.y, m_Size.z,
- MergeCombinatorDifference
- );
- break;
- } // case msDifference
-
- case msMask:
- {
- InternalMergeBlocks(
- m_BlockTypes, a_Src.GetBlockTypes(),
- DstMetas, SrcMetas,
- SizeX, SizeY, SizeZ,
- SrcOffX, SrcOffY, SrcOffZ,
- DstOffX, DstOffY, DstOffZ,
- a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
- m_Size.x, m_Size.y, m_Size.z,
- MergeCombinatorMask
- );
- break;
- } // case msMask
-
- default:
- {
- LOGWARNING("Unknown block area merge strategy: %d", a_Strategy);
- ASSERT(!"Unknown block area merge strategy");
- break;
- }
- } // switch (a_Strategy)
-
- if (IsDummyMetas)
+ else
{
- delete[] SrcMetas;
- delete[] DstMetas;
+ MergeByStrategy(a_Src, a_RelX, a_RelY, a_RelZ, a_Strategy, SrcMetas, DstMetas);
}
}
@@ -2084,7 +1958,7 @@ void cBlockArea::ExpandBlockTypes(int a_SubMinX, int a_AddMaxX, int a_SubMinY, i
int NewSizeX = m_Size.x + a_SubMinX + a_AddMaxX;
int NewSizeY = m_Size.y + a_SubMinY + a_AddMaxY;
int NewSizeZ = m_Size.z + a_SubMinZ + a_AddMaxZ;
- int BlockCount = NewSizeX * NewSizeY * NewSizeZ;
+ size_t BlockCount = (size_t)NewSizeX * NewSizeY * NewSizeZ;
BLOCKTYPE * NewBlockTypes = new BLOCKTYPE[BlockCount];
memset(NewBlockTypes, 0, BlockCount * sizeof(BLOCKTYPE));
int OldIndex = 0;
@@ -2114,7 +1988,7 @@ void cBlockArea::ExpandNibbles(NIBBLEARRAY & a_Array, int a_SubMinX, int a_AddMa
int NewSizeX = m_Size.x + a_SubMinX + a_AddMaxX;
int NewSizeY = m_Size.y + a_SubMinY + a_AddMaxY;
int NewSizeZ = m_Size.z + a_SubMinZ + a_AddMaxZ;
- int BlockCount = NewSizeX * NewSizeY * NewSizeZ;
+ size_t BlockCount = (size_t)NewSizeX * NewSizeY * NewSizeZ;
NIBBLETYPE * NewNibbles = new NIBBLETYPE[BlockCount];
memset(NewNibbles, 0, BlockCount * sizeof(NIBBLETYPE));
int OldIndex = 0;
@@ -2166,4 +2040,137 @@ void cBlockArea::RelSetData(
+template
+void cBlockArea::MergeByStrategy(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_RelZ, eMergeStrategy a_Strategy, const NIBBLETYPE * SrcMetas, NIBBLETYPE * DstMetas)
+{
+ // Block types are compulsory, block metas are voluntary
+ if (!HasBlockTypes() || !a_Src.HasBlockTypes())
+ {
+ LOGWARNING("%s: cannot merge because one of the areas doesn't have blocktypes.", __FUNCTION__);
+ return;
+ }
+
+ // Dst is *this, Src is a_Src
+ int SrcOffX = std::max(0, -a_RelX); // Offset in Src where to start reading
+ int DstOffX = std::max(0, a_RelX); // Offset in Dst where to start writing
+ int SizeX = std::min(a_Src.GetSizeX() - SrcOffX, GetSizeX() - DstOffX); // How many blocks to copy
+
+ int SrcOffY = std::max(0, -a_RelY); // Offset in Src where to start reading
+ int DstOffY = std::max(0, a_RelY); // Offset in Dst where to start writing
+ int SizeY = std::min(a_Src.GetSizeY() - SrcOffY, GetSizeY() - DstOffY); // How many blocks to copy
+
+ int SrcOffZ = std::max(0, -a_RelZ); // Offset in Src where to start reading
+ int DstOffZ = std::max(0, a_RelZ); // Offset in Dst where to start writing
+ int SizeZ = std::min(a_Src.GetSizeZ() - SrcOffZ, GetSizeZ() - DstOffZ); // How many blocks to copy
+
+ switch (a_Strategy)
+ {
+ case cBlockArea::msOverwrite:
+ {
+ InternalMergeBlocks >(
+ m_BlockTypes, a_Src.GetBlockTypes(),
+ DstMetas, SrcMetas,
+ SizeX, SizeY, SizeZ,
+ SrcOffX, SrcOffY, SrcOffZ,
+ DstOffX, DstOffY, DstOffZ,
+ a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
+ m_Size.x, m_Size.y, m_Size.z
+ );
+ break;
+ } // case msOverwrite
+
+ case cBlockArea::msFillAir:
+ {
+ InternalMergeBlocks >(
+ m_BlockTypes, a_Src.GetBlockTypes(),
+ DstMetas, SrcMetas,
+ SizeX, SizeY, SizeZ,
+ SrcOffX, SrcOffY, SrcOffZ,
+ DstOffX, DstOffY, DstOffZ,
+ a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
+ m_Size.x, m_Size.y, m_Size.z
+ );
+ break;
+ } // case msFillAir
+
+ case cBlockArea::msImprint:
+ {
+ InternalMergeBlocks >(
+ m_BlockTypes, a_Src.GetBlockTypes(),
+ DstMetas, SrcMetas,
+ SizeX, SizeY, SizeZ,
+ SrcOffX, SrcOffY, SrcOffZ,
+ DstOffX, DstOffY, DstOffZ,
+ a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
+ m_Size.x, m_Size.y, m_Size.z
+ );
+ break;
+ } // case msImprint
+
+ case cBlockArea::msLake:
+ {
+ InternalMergeBlocks >(
+ m_BlockTypes, a_Src.GetBlockTypes(),
+ DstMetas, SrcMetas,
+ SizeX, SizeY, SizeZ,
+ SrcOffX, SrcOffY, SrcOffZ,
+ DstOffX, DstOffY, DstOffZ,
+ a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
+ m_Size.x, m_Size.y, m_Size.z
+ );
+ break;
+ } // case msLake
+
+ case cBlockArea::msSpongePrint:
+ {
+ InternalMergeBlocks >(
+ m_BlockTypes, a_Src.GetBlockTypes(),
+ DstMetas, SrcMetas,
+ SizeX, SizeY, SizeZ,
+ SrcOffX, SrcOffY, SrcOffZ,
+ DstOffX, DstOffY, DstOffZ,
+ a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
+ m_Size.x, m_Size.y, m_Size.z
+ );
+ break;
+ } // case msSpongePrint
+
+ case cBlockArea::msDifference:
+ {
+ InternalMergeBlocks >(
+ m_BlockTypes, a_Src.GetBlockTypes(),
+ DstMetas, SrcMetas,
+ SizeX, SizeY, SizeZ,
+ SrcOffX, SrcOffY, SrcOffZ,
+ DstOffX, DstOffY, DstOffZ,
+ a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
+ m_Size.x, m_Size.y, m_Size.z
+ );
+ break;
+ } // case msDifference
+
+ case cBlockArea::msMask:
+ {
+ InternalMergeBlocks >(
+ m_BlockTypes, a_Src.GetBlockTypes(),
+ DstMetas, SrcMetas,
+ SizeX, SizeY, SizeZ,
+ SrcOffX, SrcOffY, SrcOffZ,
+ DstOffX, DstOffY, DstOffZ,
+ a_Src.GetSizeX(), a_Src.GetSizeY(), a_Src.GetSizeZ(),
+ m_Size.x, m_Size.y, m_Size.z
+ );
+ break;
+ } // case msMask
+
+ default:
+ {
+ LOGWARNING("Unknown block area merge strategy: %d", a_Strategy);
+ ASSERT(!"Unknown block area merge strategy");
+ break;
+ }
+ } // switch (a_Strategy)
+}
+
+
diff --git a/src/BlockArea.h b/src/BlockArea.h
index c48175b8c..4c4dfb8ff 100644
--- a/src/BlockArea.h
+++ b/src/BlockArea.h
@@ -294,7 +294,7 @@ public:
NIBBLETYPE * GetBlockMetas (void) const { return m_BlockMetas; } // NOTE: one byte per block!
NIBBLETYPE * GetBlockLight (void) const { return m_BlockLight; } // NOTE: one byte per block!
NIBBLETYPE * GetBlockSkyLight(void) const { return m_BlockSkyLight; } // NOTE: one byte per block!
- int GetBlockCount(void) const { return m_Size.x * m_Size.y * m_Size.z; }
+ size_t GetBlockCount(void) const { return m_Size.x * m_Size.y * m_Size.z; }
int MakeIndex(int a_RelX, int a_RelY, int a_RelZ) const;
protected:
@@ -363,6 +363,9 @@ protected:
int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta,
NIBBLETYPE a_BlockLight, NIBBLETYPE a_BlockSkyLight
);
+
+ template
+ void MergeByStrategy(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_RelZ, eMergeStrategy a_Strategy, const NIBBLETYPE * SrcMetas, NIBBLETYPE * DstMetas);
// tolua_begin
} ;
// tolua_end
diff --git a/src/OSSupport/File.cpp b/src/OSSupport/File.cpp
index f1b3bcf9e..33b9cfc3f 100644
--- a/src/OSSupport/File.cpp
+++ b/src/OSSupport/File.cpp
@@ -143,7 +143,7 @@ bool cFile::IsEOF(void) const
-int cFile::Read (void * iBuffer, int iNumBytes)
+int cFile::Read (void * iBuffer, size_t iNumBytes)
{
ASSERT(IsOpen());
@@ -159,7 +159,7 @@ int cFile::Read (void * iBuffer, int iNumBytes)
-int cFile::Write(const void * iBuffer, int iNumBytes)
+int cFile::Write(const void * iBuffer, size_t iNumBytes)
{
ASSERT(IsOpen());
diff --git a/src/OSSupport/File.h b/src/OSSupport/File.h
index b394c5cb9..2a7ecf0ed 100644
--- a/src/OSSupport/File.h
+++ b/src/OSSupport/File.h
@@ -80,10 +80,10 @@ public:
bool IsEOF(void) const;
/** Reads up to iNumBytes bytes into iBuffer, returns the number of bytes actually read, or -1 on failure; asserts if not open */
- int Read (void * iBuffer, int iNumBytes);
+ int Read (void * iBuffer, size_t iNumBytes);
/** Writes up to iNumBytes bytes from iBuffer, returns the number of bytes actually written, or -1 on failure; asserts if not open */
- int Write(const void * iBuffer, int iNumBytes);
+ int Write(const void * iBuffer, size_t iNumBytes);
/** Seeks to iPosition bytes from file start, returns old position or -1 for failure; asserts if not open */
int Seek (int iPosition);
--
cgit v1.2.3
From 05fe6d6c58172dc1f28c9dde06b18e7e309e5212 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Mon, 28 Apr 2014 10:52:48 -0700
Subject: Removed inlines from combinators gcc requires external linkage for
functions provided to template parameters
---
src/BlockArea.cpp | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index 359f5cb81..0c1c176d5 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -63,7 +63,7 @@ void InternalMergeBlocks(
/// Combinator used for cBlockArea::msOverwrite merging
template
-static inline void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+static void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
a_DstType = a_SrcType;
if (MetaValid) a_DstMeta = a_SrcMeta;
@@ -75,7 +75,7 @@ static inline void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_S
/// Combinator used for cBlockArea::msFillAir merging
template
-static inline void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+static void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if (a_DstType == E_BLOCK_AIR)
{
@@ -91,7 +91,7 @@ static inline void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_Src
/// Combinator used for cBlockArea::msImprint merging
template
-static inline void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+static void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if (a_SrcType != E_BLOCK_AIR)
{
@@ -107,7 +107,7 @@ static inline void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_Src
/// Combinator used for cBlockArea::msLake merging
template
-static inline void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+static void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// Sponge is the NOP block
if (a_SrcType == E_BLOCK_SPONGE)
@@ -172,7 +172,7 @@ static inline void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcTyp
/** Combinator used for cBlockArea::msSpongePrint merging */
template
-static inline void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+static void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// Sponge overwrites nothing, everything else overwrites anything
if (a_SrcType != E_BLOCK_SPONGE)
@@ -188,7 +188,7 @@ static inline void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a
/** Combinator used for cBlockArea::msDifference merging */
template
-static inline void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+static void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if ((a_DstType == a_SrcType) && (!MetaValid || (a_DstMeta == a_SrcMeta)))
{
@@ -208,7 +208,7 @@ static inline void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_
/** Combinator used for cBlockArea::msMask merging */
template
-static inline void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+static void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// If the blocks are the same, keep the dest; otherwise replace with air
if ((a_SrcType != a_DstType) || !MetaValid || (a_SrcMeta != a_DstMeta))
--
cgit v1.2.3
From 6d520e398b7da7d04f8b7377bca0db0a684452f1 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Mon, 28 Apr 2014 11:00:43 -0700
Subject: Fixed unbraced ifs
---
src/BlockArea.cpp | 50 ++++++++++++++++++++++++++++++++++++++++----------
1 file changed, 40 insertions(+), 10 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index 0c1c176d5..b7b76da26 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -66,7 +66,10 @@ template
static void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
a_DstType = a_SrcType;
- if (MetaValid) a_DstMeta = a_SrcMeta;
+ if (MetaValid)
+ {
+ a_DstMeta = a_SrcMeta;
+ }
}
@@ -80,7 +83,10 @@ static void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, N
if (a_DstType == E_BLOCK_AIR)
{
a_DstType = a_SrcType;
- if (MetaValid) a_DstMeta = a_SrcMeta;
+ if (MetaValid)
+ {
+ a_DstMeta = a_SrcMeta;
+ }
}
// "else" is the default, already in place
}
@@ -96,7 +102,10 @@ static void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, N
if (a_SrcType != E_BLOCK_AIR)
{
a_DstType = a_SrcType;
- if (MetaValid) a_DstMeta = a_SrcMeta;
+ if (MetaValid)
+ {
+ a_DstMeta = a_SrcMeta;
+ }
}
// "else" is the default, already in place
}
@@ -119,7 +128,10 @@ static void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBB
if (a_SrcType == E_BLOCK_AIR)
{
a_DstType = E_BLOCK_AIR;
- if (MetaValid) a_DstMeta = 0;
+ if (MetaValid)
+ {
+ a_DstMeta = 0;
+ }
return;
}
@@ -144,7 +156,10 @@ static void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBB
case E_BLOCK_STATIONARY_LAVA:
{
a_DstType = a_SrcType;
- if (MetaValid) a_DstMeta = a_SrcMeta;
+ if (MetaValid)
+ {
+ a_DstMeta = a_SrcMeta;
+ }
return;
}
}
@@ -158,7 +173,10 @@ static void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBB
case E_BLOCK_MYCELIUM:
{
a_DstType = E_BLOCK_STONE;
- if (MetaValid) a_DstMeta = 0;
+ if (MetaValid)
+ {
+ a_DstMeta = 0;
+ }
return;
}
}
@@ -178,7 +196,10 @@ static void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcTyp
if (a_SrcType != E_BLOCK_SPONGE)
{
a_DstType = a_SrcType;
- if (MetaValid) a_DstMeta = a_SrcMeta;
+ if (MetaValid)
+ {
+ a_DstMeta = a_SrcMeta;
+ }
}
}
@@ -193,12 +214,18 @@ static void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType
if ((a_DstType == a_SrcType) && (!MetaValid || (a_DstMeta == a_SrcMeta)))
{
a_DstType = E_BLOCK_AIR;
- if (MetaValid) a_DstMeta = 0;
+ if (MetaValid)
+ {
+ a_DstMeta = 0;
+ }
}
else
{
a_DstType = a_SrcType;
- if (MetaValid) a_DstMeta = a_SrcMeta;
+ if (MetaValid)
+ {
+ a_DstMeta = a_SrcMeta;
+ }
}
}
@@ -214,7 +241,10 @@ static void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBB
if ((a_SrcType != a_DstType) || !MetaValid || (a_SrcMeta != a_DstMeta))
{
a_DstType = E_BLOCK_AIR;
- if (MetaValid) a_DstMeta = 0;
+ if (MetaValid)
+ {
+ a_DstMeta = 0;
+ }
}
}
--
cgit v1.2.3
From ad5cdf9f2d4a5e87489a2ad460bf353b17f72b6d Mon Sep 17 00:00:00 2001
From: Tycho
Date: Mon, 28 Apr 2014 11:07:06 -0700
Subject: Removed static from combinators. THis allows us to use the functions
in template params at the cost of polluting the global namespace.
---
src/BlockArea.cpp | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index b7b76da26..f03fc6042 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -63,7 +63,7 @@ void InternalMergeBlocks(
/// Combinator used for cBlockArea::msOverwrite merging
template
-static void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
a_DstType = a_SrcType;
if (MetaValid)
@@ -78,7 +78,7 @@ static void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType,
/// Combinator used for cBlockArea::msFillAir merging
template
-static void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if (a_DstType == E_BLOCK_AIR)
{
@@ -97,7 +97,7 @@ static void MergeCombinatorFillAir(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, N
/// Combinator used for cBlockArea::msImprint merging
template
-static void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if (a_SrcType != E_BLOCK_AIR)
{
@@ -116,7 +116,7 @@ static void MergeCombinatorImprint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, N
/// Combinator used for cBlockArea::msLake merging
template
-static void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// Sponge is the NOP block
if (a_SrcType == E_BLOCK_SPONGE)
@@ -190,7 +190,7 @@ static void MergeCombinatorLake(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBB
/** Combinator used for cBlockArea::msSpongePrint merging */
template
-static void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// Sponge overwrites nothing, everything else overwrites anything
if (a_SrcType != E_BLOCK_SPONGE)
@@ -209,7 +209,7 @@ static void MergeCombinatorSpongePrint(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcTyp
/** Combinator used for cBlockArea::msDifference merging */
template
-static void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
if ((a_DstType == a_SrcType) && (!MetaValid || (a_DstMeta == a_SrcMeta)))
{
@@ -235,7 +235,7 @@ static void MergeCombinatorDifference(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType
/** Combinator used for cBlockArea::msMask merging */
template
-static void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
+void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
{
// If the blocks are the same, keep the dest; otherwise replace with air
if ((a_SrcType != a_DstType) || !MetaValid || (a_SrcMeta != a_DstMeta))
--
cgit v1.2.3
From f04957321d063f8755d4634551ab9eece05f009e Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Mon, 28 Apr 2014 20:37:12 +0200
Subject: Fixed missing return value warning in MSVC.
---
src/ClientHandle.cpp | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index fc3f98aaf..efcc89bab 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -220,6 +220,7 @@ AString cClientHandle::FormatMessageType(bool ShouldAppendChatPrefixes, eMessage
}
}
ASSERT(!"Unhandled chat prefix type!");
+ return "";
}
--
cgit v1.2.3
From 8ab8fb344f49c2c4ce857594159e9cdba3336853 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Mon, 28 Apr 2014 20:37:22 +0200
Subject: Fixed braces.
---
src/ClientHandle.cpp | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index efcc89bab..f3588c253 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -214,13 +214,17 @@ AString cClientHandle::FormatMessageType(bool ShouldAppendChatPrefixes, eMessage
case mtPrivateMessage:
{
if (ShouldAppendChatPrefixes)
+ {
return Printf("%s[MSG: %s] %s%s", cChatColor::LightBlue.c_str(), a_AdditionalData.c_str(), cChatColor::White.c_str(), cChatColor::Italic.c_str());
+ }
else
+ {
return Printf("%s: %s", a_AdditionalData.c_str(), cChatColor::LightBlue.c_str());
+ }
}
}
ASSERT(!"Unhandled chat prefix type!");
- return "";
+ return AString();
}
--
cgit v1.2.3
From 16b3eae8623916fa7bc2cd9cad292bbad8d6a116 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Mon, 28 Apr 2014 21:16:32 +0200
Subject: Added a debug cert printing function.
---
src/PolarSSL++/SslContext.cpp | 62 +++++++++++++++++++++++++++++++++++++++++++
src/PolarSSL++/SslContext.h | 3 +++
2 files changed, 65 insertions(+)
diff --git a/src/PolarSSL++/SslContext.cpp b/src/PolarSSL++/SslContext.cpp
index e7fa11c75..1994cf844 100644
--- a/src/PolarSSL++/SslContext.cpp
+++ b/src/PolarSSL++/SslContext.cpp
@@ -64,7 +64,12 @@ int cSslContext::Initialize(bool a_IsClient, const SharedPtr &
ssl_set_bio(&m_Ssl, ReceiveEncrypted, this, SendEncrypted, this);
#ifdef _DEBUG
+ /*
+ // These functions allow us to debug SSL and certificate problems, but produce way too much output,
+ // so they're disabled until someone needs them
ssl_set_dbg(&m_Ssl, &SSLDebugMessage, this);
+ ssl_set_verify(&m_Ssl, &SSLVerifyCert, this);
+ */
#endif
m_IsValid = true;
@@ -174,6 +179,63 @@ int cSslContext::NotifyClose(void)
LOGD("SSL (%d): %s", a_Level, Text.c_str());
}
+
+
+
+
+
+ int cSslContext::SSLVerifyCert(void * a_This, x509_crt * a_Crt, int a_Depth, int * a_Flags)
+ {
+ char buf[1024];
+ UNUSED(a_This);
+
+ LOG("Verify requested for (Depth %d):", a_Depth);
+ x509_crt_info(buf, sizeof(buf) - 1, "", a_Crt);
+ LOG("%s", buf);
+
+ int Flags = *a_Flags;
+ if ((Flags & BADCERT_EXPIRED) != 0)
+ {
+ LOG(" ! server certificate has expired");
+ }
+
+ if ((Flags & BADCERT_REVOKED) != 0)
+ {
+ LOG(" ! server certificate has been revoked");
+ }
+
+ if ((Flags & BADCERT_CN_MISMATCH) != 0)
+ {
+ LOG(" ! CN mismatch");
+ }
+
+ if ((Flags & BADCERT_NOT_TRUSTED) != 0)
+ {
+ LOG(" ! self-signed or not signed by a trusted CA");
+ }
+
+ if ((Flags & BADCRL_NOT_TRUSTED) != 0)
+ {
+ LOG(" ! CRL not trusted");
+ }
+
+ if ((Flags & BADCRL_EXPIRED) != 0)
+ {
+ LOG(" ! CRL expired");
+ }
+
+ if ((Flags & BADCERT_OTHER) != 0)
+ {
+ LOG(" ! other (unknown) flag");
+ }
+
+ if (Flags == 0)
+ {
+ LOG(" This certificate has no flags");
+ }
+
+ return 0;
+ }
#endif // _DEBUG
diff --git a/src/PolarSSL++/SslContext.h b/src/PolarSSL++/SslContext.h
index 6effdcaea..85add5f8b 100644
--- a/src/PolarSSL++/SslContext.h
+++ b/src/PolarSSL++/SslContext.h
@@ -120,6 +120,9 @@ protected:
#ifdef _DEBUG
/** The callback used by PolarSSL to output debug messages */
static void SSLDebugMessage(void * a_UserParam, int a_Level, const char * a_Text);
+
+ /** The callback used by PolarSSL to log information on the cert chain */
+ static int SSLVerifyCert(void * a_This, x509_crt * a_Crt, int a_Depth, int * a_Flags);
#endif // _DEBUG
/** Called when PolarSSL wants to read encrypted data. */
--
cgit v1.2.3
From bab3a3cd31c26d7c8c195888675b31ece5ab80b7 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Mon, 28 Apr 2014 21:16:52 +0200
Subject: Added the G1 root cert.
Now the authenticator finally works.
---
src/Protocol/Authenticator.cpp | 31 +++++++++++++++++++++++++++++--
1 file changed, 29 insertions(+), 2 deletions(-)
diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp
index efeb6c41c..f7008a5c4 100644
--- a/src/Protocol/Authenticator.cpp
+++ b/src/Protocol/Authenticator.cpp
@@ -152,8 +152,10 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
unsigned char buf[1024];
/* Initialize certificates */
- // This is the root cert for Starfield Technologies, the CA that signed sessionserver.mojang.com's cert:
+ // This is the data of the root certs for Starfield Technologies, the CA that signed sessionserver.mojang.com's cert:
+ // Downloaded from http://certs.starfieldtech.com/repository/
static const AString StarfieldCACert(
+ // G2 cert
"-----BEGIN CERTIFICATE-----\n"
"MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\n"
"EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\n"
@@ -176,7 +178,32 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
"8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K\n"
"pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1\n"
"mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0\n"
- "-----END CERTIFICATE-----"
+ "-----END CERTIFICATE-----\n\n"
+ // Original (G1) cert:
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl\n"
+ "MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp\n"
+ "U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw\n"
+ "NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE\n"
+ "ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp\n"
+ "ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3\n"
+ "DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf\n"
+ "8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN\n"
+ "+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0\n"
+ "X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa\n"
+ "K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA\n"
+ "1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G\n"
+ "A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR\n"
+ "zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0\n"
+ "YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD\n"
+ "bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w\n"
+ "DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3\n"
+ "L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D\n"
+ "eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl\n"
+ "xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\n"
+ "VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\n"
+ "WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\n"
+ "-----END CERTIFICATE-----\n"
);
// Connect the socket:
--
cgit v1.2.3
From dffd38e53b87b3928542ad5fb5223a6b56f20ac9 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Mon, 28 Apr 2014 22:21:49 +0200
Subject: Fixed a MSVC warning.
---
src/Entities/FallingBlock.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Entities/FallingBlock.cpp b/src/Entities/FallingBlock.cpp
index bcdac0291..99bff1100 100644
--- a/src/Entities/FallingBlock.cpp
+++ b/src/Entities/FallingBlock.cpp
@@ -88,7 +88,7 @@ void cFallingBlock::Tick(float a_Dt, cChunk & a_Chunk)
AddPosition(GetSpeed() * MilliDt);
// If not static (One billionth precision) broadcast movement.
- static const float epsilon = 0.000000001;
+ static const float epsilon = 0.000000001f;
if ((fabs(GetSpeedX()) > epsilon) || (fabs(GetSpeedZ()) > epsilon))
{
BroadcastMovementUpdate();
--
cgit v1.2.3
From 55a7f392ccf99b55ee09ade2fb15468e8d3e4d66 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Mon, 28 Apr 2014 22:22:07 +0200
Subject: Hopefully fixed repeated clang warnings.
---
src/ChunkDef.h | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)
diff --git a/src/ChunkDef.h b/src/ChunkDef.h
index 054168bdd..83f3c8f5f 100644
--- a/src/ChunkDef.h
+++ b/src/ChunkDef.h
@@ -246,8 +246,8 @@ public:
{
if ((x < Width) && (x > -1) && (y < Height) && (y > -1) && (z < Width) && (z > -1))
{
- int Index = MakeIndexNoCheck(x, y, z);
- if ((size_t)(Index / 2) >= a_Buffer.size())
+ size_t Index = (size_t)MakeIndexNoCheck(x, y, z);
+ if ((Index / 2) >= a_Buffer.size())
{
return (a_IsSkyLightNibble ? 0xff : 0);
}
@@ -281,7 +281,7 @@ public:
{
a_Buffer.resize((size_t)((a_BlockIdx / 2) + 1));
}
- a_Buffer[(size_t)(a_BlockIdx / 2)] = PackNibble(a_Buffer, a_BlockIdx, a_Nibble);
+ a_Buffer[(size_t)(a_BlockIdx / 2)] = PackNibble(a_Buffer, (size_t)a_BlockIdx, a_Nibble);
}
@@ -297,19 +297,19 @@ public:
return;
}
- int Index = MakeIndexNoCheck(x, y, z);
- if ((size_t)(Index / 2) >= a_Buffer.size())
+ size_t Index = (size_t)MakeIndexNoCheck(x, y, z);
+ if ((Index / 2) >= a_Buffer.size())
{
- a_Buffer.resize((size_t)((Index / 2) + 1));
+ a_Buffer.resize(((Index / 2) + 1));
}
- a_Buffer[(size_t)(Index / 2)] = PackNibble(a_Buffer, Index, a_Nibble);
+ a_Buffer[(Index / 2)] = PackNibble(a_Buffer, Index, a_Nibble);
}
private:
- inline static NIBBLETYPE PackNibble(const COMPRESSED_NIBBLETYPE & a_Buffer, int a_Index, NIBBLETYPE a_Nibble)
+ inline static NIBBLETYPE PackNibble(const COMPRESSED_NIBBLETYPE & a_Buffer, size_t a_Index, NIBBLETYPE a_Nibble)
{
return static_cast(
(a_Buffer[a_Index / 2] & (0xf0 >> ((a_Index & 1) * 4))) | // The untouched nibble
@@ -318,7 +318,7 @@ private:
}
- inline static NIBBLETYPE ExpandNibble(const COMPRESSED_NIBBLETYPE & a_Buffer, int a_Index)
+ inline static NIBBLETYPE ExpandNibble(const COMPRESSED_NIBBLETYPE & a_Buffer, size_t a_Index)
{
return (a_Buffer[a_Index / 2] >> ((a_Index & 1) * 4)) & 0x0f;
}
--
cgit v1.2.3
From 709ae320e079e55b2636cdd2a2008d7f420d1f60 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Mon, 28 Apr 2014 22:30:07 +0200
Subject: Disabled MSVC warnings about constant bool expressions.
---
src/BlockArea.cpp | 21 +++++++++++++++++++--
1 file changed, 19 insertions(+), 2 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index f03fc6042..55e8d6849 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -13,11 +13,21 @@
-// This wild construct allows us to pass a function argument and still have it inlined by the compiler :)
-/// Merges two blocktypes and blockmetas of the specified sizes and offsets using the specified combinator function
+
+// Disable MSVC warnings: "conditional expression is constant"
+#ifdef _MSC_VER
+ #pragma warning(push)
+ #pragma warning(disable:4127)
+#endif
+
+
+
+
typedef void (CombinatorFunc)(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta);
+// This wild construct allows us to pass a function argument and still have it inlined by the compiler :)
+/// Merges two blocktypes and blockmetas of the specified sizes and offsets using the specified combinator function
template
void InternalMergeBlocks(
BLOCKTYPE * a_DstTypes, const BLOCKTYPE * a_SrcTypes,
@@ -61,6 +71,8 @@ void InternalMergeBlocks(
+
+
/// Combinator used for cBlockArea::msOverwrite merging
template
void MergeCombinatorOverwrite(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE & a_DstMeta, NIBBLETYPE a_SrcMeta)
@@ -248,6 +260,11 @@ void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE
}
}
+// Re-enable previously disabled MSVC warnings
+#ifdef _MSC_VER
+ #pragma warning(pop)
+#endif
+
--
cgit v1.2.3
From ec33bbe2949010e1ed377b9dcc1ace56a0126bfe Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 11:04:54 +0200
Subject: Moved cRsaPrivateKey to PolarSSL++, rewritten using existing objects.
---
src/Crypto.cpp | 174 ---------------------------------------
src/Crypto.h | 43 ----------
src/PolarSSL++/CMakeLists.txt | 2 +
src/PolarSSL++/CtrDrbgContext.h | 8 +-
src/PolarSSL++/RsaPrivateKey.cpp | 173 ++++++++++++++++++++++++++++++++++++++
src/PolarSSL++/RsaPrivateKey.h | 59 +++++++++++++
src/Protocol/Protocol132.cpp | 2 +-
src/Protocol/Protocol17x.cpp | 2 +-
src/Server.h | 6 +-
9 files changed, 244 insertions(+), 225 deletions(-)
create mode 100644 src/PolarSSL++/RsaPrivateKey.cpp
create mode 100644 src/PolarSSL++/RsaPrivateKey.h
diff --git a/src/Crypto.cpp b/src/Crypto.cpp
index 16be5ec35..dd8787293 100644
--- a/src/Crypto.cpp
+++ b/src/Crypto.cpp
@@ -55,180 +55,6 @@ public:
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cRSAPrivateKey:
-cRSAPrivateKey::cRSAPrivateKey(void)
-{
- rsa_init(&m_Rsa, RSA_PKCS_V15, 0);
- InitRnd();
-}
-
-
-
-
-
-cRSAPrivateKey::cRSAPrivateKey(const cRSAPrivateKey & a_Other)
-{
- rsa_init(&m_Rsa, RSA_PKCS_V15, 0);
- rsa_copy(&m_Rsa, &a_Other.m_Rsa);
- InitRnd();
-}
-
-
-
-
-
-cRSAPrivateKey::~cRSAPrivateKey()
-{
- entropy_free(&m_Entropy);
- rsa_free(&m_Rsa);
-}
-
-
-
-
-
-void cRSAPrivateKey::InitRnd(void)
-{
- entropy_init(&m_Entropy);
- const unsigned char pers[] = "rsa_genkey";
- ctr_drbg_init(&m_Ctr_drbg, entropy_func, &m_Entropy, pers, sizeof(pers) - 1);
-}
-
-
-
-
-
-bool cRSAPrivateKey::Generate(unsigned a_KeySizeBits)
-{
- if (rsa_gen_key(&m_Rsa, ctr_drbg_random, &m_Ctr_drbg, a_KeySizeBits, 65537) != 0)
- {
- // Key generation failed
- return false;
- }
-
- return true;
-}
-
-
-
-
-
-AString cRSAPrivateKey::GetPubKeyDER(void)
-{
- class cPubKey
- {
- public:
- cPubKey(rsa_context * a_Rsa) :
- m_IsValid(false)
- {
- pk_init(&m_Key);
- if (pk_init_ctx(&m_Key, pk_info_from_type(POLARSSL_PK_RSA)) != 0)
- {
- ASSERT(!"Cannot init PrivKey context");
- return;
- }
- if (rsa_copy(pk_rsa(m_Key), a_Rsa) != 0)
- {
- ASSERT(!"Cannot copy PrivKey to PK context");
- return;
- }
- m_IsValid = true;
- }
-
- ~cPubKey()
- {
- if (m_IsValid)
- {
- pk_free(&m_Key);
- }
- }
-
- operator pk_context * (void) { return &m_Key; }
-
- protected:
- bool m_IsValid;
- pk_context m_Key;
- } PkCtx(&m_Rsa);
-
- unsigned char buf[3000];
- int res = pk_write_pubkey_der(PkCtx, buf, sizeof(buf));
- if (res < 0)
- {
- return AString();
- }
- return AString((const char *)(buf + sizeof(buf) - res), (size_t)res);
-}
-
-
-
-
-
-int cRSAPrivateKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength)
-{
- if (a_EncryptedLength < m_Rsa.len)
- {
- LOGD("%s: Invalid a_EncryptedLength: got %u, exp at least %u",
- __FUNCTION__, (unsigned)a_EncryptedLength, (unsigned)(m_Rsa.len)
- );
- ASSERT(!"Invalid a_DecryptedMaxLength!");
- return -1;
- }
- if (a_DecryptedMaxLength < m_Rsa.len)
- {
- LOGD("%s: Invalid a_DecryptedMaxLength: got %u, exp at least %u",
- __FUNCTION__, (unsigned)a_EncryptedLength, (unsigned)(m_Rsa.len)
- );
- ASSERT(!"Invalid a_DecryptedMaxLength!");
- return -1;
- }
- size_t DecryptedLength;
- int res = rsa_pkcs1_decrypt(
- &m_Rsa, ctr_drbg_random, &m_Ctr_drbg, RSA_PRIVATE, &DecryptedLength,
- a_EncryptedData, a_DecryptedData, a_DecryptedMaxLength
- );
- if (res != 0)
- {
- return -1;
- }
- return (int)DecryptedLength;
-}
-
-
-
-
-
-int cRSAPrivateKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
-{
- if (a_EncryptedMaxLength < m_Rsa.len)
- {
- LOGD("%s: Invalid a_EncryptedMaxLength: got %u, exp at least %u",
- __FUNCTION__, (unsigned)a_EncryptedMaxLength, (unsigned)(m_Rsa.len)
- );
- ASSERT(!"Invalid a_DecryptedMaxLength!");
- return -1;
- }
- if (a_PlainLength < m_Rsa.len)
- {
- LOGD("%s: Invalid a_PlainLength: got %u, exp at least %u",
- __FUNCTION__, (unsigned)a_PlainLength, (unsigned)(m_Rsa.len)
- );
- ASSERT(!"Invalid a_PlainLength!");
- return -1;
- }
- int res = rsa_pkcs1_encrypt(
- &m_Rsa, ctr_drbg_random, &m_Ctr_drbg, RSA_PRIVATE,
- a_PlainLength, a_PlainData, a_EncryptedData
- );
- if (res != 0)
- {
- return -1;
- }
- return (int)m_Rsa.len;
-}
-
-
-
-
-
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cPublicKey:
diff --git a/src/Crypto.h b/src/Crypto.h
index a9ec2c6d4..24f246897 100644
--- a/src/Crypto.h
+++ b/src/Crypto.h
@@ -20,49 +20,6 @@
-/** Encapsulates an RSA private key used in PKI cryptography */
-class cRSAPrivateKey
-{
-public:
- /** Creates a new empty object, the key is not assigned */
- cRSAPrivateKey(void);
-
- /** Deep-copies the key from a_Other */
- cRSAPrivateKey(const cRSAPrivateKey & a_Other);
-
- ~cRSAPrivateKey();
-
- /** Generates a new key within this object, with the specified size in bits.
- Returns true on success, false on failure. */
- bool Generate(unsigned a_KeySizeBits = 1024);
-
- /** Returns the public key part encoded in ASN1 DER encoding */
- AString GetPubKeyDER(void);
-
- /** Decrypts the data using RSAES-PKCS#1 algorithm.
- Both a_EncryptedData and a_DecryptedData must be at least bytes large.
- Returns the number of bytes decrypted, or negative number for error. */
- int Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength);
-
- /** Encrypts the data using RSAES-PKCS#1 algorithm.
- Both a_EncryptedData and a_DecryptedData must be at least bytes large.
- Returns the number of bytes decrypted, or negative number for error. */
- int Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength);
-
-protected:
- rsa_context m_Rsa;
- entropy_context m_Entropy;
- ctr_drbg_context m_Ctr_drbg;
-
- /** Initializes the m_Entropy and m_Ctr_drbg contexts
- Common part of this object's construction, called from all constructors. */
- void InitRnd(void);
-} ;
-
-
-
-
-
class cPublicKey
{
public:
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
index 0493baba4..ebdd52de5 100644
--- a/src/PolarSSL++/CMakeLists.txt
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -10,6 +10,7 @@ set(SOURCES
"CallbackSslContext.cpp"
"CtrDrbgContext.cpp"
"EntropyContext.cpp"
+ "RsaPrivateKey.cpp"
"SslContext.cpp"
"X509Cert.cpp"
)
@@ -20,6 +21,7 @@ set(HEADERS
"CallbackSslContext.h"
"CtrDrbgContext.h"
"EntropyContext.h"
+ "RsaPrivateKey.h"
"SslContext.h"
"X509Cert.h"
)
diff --git a/src/PolarSSL++/CtrDrbgContext.h b/src/PolarSSL++/CtrDrbgContext.h
index e9a1e17e2..817222a53 100644
--- a/src/PolarSSL++/CtrDrbgContext.h
+++ b/src/PolarSSL++/CtrDrbgContext.h
@@ -25,6 +25,7 @@ class cEntropyContext;
class cCtrDrbgContext
{
friend class cSslContext;
+ friend class cRsaPrivateKey;
public:
/** Constructs the context with a new entropy context. */
@@ -41,9 +42,6 @@ public:
/** Returns true if the object is valid (has been initialized properly) */
bool IsValid(void) const { return m_IsValid; }
- /** Returns the internal context ptr. Only use in PolarSSL API calls. */
- OBSOLETE ctr_drbg_context * Get(void) { return &m_CtrDrbg; }
-
protected:
/** The entropy source used for generating the random */
SharedPtr m_EntropyContext;
@@ -53,6 +51,10 @@ protected:
/** Set to true if the object is valid (has been initialized properly) */
bool m_IsValid;
+
+
+ /** Returns the internal context ptr. Only use in PolarSSL API calls. */
+ ctr_drbg_context * GetInternal(void) { return &m_CtrDrbg; }
} ;
diff --git a/src/PolarSSL++/RsaPrivateKey.cpp b/src/PolarSSL++/RsaPrivateKey.cpp
new file mode 100644
index 000000000..d042139cf
--- /dev/null
+++ b/src/PolarSSL++/RsaPrivateKey.cpp
@@ -0,0 +1,173 @@
+
+// RsaPrivateKey.cpp
+
+#include "Globals.h"
+#include "RsaPrivateKey.h"
+#include "CtrDrbgContext.h"
+#include "polarssl/pk.h"
+
+
+
+
+
+
+cRsaPrivateKey::cRsaPrivateKey(void)
+{
+ rsa_init(&m_Rsa, RSA_PKCS_V15, 0);
+}
+
+
+
+
+
+cRsaPrivateKey::cRsaPrivateKey(const cRsaPrivateKey & a_Other)
+{
+ rsa_init(&m_Rsa, RSA_PKCS_V15, 0);
+ rsa_copy(&m_Rsa, &a_Other.m_Rsa);
+}
+
+
+
+
+
+cRsaPrivateKey::~cRsaPrivateKey()
+{
+ rsa_free(&m_Rsa);
+}
+
+
+
+
+
+bool cRsaPrivateKey::Generate(unsigned a_KeySizeBits)
+{
+ if (rsa_gen_key(&m_Rsa, ctr_drbg_random, m_CtrDrbg.GetInternal(), a_KeySizeBits, 65537) != 0)
+ {
+ // Key generation failed
+ return false;
+ }
+
+ return true;
+}
+
+
+
+
+
+AString cRsaPrivateKey::GetPubKeyDER(void)
+{
+ class cPubKey
+ {
+ public:
+ cPubKey(rsa_context * a_Rsa) :
+ m_IsValid(false)
+ {
+ pk_init(&m_Key);
+ if (pk_init_ctx(&m_Key, pk_info_from_type(POLARSSL_PK_RSA)) != 0)
+ {
+ ASSERT(!"Cannot init PrivKey context");
+ return;
+ }
+ if (rsa_copy(pk_rsa(m_Key), a_Rsa) != 0)
+ {
+ ASSERT(!"Cannot copy PrivKey to PK context");
+ return;
+ }
+ m_IsValid = true;
+ }
+
+ ~cPubKey()
+ {
+ if (m_IsValid)
+ {
+ pk_free(&m_Key);
+ }
+ }
+
+ operator pk_context * (void) { return &m_Key; }
+
+ protected:
+ bool m_IsValid;
+ pk_context m_Key;
+ } PkCtx(&m_Rsa);
+
+ unsigned char buf[3000];
+ int res = pk_write_pubkey_der(PkCtx, buf, sizeof(buf));
+ if (res < 0)
+ {
+ return AString();
+ }
+ return AString((const char *)(buf + sizeof(buf) - res), (size_t)res);
+}
+
+
+
+
+
+int cRsaPrivateKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength)
+{
+ if (a_EncryptedLength < m_Rsa.len)
+ {
+ LOGD("%s: Invalid a_EncryptedLength: got %u, exp at least %u",
+ __FUNCTION__, (unsigned)a_EncryptedLength, (unsigned)(m_Rsa.len)
+ );
+ ASSERT(!"Invalid a_DecryptedMaxLength!");
+ return -1;
+ }
+ if (a_DecryptedMaxLength < m_Rsa.len)
+ {
+ LOGD("%s: Invalid a_DecryptedMaxLength: got %u, exp at least %u",
+ __FUNCTION__, (unsigned)a_EncryptedLength, (unsigned)(m_Rsa.len)
+ );
+ ASSERT(!"Invalid a_DecryptedMaxLength!");
+ return -1;
+ }
+ size_t DecryptedLength;
+ int res = rsa_pkcs1_decrypt(
+ &m_Rsa, ctr_drbg_random, m_CtrDrbg.GetInternal(), RSA_PRIVATE, &DecryptedLength,
+ a_EncryptedData, a_DecryptedData, a_DecryptedMaxLength
+ );
+ if (res != 0)
+ {
+ return -1;
+ }
+ return (int)DecryptedLength;
+}
+
+
+
+
+
+int cRsaPrivateKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
+{
+ if (a_EncryptedMaxLength < m_Rsa.len)
+ {
+ LOGD("%s: Invalid a_EncryptedMaxLength: got %u, exp at least %u",
+ __FUNCTION__, (unsigned)a_EncryptedMaxLength, (unsigned)(m_Rsa.len)
+ );
+ ASSERT(!"Invalid a_DecryptedMaxLength!");
+ return -1;
+ }
+ if (a_PlainLength < m_Rsa.len)
+ {
+ LOGD("%s: Invalid a_PlainLength: got %u, exp at least %u",
+ __FUNCTION__, (unsigned)a_PlainLength, (unsigned)(m_Rsa.len)
+ );
+ ASSERT(!"Invalid a_PlainLength!");
+ return -1;
+ }
+ int res = rsa_pkcs1_encrypt(
+ &m_Rsa, ctr_drbg_random, m_CtrDrbg.GetInternal(), RSA_PRIVATE,
+ a_PlainLength, a_PlainData, a_EncryptedData
+ );
+ if (res != 0)
+ {
+ return -1;
+ }
+ return (int)m_Rsa.len;
+}
+
+
+
+
+
diff --git a/src/PolarSSL++/RsaPrivateKey.h b/src/PolarSSL++/RsaPrivateKey.h
new file mode 100644
index 000000000..ffacde11b
--- /dev/null
+++ b/src/PolarSSL++/RsaPrivateKey.h
@@ -0,0 +1,59 @@
+
+// RsaPrivateKey.h
+
+// Declares the cRsaPrivateKey class representing a private key for RSA operations.
+
+
+
+
+
+#pragma once
+
+#include "CtrDrbgContext.h"
+#include "polarssl/rsa.h"
+
+
+
+
+
+/** Encapsulates an RSA private key used in PKI cryptography */
+class cRsaPrivateKey
+{
+public:
+ /** Creates a new empty object, the key is not assigned */
+ cRsaPrivateKey(void);
+
+ /** Deep-copies the key from a_Other */
+ cRsaPrivateKey(const cRsaPrivateKey & a_Other);
+
+ ~cRsaPrivateKey();
+
+ /** Generates a new key within this object, with the specified size in bits.
+ Returns true on success, false on failure. */
+ bool Generate(unsigned a_KeySizeBits = 1024);
+
+ /** Returns the public key part encoded in ASN1 DER encoding */
+ AString GetPubKeyDER(void);
+
+ /** Decrypts the data using RSAES-PKCS#1 algorithm.
+ Both a_EncryptedData and a_DecryptedData must be at least bytes large.
+ Returns the number of bytes decrypted, or negative number for error. */
+ int Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength);
+
+ /** Encrypts the data using RSAES-PKCS#1 algorithm.
+ Both a_EncryptedData and a_DecryptedData must be at least bytes large.
+ Returns the number of bytes decrypted, or negative number for error. */
+ int Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength);
+
+protected:
+ /** The PolarSSL key context */
+ rsa_context m_Rsa;
+
+ /** The random generator used for generating the key and encryption / decryption */
+ cCtrDrbgContext m_CtrDrbg;
+} ;
+
+
+
+
+
diff --git a/src/Protocol/Protocol132.cpp b/src/Protocol/Protocol132.cpp
index 53d8c1561..acfa5e811 100644
--- a/src/Protocol/Protocol132.cpp
+++ b/src/Protocol/Protocol132.cpp
@@ -819,7 +819,7 @@ void cProtocol132::SendEncryptionKeyRequest(void)
void cProtocol132::HandleEncryptionKeyResponse(const AString & a_EncKey, const AString & a_EncNonce)
{
// Decrypt EncNonce using privkey
- cRSAPrivateKey & rsaDecryptor = cRoot::Get()->GetServer()->GetPrivateKey();
+ cRsaPrivateKey & rsaDecryptor = cRoot::Get()->GetServer()->GetPrivateKey();
Int32 DecryptedNonce[MAX_ENC_LEN / sizeof(Int32)];
int res = rsaDecryptor.Decrypt((const Byte *)a_EncNonce.data(), a_EncNonce.size(), (Byte *)DecryptedNonce, sizeof(DecryptedNonce));
diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp
index a04d8ac3c..001b8c219 100644
--- a/src/Protocol/Protocol17x.cpp
+++ b/src/Protocol/Protocol17x.cpp
@@ -1690,7 +1690,7 @@ void cProtocol172::HandlePacketLoginEncryptionResponse(cByteBuffer & a_ByteBuffe
}
// Decrypt EncNonce using privkey
- cRSAPrivateKey & rsaDecryptor = cRoot::Get()->GetServer()->GetPrivateKey();
+ cRsaPrivateKey & rsaDecryptor = cRoot::Get()->GetServer()->GetPrivateKey();
Int32 DecryptedNonce[MAX_ENC_LEN / sizeof(Int32)];
int res = rsaDecryptor.Decrypt((const Byte *)EncNonce.data(), EncNonce.size(), (Byte *)DecryptedNonce, sizeof(DecryptedNonce));
if (res != 4)
diff --git a/src/Server.h b/src/Server.h
index 51c450ebd..3d76c8ccf 100644
--- a/src/Server.h
+++ b/src/Server.h
@@ -23,7 +23,7 @@
#pragma warning(disable:4702)
#endif
-#include "Crypto.h"
+#include "PolarSSL++/RsaPrivateKey.h"
#ifdef _MSC_VER
#pragma warning(pop)
@@ -109,7 +109,7 @@ public: // tolua_export
/** Returns base64 encoded favicon data (obtained from favicon.png) */
const AString & GetFaviconData(void) const { return m_FaviconData; }
- cRSAPrivateKey & GetPrivateKey(void) { return m_PrivateKey; }
+ cRsaPrivateKey & GetPrivateKey(void) { return m_PrivateKey; }
const AString & GetPublicKeyDER(void) const { return m_PublicKeyDER; }
bool ShouldAuthenticate(void) const { return m_ShouldAuthenticate; }
@@ -182,7 +182,7 @@ private:
bool m_bRestarting;
/** The private key used for the assymetric encryption start in the protocols */
- cRSAPrivateKey m_PrivateKey;
+ cRsaPrivateKey m_PrivateKey;
/** Public key for m_PrivateKey, ASN1-DER-encoded */
AString m_PublicKeyDER;
--
cgit v1.2.3
From 79ec770d77beb0ce9176ee9858b830c32380b742 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 11:17:47 +0200
Subject: Added missing initialization.
---
src/PolarSSL++/RsaPrivateKey.cpp | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/src/PolarSSL++/RsaPrivateKey.cpp b/src/PolarSSL++/RsaPrivateKey.cpp
index d042139cf..2d5a2a4b1 100644
--- a/src/PolarSSL++/RsaPrivateKey.cpp
+++ b/src/PolarSSL++/RsaPrivateKey.cpp
@@ -14,6 +14,7 @@
cRsaPrivateKey::cRsaPrivateKey(void)
{
rsa_init(&m_Rsa, RSA_PKCS_V15, 0);
+ m_CtrDrbg.Initialize("RSA", 3);
}
@@ -24,6 +25,7 @@ cRsaPrivateKey::cRsaPrivateKey(const cRsaPrivateKey & a_Other)
{
rsa_init(&m_Rsa, RSA_PKCS_V15, 0);
rsa_copy(&m_Rsa, &a_Other.m_Rsa);
+ m_CtrDrbg.Initialize("RSA", 3);
}
@@ -41,9 +43,10 @@ cRsaPrivateKey::~cRsaPrivateKey()
bool cRsaPrivateKey::Generate(unsigned a_KeySizeBits)
{
- if (rsa_gen_key(&m_Rsa, ctr_drbg_random, m_CtrDrbg.GetInternal(), a_KeySizeBits, 65537) != 0)
+ int res = rsa_gen_key(&m_Rsa, ctr_drbg_random, m_CtrDrbg.GetInternal(), a_KeySizeBits, 65537);
+ if (res != 0)
{
- // Key generation failed
+ LOG("RSA key generation failed: -0x%x", -res);
return false;
}
--
cgit v1.2.3
From e39f2a21d550626b962a342b23e0adfb491e6e48 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 11:48:57 +0200
Subject: Fixed ProtoProxy.
---
Tools/ProtoProxy/CMakeLists.txt | 6 ++++++
Tools/ProtoProxy/Globals.h | 14 ++++++++++++++
Tools/ProtoProxy/ProtoProxy.txt | 2 +-
Tools/ProtoProxy/Server.h | 6 ++++--
4 files changed, 25 insertions(+), 3 deletions(-)
diff --git a/Tools/ProtoProxy/CMakeLists.txt b/Tools/ProtoProxy/CMakeLists.txt
index 01f1e88ad..a94df0e24 100644
--- a/Tools/ProtoProxy/CMakeLists.txt
+++ b/Tools/ProtoProxy/CMakeLists.txt
@@ -37,6 +37,9 @@ set(SHARED_SRC
../../src/Log.cpp
../../src/MCLogger.cpp
../../src/Crypto.cpp
+ ../../src/PolarSSL++/CtrDrbgContext.cpp
+ ../../src/PolarSSL++/EntropyContext.cpp
+ ../../src/PolarSSL++/RsaPrivateKey.cpp
)
set(SHARED_HDR
../../src/ByteBuffer.h
@@ -44,6 +47,9 @@ set(SHARED_HDR
../../src/Log.h
../../src/MCLogger.h
../../src/Crypto.h
+ ../../src/PolarSSL++/CtrDrbgContext.h
+ ../../src/PolarSSL++/EntropyContext.h
+ ../../src/PolarSSL++/RsaPrivateKey.h
)
set(SHARED_OSS_SRC
../../src/OSSupport/CriticalSection.cpp
diff --git a/Tools/ProtoProxy/Globals.h b/Tools/ProtoProxy/Globals.h
index e2f5aa860..186efa611 100644
--- a/Tools/ProtoProxy/Globals.h
+++ b/Tools/ProtoProxy/Globals.h
@@ -216,6 +216,20 @@ typedef unsigned char Byte;
// Pretty much the same as ASSERT() but stays in Release builds
#define VERIFY( x ) ( !!(x) || ( LOGERROR("Verification failed: %s, file %s, line %i", #x, __FILE__, __LINE__ ), exit(1), 0 ) )
+// Allow both Older versions of MSVC and newer versions of everything use a shared_ptr:
+// Note that we cannot typedef, because C++ doesn't allow (partial) templates to be typedeffed.
+#if (defined(_MSC_VER) && (_MSC_VER < 1600))
+ // MSVC before 2010 doesn't have std::shared_ptr, but has std::tr1::shared_ptr, defined in included earlier
+ #define SharedPtr std::tr1::shared_ptr
+#elif (__cplusplus >= 201103L)
+ // C++11 has std::shared_ptr in , included earlier
+ #define SharedPtr std::shared_ptr
+#else
+ // C++03 has std::tr1::shared_ptr in
+ #include
+ #define SharedPtr std::tr1::shared_ptr
+#endif
+
diff --git a/Tools/ProtoProxy/ProtoProxy.txt b/Tools/ProtoProxy/ProtoProxy.txt
index e25d513f3..ee52f393e 100644
--- a/Tools/ProtoProxy/ProtoProxy.txt
+++ b/Tools/ProtoProxy/ProtoProxy.txt
@@ -20,7 +20,7 @@ You need to set the server *not* to verify usernames ("online-mode=false" in ser
ProtoProxy is not much dependent on the protocol - it will work with unknown packets, it just won't parse them into human-readable format.
-The latest protocol which has been tested is 1.6.1 (#73).
+The latest protocol which has been tested is 1.7.9 (#5).
*/
diff --git a/Tools/ProtoProxy/Server.h b/Tools/ProtoProxy/Server.h
index 85f817a4d..8adc7093d 100644
--- a/Tools/ProtoProxy/Server.h
+++ b/Tools/ProtoProxy/Server.h
@@ -9,6 +9,8 @@
#pragma once
+#include "PolarSSL++/RsaPrivateKey.h"
+
@@ -17,7 +19,7 @@
class cServer
{
SOCKET m_ListenSocket;
- cRSAPrivateKey m_PrivateKey;
+ cRsaPrivateKey m_PrivateKey;
AString m_PublicKeyDER;
short m_ConnectPort;
@@ -27,7 +29,7 @@ public:
int Init(short a_ListenPort, short a_ConnectPort);
void Run(void);
- cRSAPrivateKey & GetPrivateKey(void) { return m_PrivateKey; }
+ cRsaPrivateKey & GetPrivateKey(void) { return m_PrivateKey; }
const AString & GetPublicKeyDER (void) { return m_PublicKeyDER; }
short GetConnectPort(void) const { return m_ConnectPort; }
--
cgit v1.2.3
From 5d33ce226ff95b527b0e5e620078bf79b0bb11b9 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 15:36:05 +0200
Subject: Added BiomeToString() API function.
---
src/BiomeDef.cpp | 180 +++++++++++++++++++++++++++++++------------------------
src/BiomeDef.h | 7 ++-
2 files changed, 106 insertions(+), 81 deletions(-)
diff --git a/src/BiomeDef.cpp b/src/BiomeDef.cpp
index 3fba93e8a..9852b3dd9 100644
--- a/src/BiomeDef.cpp
+++ b/src/BiomeDef.cpp
@@ -7,6 +7,88 @@
#include "BiomeDef.h"
+
+
+// The "map" used for biome <-> string conversions:
+static struct {
+ EMCSBiome m_Biome;
+ const char * m_String;
+} g_BiomeMap[] =
+{
+ {biOcean, "Ocean"} ,
+ {biPlains, "Plains"},
+ {biDesert, "Desert"},
+ {biExtremeHills, "ExtremeHills"},
+ {biForest, "Forest"},
+ {biTaiga, "Taiga"},
+ {biSwampland, "Swampland"},
+ {biRiver, "River"},
+ {biNether, "Hell"},
+ {biNether, "Nether"},
+ {biEnd, "Sky"},
+ {biEnd, "End"},
+ {biFrozenOcean, "FrozenOcean"},
+ {biFrozenRiver, "FrozenRiver"},
+ {biIcePlains, "IcePlains"},
+ {biIcePlains, "Tundra"},
+ {biIceMountains, "IceMountains"},
+ {biMushroomIsland, "MushroomIsland"},
+ {biMushroomShore, "MushroomShore"},
+ {biBeach, "Beach"},
+ {biDesertHills, "DesertHills"},
+ {biForestHills, "ForestHills"},
+ {biTaigaHills, "TaigaHills"},
+ {biExtremeHillsEdge, "ExtremeHillsEdge"},
+ {biJungle, "Jungle"},
+ {biJungleHills, "JungleHills"},
+
+ // Release 1.7 biomes:
+ {biJungleEdge, "JungleEdge"},
+ {biDeepOcean, "DeepOcean"},
+ {biStoneBeach, "StoneBeach"},
+ {biColdBeach, "ColdBeach"},
+ {biBirchForest, "BirchForest"},
+ {biBirchForestHills, "BirchForestHills"},
+ {biRoofedForest, "RoofedForest"},
+ {biColdTaiga, "ColdTaiga"},
+ {biColdTaigaHills, "ColdTaigaHills"},
+ {biMegaTaiga, "MegaTaiga"},
+ {biMegaTaigaHills, "MegaTaigaHills"},
+ {biExtremeHillsPlus, "ExtremeHillsPlus"},
+ {biSavanna, "Savanna"},
+ {biSavannaPlateau, "SavannaPlateau"},
+ {biMesa, "Mesa"},
+ {biMesaPlateauF, "MesaPlateauF"},
+ {biMesaPlateau, "MesaPlateau"},
+
+ // Release 1.7 variants:
+ {biSunflowerPlains, "SunflowerPlains"},
+ {biDesertM, "DesertM"},
+ {biExtremeHillsM, "ExtremeHillsM"},
+ {biFlowerForest, "FlowerForest"},
+ {biTaigaM, "TaigaM"},
+ {biSwamplandM, "SwamplandM"},
+ {biIcePlainsSpikes, "IcePlainsSpikes"},
+ {biJungleM, "JungleM"},
+ {biJungleEdgeM, "JungleEdgeM"},
+ {biBirchForestM, "BirchForestM"},
+ {biBirchForestHillsM, "BirchForestHillsM"},
+ {biRoofedForestM, "RoofedForestM"},
+ {biColdTaigaM, "ColdTaigaM"},
+ {biMegaSpruceTaiga, "MegaSpruceTaiga"},
+ {biMegaSpruceTaigaHills, "MegaSpruceTaigaHills"},
+ {biExtremeHillsPlusM, "ExtremeHillsPlusM"},
+ {biSavannaM, "SavannaM"},
+ {biSavannaPlateauM, "SavannaPlateauM"},
+ {biMesaBryce, "MesaBryce"},
+ {biMesaPlateauFM, "MesaPlateauFM"},
+ {biMesaPlateauM, "MesaPlateauM"},
+} ;
+
+
+
+
+
EMCSBiome StringToBiome(const AString & a_BiomeString)
{
// If it is a number, return it:
@@ -25,87 +107,11 @@ EMCSBiome StringToBiome(const AString & a_BiomeString)
return biInvalidBiome;
}
- // Convert using the built-in map:
- static struct {
- EMCSBiome m_Biome;
- const char * m_String;
- } BiomeMap[] =
- {
- {biOcean, "Ocean"} ,
- {biPlains, "Plains"},
- {biDesert, "Desert"},
- {biExtremeHills, "ExtremeHills"},
- {biForest, "Forest"},
- {biTaiga, "Taiga"},
- {biSwampland, "Swampland"},
- {biRiver, "River"},
- {biNether, "Hell"},
- {biNether, "Nether"},
- {biEnd, "Sky"},
- {biEnd, "End"},
- {biFrozenOcean, "FrozenOcean"},
- {biFrozenRiver, "FrozenRiver"},
- {biIcePlains, "IcePlains"},
- {biIcePlains, "Tundra"},
- {biIceMountains, "IceMountains"},
- {biMushroomIsland, "MushroomIsland"},
- {biMushroomShore, "MushroomShore"},
- {biBeach, "Beach"},
- {biDesertHills, "DesertHills"},
- {biForestHills, "ForestHills"},
- {biTaigaHills, "TaigaHills"},
- {biExtremeHillsEdge, "ExtremeHillsEdge"},
- {biJungle, "Jungle"},
- {biJungleHills, "JungleHills"},
-
- // Release 1.7 biomes:
- {biJungleEdge, "JungleEdge"},
- {biDeepOcean, "DeepOcean"},
- {biStoneBeach, "StoneBeach"},
- {biColdBeach, "ColdBeach"},
- {biBirchForest, "BirchForest"},
- {biBirchForestHills, "BirchForestHills"},
- {biRoofedForest, "RoofedForest"},
- {biColdTaiga, "ColdTaiga"},
- {biColdTaigaHills, "ColdTaigaHills"},
- {biMegaTaiga, "MegaTaiga"},
- {biMegaTaigaHills, "MegaTaigaHills"},
- {biExtremeHillsPlus, "ExtremeHillsPlus"},
- {biSavanna, "Savanna"},
- {biSavannaPlateau, "SavannaPlateau"},
- {biMesa, "Mesa"},
- {biMesaPlateauF, "MesaPlateauF"},
- {biMesaPlateau, "MesaPlateau"},
-
- // Release 1.7 variants:
- {biSunflowerPlains, "SunflowerPlains"},
- {biDesertM, "DesertM"},
- {biExtremeHillsM, "ExtremeHillsM"},
- {biFlowerForest, "FlowerForest"},
- {biTaigaM, "TaigaM"},
- {biSwamplandM, "SwamplandM"},
- {biIcePlainsSpikes, "IcePlainsSpikes"},
- {biJungleM, "JungleM"},
- {biJungleEdgeM, "JungleEdgeM"},
- {biBirchForestM, "BirchForestM"},
- {biBirchForestHillsM, "BirchForestHillsM"},
- {biRoofedForestM, "RoofedForestM"},
- {biColdTaigaM, "ColdTaigaM"},
- {biMegaSpruceTaiga, "MegaSpruceTaiga"},
- {biMegaSpruceTaigaHills, "MegaSpruceTaigaHills"},
- {biExtremeHillsPlusM, "ExtremeHillsPlusM"},
- {biSavannaM, "SavannaM"},
- {biSavannaPlateauM, "SavannaPlateauM"},
- {biMesaBryce, "MesaBryce"},
- {biMesaPlateauFM, "MesaPlateauFM"},
- {biMesaPlateauM, "MesaPlateauM"},
- } ;
-
- for (size_t i = 0; i < ARRAYCOUNT(BiomeMap); i++)
+ for (size_t i = 0; i < ARRAYCOUNT(g_BiomeMap); i++)
{
- if (NoCaseCompare(BiomeMap[i].m_String, a_BiomeString) == 0)
+ if (NoCaseCompare(g_BiomeMap[i].m_String, a_BiomeString) == 0)
{
- return BiomeMap[i].m_Biome;
+ return g_BiomeMap[i].m_Biome;
}
} // for i - BiomeMap[]
return biInvalidBiome;
@@ -115,6 +121,22 @@ EMCSBiome StringToBiome(const AString & a_BiomeString)
+AString BiomeToString(int a_Biome)
+{
+ for (size_t i = 0; i < ARRAYCOUNT(g_BiomeMap); i++)
+ {
+ if (g_BiomeMap[i].m_Biome == a_Biome)
+ {
+ return g_BiomeMap[i].m_String;
+ }
+ }
+ return AString();
+}
+
+
+
+
+
bool IsBiomeNoDownfall(EMCSBiome a_Biome)
{
switch (a_Biome)
diff --git a/src/BiomeDef.h b/src/BiomeDef.h
index 474d4df76..67916890d 100644
--- a/src/BiomeDef.h
+++ b/src/BiomeDef.h
@@ -104,10 +104,13 @@ enum EMCSBiome
biMaxVariantBiome = biNumVariantBiomes - 1, // The maximum biome value
} ;
-/// Translates a biome string to biome enum. Takes either a number or a biome alias (built-in). Returns biInvalidBiome on failure.
+/** Translates a biome string to biome enum. Takes either a number or a biome alias (built-in). Returns biInvalidBiome on failure. */
extern EMCSBiome StringToBiome(const AString & a_BiomeString);
-/// Returns true if the biome has no downfall - deserts and savannas
+/** Translates biome enum into biome string. Returns empty string on failure (unknown biome). */
+extern AString BiomeToString(int a_Biome);
+
+/** Returns true if the biome has no downfall - deserts and savannas */
extern bool IsBiomeNoDownfall(EMCSBiome a_Biome);
--
cgit v1.2.3
From 015bf244b5d1f5d9dac7ee85a406dd95c974697b Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 15:36:05 +0200
Subject: Added BiomeToString() API function.
---
src/BiomeDef.cpp | 180 +++++++++++++++++++++++++++++++------------------------
src/BiomeDef.h | 7 ++-
2 files changed, 106 insertions(+), 81 deletions(-)
diff --git a/src/BiomeDef.cpp b/src/BiomeDef.cpp
index 3fba93e8a..9852b3dd9 100644
--- a/src/BiomeDef.cpp
+++ b/src/BiomeDef.cpp
@@ -7,6 +7,88 @@
#include "BiomeDef.h"
+
+
+// The "map" used for biome <-> string conversions:
+static struct {
+ EMCSBiome m_Biome;
+ const char * m_String;
+} g_BiomeMap[] =
+{
+ {biOcean, "Ocean"} ,
+ {biPlains, "Plains"},
+ {biDesert, "Desert"},
+ {biExtremeHills, "ExtremeHills"},
+ {biForest, "Forest"},
+ {biTaiga, "Taiga"},
+ {biSwampland, "Swampland"},
+ {biRiver, "River"},
+ {biNether, "Hell"},
+ {biNether, "Nether"},
+ {biEnd, "Sky"},
+ {biEnd, "End"},
+ {biFrozenOcean, "FrozenOcean"},
+ {biFrozenRiver, "FrozenRiver"},
+ {biIcePlains, "IcePlains"},
+ {biIcePlains, "Tundra"},
+ {biIceMountains, "IceMountains"},
+ {biMushroomIsland, "MushroomIsland"},
+ {biMushroomShore, "MushroomShore"},
+ {biBeach, "Beach"},
+ {biDesertHills, "DesertHills"},
+ {biForestHills, "ForestHills"},
+ {biTaigaHills, "TaigaHills"},
+ {biExtremeHillsEdge, "ExtremeHillsEdge"},
+ {biJungle, "Jungle"},
+ {biJungleHills, "JungleHills"},
+
+ // Release 1.7 biomes:
+ {biJungleEdge, "JungleEdge"},
+ {biDeepOcean, "DeepOcean"},
+ {biStoneBeach, "StoneBeach"},
+ {biColdBeach, "ColdBeach"},
+ {biBirchForest, "BirchForest"},
+ {biBirchForestHills, "BirchForestHills"},
+ {biRoofedForest, "RoofedForest"},
+ {biColdTaiga, "ColdTaiga"},
+ {biColdTaigaHills, "ColdTaigaHills"},
+ {biMegaTaiga, "MegaTaiga"},
+ {biMegaTaigaHills, "MegaTaigaHills"},
+ {biExtremeHillsPlus, "ExtremeHillsPlus"},
+ {biSavanna, "Savanna"},
+ {biSavannaPlateau, "SavannaPlateau"},
+ {biMesa, "Mesa"},
+ {biMesaPlateauF, "MesaPlateauF"},
+ {biMesaPlateau, "MesaPlateau"},
+
+ // Release 1.7 variants:
+ {biSunflowerPlains, "SunflowerPlains"},
+ {biDesertM, "DesertM"},
+ {biExtremeHillsM, "ExtremeHillsM"},
+ {biFlowerForest, "FlowerForest"},
+ {biTaigaM, "TaigaM"},
+ {biSwamplandM, "SwamplandM"},
+ {biIcePlainsSpikes, "IcePlainsSpikes"},
+ {biJungleM, "JungleM"},
+ {biJungleEdgeM, "JungleEdgeM"},
+ {biBirchForestM, "BirchForestM"},
+ {biBirchForestHillsM, "BirchForestHillsM"},
+ {biRoofedForestM, "RoofedForestM"},
+ {biColdTaigaM, "ColdTaigaM"},
+ {biMegaSpruceTaiga, "MegaSpruceTaiga"},
+ {biMegaSpruceTaigaHills, "MegaSpruceTaigaHills"},
+ {biExtremeHillsPlusM, "ExtremeHillsPlusM"},
+ {biSavannaM, "SavannaM"},
+ {biSavannaPlateauM, "SavannaPlateauM"},
+ {biMesaBryce, "MesaBryce"},
+ {biMesaPlateauFM, "MesaPlateauFM"},
+ {biMesaPlateauM, "MesaPlateauM"},
+} ;
+
+
+
+
+
EMCSBiome StringToBiome(const AString & a_BiomeString)
{
// If it is a number, return it:
@@ -25,87 +107,11 @@ EMCSBiome StringToBiome(const AString & a_BiomeString)
return biInvalidBiome;
}
- // Convert using the built-in map:
- static struct {
- EMCSBiome m_Biome;
- const char * m_String;
- } BiomeMap[] =
- {
- {biOcean, "Ocean"} ,
- {biPlains, "Plains"},
- {biDesert, "Desert"},
- {biExtremeHills, "ExtremeHills"},
- {biForest, "Forest"},
- {biTaiga, "Taiga"},
- {biSwampland, "Swampland"},
- {biRiver, "River"},
- {biNether, "Hell"},
- {biNether, "Nether"},
- {biEnd, "Sky"},
- {biEnd, "End"},
- {biFrozenOcean, "FrozenOcean"},
- {biFrozenRiver, "FrozenRiver"},
- {biIcePlains, "IcePlains"},
- {biIcePlains, "Tundra"},
- {biIceMountains, "IceMountains"},
- {biMushroomIsland, "MushroomIsland"},
- {biMushroomShore, "MushroomShore"},
- {biBeach, "Beach"},
- {biDesertHills, "DesertHills"},
- {biForestHills, "ForestHills"},
- {biTaigaHills, "TaigaHills"},
- {biExtremeHillsEdge, "ExtremeHillsEdge"},
- {biJungle, "Jungle"},
- {biJungleHills, "JungleHills"},
-
- // Release 1.7 biomes:
- {biJungleEdge, "JungleEdge"},
- {biDeepOcean, "DeepOcean"},
- {biStoneBeach, "StoneBeach"},
- {biColdBeach, "ColdBeach"},
- {biBirchForest, "BirchForest"},
- {biBirchForestHills, "BirchForestHills"},
- {biRoofedForest, "RoofedForest"},
- {biColdTaiga, "ColdTaiga"},
- {biColdTaigaHills, "ColdTaigaHills"},
- {biMegaTaiga, "MegaTaiga"},
- {biMegaTaigaHills, "MegaTaigaHills"},
- {biExtremeHillsPlus, "ExtremeHillsPlus"},
- {biSavanna, "Savanna"},
- {biSavannaPlateau, "SavannaPlateau"},
- {biMesa, "Mesa"},
- {biMesaPlateauF, "MesaPlateauF"},
- {biMesaPlateau, "MesaPlateau"},
-
- // Release 1.7 variants:
- {biSunflowerPlains, "SunflowerPlains"},
- {biDesertM, "DesertM"},
- {biExtremeHillsM, "ExtremeHillsM"},
- {biFlowerForest, "FlowerForest"},
- {biTaigaM, "TaigaM"},
- {biSwamplandM, "SwamplandM"},
- {biIcePlainsSpikes, "IcePlainsSpikes"},
- {biJungleM, "JungleM"},
- {biJungleEdgeM, "JungleEdgeM"},
- {biBirchForestM, "BirchForestM"},
- {biBirchForestHillsM, "BirchForestHillsM"},
- {biRoofedForestM, "RoofedForestM"},
- {biColdTaigaM, "ColdTaigaM"},
- {biMegaSpruceTaiga, "MegaSpruceTaiga"},
- {biMegaSpruceTaigaHills, "MegaSpruceTaigaHills"},
- {biExtremeHillsPlusM, "ExtremeHillsPlusM"},
- {biSavannaM, "SavannaM"},
- {biSavannaPlateauM, "SavannaPlateauM"},
- {biMesaBryce, "MesaBryce"},
- {biMesaPlateauFM, "MesaPlateauFM"},
- {biMesaPlateauM, "MesaPlateauM"},
- } ;
-
- for (size_t i = 0; i < ARRAYCOUNT(BiomeMap); i++)
+ for (size_t i = 0; i < ARRAYCOUNT(g_BiomeMap); i++)
{
- if (NoCaseCompare(BiomeMap[i].m_String, a_BiomeString) == 0)
+ if (NoCaseCompare(g_BiomeMap[i].m_String, a_BiomeString) == 0)
{
- return BiomeMap[i].m_Biome;
+ return g_BiomeMap[i].m_Biome;
}
} // for i - BiomeMap[]
return biInvalidBiome;
@@ -115,6 +121,22 @@ EMCSBiome StringToBiome(const AString & a_BiomeString)
+AString BiomeToString(int a_Biome)
+{
+ for (size_t i = 0; i < ARRAYCOUNT(g_BiomeMap); i++)
+ {
+ if (g_BiomeMap[i].m_Biome == a_Biome)
+ {
+ return g_BiomeMap[i].m_String;
+ }
+ }
+ return AString();
+}
+
+
+
+
+
bool IsBiomeNoDownfall(EMCSBiome a_Biome)
{
switch (a_Biome)
diff --git a/src/BiomeDef.h b/src/BiomeDef.h
index 474d4df76..67916890d 100644
--- a/src/BiomeDef.h
+++ b/src/BiomeDef.h
@@ -104,10 +104,13 @@ enum EMCSBiome
biMaxVariantBiome = biNumVariantBiomes - 1, // The maximum biome value
} ;
-/// Translates a biome string to biome enum. Takes either a number or a biome alias (built-in). Returns biInvalidBiome on failure.
+/** Translates a biome string to biome enum. Takes either a number or a biome alias (built-in). Returns biInvalidBiome on failure. */
extern EMCSBiome StringToBiome(const AString & a_BiomeString);
-/// Returns true if the biome has no downfall - deserts and savannas
+/** Translates biome enum into biome string. Returns empty string on failure (unknown biome). */
+extern AString BiomeToString(int a_Biome);
+
+/** Returns true if the biome has no downfall - deserts and savannas */
extern bool IsBiomeNoDownfall(EMCSBiome a_Biome);
--
cgit v1.2.3
From d9f7ae6a4d0895752c1a62657c36433e92104346 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 17:13:08 +0200
Subject: Moved cPublicKey to its separate file in PolarSSL++.
---
Tools/ProtoProxy/CMakeLists.txt | 2 ++
Tools/ProtoProxy/Connection.cpp | 1 +
src/Crypto.cpp | 78 -----------------------------------------
src/Crypto.h | 31 ----------------
src/PolarSSL++/CMakeLists.txt | 2 ++
src/PolarSSL++/CtrDrbgContext.h | 1 +
src/PolarSSL++/PublicKey.cpp | 73 ++++++++++++++++++++++++++++++++++++++
src/PolarSSL++/PublicKey.h | 48 +++++++++++++++++++++++++
8 files changed, 127 insertions(+), 109 deletions(-)
create mode 100644 src/PolarSSL++/PublicKey.cpp
create mode 100644 src/PolarSSL++/PublicKey.h
diff --git a/Tools/ProtoProxy/CMakeLists.txt b/Tools/ProtoProxy/CMakeLists.txt
index a94df0e24..a2241f355 100644
--- a/Tools/ProtoProxy/CMakeLists.txt
+++ b/Tools/ProtoProxy/CMakeLists.txt
@@ -39,6 +39,7 @@ set(SHARED_SRC
../../src/Crypto.cpp
../../src/PolarSSL++/CtrDrbgContext.cpp
../../src/PolarSSL++/EntropyContext.cpp
+ ../../src/PolarSSL++/PublicKey.cpp
../../src/PolarSSL++/RsaPrivateKey.cpp
)
set(SHARED_HDR
@@ -49,6 +50,7 @@ set(SHARED_HDR
../../src/Crypto.h
../../src/PolarSSL++/CtrDrbgContext.h
../../src/PolarSSL++/EntropyContext.h
+ ../../src/PolarSSL++/PublicKey.h
../../src/PolarSSL++/RsaPrivateKey.h
)
set(SHARED_OSS_SRC
diff --git a/Tools/ProtoProxy/Connection.cpp b/Tools/ProtoProxy/Connection.cpp
index b21d2ae59..fcbd9190c 100644
--- a/Tools/ProtoProxy/Connection.cpp
+++ b/Tools/ProtoProxy/Connection.cpp
@@ -7,6 +7,7 @@
#include "Connection.h"
#include "Server.h"
#include
+#include "PolarSSL++/PublicKey.h"
#ifdef _WIN32
#include // For _mkdir()
diff --git a/src/Crypto.cpp b/src/Crypto.cpp
index dd8787293..370b498bf 100644
--- a/src/Crypto.cpp
+++ b/src/Crypto.cpp
@@ -52,84 +52,6 @@ public:
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// cRSAPrivateKey:
-
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// cPublicKey:
-
-cPublicKey::cPublicKey(const AString & a_PublicKeyDER)
-{
- pk_init(&m_Pk);
- if (pk_parse_public_key(&m_Pk, (const Byte *)a_PublicKeyDER.data(), a_PublicKeyDER.size()) != 0)
- {
- ASSERT(!"Cannot parse PubKey");
- return;
- }
- InitRnd();
-}
-
-
-
-
-
-cPublicKey::~cPublicKey()
-{
- pk_free(&m_Pk);
-}
-
-
-
-
-
-int cPublicKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength)
-{
- size_t DecryptedLen = a_DecryptedMaxLength;
- int res = pk_decrypt(&m_Pk,
- a_EncryptedData, a_EncryptedLength,
- a_DecryptedData, &DecryptedLen, a_DecryptedMaxLength,
- ctr_drbg_random, &m_Ctr_drbg
- );
- if (res != 0)
- {
- return res;
- }
- return (int)DecryptedLen;
-}
-
-
-
-
-
-int cPublicKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
-{
- size_t EncryptedLength = a_EncryptedMaxLength;
- int res = pk_encrypt(&m_Pk,
- a_PlainData, a_PlainLength, a_EncryptedData, &EncryptedLength, a_EncryptedMaxLength,
- ctr_drbg_random, &m_Ctr_drbg
- );
- if (res != 0)
- {
- return res;
- }
- return (int)EncryptedLength;
-}
-
-
-
-
-
-void cPublicKey::InitRnd(void)
-{
- entropy_init(&m_Entropy);
- const unsigned char pers[] = "rsa_genkey";
- ctr_drbg_init(&m_Ctr_drbg, entropy_func, &m_Entropy, pers, sizeof(pers) - 1);
-}
-
-
-
-
-
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cAESCFBDecryptor:
diff --git a/src/Crypto.h b/src/Crypto.h
index 24f246897..993b21afb 100644
--- a/src/Crypto.h
+++ b/src/Crypto.h
@@ -14,37 +14,6 @@
#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/sha1.h"
-#include "polarssl/pk.h"
-
-
-
-
-
-class cPublicKey
-{
-public:
- cPublicKey(const AString & a_PublicKeyDER);
- ~cPublicKey();
-
- /** Decrypts the data using the stored public key
- Both a_EncryptedData and a_DecryptedData must be at least bytes large.
- Returns the number of bytes decrypted, or negative number for error. */
- int Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength);
-
- /** Encrypts the data using the stored public key
- Both a_EncryptedData and a_DecryptedData must be at least bytes large.
- Returns the number of bytes decrypted, or negative number for error. */
- int Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength);
-
-protected:
- pk_context m_Pk;
- entropy_context m_Entropy;
- ctr_drbg_context m_Ctr_drbg;
-
- /** Initializes the m_Entropy and m_Ctr_drbg contexts
- Common part of this object's construction, called from all constructors. */
- void InitRnd(void);
-} ;
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
index ebdd52de5..bf7720abc 100644
--- a/src/PolarSSL++/CMakeLists.txt
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -10,6 +10,7 @@ set(SOURCES
"CallbackSslContext.cpp"
"CtrDrbgContext.cpp"
"EntropyContext.cpp"
+ "PublicKey.cpp"
"RsaPrivateKey.cpp"
"SslContext.cpp"
"X509Cert.cpp"
@@ -21,6 +22,7 @@ set(HEADERS
"CallbackSslContext.h"
"CtrDrbgContext.h"
"EntropyContext.h"
+ "PublicKey.h"
"RsaPrivateKey.h"
"SslContext.h"
"X509Cert.h"
diff --git a/src/PolarSSL++/CtrDrbgContext.h b/src/PolarSSL++/CtrDrbgContext.h
index 817222a53..65e9a2374 100644
--- a/src/PolarSSL++/CtrDrbgContext.h
+++ b/src/PolarSSL++/CtrDrbgContext.h
@@ -26,6 +26,7 @@ class cCtrDrbgContext
{
friend class cSslContext;
friend class cRsaPrivateKey;
+ friend class cPublicKey;
public:
/** Constructs the context with a new entropy context. */
diff --git a/src/PolarSSL++/PublicKey.cpp b/src/PolarSSL++/PublicKey.cpp
new file mode 100644
index 000000000..49794a0c8
--- /dev/null
+++ b/src/PolarSSL++/PublicKey.cpp
@@ -0,0 +1,73 @@
+
+// PublicKey.cpp
+
+// Implements the cPublicKey class representing a RSA public key in PolarSSL
+
+#include "Globals.h"
+#include "PublicKey.h"
+
+
+
+
+
+cPublicKey::cPublicKey(const AString & a_PublicKeyDER)
+{
+ pk_init(&m_Pk);
+ if (pk_parse_public_key(&m_Pk, (const Byte *)a_PublicKeyDER.data(), a_PublicKeyDER.size()) != 0)
+ {
+ ASSERT(!"Cannot parse PubKey");
+ return;
+ }
+ m_CtrDrbg.Initialize("rsa_pubkey", 10);
+}
+
+
+
+
+
+cPublicKey::~cPublicKey()
+{
+ pk_free(&m_Pk);
+}
+
+
+
+
+
+int cPublicKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength)
+{
+ size_t DecryptedLen = a_DecryptedMaxLength;
+ int res = pk_decrypt(&m_Pk,
+ a_EncryptedData, a_EncryptedLength,
+ a_DecryptedData, &DecryptedLen, a_DecryptedMaxLength,
+ ctr_drbg_random, m_CtrDrbg.GetInternal()
+ );
+ if (res != 0)
+ {
+ return res;
+ }
+ return (int)DecryptedLen;
+}
+
+
+
+
+
+int cPublicKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
+{
+ size_t EncryptedLength = a_EncryptedMaxLength;
+ int res = pk_encrypt(&m_Pk,
+ a_PlainData, a_PlainLength, a_EncryptedData, &EncryptedLength, a_EncryptedMaxLength,
+ ctr_drbg_random, m_CtrDrbg.GetInternal()
+ );
+ if (res != 0)
+ {
+ return res;
+ }
+ return (int)EncryptedLength;
+}
+
+
+
+
+
diff --git a/src/PolarSSL++/PublicKey.h b/src/PolarSSL++/PublicKey.h
new file mode 100644
index 000000000..5a0a57147
--- /dev/null
+++ b/src/PolarSSL++/PublicKey.h
@@ -0,0 +1,48 @@
+
+// PublicKey.h
+
+// Declares the cPublicKey class representing a RSA public key in PolarSSL
+
+
+
+
+
+#pragma once
+
+#include "CtrDrbgContext.h"
+#include "polarssl/pk.h"
+
+
+
+
+
+class cPublicKey
+{
+public:
+ /** Constructs the public key out of the DER-encoded pubkey data */
+ cPublicKey(const AString & a_PublicKeyDER);
+
+ ~cPublicKey();
+
+ /** Decrypts the data using the stored public key
+ Both a_EncryptedData and a_DecryptedData must be at least bytes large.
+ Returns the number of bytes decrypted, or negative number for error. */
+ int Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength);
+
+ /** Encrypts the data using the stored public key
+ Both a_EncryptedData and a_DecryptedData must be at least bytes large.
+ Returns the number of bytes decrypted, or negative number for error. */
+ int Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength);
+
+protected:
+ /** The public key PolarSSL representation */
+ pk_context m_Pk;
+
+ /** The random generator used in encryption and decryption */
+ cCtrDrbgContext m_CtrDrbg;
+} ;
+
+
+
+
+
--
cgit v1.2.3
From 6cb2d2461f869d5c9d986cccec5edf1021878df2 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 17:37:15 +0200
Subject: Moved the rest of the Crypto objects into their own respective files.
---
Tools/ProtoProxy/CMakeLists.txt | 6 +-
Tools/ProtoProxy/Connection.cpp | 4 +-
Tools/ProtoProxy/Connection.h | 10 +-
Tools/ProtoProxy/Globals.h | 6 -
src/Crypto.cpp | 257 ----------------------------------
src/Crypto.h | 124 ----------------
src/PolarSSL++/AesCfb128Decryptor.cpp | 67 +++++++++
src/PolarSSL++/AesCfb128Decryptor.h | 52 +++++++
src/PolarSSL++/AesCfb128Encryptor.cpp | 68 +++++++++
src/PolarSSL++/AesCfb128Encryptor.h | 50 +++++++
src/PolarSSL++/CMakeLists.txt | 42 +++---
src/PolarSSL++/Sha1Checksum.cpp | 138 ++++++++++++++++++
src/PolarSSL++/Sha1Checksum.h | 52 +++++++
src/Protocol/Protocol132.cpp | 18 +--
src/Protocol/Protocol132.h | 7 +-
src/Protocol/Protocol17x.cpp | 5 +-
src/Protocol/Protocol17x.h | 7 +-
17 files changed, 477 insertions(+), 436 deletions(-)
delete mode 100644 src/Crypto.cpp
delete mode 100644 src/Crypto.h
create mode 100644 src/PolarSSL++/AesCfb128Decryptor.cpp
create mode 100644 src/PolarSSL++/AesCfb128Decryptor.h
create mode 100644 src/PolarSSL++/AesCfb128Encryptor.cpp
create mode 100644 src/PolarSSL++/AesCfb128Encryptor.h
create mode 100644 src/PolarSSL++/Sha1Checksum.cpp
create mode 100644 src/PolarSSL++/Sha1Checksum.h
diff --git a/Tools/ProtoProxy/CMakeLists.txt b/Tools/ProtoProxy/CMakeLists.txt
index a2241f355..a136c95df 100644
--- a/Tools/ProtoProxy/CMakeLists.txt
+++ b/Tools/ProtoProxy/CMakeLists.txt
@@ -36,7 +36,8 @@ set(SHARED_SRC
../../src/StringUtils.cpp
../../src/Log.cpp
../../src/MCLogger.cpp
- ../../src/Crypto.cpp
+ ../../src/PolarSSL++/AesCfb128Decryptor.cpp
+ ../../src/PolarSSL++/AesCfb128Encryptor.cpp
../../src/PolarSSL++/CtrDrbgContext.cpp
../../src/PolarSSL++/EntropyContext.cpp
../../src/PolarSSL++/PublicKey.cpp
@@ -47,7 +48,8 @@ set(SHARED_HDR
../../src/StringUtils.h
../../src/Log.h
../../src/MCLogger.h
- ../../src/Crypto.h
+ ../../src/PolarSSL++/AesCfb128Decryptor.h
+ ../../src/PolarSSL++/AesCfb128Encryptor.h
../../src/PolarSSL++/CtrDrbgContext.h
../../src/PolarSSL++/EntropyContext.h
../../src/PolarSSL++/PublicKey.h
diff --git a/Tools/ProtoProxy/Connection.cpp b/Tools/ProtoProxy/Connection.cpp
index fcbd9190c..26aed2206 100644
--- a/Tools/ProtoProxy/Connection.cpp
+++ b/Tools/ProtoProxy/Connection.cpp
@@ -472,7 +472,7 @@ bool cConnection::SendData(SOCKET a_Socket, cByteBuffer & a_Data, const char * a
-bool cConnection::SendEncryptedData(SOCKET a_Socket, cAESCFBEncryptor & a_Encryptor, const char * a_Data, size_t a_Size, const char * a_Peer)
+bool cConnection::SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, const char * a_Data, size_t a_Size, const char * a_Peer)
{
DataLog(a_Data, a_Size, "Encrypting %d bytes to %s", a_Size, a_Peer);
const Byte * Data = (const Byte *)a_Data;
@@ -496,7 +496,7 @@ bool cConnection::SendEncryptedData(SOCKET a_Socket, cAESCFBEncryptor & a_Encryp
-bool cConnection::SendEncryptedData(SOCKET a_Socket, cAESCFBEncryptor & a_Encryptor, cByteBuffer & a_Data, const char * a_Peer)
+bool cConnection::SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, cByteBuffer & a_Data, const char * a_Peer)
{
AString All;
a_Data.ReadAll(All);
diff --git a/Tools/ProtoProxy/Connection.h b/Tools/ProtoProxy/Connection.h
index 9e04994b7..1fc9536de 100644
--- a/Tools/ProtoProxy/Connection.h
+++ b/Tools/ProtoProxy/Connection.h
@@ -11,6 +11,8 @@
#include "ByteBuffer.h"
#include "OSSupport/Timer.h"
+#include "PolarSSL++/AesCfb128Decryptor.h"
+#include "PolarSSL++/AesCfb128Encryptor.h"
@@ -66,8 +68,8 @@ protected:
cByteBuffer m_ClientBuffer;
cByteBuffer m_ServerBuffer;
- cAESCFBDecryptor m_ServerDecryptor;
- cAESCFBEncryptor m_ServerEncryptor;
+ cAesCfb128Decryptor m_ServerDecryptor;
+ cAesCfb128Encryptor m_ServerEncryptor;
AString m_ServerEncryptionBuffer; // Buffer for the data to be sent to the server once encryption is established
@@ -109,10 +111,10 @@ protected:
bool SendData(SOCKET a_Socket, cByteBuffer & a_Data, const char * a_Peer);
/// Sends data to the specfied socket, after encrypting it using a_Encryptor. If sending fails, prints a fail message using a_Peer and returns false
- bool SendEncryptedData(SOCKET a_Socket, cAESCFBEncryptor & a_Encryptor, const char * a_Data, size_t a_Size, const char * a_Peer);
+ bool SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, const char * a_Data, size_t a_Size, const char * a_Peer);
/// Sends data to the specfied socket, after encrypting it using a_Encryptor. If sending fails, prints a fail message using a_Peer and returns false
- bool SendEncryptedData(SOCKET a_Socket, cAESCFBEncryptor & a_Encryptor, cByteBuffer & a_Data, const char * a_Peer);
+ bool SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, cByteBuffer & a_Data, const char * a_Peer);
/// Decodes packets coming from the client, sends appropriate counterparts to the server; returns false if the connection is to be dropped
bool DecodeClientsPackets(const char * a_Data, int a_Size);
diff --git a/Tools/ProtoProxy/Globals.h b/Tools/ProtoProxy/Globals.h
index 186efa611..54e7e9251 100644
--- a/Tools/ProtoProxy/Globals.h
+++ b/Tools/ProtoProxy/Globals.h
@@ -246,12 +246,6 @@ public:
-#include "../../src/Crypto.h"
-
-
-
-
-
#define LOGERROR printf
#define LOGINFO printf
#define LOGWARNING printf
diff --git a/src/Crypto.cpp b/src/Crypto.cpp
deleted file mode 100644
index 370b498bf..000000000
--- a/src/Crypto.cpp
+++ /dev/null
@@ -1,257 +0,0 @@
-
-// Crypto.cpp
-
-// Implements classes that wrap the cryptographic code library
-
-#include "Globals.h"
-#include "Crypto.h"
-
-#include "polarssl/pk.h"
-
-
-
-
-
-/*
-// Self-test the hash formatting for known values:
-// sha1(Notch) : 4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48
-// sha1(jeb_) : -7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1
-// sha1(simon) : 88e16a1019277b15d58faf0541e11910eb756f6
-
-class Test
-{
-public:
- Test(void)
- {
- AString DigestNotch, DigestJeb, DigestSimon;
- Byte Digest[20];
- cSHA1Checksum Checksum;
- Checksum.Update((const Byte *)"Notch", 5);
- Checksum.Finalize(Digest);
- cSHA1Checksum::DigestToJava(Digest, DigestNotch);
- Checksum.Restart();
- Checksum.Update((const Byte *)"jeb_", 4);
- Checksum.Finalize(Digest);
- cSHA1Checksum::DigestToJava(Digest, DigestJeb);
- Checksum.Restart();
- Checksum.Update((const Byte *)"simon", 5);
- Checksum.Finalize(Digest);
- cSHA1Checksum::DigestToJava(Digest, DigestSimon);
- printf("Notch: \"%s\"\n", DigestNotch.c_str());
- printf("jeb_: \"%s\"\n", DigestJeb.c_str());
- printf("simon: \"%s\"\n", DigestSimon.c_str());
- assert(DigestNotch == "4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48");
- assert(DigestJeb == "-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1");
- assert(DigestSimon == "88e16a1019277b15d58faf0541e11910eb756f6");
- }
-} test;
-*/
-
-
-
-
-
-
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// cAESCFBDecryptor:
-
-cAESCFBDecryptor::cAESCFBDecryptor(void) :
- m_IVOffset(0),
- m_IsValid(false)
-{
-}
-
-
-
-
-
-cAESCFBDecryptor::~cAESCFBDecryptor()
-{
- // Clear the leftover in-memory data, so that they can't be accessed by a backdoor
- memset(&m_Aes, 0, sizeof(m_Aes));
-}
-
-
-
-
-
-void cAESCFBDecryptor::Init(const Byte a_Key[16], const Byte a_IV[16])
-{
- ASSERT(!IsValid()); // Cannot Init twice
-
- memcpy(m_IV, a_IV, 16);
- aes_setkey_enc(&m_Aes, a_Key, 128);
- m_IsValid = true;
-}
-
-
-
-
-
-void cAESCFBDecryptor::ProcessData(Byte * a_DecryptedOut, const Byte * a_EncryptedIn, size_t a_Length)
-{
- ASSERT(IsValid()); // Must Init() first
-
- // PolarSSL doesn't support AES-CFB8, need to implement it manually:
- for (size_t i = 0; i < a_Length; i++)
- {
- Byte Buffer[sizeof(m_IV)];
- aes_crypt_ecb(&m_Aes, AES_ENCRYPT, m_IV, Buffer);
- for (size_t idx = 0; idx < sizeof(m_IV) - 1; idx++)
- {
- m_IV[idx] = m_IV[idx + 1];
- }
- m_IV[sizeof(m_IV) - 1] = a_EncryptedIn[i];
- a_DecryptedOut[i] = a_EncryptedIn[i] ^ Buffer[0];
- }
-}
-
-
-
-
-
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// cAESCFBEncryptor:
-
-cAESCFBEncryptor::cAESCFBEncryptor(void) :
- m_IVOffset(0),
- m_IsValid(false)
-{
-}
-
-
-
-
-
-cAESCFBEncryptor::~cAESCFBEncryptor()
-{
- // Clear the leftover in-memory data, so that they can't be accessed by a backdoor
- memset(&m_Aes, 0, sizeof(m_Aes));
-}
-
-
-
-
-
-void cAESCFBEncryptor::Init(const Byte a_Key[16], const Byte a_IV[16])
-{
- ASSERT(!IsValid()); // Cannot Init twice
- ASSERT(m_IVOffset == 0);
-
- memcpy(m_IV, a_IV, 16);
- aes_setkey_enc(&m_Aes, a_Key, 128);
- m_IsValid = true;
-}
-
-
-
-
-
-void cAESCFBEncryptor::ProcessData(Byte * a_EncryptedOut, const Byte * a_PlainIn, size_t a_Length)
-{
- ASSERT(IsValid()); // Must Init() first
-
- // PolarSSL doesn't do AES-CFB8, so we need to implement it ourselves:
- for (size_t i = 0; i < a_Length; i++)
- {
- Byte Buffer[sizeof(m_IV)];
- aes_crypt_ecb(&m_Aes, AES_ENCRYPT, m_IV, Buffer);
- for (size_t idx = 0; idx < sizeof(m_IV) - 1; idx++)
- {
- m_IV[idx] = m_IV[idx + 1];
- }
- a_EncryptedOut[i] = a_PlainIn[i] ^ Buffer[0];
- m_IV[sizeof(m_IV) - 1] = a_EncryptedOut[i];
- }
-}
-
-
-
-
-
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-// cSHA1Checksum:
-
-cSHA1Checksum::cSHA1Checksum(void) :
- m_DoesAcceptInput(true)
-{
- sha1_starts(&m_Sha1);
-}
-
-
-
-
-
-void cSHA1Checksum::Update(const Byte * a_Data, size_t a_Length)
-{
- ASSERT(m_DoesAcceptInput); // Not Finalize()-d yet, or Restart()-ed
-
- sha1_update(&m_Sha1, a_Data, a_Length);
-}
-
-
-
-
-
-void cSHA1Checksum::Finalize(cSHA1Checksum::Checksum & a_Output)
-{
- ASSERT(m_DoesAcceptInput); // Not Finalize()-d yet, or Restart()-ed
-
- sha1_finish(&m_Sha1, a_Output);
- m_DoesAcceptInput = false;
-}
-
-
-
-
-
-void cSHA1Checksum::DigestToJava(const Checksum & a_Digest, AString & a_Out)
-{
- Checksum Digest;
- memcpy(Digest, a_Digest, sizeof(Digest));
-
- bool IsNegative = (Digest[0] >= 0x80);
- if (IsNegative)
- {
- // Two's complement:
- bool carry = true; // Add one to the whole number
- for (int i = 19; i >= 0; i--)
- {
- Digest[i] = ~Digest[i];
- if (carry)
- {
- carry = (Digest[i] == 0xff);
- Digest[i]++;
- }
- }
- }
- a_Out.clear();
- a_Out.reserve(40);
- for (int i = 0; i < 20; i++)
- {
- AppendPrintf(a_Out, "%02x", Digest[i]);
- }
- while ((a_Out.length() > 0) && (a_Out[0] == '0'))
- {
- a_Out.erase(0, 1);
- }
- if (IsNegative)
- {
- a_Out.insert(0, "-");
- }
-}
-
-
-
-
-
-
-void cSHA1Checksum::Restart(void)
-{
- sha1_starts(&m_Sha1);
- m_DoesAcceptInput = true;
-}
-
-
-
-
diff --git a/src/Crypto.h b/src/Crypto.h
deleted file mode 100644
index 993b21afb..000000000
--- a/src/Crypto.h
+++ /dev/null
@@ -1,124 +0,0 @@
-
-// Crypto.h
-
-// Declares classes that wrap the cryptographic code library
-
-
-
-
-
-#pragma once
-
-#include "polarssl/rsa.h"
-#include "polarssl/aes.h"
-#include "polarssl/entropy.h"
-#include "polarssl/ctr_drbg.h"
-#include "polarssl/sha1.h"
-
-
-
-
-
-/** Decrypts data using the AES / CFB (128) algorithm */
-class cAESCFBDecryptor
-{
-public:
- Byte test;
-
- cAESCFBDecryptor(void);
- ~cAESCFBDecryptor();
-
- /** Initializes the decryptor with the specified Key / IV */
- void Init(const Byte a_Key[16], const Byte a_IV[16]);
-
- /** Decrypts a_Length bytes of the encrypted data; produces a_Length output bytes */
- void ProcessData(Byte * a_DecryptedOut, const Byte * a_EncryptedIn, size_t a_Length);
-
- /** Returns true if the object has been initialized with the Key / IV */
- bool IsValid(void) const { return m_IsValid; }
-
-protected:
- aes_context m_Aes;
-
- /** The InitialVector, used by the CFB mode decryption */
- Byte m_IV[16];
-
- /** Current offset in the m_IV, used by the CFB mode decryption */
- size_t m_IVOffset;
-
- /** Indicates whether the object has been initialized with the Key / IV */
- bool m_IsValid;
-} ;
-
-
-
-
-
-/** Encrypts data using the AES / CFB (128) algorithm */
-class cAESCFBEncryptor
-{
-public:
- cAESCFBEncryptor(void);
- ~cAESCFBEncryptor();
-
- /** Initializes the decryptor with the specified Key / IV */
- void Init(const Byte a_Key[16], const Byte a_IV[16]);
-
- /** Encrypts a_Length bytes of the plain data; produces a_Length output bytes */
- void ProcessData(Byte * a_EncryptedOut, const Byte * a_PlainIn, size_t a_Length);
-
- /** Returns true if the object has been initialized with the Key / IV */
- bool IsValid(void) const { return m_IsValid; }
-
-protected:
- aes_context m_Aes;
-
- /** The InitialVector, used by the CFB mode encryption */
- Byte m_IV[16];
-
- /** Current offset in the m_IV, used by the CFB mode encryption */
- size_t m_IVOffset;
-
- /** Indicates whether the object has been initialized with the Key / IV */
- bool m_IsValid;
-} ;
-
-
-
-
-
-/** Calculates a SHA1 checksum for data stream */
-class cSHA1Checksum
-{
-public:
- typedef Byte Checksum[20]; // The type used for storing the checksum
-
- cSHA1Checksum(void);
-
- /** Adds the specified data to the checksum */
- void Update(const Byte * a_Data, size_t a_Length);
-
- /** Calculates and returns the final checksum */
- void Finalize(Checksum & a_Output);
-
- /** Returns true if the object is accepts more input data, false if Finalize()-d (need to Restart()) */
- bool DoesAcceptInput(void) const { return m_DoesAcceptInput; }
-
- /** Converts a raw 160-bit SHA1 digest into a Java Hex representation
- According to http://wiki.vg/wiki/index.php?title=Protocol_Encryption&oldid=2802
- */
- static void DigestToJava(const Checksum & a_Digest, AString & a_JavaOut);
-
- /** Clears the current context and start a new checksum calculation */
- void Restart(void);
-
-protected:
- /** True if the object is accepts more input data, false if Finalize()-d (need to Restart()) */
- bool m_DoesAcceptInput;
-
- sha1_context m_Sha1;
-} ;
-
-
-
-
diff --git a/src/PolarSSL++/AesCfb128Decryptor.cpp b/src/PolarSSL++/AesCfb128Decryptor.cpp
new file mode 100644
index 000000000..af0d5106e
--- /dev/null
+++ b/src/PolarSSL++/AesCfb128Decryptor.cpp
@@ -0,0 +1,67 @@
+
+// AesCfb128Decryptor.cpp
+
+// Implements the cAesCfb128Decryptor class decrypting data using AES CFB-128
+
+#include "Globals.h"
+#include "AesCfb128Decryptor.h"
+
+
+
+
+
+cAesCfb128Decryptor::cAesCfb128Decryptor(void) :
+ m_IVOffset(0),
+ m_IsValid(false)
+{
+}
+
+
+
+
+
+cAesCfb128Decryptor::~cAesCfb128Decryptor()
+{
+ // Clear the leftover in-memory data, so that they can't be accessed by a backdoor
+ memset(&m_Aes, 0, sizeof(m_Aes));
+}
+
+
+
+
+
+void cAesCfb128Decryptor::Init(const Byte a_Key[16], const Byte a_IV[16])
+{
+ ASSERT(!IsValid()); // Cannot Init twice
+
+ memcpy(m_IV, a_IV, 16);
+ aes_setkey_enc(&m_Aes, a_Key, 128);
+ m_IsValid = true;
+}
+
+
+
+
+
+void cAesCfb128Decryptor::ProcessData(Byte * a_DecryptedOut, const Byte * a_EncryptedIn, size_t a_Length)
+{
+ ASSERT(IsValid()); // Must Init() first
+
+ // PolarSSL doesn't support AES-CFB8, need to implement it manually:
+ for (size_t i = 0; i < a_Length; i++)
+ {
+ Byte Buffer[sizeof(m_IV)];
+ aes_crypt_ecb(&m_Aes, AES_ENCRYPT, m_IV, Buffer);
+ for (size_t idx = 0; idx < sizeof(m_IV) - 1; idx++)
+ {
+ m_IV[idx] = m_IV[idx + 1];
+ }
+ m_IV[sizeof(m_IV) - 1] = a_EncryptedIn[i];
+ a_DecryptedOut[i] = a_EncryptedIn[i] ^ Buffer[0];
+ }
+}
+
+
+
+
+
diff --git a/src/PolarSSL++/AesCfb128Decryptor.h b/src/PolarSSL++/AesCfb128Decryptor.h
new file mode 100644
index 000000000..68c203d70
--- /dev/null
+++ b/src/PolarSSL++/AesCfb128Decryptor.h
@@ -0,0 +1,52 @@
+
+// AesCfb128Decryptor.h
+
+// Declares the cAesCfb128Decryptor class decrypting data using AES CFB-128
+
+
+
+
+
+#pragma once
+
+#include "polarssl/aes.h"
+
+
+
+
+
+/** Decrypts data using the AES / CFB 128 algorithm */
+class cAesCfb128Decryptor
+{
+public:
+ Byte test;
+
+ cAesCfb128Decryptor(void);
+ ~cAesCfb128Decryptor();
+
+ /** Initializes the decryptor with the specified Key / IV */
+ void Init(const Byte a_Key[16], const Byte a_IV[16]);
+
+ /** Decrypts a_Length bytes of the encrypted data; produces a_Length output bytes */
+ void ProcessData(Byte * a_DecryptedOut, const Byte * a_EncryptedIn, size_t a_Length);
+
+ /** Returns true if the object has been initialized with the Key / IV */
+ bool IsValid(void) const { return m_IsValid; }
+
+protected:
+ aes_context m_Aes;
+
+ /** The InitialVector, used by the CFB mode decryption */
+ Byte m_IV[16];
+
+ /** Current offset in the m_IV, used by the CFB mode decryption */
+ size_t m_IVOffset;
+
+ /** Indicates whether the object has been initialized with the Key / IV */
+ bool m_IsValid;
+} ;
+
+
+
+
+
diff --git a/src/PolarSSL++/AesCfb128Encryptor.cpp b/src/PolarSSL++/AesCfb128Encryptor.cpp
new file mode 100644
index 000000000..a641ad48e
--- /dev/null
+++ b/src/PolarSSL++/AesCfb128Encryptor.cpp
@@ -0,0 +1,68 @@
+
+// AesCfb128Encryptor.cpp
+
+// Implements the cAesCfb128Encryptor class encrypting data using AES CFB-128
+
+#include "Globals.h"
+#include "AesCfb128Encryptor.h"
+
+
+
+
+
+cAesCfb128Encryptor::cAesCfb128Encryptor(void) :
+ m_IVOffset(0),
+ m_IsValid(false)
+{
+}
+
+
+
+
+
+cAesCfb128Encryptor::~cAesCfb128Encryptor()
+{
+ // Clear the leftover in-memory data, so that they can't be accessed by a backdoor
+ memset(&m_Aes, 0, sizeof(m_Aes));
+}
+
+
+
+
+
+void cAesCfb128Encryptor::Init(const Byte a_Key[16], const Byte a_IV[16])
+{
+ ASSERT(!IsValid()); // Cannot Init twice
+ ASSERT(m_IVOffset == 0);
+
+ memcpy(m_IV, a_IV, 16);
+ aes_setkey_enc(&m_Aes, a_Key, 128);
+ m_IsValid = true;
+}
+
+
+
+
+
+void cAesCfb128Encryptor::ProcessData(Byte * a_EncryptedOut, const Byte * a_PlainIn, size_t a_Length)
+{
+ ASSERT(IsValid()); // Must Init() first
+
+ // PolarSSL doesn't do AES-CFB8, so we need to implement it ourselves:
+ for (size_t i = 0; i < a_Length; i++)
+ {
+ Byte Buffer[sizeof(m_IV)];
+ aes_crypt_ecb(&m_Aes, AES_ENCRYPT, m_IV, Buffer);
+ for (size_t idx = 0; idx < sizeof(m_IV) - 1; idx++)
+ {
+ m_IV[idx] = m_IV[idx + 1];
+ }
+ a_EncryptedOut[i] = a_PlainIn[i] ^ Buffer[0];
+ m_IV[sizeof(m_IV) - 1] = a_EncryptedOut[i];
+ }
+}
+
+
+
+
+
diff --git a/src/PolarSSL++/AesCfb128Encryptor.h b/src/PolarSSL++/AesCfb128Encryptor.h
new file mode 100644
index 000000000..9dbb5d2c3
--- /dev/null
+++ b/src/PolarSSL++/AesCfb128Encryptor.h
@@ -0,0 +1,50 @@
+
+// AesCfb128Encryptor.h
+
+// Declares the cAesCfb128Encryptor class encrypting data using AES CFB-128
+
+
+
+
+
+#pragma once
+
+#include "polarssl/aes.h"
+
+
+
+
+
+/** Encrypts data using the AES / CFB (128) algorithm */
+class cAesCfb128Encryptor
+{
+public:
+ cAesCfb128Encryptor(void);
+ ~cAesCfb128Encryptor();
+
+ /** Initializes the decryptor with the specified Key / IV */
+ void Init(const Byte a_Key[16], const Byte a_IV[16]);
+
+ /** Encrypts a_Length bytes of the plain data; produces a_Length output bytes */
+ void ProcessData(Byte * a_EncryptedOut, const Byte * a_PlainIn, size_t a_Length);
+
+ /** Returns true if the object has been initialized with the Key / IV */
+ bool IsValid(void) const { return m_IsValid; }
+
+protected:
+ aes_context m_Aes;
+
+ /** The InitialVector, used by the CFB mode encryption */
+ Byte m_IV[16];
+
+ /** Current offset in the m_IV, used by the CFB mode encryption */
+ size_t m_IVOffset;
+
+ /** Indicates whether the object has been initialized with the Key / IV */
+ bool m_IsValid;
+} ;
+
+
+
+
+
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
index bf7720abc..b0a592760 100644
--- a/src/PolarSSL++/CMakeLists.txt
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -5,27 +5,33 @@ project (MCServer)
include_directories ("${PROJECT_SOURCE_DIR}/../")
set(SOURCES
- "BlockingSslClientSocket.cpp"
- "BufferedSslContext.cpp"
- "CallbackSslContext.cpp"
- "CtrDrbgContext.cpp"
- "EntropyContext.cpp"
- "PublicKey.cpp"
- "RsaPrivateKey.cpp"
- "SslContext.cpp"
- "X509Cert.cpp"
+ AesCfb128Decryptor.cpp
+ AesCfb128Encryptor.cpp
+ BlockingSslClientSocket.cpp
+ BufferedSslContext.cpp
+ CallbackSslContext.cpp
+ CtrDrbgContext.cpp
+ EntropyContext.cpp
+ PublicKey.cpp
+ RsaPrivateKey.cpp
+ Sha1Checksum.cpp
+ SslContext.cpp
+ X509Cert.cpp
)
set(HEADERS
- "BlockingSslClientSocket.h"
- "BufferedSslContext.h"
- "CallbackSslContext.h"
- "CtrDrbgContext.h"
- "EntropyContext.h"
- "PublicKey.h"
- "RsaPrivateKey.h"
- "SslContext.h"
- "X509Cert.h"
+ AesCfb128Decryptor.h
+ AesCfb128Encryptor.h
+ BlockingSslClientSocket.h
+ BufferedSslContext.h
+ CallbackSslContext.h
+ CtrDrbgContext.h
+ EntropyContext.h
+ PublicKey.h
+ RsaPrivateKey.h
+ SslContext.h
+ Sha1Checksum.h
+ X509Cert.h
)
add_library(PolarSSL++ ${SOURCES} ${HEADERS})
diff --git a/src/PolarSSL++/Sha1Checksum.cpp b/src/PolarSSL++/Sha1Checksum.cpp
new file mode 100644
index 000000000..a1ee9d7b9
--- /dev/null
+++ b/src/PolarSSL++/Sha1Checksum.cpp
@@ -0,0 +1,138 @@
+
+// Sha1Checksum.cpp
+
+// Declares the cSha1Checksum class representing the SHA-1 checksum calculator
+
+#include "Globals.h"
+#include "Sha1Checksum.h"
+
+
+
+
+
+/*
+// Self-test the hash formatting for known values:
+// sha1(Notch) : 4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48
+// sha1(jeb_) : -7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1
+// sha1(simon) : 88e16a1019277b15d58faf0541e11910eb756f6
+
+static class Test
+{
+public:
+ Test(void)
+ {
+ AString DigestNotch, DigestJeb, DigestSimon;
+ Byte Digest[20];
+ cSha1Checksum Checksum;
+ Checksum.Update((const Byte *)"Notch", 5);
+ Checksum.Finalize(Digest);
+ cSha1Checksum::DigestToJava(Digest, DigestNotch);
+ Checksum.Restart();
+ Checksum.Update((const Byte *)"jeb_", 4);
+ Checksum.Finalize(Digest);
+ cSha1Checksum::DigestToJava(Digest, DigestJeb);
+ Checksum.Restart();
+ Checksum.Update((const Byte *)"simon", 5);
+ Checksum.Finalize(Digest);
+ cSha1Checksum::DigestToJava(Digest, DigestSimon);
+ printf("Notch: \"%s\"\n", DigestNotch.c_str());
+ printf("jeb_: \"%s\"\n", DigestJeb.c_str());
+ printf("simon: \"%s\"\n", DigestSimon.c_str());
+ assert(DigestNotch == "4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48");
+ assert(DigestJeb == "-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1");
+ assert(DigestSimon == "88e16a1019277b15d58faf0541e11910eb756f6");
+ }
+} test;
+*/
+
+
+
+
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// cSha1Checksum:
+
+cSha1Checksum::cSha1Checksum(void) :
+ m_DoesAcceptInput(true)
+{
+ sha1_starts(&m_Sha1);
+}
+
+
+
+
+
+void cSha1Checksum::Update(const Byte * a_Data, size_t a_Length)
+{
+ ASSERT(m_DoesAcceptInput); // Not Finalize()-d yet, or Restart()-ed
+
+ sha1_update(&m_Sha1, a_Data, a_Length);
+}
+
+
+
+
+
+void cSha1Checksum::Finalize(cSha1Checksum::Checksum & a_Output)
+{
+ ASSERT(m_DoesAcceptInput); // Not Finalize()-d yet, or Restart()-ed
+
+ sha1_finish(&m_Sha1, a_Output);
+ m_DoesAcceptInput = false;
+}
+
+
+
+
+
+void cSha1Checksum::DigestToJava(const Checksum & a_Digest, AString & a_Out)
+{
+ Checksum Digest;
+ memcpy(Digest, a_Digest, sizeof(Digest));
+
+ bool IsNegative = (Digest[0] >= 0x80);
+ if (IsNegative)
+ {
+ // Two's complement:
+ bool carry = true; // Add one to the whole number
+ for (int i = 19; i >= 0; i--)
+ {
+ Digest[i] = ~Digest[i];
+ if (carry)
+ {
+ carry = (Digest[i] == 0xff);
+ Digest[i]++;
+ }
+ }
+ }
+ a_Out.clear();
+ a_Out.reserve(40);
+ for (int i = 0; i < 20; i++)
+ {
+ AppendPrintf(a_Out, "%02x", Digest[i]);
+ }
+ while ((a_Out.length() > 0) && (a_Out[0] == '0'))
+ {
+ a_Out.erase(0, 1);
+ }
+ if (IsNegative)
+ {
+ a_Out.insert(0, "-");
+ }
+}
+
+
+
+
+
+
+void cSha1Checksum::Restart(void)
+{
+ sha1_starts(&m_Sha1);
+ m_DoesAcceptInput = true;
+}
+
+
+
+
diff --git a/src/PolarSSL++/Sha1Checksum.h b/src/PolarSSL++/Sha1Checksum.h
new file mode 100644
index 000000000..68fdbcf1b
--- /dev/null
+++ b/src/PolarSSL++/Sha1Checksum.h
@@ -0,0 +1,52 @@
+
+// Sha1Checksum.h
+
+// Declares the cSha1Checksum class representing the SHA-1 checksum calculator
+
+
+
+
+
+#pragma once
+
+#include "polarssl/sha1.h"
+
+
+
+
+
+/** Calculates a SHA1 checksum for data stream */
+class cSha1Checksum
+{
+public:
+ typedef Byte Checksum[20]; // The type used for storing the checksum
+
+ cSha1Checksum(void);
+
+ /** Adds the specified data to the checksum */
+ void Update(const Byte * a_Data, size_t a_Length);
+
+ /** Calculates and returns the final checksum */
+ void Finalize(Checksum & a_Output);
+
+ /** Returns true if the object is accepts more input data, false if Finalize()-d (need to Restart()) */
+ bool DoesAcceptInput(void) const { return m_DoesAcceptInput; }
+
+ /** Converts a raw 160-bit SHA1 digest into a Java Hex representation
+ According to http://wiki.vg/wiki/index.php?title=Protocol_Encryption&oldid=2802
+ */
+ static void DigestToJava(const Checksum & a_Digest, AString & a_JavaOut);
+
+ /** Clears the current context and start a new checksum calculation */
+ void Restart(void);
+
+protected:
+ /** True if the object is accepts more input data, false if Finalize()-d (need to Restart()) */
+ bool m_DoesAcceptInput;
+
+ sha1_context m_Sha1;
+} ;
+
+
+
+
diff --git a/src/Protocol/Protocol132.cpp b/src/Protocol/Protocol132.cpp
index acfa5e811..f4717f592 100644
--- a/src/Protocol/Protocol132.cpp
+++ b/src/Protocol/Protocol132.cpp
@@ -18,19 +18,7 @@
#include "../WorldStorage/FastNBT.h"
#include "../WorldStorage/EnchantmentSerializer.h"
#include "../StringCompression.h"
-
-#ifdef _MSC_VER
- #pragma warning(push)
- #pragma warning(disable:4127)
- #pragma warning(disable:4244)
- #pragma warning(disable:4231)
- #pragma warning(disable:4189)
- #pragma warning(disable:4702)
-#endif
-
-#ifdef _MSC_VER
- #pragma warning(pop)
-#endif
+#include "PolarSSL++/Sha1Checksum.h"
@@ -876,7 +864,7 @@ void cProtocol132::StartEncryption(const Byte * a_Key)
m_IsEncrypted = true;
// Prepare the m_AuthServerID:
- cSHA1Checksum Checksum;
+ cSha1Checksum Checksum;
cServer * Server = cRoot::Get()->GetServer();
AString ServerID = Server->GetServerID();
Checksum.Update((const Byte *)ServerID.c_str(), ServerID.length());
@@ -884,7 +872,7 @@ void cProtocol132::StartEncryption(const Byte * a_Key)
Checksum.Update((const Byte *)Server->GetPublicKeyDER().data(), Server->GetPublicKeyDER().size());
Byte Digest[20];
Checksum.Finalize(Digest);
- cSHA1Checksum::DigestToJava(Digest, m_AuthServerID);
+ cSha1Checksum::DigestToJava(Digest, m_AuthServerID);
}
diff --git a/src/Protocol/Protocol132.h b/src/Protocol/Protocol132.h
index b280c8a41..32bc7d581 100644
--- a/src/Protocol/Protocol132.h
+++ b/src/Protocol/Protocol132.h
@@ -24,7 +24,8 @@
#pragma warning(pop)
#endif
-#include "../Crypto.h"
+#include "PolarSSL++/AesCfb128Decryptor.h"
+#include "PolarSSL++/AesCfb128Encryptor.h"
@@ -79,8 +80,8 @@ public:
protected:
bool m_IsEncrypted;
- cAESCFBDecryptor m_Decryptor;
- cAESCFBEncryptor m_Encryptor;
+ cAesCfb128Decryptor m_Decryptor;
+ cAesCfb128Encryptor m_Encryptor;
AString m_DataToSend;
diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp
index 001b8c219..a6d566625 100644
--- a/src/Protocol/Protocol17x.cpp
+++ b/src/Protocol/Protocol17x.cpp
@@ -33,6 +33,7 @@ Implements the 1.7.x protocol classes:
#include "../CompositeChat.h"
#include "../Entities/ArrowEntity.h"
#include "../Entities/FireworkEntity.h"
+#include "PolarSSL++/Sha1Checksum.h"
@@ -2293,7 +2294,7 @@ void cProtocol172::StartEncryption(const Byte * a_Key)
m_IsEncrypted = true;
// Prepare the m_AuthServerID:
- cSHA1Checksum Checksum;
+ cSha1Checksum Checksum;
cServer * Server = cRoot::Get()->GetServer();
const AString & ServerID = Server->GetServerID();
Checksum.Update((const Byte *)ServerID.c_str(), ServerID.length());
@@ -2301,7 +2302,7 @@ void cProtocol172::StartEncryption(const Byte * a_Key)
Checksum.Update((const Byte *)Server->GetPublicKeyDER().data(), Server->GetPublicKeyDER().size());
Byte Digest[20];
Checksum.Finalize(Digest);
- cSHA1Checksum::DigestToJava(Digest, m_AuthServerID);
+ cSha1Checksum::DigestToJava(Digest, m_AuthServerID);
}
diff --git a/src/Protocol/Protocol17x.h b/src/Protocol/Protocol17x.h
index 6a3e81eff..3f9c93357 100644
--- a/src/Protocol/Protocol17x.h
+++ b/src/Protocol/Protocol17x.h
@@ -30,7 +30,8 @@ Declares the 1.7.x protocol classes:
#pragma warning(pop)
#endif
-#include "../Crypto.h"
+#include "PolarSSL++/AesCfb128Decryptor.h"
+#include "PolarSSL++/AesCfb128Encryptor.h"
@@ -236,8 +237,8 @@ protected:
bool m_IsEncrypted;
- cAESCFBDecryptor m_Decryptor;
- cAESCFBEncryptor m_Encryptor;
+ cAesCfb128Decryptor m_Decryptor;
+ cAesCfb128Decryptor m_Encryptor;
/** The logfile where the comm is logged, when g_ShouldLogComm is true */
cFile m_CommLogFile;
--
cgit v1.2.3
From c045bb3f4ccea1c357a726d73cd75d699cfe901c Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 17:45:20 +0200
Subject: Removed unneeded #includes.
---
src/Protocol/Authenticator.cpp | 6 ------
1 file changed, 6 deletions(-)
diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp
index f7008a5c4..8100b6395 100644
--- a/src/Protocol/Authenticator.cpp
+++ b/src/Protocol/Authenticator.cpp
@@ -10,12 +10,6 @@
#include "inifile/iniFile.h"
#include "json/json.h"
-#include "polarssl/config.h"
-#include "polarssl/net.h"
-#include "polarssl/ssl.h"
-#include "polarssl/ctr_drbg.h"
-#include "polarssl/error.h"
-
#include "PolarSSL++/BlockingSslClientSocket.h"
#include
--
cgit v1.2.3
From 1dbdb8ed912ff235538b9b2dc75575cadc3a5566 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Tue, 29 Apr 2014 23:10:50 +0200
Subject: Delayed sending the KeepAlive packet for 3 seconds after login.
This should alleviate #889.
---
src/ClientHandle.cpp | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index f3588c253..2362abe1e 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -336,6 +336,11 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID)
// Send scoreboard data
World->GetScoreBoard().SendTo(*this);
+
+ // Delay the first ping until the client "settles down"
+ // This should fix #889, "BadCast exception, cannot convert bit to fm" error in client
+ cTimer t1;
+ m_LastPingTime = t1.GetNowTime() + 3000; // Send the first KeepAlive packet in 3 seconds
cRoot::Get()->GetPluginManager()->CallHookPlayerSpawned(*m_Player);
}
--
cgit v1.2.3
From 58929a994830329120c68bf43cf6fcb8a90be960 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Wed, 30 Apr 2014 17:06:31 +0200
Subject: Removed the unused cBlockingTCPLink class.
---
src/OSSupport/BlockingTCPLink.cpp | 142 --------------------------------------
src/OSSupport/BlockingTCPLink.h | 28 --------
src/Protocol/Authenticator.cpp | 1 -
3 files changed, 171 deletions(-)
delete mode 100644 src/OSSupport/BlockingTCPLink.cpp
delete mode 100644 src/OSSupport/BlockingTCPLink.h
diff --git a/src/OSSupport/BlockingTCPLink.cpp b/src/OSSupport/BlockingTCPLink.cpp
deleted file mode 100644
index 07f48b955..000000000
--- a/src/OSSupport/BlockingTCPLink.cpp
+++ /dev/null
@@ -1,142 +0,0 @@
-
-#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
-
-#include "BlockingTCPLink.h"
-#include "Errors.h"
-
-
-
-
-cBlockingTCPLink::cBlockingTCPLink(void)
-{
-}
-
-
-
-
-
-cBlockingTCPLink::~cBlockingTCPLink()
-{
- CloseSocket();
-}
-
-
-
-
-
-void cBlockingTCPLink::CloseSocket()
-{
- if (!m_Socket.IsValid())
- {
- m_Socket.CloseSocket();
- }
-}
-
-
-
-
-
-bool cBlockingTCPLink::Connect(const char * iAddress, unsigned int iPort)
-{
- ASSERT(!m_Socket.IsValid());
- if (m_Socket.IsValid())
- {
- LOGWARN("WARNING: cTCPLink Connect() called while still connected.");
- m_Socket.CloseSocket();
- }
-
- struct hostent *hp;
- unsigned int addr;
- struct sockaddr_in server;
-
- m_Socket = socket(AF_INET, SOCK_STREAM, 0);
- if (!m_Socket.IsValid())
- {
- LOGERROR("cTCPLink: Cannot create a socket");
- return false;
- }
-
- addr = inet_addr(iAddress);
- hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
- if (hp == NULL)
- {
- //LOGWARN("cTCPLink: gethostbyaddr returned NULL");
- hp = gethostbyname(iAddress);
- if (hp == NULL)
- {
- LOGWARN("cTCPLink: Could not resolve %s", iAddress);
- CloseSocket();
- return false;
- }
- }
-
- memcpy(&server.sin_addr.s_addr,hp->h_addr, hp->h_length);
- server.sin_family = AF_INET;
- server.sin_port = htons( (unsigned short)iPort);
- if (connect(m_Socket, (struct sockaddr *)&server, sizeof(server)))
- {
- LOGWARN("cTCPLink: Connection to \"%s:%d\" failed (%s)", iAddress, iPort,GetOSErrorString( cSocket::GetLastError() ).c_str() );
- CloseSocket();
- return false;
- }
-
- return true;
-}
-
-
-
-
-
-int cBlockingTCPLink::Send(char * a_Data, unsigned int a_Size, int a_Flags /* = 0 */ )
-{
- UNUSED(a_Flags);
-
- ASSERT(m_Socket.IsValid());
- if (!m_Socket.IsValid())
- {
- LOGERROR("cBlockingTCPLink: Trying to send data without a valid connection!");
- return -1;
- }
- return m_Socket.Send(a_Data, a_Size);
-}
-
-
-
-
-
-int cBlockingTCPLink::SendMessage( const char* a_Message, int a_Flags /* = 0 */ )
-{
- UNUSED(a_Flags);
-
- ASSERT(m_Socket.IsValid());
- if (!m_Socket.IsValid())
- {
- LOGWARN("cBlockingTCPLink: Trying to send message without a valid connection!");
- return -1;
- }
- return m_Socket.Send(a_Message, strlen(a_Message));
-}
-
-
-
-
-
-void cBlockingTCPLink::ReceiveData(AString & oData)
-{
- ASSERT(m_Socket.IsValid());
- if (!m_Socket.IsValid())
- {
- return;
- }
-
- int Received = 0;
- char Buffer[256];
- while ((Received = recv(m_Socket, Buffer, sizeof(Buffer), 0)) > 0)
- {
- oData.append(Buffer, Received);
- }
-}
-
-
-
-
diff --git a/src/OSSupport/BlockingTCPLink.h b/src/OSSupport/BlockingTCPLink.h
deleted file mode 100644
index cb5f9e3f4..000000000
--- a/src/OSSupport/BlockingTCPLink.h
+++ /dev/null
@@ -1,28 +0,0 @@
-
-#pragma once
-
-#include "Socket.h"
-
-
-
-
-
-class cBlockingTCPLink // tolua_export
-{ // tolua_export
-public: // tolua_export
- cBlockingTCPLink(void); // tolua_export
- ~cBlockingTCPLink(); // tolua_export
-
- bool Connect( const char* a_Address, unsigned int a_Port ); // tolua_export
- int Send( char* a_Data, unsigned int a_Size, int a_Flags = 0 ); // tolua_export
- int SendMessage( const char* a_Message, int a_Flags = 0 ); // tolua_export
- void CloseSocket(); // tolua_export
- void ReceiveData(AString & oData); // tolua_export
-protected:
-
- cSocket m_Socket;
-}; // tolua_export
-
-
-
-
diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp
index 8100b6395..41d614e58 100644
--- a/src/Protocol/Authenticator.cpp
+++ b/src/Protocol/Authenticator.cpp
@@ -2,7 +2,6 @@
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
-#include "../OSSupport/BlockingTCPLink.h"
#include "../Root.h"
#include "../Server.h"
#include "../ClientHandle.h"
--
cgit v1.2.3
From ae2d18daeedafea47a775a3f319811d00bed260c Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Wed, 30 Apr 2014 17:13:56 +0200
Subject: Ladders set as transparent.
---
src/BlockInfo.cpp | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp
index 6fb5aa5b3..def98fdf5 100644
--- a/src/BlockInfo.cpp
+++ b/src/BlockInfo.cpp
@@ -129,6 +129,7 @@ void cBlockInfo::Initialize(void)
ms_Info[E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE].m_Transparent = true;
ms_Info[E_BLOCK_ICE ].m_Transparent = true;
ms_Info[E_BLOCK_IRON_DOOR ].m_Transparent = true;
+ ms_Info[E_BLOCK_LADDER ].m_Transparent = true;
ms_Info[E_BLOCK_LAVA ].m_Transparent = true;
ms_Info[E_BLOCK_LEAVES ].m_Transparent = true;
ms_Info[E_BLOCK_LEVER ].m_Transparent = true;
--
cgit v1.2.3
From f2b579077649d5f40e0e60b53e60fe3b4804dada Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Wed, 30 Apr 2014 17:36:51 +0200
Subject: Fixed a warning when an empty item is being created.
---
src/Item.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Item.h b/src/Item.h
index 00316c188..641c681db 100644
--- a/src/Item.h
+++ b/src/Item.h
@@ -64,7 +64,7 @@ public:
{
if (!IsValidItem(m_ItemType))
{
- if (m_ItemType != E_BLOCK_AIR)
+ if ((m_ItemType != E_BLOCK_AIR) && (m_ItemType != E_ITEM_EMPTY))
{
LOGWARNING("%s: creating an invalid item type (%d), resetting to empty.", __FUNCTION__, a_ItemType);
}
--
cgit v1.2.3
From ab2dfb44faf94fcae4b9ca2af13aa14035e96a97 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Wed, 30 Apr 2014 17:37:25 +0200
Subject: If webadmin.ini doesn't exist, example one is written immediately.
---
src/WebAdmin.cpp | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/WebAdmin.cpp b/src/WebAdmin.cpp
index 737705d7c..08e164d78 100644
--- a/src/WebAdmin.cpp
+++ b/src/WebAdmin.cpp
@@ -89,6 +89,7 @@ bool cWebAdmin::Init(void)
m_IniFile.AddHeaderComment(" Password format: Password=*password*; for example:");
m_IniFile.AddHeaderComment(" [User:admin]");
m_IniFile.AddHeaderComment(" Password=admin");
+ m_IniFile.WriteFile("webadmin.ini");
}
if (!m_IniFile.GetValueSetB("WebAdmin", "Enabled", true))
--
cgit v1.2.3
From e6786074d58d81a230a6d5d01a5d89fa2f5ab16e Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 00:27:42 +0200
Subject: Added cBufferedSslContext implementation.
---
src/ByteBuffer.h | 40 +++++++++++++++++------------------
src/PolarSSL++/BufferedSslContext.cpp | 31 +++++++++++++++++++++++++++
2 files changed, 51 insertions(+), 20 deletions(-)
diff --git a/src/ByteBuffer.h b/src/ByteBuffer.h
index 7656a5b13..c5ff05922 100644
--- a/src/ByteBuffer.h
+++ b/src/ByteBuffer.h
@@ -30,25 +30,25 @@ public:
cByteBuffer(size_t a_BufferSize);
~cByteBuffer();
- /// Writes the bytes specified to the ringbuffer. Returns true if successful, false if not
+ /** Writes the bytes specified to the ringbuffer. Returns true if successful, false if not */
bool Write(const void * a_Bytes, size_t a_Count);
- /// Returns the number of bytes that can be successfully written to the ringbuffer
+ /** Returns the number of bytes that can be successfully written to the ringbuffer */
size_t GetFreeSpace(void) const;
- /// Returns the number of bytes that are currently in the ringbuffer. Note GetReadableBytes()
+ /** Returns the number of bytes that are currently in the ringbuffer. Note GetReadableBytes() */
size_t GetUsedSpace(void) const;
- /// Returns the number of bytes that are currently available for reading (may be less than UsedSpace due to some data having been read already)
+ /** Returns the number of bytes that are currently available for reading (may be less than UsedSpace due to some data having been read already) */
size_t GetReadableSpace(void) const;
- /// Returns the current data start index. For debugging purposes.
+ /** Returns the current data start index. For debugging purposes. */
size_t GetDataStart(void) const { return m_DataStart; }
- /// Returns true if the specified amount of bytes are available for reading
+ /** Returns true if the specified amount of bytes are available for reading */
bool CanReadBytes(size_t a_Count) const;
- /// Returns true if the specified amount of bytes are available for writing
+ /** Returns true if the specified amount of bytes are available for writing */
bool CanWriteBytes(size_t a_Count) const;
// Read the specified datatype and advance the read pointer; return true if successfully read:
@@ -65,7 +65,7 @@ public:
bool ReadVarUTF8String (AString & a_Value); // string length as VarInt, then string as UTF-8
bool ReadLEInt (int & a_Value);
- /// Reads VarInt, assigns it to anything that can be assigned from an UInt32 (unsigned short, char, Byte, double, ...)
+ /** Reads VarInt, assigns it to anything that can be assigned from an UInt32 (unsigned short, char, Byte, double, ...) */
template bool ReadVarInt(T & a_Value)
{
UInt32 v;
@@ -91,37 +91,37 @@ public:
bool WriteVarUTF8String (const AString & a_Value); // string length as VarInt, then string as UTF-8
bool WriteLEInt (int a_Value);
- /// Reads a_Count bytes into a_Buffer; returns true if successful
+ /** Reads a_Count bytes into a_Buffer; returns true if successful */
bool ReadBuf(void * a_Buffer, size_t a_Count);
- /// Writes a_Count bytes into a_Buffer; returns true if successful
+ /** Writes a_Count bytes into a_Buffer; returns true if successful */
bool WriteBuf(const void * a_Buffer, size_t a_Count);
- /// Reads a_Count bytes into a_String; returns true if successful
+ /** Reads a_Count bytes into a_String; returns true if successful */
bool ReadString(AString & a_String, size_t a_Count);
- /// Reads 2 * a_NumChars bytes and interprets it as a UTF16-BE string, converting it into UTF8 string a_String
+ /** Reads 2 * a_NumChars bytes and interprets it as a UTF16-BE string, converting it into UTF8 string a_String */
bool ReadUTF16String(AString & a_String, int a_NumChars);
- /// Skips reading by a_Count bytes; returns false if not enough bytes in the ringbuffer
+ /** Skips reading by a_Count bytes; returns false if not enough bytes in the ringbuffer */
bool SkipRead(size_t a_Count);
- /// Reads all available data into a_Data
+ /** Reads all available data into a_Data */
void ReadAll(AString & a_Data);
- /// Reads the specified number of bytes and writes it into the destinatio bytebuffer. Returns true on success.
+ /** Reads the specified number of bytes and writes it into the destinatio bytebuffer. Returns true on success. */
bool ReadToByteBuffer(cByteBuffer & a_Dst, size_t a_NumBytes);
- /// Removes the bytes that have been read from the ringbuffer
+ /** Removes the bytes that have been read from the ringbuffer */
void CommitRead(void);
- /// Restarts next reading operation at the start of the ringbuffer
+ /** Restarts next reading operation at the start of the ringbuffer */
void ResetRead(void);
- /// Re-reads the data that has been read since the last commit to the current readpos. Used by ProtoProxy to duplicate communication
+ /** Re-reads the data that has been read since the last commit to the current readpos. Used by ProtoProxy to duplicate communication */
void ReadAgain(AString & a_Out);
- /// Checks if the internal state is valid (read and write positions in the correct bounds) using ASSERTs
+ /** Checks if the internal state is valid (read and write positions in the correct bounds) using ASSERTs */
void CheckValid(void) const;
protected:
@@ -136,7 +136,7 @@ protected:
size_t m_WritePos; // Where the data ends in the ringbuffer
size_t m_ReadPos; // Where the next read will start in the ringbuffer
- /// Advances the m_ReadPos by a_Count bytes
+ /** Advances the m_ReadPos by a_Count bytes */
void AdvanceReadPos(size_t a_Count);
} ;
diff --git a/src/PolarSSL++/BufferedSslContext.cpp b/src/PolarSSL++/BufferedSslContext.cpp
index 885b30c68..2455d5781 100644
--- a/src/PolarSSL++/BufferedSslContext.cpp
+++ b/src/PolarSSL++/BufferedSslContext.cpp
@@ -20,6 +20,37 @@ cBufferedSslContext::cBufferedSslContext(size_t a_BufferSize):
+size_t cBufferedSslContext::WriteIncoming(const void * a_Data, size_t a_NumBytes)
+{
+ size_t NumBytes = std::min(m_IncomingData.GetFreeSpace(), a_NumBytes);
+ if (NumBytes > 0)
+ {
+ m_IncomingData.Write(a_Data, NumBytes);
+ return a_NumBytes - NumBytes;
+ }
+ return 0;
+}
+
+
+
+
+
+size_t cBufferedSslContext::ReadOutgoing(void * a_Data, size_t a_DataMaxSize)
+{
+ size_t NumBytes = std::min(m_OutgoingData.GetReadableSpace(), a_DataMaxSize);
+ if (NumBytes > 0)
+ {
+ m_OutgoingData.ReadBuf(a_Data, NumBytes);
+ m_OutgoingData.CommitRead();
+ return a_DataMaxSize - NumBytes;
+ }
+ return 0;
+}
+
+
+
+
+
int cBufferedSslContext::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes)
{
// Called when PolarSSL wants to read encrypted data from the SSL peer
--
cgit v1.2.3
From 47feb91e57f83c81722188ec3025c3109758dd33 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 00:28:27 +0200
Subject: cSslContext supports setting own cert / privkey.
---
src/PolarSSL++/PublicKey.cpp | 82 ++++++++++++++++++++++++++++++++++++++++--
src/PolarSSL++/PublicKey.h | 32 +++++++++++++++--
src/PolarSSL++/RsaPrivateKey.h | 8 +++++
src/PolarSSL++/SslContext.cpp | 50 +++++++++++++++++++++++++-
src/PolarSSL++/SslContext.h | 22 +++++++++++-
5 files changed, 187 insertions(+), 7 deletions(-)
diff --git a/src/PolarSSL++/PublicKey.cpp b/src/PolarSSL++/PublicKey.cpp
index 49794a0c8..dae026082 100644
--- a/src/PolarSSL++/PublicKey.cpp
+++ b/src/PolarSSL++/PublicKey.cpp
@@ -10,15 +10,44 @@
-cPublicKey::cPublicKey(const AString & a_PublicKeyDER)
+cPublicKey::cPublicKey(void)
{
pk_init(&m_Pk);
- if (pk_parse_public_key(&m_Pk, (const Byte *)a_PublicKeyDER.data(), a_PublicKeyDER.size()) != 0)
+ m_CtrDrbg.Initialize("rsa_pubkey", 10);
+}
+
+
+
+
+
+cPublicKey::cPublicKey(const AString & a_PublicKeyData)
+{
+ pk_init(&m_Pk);
+ m_CtrDrbg.Initialize("rsa_pubkey", 10);
+ int res = ParsePublic(a_PublicKeyData.data(), a_PublicKeyData.size());
+ if (res != 0)
{
+ LOGWARNING("Failed to parse public key: -0x%x", res);
+ ASSERT(!"Cannot parse PubKey");
+ return;
+ }
+}
+
+
+
+
+
+cPublicKey::cPublicKey(const AString & a_PrivateKeyData, const AString & a_Password)
+{
+ pk_init(&m_Pk);
+ m_CtrDrbg.Initialize("rsa_privkey", 11);
+ int res = ParsePrivate(a_PrivateKeyData.data(), a_PrivateKeyData.size(), a_Password);
+ if (res != 0)
+ {
+ LOGWARNING("Failed to parse private key: -0x%x", res);
ASSERT(!"Cannot parse PubKey");
return;
}
- m_CtrDrbg.Initialize("rsa_pubkey", 10);
}
@@ -36,6 +65,8 @@ cPublicKey::~cPublicKey()
int cPublicKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength)
{
+ ASSERT(IsValid());
+
size_t DecryptedLen = a_DecryptedMaxLength;
int res = pk_decrypt(&m_Pk,
a_EncryptedData, a_EncryptedLength,
@@ -55,6 +86,8 @@ int cPublicKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength,
int cPublicKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
{
+ ASSERT(IsValid());
+
size_t EncryptedLength = a_EncryptedMaxLength;
int res = pk_encrypt(&m_Pk,
a_PlainData, a_PlainLength, a_EncryptedData, &EncryptedLength, a_EncryptedMaxLength,
@@ -71,3 +104,46 @@ int cPublicKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a
+
+int cPublicKey::ParsePublic(const void * a_Data, size_t a_NumBytes)
+{
+ ASSERT(!IsValid()); // Cannot parse a second key
+
+ return pk_parse_public_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes);
+}
+
+
+
+
+
+
+int cPublicKey::ParsePrivate(const void * a_Data, size_t a_NumBytes, const AString & a_Password)
+{
+ ASSERT(!IsValid()); // Cannot parse a second key
+
+ if (a_Password.empty())
+ {
+ return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, NULL, 0);
+ }
+ else
+ {
+ return pk_parse_key(
+ &m_Pk,
+ (const unsigned char *)a_Data, a_NumBytes,
+ (const unsigned char *)a_Password.c_str(), a_Password.size()
+ );
+ }
+}
+
+
+
+
+
+bool cPublicKey::IsValid(void) const
+{
+ return (pk_get_type(&m_Pk) != POLARSSL_PK_NONE);
+}
+
+
+
+
diff --git a/src/PolarSSL++/PublicKey.h b/src/PolarSSL++/PublicKey.h
index 5a0a57147..df52a4143 100644
--- a/src/PolarSSL++/PublicKey.h
+++ b/src/PolarSSL++/PublicKey.h
@@ -18,9 +18,18 @@
class cPublicKey
{
+ friend class cSslContext;
+
public:
- /** Constructs the public key out of the DER-encoded pubkey data */
- cPublicKey(const AString & a_PublicKeyDER);
+ /** Constructs an empty key instance. Before use, it needs to be filled by ParsePublic() or ParsePrivate() */
+ cPublicKey(void);
+
+ /** Constructs the public key out of the DER- or PEM-encoded pubkey data */
+ cPublicKey(const AString & a_PublicKeyData);
+
+ /** Constructs the private key out of the DER- or PEM-encoded privkey data, with the specified password.
+ If a_Password is empty, no password is assumed. */
+ cPublicKey(const AString & a_PrivateKeyData, const AString & a_Password);
~cPublicKey();
@@ -33,6 +42,20 @@ public:
Both a_EncryptedData and a_DecryptedData must be at least bytes large.
Returns the number of bytes decrypted, or negative number for error. */
int Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength);
+
+ /** Parses the specified data into a public key representation.
+ The key can be DER- or PEM-encoded.
+ Returns 0 on success, PolarSSL error code on failure. */
+ int ParsePublic(const void * a_Data, size_t a_NumBytes);
+
+ /** Parses the specified data into a private key representation.
+ If a_Password is empty, no password is assumed.
+ The key can be DER- or PEM-encoded.
+ Returns 0 on success, PolarSSL error code on failure. */
+ int ParsePrivate(const void * a_Data, size_t a_NumBytes, const AString & a_Password);
+
+ /** Returns true if the contained key is valid. */
+ bool IsValid(void) const;
protected:
/** The public key PolarSSL representation */
@@ -40,8 +63,13 @@ protected:
/** The random generator used in encryption and decryption */
cCtrDrbgContext m_CtrDrbg;
+
+
+ /** Returns the internal context ptr. Only use in PolarSSL API calls. */
+ pk_context * GetInternal(void) { return &m_Pk; }
} ;
+typedef SharedPtr cPublicKeyPtr;
diff --git a/src/PolarSSL++/RsaPrivateKey.h b/src/PolarSSL++/RsaPrivateKey.h
index ffacde11b..4d03f27df 100644
--- a/src/PolarSSL++/RsaPrivateKey.h
+++ b/src/PolarSSL++/RsaPrivateKey.h
@@ -19,6 +19,8 @@
/** Encapsulates an RSA private key used in PKI cryptography */
class cRsaPrivateKey
{
+ friend class cSslContext;
+
public:
/** Creates a new empty object, the key is not assigned */
cRsaPrivateKey(void);
@@ -51,8 +53,14 @@ protected:
/** The random generator used for generating the key and encryption / decryption */
cCtrDrbgContext m_CtrDrbg;
+
+
+ /** Returns the internal context ptr. Only use in PolarSSL API calls. */
+ rsa_context * GetInternal(void) { return &m_Rsa; }
} ;
+typedef SharedPtr cRsaPrivateKeyPtr;
+
diff --git a/src/PolarSSL++/SslContext.cpp b/src/PolarSSL++/SslContext.cpp
index 1994cf844..3d2b8cef7 100644
--- a/src/PolarSSL++/SslContext.cpp
+++ b/src/PolarSSL++/SslContext.cpp
@@ -40,7 +40,7 @@ int cSslContext::Initialize(bool a_IsClient, const SharedPtr &
if (m_IsValid)
{
LOGWARNING("SSL: Double initialization is not supported.");
- return POLARSSL_ERR_SSL_MALLOC_FAILED; // There is no return value well-suited for this, reuse this one.
+ return POLARSSL_ERR_SSL_BAD_INPUT_DATA; // There is no return value well-suited for this, reuse this one.
}
// Set the CtrDrbg context, create a new one if needed:
@@ -80,8 +80,56 @@ int cSslContext::Initialize(bool a_IsClient, const SharedPtr &
+void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cRsaPrivateKeyPtr & a_OwnCertPrivKey)
+{
+ ASSERT(m_IsValid); // Call Initialize() first
+
+ // Check that both the cert and the key is valid:
+ if ((a_OwnCert.get() == NULL) || (a_OwnCertPrivKey.get() == NULL))
+ {
+ LOGWARNING("SSL: Own certificate is not valid, skipping the set.");
+ return;
+ }
+
+ // Make sure we have the cert stored for later, PolarSSL only uses the cert later on
+ m_OwnCert = a_OwnCert;
+ m_OwnCertPrivKey = a_OwnCertPrivKey;
+
+ // Set into the context:
+ ssl_set_own_cert_rsa(&m_Ssl, m_OwnCert->GetInternal(), m_OwnCertPrivKey->GetInternal());
+}
+
+
+
+
+
+void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cPublicKeyPtr & a_OwnCertPrivKey)
+{
+ ASSERT(m_IsValid); // Call Initialize() first
+
+ // Check that both the cert and the key is valid:
+ if ((a_OwnCert.get() == NULL) || (a_OwnCertPrivKey.get() == NULL))
+ {
+ LOGWARNING("SSL: Own certificate is not valid, skipping the set.");
+ return;
+ }
+
+ // Make sure we have the cert stored for later, PolarSSL only uses the cert later on
+ m_OwnCert = a_OwnCert;
+ m_OwnCertPrivKey2 = a_OwnCertPrivKey;
+
+ // Set into the context:
+ ssl_set_own_cert(&m_Ssl, m_OwnCert->GetInternal(), m_OwnCertPrivKey2->GetInternal());
+}
+
+
+
+
+
void cSslContext::SetCACerts(const cX509CertPtr & a_CACert, const AString & a_ExpectedPeerName)
{
+ ASSERT(m_IsValid); // Call Initialize() first
+
// Store the data in our internal buffers, to avoid losing the pointers later on
// PolarSSL will need these after this call returns, and the caller may move / delete the data before that:
m_ExpectedPeerName = a_ExpectedPeerName;
diff --git a/src/PolarSSL++/SslContext.h b/src/PolarSSL++/SslContext.h
index 85add5f8b..273939b9f 100644
--- a/src/PolarSSL++/SslContext.h
+++ b/src/PolarSSL++/SslContext.h
@@ -11,6 +11,8 @@
#include "polarssl/ssl.h"
#include "../ByteBuffer.h"
+#include "PublicKey.h"
+#include "RsaPrivateKey.h"
#include "X509Cert.h"
@@ -47,7 +49,16 @@ public:
/** Returns true if the object has been initialized properly. */
bool IsValid(void) const { return m_IsValid; }
- /** Sets a cert chain as the trusted cert store for this context.
+ /** Sets the certificate to use as our own. Must be used when representing a server, optional when client.
+ Must be called after Initialize(). */
+ void SetOwnCert(const cX509CertPtr & a_OwnCert, const cRsaPrivateKeyPtr & a_OwnCertPrivKey);
+
+ /** Sets the certificate to use as our own. Must be used when representing a server, optional when client.
+ Must be called after Initialize().
+ Despite the class name, a_OwnCertPrivKey is a PRIVATE key. */
+ void SetOwnCert(const cX509CertPtr & a_OwnCert, const cPublicKeyPtr & a_OwnCertPrivKey);
+
+ /** Sets a cert chain as the trusted cert store for this context. Must be called after Initialize().
Calling this will switch the context into strict cert verification mode.
a_ExpectedPeerName is the CommonName that we expect the SSL peer to have in its cert,
if it is different, the verification will fail. An empty string will disable the CN check. */
@@ -93,6 +104,15 @@ protected:
/** The SSL context that PolarSSL uses. */
ssl_context m_Ssl;
+ /** The certificate that we present to the peer. */
+ cX509CertPtr m_OwnCert;
+
+ /** Private key for m_OwnCert, if initialized from a cRsaPrivateKey */
+ cRsaPrivateKeyPtr m_OwnCertPrivKey;
+
+ /** Private key for m_OwnCert, if initialized from a cPublicKey. Despite the class name, this is a PRIVATE key. */
+ cPublicKeyPtr m_OwnCertPrivKey2;
+
/** True if the SSL handshake has been completed. */
bool m_HasHandshaken;
--
cgit v1.2.3
From e2bf3783e8c8f7855532e04203bb1b46b976cfee Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 11:32:25 +0200
Subject: Fixed BufferedSslContext's buffer reading and writing.
---
src/PolarSSL++/BufferedSslContext.cpp | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/PolarSSL++/BufferedSslContext.cpp b/src/PolarSSL++/BufferedSslContext.cpp
index 2455d5781..9f7caeb8a 100644
--- a/src/PolarSSL++/BufferedSslContext.cpp
+++ b/src/PolarSSL++/BufferedSslContext.cpp
@@ -26,7 +26,7 @@ size_t cBufferedSslContext::WriteIncoming(const void * a_Data, size_t a_NumBytes
if (NumBytes > 0)
{
m_IncomingData.Write(a_Data, NumBytes);
- return a_NumBytes - NumBytes;
+ return NumBytes;
}
return 0;
}
@@ -42,7 +42,7 @@ size_t cBufferedSslContext::ReadOutgoing(void * a_Data, size_t a_DataMaxSize)
{
m_OutgoingData.ReadBuf(a_Data, NumBytes);
m_OutgoingData.CommitRead();
- return a_DataMaxSize - NumBytes;
+ return NumBytes;
}
return 0;
}
--
cgit v1.2.3
From e1b6a169457b267c3e11bbdb9e58e9ab7b3f0136 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 11:33:29 +0200
Subject: Added a (disabled) test of low-security ciphersuites.
Enabling this allows the connection to be sniffed and decoded using Wireshark, when given the SSL private key.
---
src/PolarSSL++/SslContext.cpp | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/src/PolarSSL++/SslContext.cpp b/src/PolarSSL++/SslContext.cpp
index 3d2b8cef7..df0219610 100644
--- a/src/PolarSSL++/SslContext.cpp
+++ b/src/PolarSSL++/SslContext.cpp
@@ -70,6 +70,18 @@ int cSslContext::Initialize(bool a_IsClient, const SharedPtr &
ssl_set_dbg(&m_Ssl, &SSLDebugMessage, this);
ssl_set_verify(&m_Ssl, &SSLVerifyCert, this);
*/
+
+ /*
+ // Set ciphersuite to the easiest one to decode, so that the connection can be wireshark-decoded:
+ static const int CipherSuites[] =
+ {
+ TLS_RSA_WITH_RC4_128_MD5,
+ TLS_RSA_WITH_RC4_128_SHA,
+ TLS_RSA_WITH_AES_128_CBC_SHA,
+ 0, // Must be 0-terminated!
+ };
+ ssl_set_ciphersuites(&m_Ssl, CipherSuites);
+ */
#endif
m_IsValid = true;
--
cgit v1.2.3
From a04cb6d146dfb8f04b0a8943c1e185fc25bf2829 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 11:34:15 +0200
Subject: Fixed HTTP message parsing, prepared for SSL.
---
src/HTTPServer/HTTPConnection.cpp | 5 +++--
src/HTTPServer/HTTPMessage.cpp | 2 +-
2 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/src/HTTPServer/HTTPConnection.cpp b/src/HTTPServer/HTTPConnection.cpp
index da4df0e34..8e95eff2d 100644
--- a/src/HTTPServer/HTTPConnection.cpp
+++ b/src/HTTPServer/HTTPConnection.cpp
@@ -26,6 +26,7 @@ cHTTPConnection::cHTTPConnection(cHTTPServer & a_HTTPServer) :
cHTTPConnection::~cHTTPConnection()
{
+ // LOGD("HTTP: Connection deleting: %p", this);
delete m_CurrentRequest;
}
@@ -183,11 +184,11 @@ void cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
// Process the rest of the incoming data into the request body:
if (a_Size > BytesConsumed)
{
- DataReceived(a_Data + BytesConsumed, a_Size - BytesConsumed);
+ cHTTPConnection::DataReceived(a_Data + BytesConsumed, a_Size - BytesConsumed);
}
else
{
- DataReceived("", 0); // If the request has zero body length, let it be processed right-away
+ cHTTPConnection::DataReceived("", 0); // If the request has zero body length, let it be processed right-away
}
break;
}
diff --git a/src/HTTPServer/HTTPMessage.cpp b/src/HTTPServer/HTTPMessage.cpp
index 4a3611050..44feda469 100644
--- a/src/HTTPServer/HTTPMessage.cpp
+++ b/src/HTTPServer/HTTPMessage.cpp
@@ -201,7 +201,7 @@ size_t cHTTPRequest::ParseRequestLine(const char * a_Data, size_t a_Size)
return AString::npos;
}
// Check that there's HTTP/version at the end
- if (strncmp(a_Data + URLEnd + 1, "HTTP/1.", 7) != 0)
+ if (strncmp(m_IncomingHeaderData.c_str() + URLEnd + 1, "HTTP/1.", 7) != 0)
{
m_IsValid = false;
return AString::npos;
--
cgit v1.2.3
From 272c232efb645c9f7d75556aeb047e13b244c9ed Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 11:48:03 +0200
Subject: Implemented SSL connection for WebAdmin.
Fixes FS-319.
---
MCServer/.gitignore | 4 ++
src/HTTPServer/HTTPServer.cpp | 35 +++++++++++-
src/HTTPServer/HTTPServer.h | 10 ++++
src/HTTPServer/SslHTTPConnection.cpp | 103 +++++++++++++++++++++++++++++++++++
src/HTTPServer/SslHTTPConnection.h | 45 +++++++++++++++
5 files changed, 195 insertions(+), 2 deletions(-)
create mode 100644 src/HTTPServer/SslHTTPConnection.cpp
create mode 100644 src/HTTPServer/SslHTTPConnection.h
diff --git a/MCServer/.gitignore b/MCServer/.gitignore
index 32a634a03..6da9aa7c7 100644
--- a/MCServer/.gitignore
+++ b/MCServer/.gitignore
@@ -30,3 +30,7 @@ motd.txt
*.xml
mcserver_api.lua
+# Ignore the webadmin certs / privkey, so that no-one commits theirs by accident:
+webadmin/httpscert.crt
+webadmin/httpskey.pem
+
diff --git a/src/HTTPServer/HTTPServer.cpp b/src/HTTPServer/HTTPServer.cpp
index eaf8405a3..9e3e0a17b 100644
--- a/src/HTTPServer/HTTPServer.cpp
+++ b/src/HTTPServer/HTTPServer.cpp
@@ -8,6 +8,7 @@
#include "HTTPMessage.h"
#include "HTTPConnection.h"
#include "HTTPFormParser.h"
+#include "SslHTTPConnection.h"
@@ -123,8 +124,30 @@ class cDebugCallbacks :
cHTTPServer::cHTTPServer(void) :
m_ListenThreadIPv4(*this, cSocket::IPv4, "WebServer IPv4"),
m_ListenThreadIPv6(*this, cSocket::IPv6, "WebServer IPv6"),
- m_Callbacks(NULL)
+ m_Callbacks(NULL),
+ m_Cert(new cX509Cert),
+ m_CertPrivKey(new cPublicKey)
{
+ AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt");
+ AString KeyFile = cFile::ReadWholeFile("webadmin/httpskey.pem");
+ if (!CertFile.empty() && !KeyFile.empty())
+ {
+ int res = m_Cert->Parse(CertFile.data(), CertFile.size());
+ if (res == 0)
+ {
+ int res2 = m_CertPrivKey->ParsePrivate(KeyFile.data(), KeyFile.size(), "");
+ if (res2 != 0)
+ {
+ // Reading the private key failed, reset the cert:
+ LOGWARNING("WebAdmin: Cannot read HTTPS certificate private key: -0x%x", -res2);
+ m_Cert.reset();
+ }
+ }
+ else
+ {
+ LOGWARNING("WebAdmin: Cannot read HTTPS certificate: -0x%x", -res);
+ }
+ }
}
@@ -195,7 +218,15 @@ void cHTTPServer::Stop(void)
void cHTTPServer::OnConnectionAccepted(cSocket & a_Socket)
{
- cHTTPConnection * Connection = new cHTTPConnection(*this);
+ cHTTPConnection * Connection;
+ if (m_Cert.get() != NULL)
+ {
+ Connection = new cSslHTTPConnection(*this, m_Cert, m_CertPrivKey);
+ }
+ else
+ {
+ Connection = new cHTTPConnection(*this);
+ }
m_SocketThreads.AddClient(a_Socket, Connection);
cCSLock Lock(m_CSConnections);
m_Connections.push_back(Connection);
diff --git a/src/HTTPServer/HTTPServer.h b/src/HTTPServer/HTTPServer.h
index 8eff7d879..eb91dd5a3 100644
--- a/src/HTTPServer/HTTPServer.h
+++ b/src/HTTPServer/HTTPServer.h
@@ -12,6 +12,9 @@
#include "../OSSupport/ListenThread.h"
#include "../OSSupport/SocketThreads.h"
#include "inifile/iniFile.h"
+#include "PolarSSL++/RsaPrivateKey.h"
+#include "PolarSSL++/PublicKey.h"
+#include "PolarSSL++/X509Cert.h"
@@ -66,6 +69,7 @@ public:
protected:
friend class cHTTPConnection;
+ friend class cSslHTTPConnection;
cListenThread m_ListenThreadIPv4;
cListenThread m_ListenThreadIPv6;
@@ -78,6 +82,12 @@ protected:
/// The callbacks to call for various events
cCallbacks * m_Callbacks;
+ /** The server certificate to use for the SSL connections */
+ cX509CertPtr m_Cert;
+
+ /** The private key for m_Cert. Despite the class name, this is the PRIVATE key. */
+ cPublicKeyPtr m_CertPrivKey;
+
// cListenThread::cCallback overrides:
virtual void OnConnectionAccepted(cSocket & a_Socket) override;
diff --git a/src/HTTPServer/SslHTTPConnection.cpp b/src/HTTPServer/SslHTTPConnection.cpp
new file mode 100644
index 000000000..fff96bb2e
--- /dev/null
+++ b/src/HTTPServer/SslHTTPConnection.cpp
@@ -0,0 +1,103 @@
+
+// SslHTTPConnection.cpp
+
+// Implements the cSslHTTPConnection class representing a HTTP connection made over a SSL link
+
+#include "Globals.h"
+#include "SslHTTPConnection.h"
+#include "HTTPServer.h"
+
+
+
+
+
+cSslHTTPConnection::cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cPublicKeyPtr & a_PrivateKey) :
+ super(a_HTTPServer),
+ m_Ssl(64000),
+ m_Cert(a_Cert),
+ m_PrivateKey(a_PrivateKey)
+{
+ m_Ssl.Initialize(false);
+ m_Ssl.SetOwnCert(a_Cert, a_PrivateKey);
+}
+
+
+
+
+
+void cSslHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
+{
+ // If there is outgoing data in the queue, notify the server that it should write it out:
+ if (!m_OutgoingData.empty())
+ {
+ m_HTTPServer.NotifyConnectionWrite(*this);
+ }
+
+ // Process the received data:
+ const char * Data = a_Data;
+ size_t Size = a_Size;
+ for (;;)
+ {
+ // Try to write as many bytes into Ssl's "incoming" buffer as possible:
+ size_t BytesWritten = 0;
+ if (Size > 0)
+ {
+ BytesWritten = m_Ssl.WriteIncoming(Data, Size);
+ Data += BytesWritten;
+ Size -= BytesWritten;
+ }
+
+ // Try to read as many bytes from SSL's decryption as possible:
+ char Buffer[32000];
+ int NumRead = m_Ssl.ReadPlain(Buffer, sizeof(Buffer));
+ if (NumRead > 0)
+ {
+ super::DataReceived(Buffer, (size_t)NumRead);
+ }
+
+ // If both failed, bail out:
+ if ((BytesWritten == 0) && (NumRead <= 0))
+ {
+ return;
+ }
+ }
+}
+
+
+
+
+
+void cSslHTTPConnection::GetOutgoingData(AString & a_Data)
+{
+ for (;;)
+ {
+ // Write as many bytes from our buffer to SSL's encryption as possible:
+ int NumWritten = 0;
+ if (!m_OutgoingData.empty())
+ {
+ NumWritten = m_Ssl.WritePlain(m_OutgoingData.data(), m_OutgoingData.size());
+ if (NumWritten > 0)
+ {
+ m_OutgoingData.erase(0, (size_t)NumWritten);
+ }
+ }
+
+ // Read as many bytes from SSL's "outgoing" buffer as possible:
+ char Buffer[32000];
+ size_t NumBytes = m_Ssl.ReadOutgoing(Buffer, sizeof(Buffer));
+ if (NumBytes > 0)
+ {
+ a_Data.append(Buffer, NumBytes);
+ }
+
+ // If both failed, bail out:
+ if ((NumWritten <= 0) && (NumBytes == 0))
+ {
+ return;
+ }
+ }
+}
+
+
+
+
diff --git a/src/HTTPServer/SslHTTPConnection.h b/src/HTTPServer/SslHTTPConnection.h
new file mode 100644
index 000000000..2a648e8c8
--- /dev/null
+++ b/src/HTTPServer/SslHTTPConnection.h
@@ -0,0 +1,45 @@
+
+// SslHTTPConnection.h
+
+// Declared the cSslHTTPConnection class representing a HTTP connection made over a SSL link
+
+
+
+
+
+#pragma once
+
+#include "HTTPConnection.h"
+#include "PolarSSL++/BufferedSslContext.h"
+
+
+
+
+
+class cSslHTTPConnection :
+ public cHTTPConnection
+{
+ typedef cHTTPConnection super;
+
+public:
+ /** Creates a new connection on the specified server; sends the specified cert as the server certificate,
+ uses the private key for decryption. a_Private key is, despite the class name, a PRIVATE key for the cert. */
+ cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cPublicKeyPtr & a_PrivateKey);
+
+protected:
+ cBufferedSslContext m_Ssl;
+
+ /** The certificate to send to the client */
+ cX509CertPtr m_Cert;
+
+ /** The private key used for the certificate */
+ cPublicKeyPtr m_PrivateKey;
+
+ // cHTTPConnection overrides:
+ virtual void DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
+ virtual void GetOutgoingData(AString & a_Data) override; // Data can be sent to client
+} ;
+
+
+
+
--
cgit v1.2.3
From cf821bc9a4b156d6ffb8a79502936a1de36bb074 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 11:48:45 +0200
Subject: Added scripts for generating HTTPS cert and key.
---
MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd | 9 +++++++++
MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.sh | 10 ++++++++++
2 files changed, 19 insertions(+)
create mode 100644 MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd
create mode 100644 MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.sh
diff --git a/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd b/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd
new file mode 100644
index 000000000..5257e1bd6
--- /dev/null
+++ b/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd
@@ -0,0 +1,9 @@
+echo This script generates the certificate and private key for the https webadmin
+echo Note that the generated certificate is self-signed, and therefore not trusted by browsers
+echo Note that this script requires openssl to be installed and in PATH
+echo.
+echo When OpenSSL asks you for Common Name, you need to enter the fully qualified domain name of the server, that is, e. g. gallery.xoft.cz
+echo.
+
+openssl req -x509 -newkey rsa:2048 -keyout httpskey.pem -out httpscert.crt -days 3650 -nodes
+pause
\ No newline at end of file
diff --git a/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.sh b/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.sh
new file mode 100644
index 000000000..0c8594f1a
--- /dev/null
+++ b/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.sh
@@ -0,0 +1,10 @@
+#!/bin/bash
+
+echo "This script generates the certificate and private key for the https webadmin"
+echo "Note that the generated certificate is self-signed, and therefore not trusted by browsers"
+echo "Note that this script requires openssl to be installed and in PATH"
+echo ""
+echo "When OpenSSL asks you for Common Name, you need to enter the fully qualified domain name of the server, that is, e. g. gallery.xoft.cz"
+echo ""
+
+openssl req -x509 -newkey rsa:2048 -keyout httpskey.pem -out httpscert.pem -days 3650 -nodes
\ No newline at end of file
--
cgit v1.2.3
From dc2d2ce53c2f751f72217a26d4f68d72f5f0f5f0 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 12:27:07 +0200
Subject: Added a mention to run as admin.
---
MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd | 2 ++
1 file changed, 2 insertions(+)
diff --git a/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd b/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd
index 5257e1bd6..661cc34e8 100644
--- a/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd
+++ b/MCServer/webadmin/GenerateSelfSignedHTTPSCertUsingOpenssl.cmd
@@ -4,6 +4,8 @@ echo Note that this script requires openssl to be installed and in PATH
echo.
echo When OpenSSL asks you for Common Name, you need to enter the fully qualified domain name of the server, that is, e. g. gallery.xoft.cz
echo.
+echo If OpenSSL fails with an error, "WARNING: can't open config file: /usr/local/ssl/openssl.cnf", you need to run this script as an administrator
+echo.
openssl req -x509 -newkey rsa:2048 -keyout httpskey.pem -out httpscert.crt -days 3650 -nodes
pause
\ No newline at end of file
--
cgit v1.2.3
From 60850fe3e8da936d5b24460f33a1bf8f4d321ace Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 15:08:15 +0200
Subject: Fixed crashes in the SSL HTTP connection.
---
src/ClientHandle.cpp | 3 ++-
src/ClientHandle.h | 2 +-
src/HTTPServer/HTTPConnection.cpp | 14 +++++++-------
src/HTTPServer/HTTPConnection.h | 12 +++++++++---
src/HTTPServer/SslHTTPConnection.cpp | 10 +++++++---
src/HTTPServer/SslHTTPConnection.h | 2 +-
src/OSSupport/SocketThreads.h | 6 ++++--
src/RCONServer.cpp | 8 ++++----
src/RCONServer.h | 2 +-
9 files changed, 36 insertions(+), 23 deletions(-)
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index 2362abe1e..a2bfdd381 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -2649,12 +2649,13 @@ void cClientHandle::PacketError(unsigned char a_PacketType)
-void cClientHandle::DataReceived(const char * a_Data, size_t a_Size)
+bool cClientHandle::DataReceived(const char * a_Data, size_t a_Size)
{
// Data is received from the client, store it in the buffer to be processed by the Tick thread:
m_TimeSinceLastPacket = 0;
cCSLock Lock(m_CSIncomingData);
m_IncomingData.append(a_Data, a_Size);
+ return false;
}
diff --git a/src/ClientHandle.h b/src/ClientHandle.h
index 9f8d44129..ac44e43dc 100644
--- a/src/ClientHandle.h
+++ b/src/ClientHandle.h
@@ -387,7 +387,7 @@ private:
void HandleCommandBlockMessage(const char * a_Data, unsigned int a_Length);
// cSocketThreads::cCallback overrides:
- virtual void DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
+ virtual bool DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
virtual void GetOutgoingData(AString & a_Data) override; // Data can be sent to client
virtual void SocketClosed (void) override; // The socket has been closed for any reason
}; // tolua_export
diff --git a/src/HTTPServer/HTTPConnection.cpp b/src/HTTPServer/HTTPConnection.cpp
index 8e95eff2d..b127e7091 100644
--- a/src/HTTPServer/HTTPConnection.cpp
+++ b/src/HTTPServer/HTTPConnection.cpp
@@ -145,7 +145,7 @@ void cHTTPConnection::Terminate(void)
-void cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
+bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
{
switch (m_State)
{
@@ -163,12 +163,12 @@ void cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
m_CurrentRequest = NULL;
m_State = wcsInvalid;
m_HTTPServer.CloseConnection(*this);
- return;
+ return true;
}
if (m_CurrentRequest->IsInHeaders())
{
// The request headers are not yet complete
- return;
+ return false;
}
// The request has finished parsing its headers successfully, notify of it:
@@ -184,13 +184,12 @@ void cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
// Process the rest of the incoming data into the request body:
if (a_Size > BytesConsumed)
{
- cHTTPConnection::DataReceived(a_Data + BytesConsumed, a_Size - BytesConsumed);
+ return cHTTPConnection::DataReceived(a_Data + BytesConsumed, a_Size - BytesConsumed);
}
else
{
- cHTTPConnection::DataReceived("", 0); // If the request has zero body length, let it be processed right-away
+ return cHTTPConnection::DataReceived("", 0); // If the request has zero body length, let it be processed right-away
}
- break;
}
case wcsRecvBody:
@@ -210,7 +209,7 @@ void cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
{
m_State = wcsInvalid;
m_HTTPServer.CloseConnection(*this);
- return;
+ return true;
}
delete m_CurrentRequest;
m_CurrentRequest = NULL;
@@ -224,6 +223,7 @@ void cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
break;
}
}
+ return false;
}
diff --git a/src/HTTPServer/HTTPConnection.h b/src/HTTPServer/HTTPConnection.h
index fc11f1ba6..6ea8a1ae8 100644
--- a/src/HTTPServer/HTTPConnection.h
+++ b/src/HTTPServer/HTTPConnection.h
@@ -91,9 +91,15 @@ protected:
// cSocketThreads::cCallback overrides:
- virtual void DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
- virtual void GetOutgoingData(AString & a_Data) override; // Data can be sent to client
- virtual void SocketClosed (void) override; // The socket has been closed for any reason
+ /** Data is received from the client.
+ Returns true if the connection has been closed as the result of parsing the data. */
+ virtual bool DataReceived(const char * a_Data, size_t a_Size) override;
+
+ /** Data can be sent to client */
+ virtual void GetOutgoingData(AString & a_Data) override;
+
+ /** The socket has been closed for any reason */
+ virtual void SocketClosed(void) override;
} ;
typedef std::vector cHTTPConnections;
diff --git a/src/HTTPServer/SslHTTPConnection.cpp b/src/HTTPServer/SslHTTPConnection.cpp
index fff96bb2e..b6b222b47 100644
--- a/src/HTTPServer/SslHTTPConnection.cpp
+++ b/src/HTTPServer/SslHTTPConnection.cpp
@@ -25,7 +25,7 @@ cSslHTTPConnection::cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509Ce
-void cSslHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
+bool cSslHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
{
// If there is outgoing data in the queue, notify the server that it should write it out:
if (!m_OutgoingData.empty())
@@ -52,13 +52,17 @@ void cSslHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
int NumRead = m_Ssl.ReadPlain(Buffer, sizeof(Buffer));
if (NumRead > 0)
{
- super::DataReceived(Buffer, (size_t)NumRead);
+ if (super::DataReceived(Buffer, (size_t)NumRead))
+ {
+ // The socket has been closed, and the object is already deleted. Bail out.
+ return true;
+ }
}
// If both failed, bail out:
if ((BytesWritten == 0) && (NumRead <= 0))
{
- return;
+ return false;
}
}
}
diff --git a/src/HTTPServer/SslHTTPConnection.h b/src/HTTPServer/SslHTTPConnection.h
index 2a648e8c8..653acbfce 100644
--- a/src/HTTPServer/SslHTTPConnection.h
+++ b/src/HTTPServer/SslHTTPConnection.h
@@ -36,7 +36,7 @@ protected:
cPublicKeyPtr m_PrivateKey;
// cHTTPConnection overrides:
- virtual void DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
+ virtual bool DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
virtual void GetOutgoingData(AString & a_Data) override; // Data can be sent to client
} ;
diff --git a/src/OSSupport/SocketThreads.h b/src/OSSupport/SocketThreads.h
index 679e374e1..944f5f3bc 100644
--- a/src/OSSupport/SocketThreads.h
+++ b/src/OSSupport/SocketThreads.h
@@ -63,8 +63,10 @@ public:
// Force a virtual destructor in all subclasses:
virtual ~cCallback() {}
- /** Called when data is received from the remote party */
- virtual void DataReceived(const char * a_Data, size_t a_Size) = 0;
+ /** Called when data is received from the remote party.
+ SocketThreads does not care about the return value, others can use it for their specific purpose -
+ for example HTTPServer uses it to signal if the connection was terminated as a result of the data received. */
+ virtual bool DataReceived(const char * a_Data, size_t a_Size) = 0;
/** Called when data can be sent to remote party
The function is supposed to *set* outgoing data to a_Data (overwrite) */
diff --git a/src/RCONServer.cpp b/src/RCONServer.cpp
index d7083ff2b..fd4b26cab 100644
--- a/src/RCONServer.cpp
+++ b/src/RCONServer.cpp
@@ -169,7 +169,7 @@ cRCONServer::cConnection::cConnection(cRCONServer & a_RCONServer, cSocket & a_So
-void cRCONServer::cConnection::DataReceived(const char * a_Data, size_t a_Size)
+bool cRCONServer::cConnection::DataReceived(const char * a_Data, size_t a_Size)
{
// Append data to the buffer:
m_Buffer.append(a_Data, a_Size);
@@ -187,12 +187,12 @@ void cRCONServer::cConnection::DataReceived(const char * a_Data, size_t a_Size)
m_RCONServer.m_SocketThreads.RemoveClient(this);
m_Socket.CloseSocket();
delete this;
- return;
+ return false;
}
if (Length > (int)(m_Buffer.size() + 4))
{
// Incomplete packet yet, wait for more data to come
- return;
+ return false;
}
int RequestID = IntFromBuffer(m_Buffer.data() + 4);
@@ -202,7 +202,7 @@ void cRCONServer::cConnection::DataReceived(const char * a_Data, size_t a_Size)
m_RCONServer.m_SocketThreads.RemoveClient(this);
m_Socket.CloseSocket();
delete this;
- return;
+ return false;
}
m_Buffer.erase(0, Length + 4);
} // while (m_Buffer.size() >= 14)
diff --git a/src/RCONServer.h b/src/RCONServer.h
index b964852ab..47c746736 100644
--- a/src/RCONServer.h
+++ b/src/RCONServer.h
@@ -65,7 +65,7 @@ protected:
// cSocketThreads::cCallback overrides:
- virtual void DataReceived(const char * a_Data, size_t a_Size) override;
+ virtual bool DataReceived(const char * a_Data, size_t a_Size) override;
virtual void GetOutgoingData(AString & a_Data) override;
virtual void SocketClosed(void) override;
--
cgit v1.2.3
From 1587b21edded56dbfb88150500336c2853b460c6 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 15:21:41 +0200
Subject: Renamed cPublicKey to cCryptoKey.
The class can hold both the private key and the public key, bad naming on PolarSSL's part.
Also somewhat fixed the cert and key loading in cHTTPServer.
---
src/HTTPServer/HTTPServer.cpp | 6 +-
src/HTTPServer/HTTPServer.h | 6 +-
src/HTTPServer/SslHTTPConnection.cpp | 2 +-
src/HTTPServer/SslHTTPConnection.h | 8 +-
src/PolarSSL++/CryptoKey.cpp | 149 +++++++++++++++++++++++++++++++++++
src/PolarSSL++/CryptoKey.h | 76 ++++++++++++++++++
src/PolarSSL++/CtrDrbgContext.h | 2 +-
src/PolarSSL++/PublicKey.cpp | 149 -----------------------------------
src/PolarSSL++/PublicKey.h | 76 ------------------
src/PolarSSL++/SslContext.cpp | 2 +-
src/PolarSSL++/SslContext.h | 13 ++-
11 files changed, 244 insertions(+), 245 deletions(-)
create mode 100644 src/PolarSSL++/CryptoKey.cpp
create mode 100644 src/PolarSSL++/CryptoKey.h
delete mode 100644 src/PolarSSL++/PublicKey.cpp
delete mode 100644 src/PolarSSL++/PublicKey.h
diff --git a/src/HTTPServer/HTTPServer.cpp b/src/HTTPServer/HTTPServer.cpp
index 9e3e0a17b..c45044c66 100644
--- a/src/HTTPServer/HTTPServer.cpp
+++ b/src/HTTPServer/HTTPServer.cpp
@@ -124,17 +124,17 @@ class cDebugCallbacks :
cHTTPServer::cHTTPServer(void) :
m_ListenThreadIPv4(*this, cSocket::IPv4, "WebServer IPv4"),
m_ListenThreadIPv6(*this, cSocket::IPv6, "WebServer IPv6"),
- m_Callbacks(NULL),
- m_Cert(new cX509Cert),
- m_CertPrivKey(new cPublicKey)
+ m_Callbacks(NULL)
{
AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt");
AString KeyFile = cFile::ReadWholeFile("webadmin/httpskey.pem");
if (!CertFile.empty() && !KeyFile.empty())
{
+ m_Cert.reset(new cX509Cert);
int res = m_Cert->Parse(CertFile.data(), CertFile.size());
if (res == 0)
{
+ m_CertPrivKey.reset(new cCryptoKey);
int res2 = m_CertPrivKey->ParsePrivate(KeyFile.data(), KeyFile.size(), "");
if (res2 != 0)
{
diff --git a/src/HTTPServer/HTTPServer.h b/src/HTTPServer/HTTPServer.h
index eb91dd5a3..522b7da62 100644
--- a/src/HTTPServer/HTTPServer.h
+++ b/src/HTTPServer/HTTPServer.h
@@ -13,7 +13,7 @@
#include "../OSSupport/SocketThreads.h"
#include "inifile/iniFile.h"
#include "PolarSSL++/RsaPrivateKey.h"
-#include "PolarSSL++/PublicKey.h"
+#include "PolarSSL++/CryptoKey.h"
#include "PolarSSL++/X509Cert.h"
@@ -85,8 +85,8 @@ protected:
/** The server certificate to use for the SSL connections */
cX509CertPtr m_Cert;
- /** The private key for m_Cert. Despite the class name, this is the PRIVATE key. */
- cPublicKeyPtr m_CertPrivKey;
+ /** The private key for m_Cert. */
+ cCryptoKeyPtr m_CertPrivKey;
// cListenThread::cCallback overrides:
diff --git a/src/HTTPServer/SslHTTPConnection.cpp b/src/HTTPServer/SslHTTPConnection.cpp
index b6b222b47..d237089d9 100644
--- a/src/HTTPServer/SslHTTPConnection.cpp
+++ b/src/HTTPServer/SslHTTPConnection.cpp
@@ -11,7 +11,7 @@
-cSslHTTPConnection::cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cPublicKeyPtr & a_PrivateKey) :
+cSslHTTPConnection::cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cCryptoKeyPtr & a_PrivateKey) :
super(a_HTTPServer),
m_Ssl(64000),
m_Cert(a_Cert),
diff --git a/src/HTTPServer/SslHTTPConnection.h b/src/HTTPServer/SslHTTPConnection.h
index 653acbfce..c2c1585cd 100644
--- a/src/HTTPServer/SslHTTPConnection.h
+++ b/src/HTTPServer/SslHTTPConnection.h
@@ -22,9 +22,9 @@ class cSslHTTPConnection :
typedef cHTTPConnection super;
public:
- /** Creates a new connection on the specified server; sends the specified cert as the server certificate,
- uses the private key for decryption. a_Private key is, despite the class name, a PRIVATE key for the cert. */
- cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cPublicKeyPtr & a_PrivateKey);
+ /** Creates a new connection on the specified server.
+ Sends the specified cert as the server certificate, uses the private key for decryption. */
+ cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509CertPtr & a_Cert, const cCryptoKeyPtr & a_PrivateKey);
protected:
cBufferedSslContext m_Ssl;
@@ -33,7 +33,7 @@ protected:
cX509CertPtr m_Cert;
/** The private key used for the certificate */
- cPublicKeyPtr m_PrivateKey;
+ cCryptoKeyPtr m_PrivateKey;
// cHTTPConnection overrides:
virtual bool DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
diff --git a/src/PolarSSL++/CryptoKey.cpp b/src/PolarSSL++/CryptoKey.cpp
new file mode 100644
index 000000000..0763c387b
--- /dev/null
+++ b/src/PolarSSL++/CryptoKey.cpp
@@ -0,0 +1,149 @@
+
+// CryptoKey.cpp
+
+// Implements the cCryptoKey class representing a RSA public key in PolarSSL
+
+#include "Globals.h"
+#include "CryptoKey.h"
+
+
+
+
+
+cCryptoKey::cCryptoKey(void)
+{
+ pk_init(&m_Pk);
+ m_CtrDrbg.Initialize("rsa_pubkey", 10);
+}
+
+
+
+
+
+cCryptoKey::cCryptoKey(const AString & a_PublicKeyData)
+{
+ pk_init(&m_Pk);
+ m_CtrDrbg.Initialize("rsa_pubkey", 10);
+ int res = ParsePublic(a_PublicKeyData.data(), a_PublicKeyData.size());
+ if (res != 0)
+ {
+ LOGWARNING("Failed to parse public key: -0x%x", res);
+ ASSERT(!"Cannot parse PubKey");
+ return;
+ }
+}
+
+
+
+
+
+cCryptoKey::cCryptoKey(const AString & a_PrivateKeyData, const AString & a_Password)
+{
+ pk_init(&m_Pk);
+ m_CtrDrbg.Initialize("rsa_privkey", 11);
+ int res = ParsePrivate(a_PrivateKeyData.data(), a_PrivateKeyData.size(), a_Password);
+ if (res != 0)
+ {
+ LOGWARNING("Failed to parse private key: -0x%x", res);
+ ASSERT(!"Cannot parse PubKey");
+ return;
+ }
+}
+
+
+
+
+
+cCryptoKey::~cCryptoKey()
+{
+ pk_free(&m_Pk);
+}
+
+
+
+
+
+int cCryptoKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength)
+{
+ ASSERT(IsValid());
+
+ size_t DecryptedLen = a_DecryptedMaxLength;
+ int res = pk_decrypt(&m_Pk,
+ a_EncryptedData, a_EncryptedLength,
+ a_DecryptedData, &DecryptedLen, a_DecryptedMaxLength,
+ ctr_drbg_random, m_CtrDrbg.GetInternal()
+ );
+ if (res != 0)
+ {
+ return res;
+ }
+ return (int)DecryptedLen;
+}
+
+
+
+
+
+int cCryptoKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
+{
+ ASSERT(IsValid());
+
+ size_t EncryptedLength = a_EncryptedMaxLength;
+ int res = pk_encrypt(&m_Pk,
+ a_PlainData, a_PlainLength, a_EncryptedData, &EncryptedLength, a_EncryptedMaxLength,
+ ctr_drbg_random, m_CtrDrbg.GetInternal()
+ );
+ if (res != 0)
+ {
+ return res;
+ }
+ return (int)EncryptedLength;
+}
+
+
+
+
+
+
+int cCryptoKey::ParsePublic(const void * a_Data, size_t a_NumBytes)
+{
+ ASSERT(!IsValid()); // Cannot parse a second key
+
+ return pk_parse_public_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes);
+}
+
+
+
+
+
+
+int cCryptoKey::ParsePrivate(const void * a_Data, size_t a_NumBytes, const AString & a_Password)
+{
+ ASSERT(!IsValid()); // Cannot parse a second key
+
+ if (a_Password.empty())
+ {
+ return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, NULL, 0);
+ }
+ else
+ {
+ return pk_parse_key(
+ &m_Pk,
+ (const unsigned char *)a_Data, a_NumBytes,
+ (const unsigned char *)a_Password.c_str(), a_Password.size()
+ );
+ }
+}
+
+
+
+
+
+bool cCryptoKey::IsValid(void) const
+{
+ return (pk_get_type(&m_Pk) != POLARSSL_PK_NONE);
+}
+
+
+
+
diff --git a/src/PolarSSL++/CryptoKey.h b/src/PolarSSL++/CryptoKey.h
new file mode 100644
index 000000000..9c298e501
--- /dev/null
+++ b/src/PolarSSL++/CryptoKey.h
@@ -0,0 +1,76 @@
+
+// CryptoKey.h
+
+// Declares the cCryptoKey class representing a RSA public key in PolarSSL
+
+
+
+
+
+#pragma once
+
+#include "CtrDrbgContext.h"
+#include "polarssl/pk.h"
+
+
+
+
+
+class cCryptoKey
+{
+ friend class cSslContext;
+
+public:
+ /** Constructs an empty key instance. Before use, it needs to be filled by ParsePublic() or ParsePrivate() */
+ cCryptoKey(void);
+
+ /** Constructs the public key out of the DER- or PEM-encoded pubkey data */
+ cCryptoKey(const AString & a_PublicKeyData);
+
+ /** Constructs the private key out of the DER- or PEM-encoded privkey data, with the specified password.
+ If a_Password is empty, no password is assumed. */
+ cCryptoKey(const AString & a_PrivateKeyData, const AString & a_Password);
+
+ ~cCryptoKey();
+
+ /** Decrypts the data using the stored public key
+ Both a_EncryptedData and a_DecryptedData must be at least bytes large.
+ Returns the number of bytes decrypted, or negative number for error. */
+ int Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength);
+
+ /** Encrypts the data using the stored public key
+ Both a_EncryptedData and a_DecryptedData must be at least bytes large.
+ Returns the number of bytes decrypted, or negative number for error. */
+ int Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength);
+
+ /** Parses the specified data into a public key representation.
+ The key can be DER- or PEM-encoded.
+ Returns 0 on success, PolarSSL error code on failure. */
+ int ParsePublic(const void * a_Data, size_t a_NumBytes);
+
+ /** Parses the specified data into a private key representation.
+ If a_Password is empty, no password is assumed.
+ The key can be DER- or PEM-encoded.
+ Returns 0 on success, PolarSSL error code on failure. */
+ int ParsePrivate(const void * a_Data, size_t a_NumBytes, const AString & a_Password);
+
+ /** Returns true if the contained key is valid. */
+ bool IsValid(void) const;
+
+protected:
+ /** The PolarSSL representation of the key data */
+ pk_context m_Pk;
+
+ /** The random generator used in encryption and decryption */
+ cCtrDrbgContext m_CtrDrbg;
+
+
+ /** Returns the internal context ptr. Only use in PolarSSL API calls. */
+ pk_context * GetInternal(void) { return &m_Pk; }
+} ;
+
+typedef SharedPtr cCryptoKeyPtr;
+
+
+
+
diff --git a/src/PolarSSL++/CtrDrbgContext.h b/src/PolarSSL++/CtrDrbgContext.h
index 65e9a2374..230db8753 100644
--- a/src/PolarSSL++/CtrDrbgContext.h
+++ b/src/PolarSSL++/CtrDrbgContext.h
@@ -26,7 +26,7 @@ class cCtrDrbgContext
{
friend class cSslContext;
friend class cRsaPrivateKey;
- friend class cPublicKey;
+ friend class cCryptoKey;
public:
/** Constructs the context with a new entropy context. */
diff --git a/src/PolarSSL++/PublicKey.cpp b/src/PolarSSL++/PublicKey.cpp
deleted file mode 100644
index dae026082..000000000
--- a/src/PolarSSL++/PublicKey.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-
-// PublicKey.cpp
-
-// Implements the cPublicKey class representing a RSA public key in PolarSSL
-
-#include "Globals.h"
-#include "PublicKey.h"
-
-
-
-
-
-cPublicKey::cPublicKey(void)
-{
- pk_init(&m_Pk);
- m_CtrDrbg.Initialize("rsa_pubkey", 10);
-}
-
-
-
-
-
-cPublicKey::cPublicKey(const AString & a_PublicKeyData)
-{
- pk_init(&m_Pk);
- m_CtrDrbg.Initialize("rsa_pubkey", 10);
- int res = ParsePublic(a_PublicKeyData.data(), a_PublicKeyData.size());
- if (res != 0)
- {
- LOGWARNING("Failed to parse public key: -0x%x", res);
- ASSERT(!"Cannot parse PubKey");
- return;
- }
-}
-
-
-
-
-
-cPublicKey::cPublicKey(const AString & a_PrivateKeyData, const AString & a_Password)
-{
- pk_init(&m_Pk);
- m_CtrDrbg.Initialize("rsa_privkey", 11);
- int res = ParsePrivate(a_PrivateKeyData.data(), a_PrivateKeyData.size(), a_Password);
- if (res != 0)
- {
- LOGWARNING("Failed to parse private key: -0x%x", res);
- ASSERT(!"Cannot parse PubKey");
- return;
- }
-}
-
-
-
-
-
-cPublicKey::~cPublicKey()
-{
- pk_free(&m_Pk);
-}
-
-
-
-
-
-int cPublicKey::Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength)
-{
- ASSERT(IsValid());
-
- size_t DecryptedLen = a_DecryptedMaxLength;
- int res = pk_decrypt(&m_Pk,
- a_EncryptedData, a_EncryptedLength,
- a_DecryptedData, &DecryptedLen, a_DecryptedMaxLength,
- ctr_drbg_random, m_CtrDrbg.GetInternal()
- );
- if (res != 0)
- {
- return res;
- }
- return (int)DecryptedLen;
-}
-
-
-
-
-
-int cPublicKey::Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength)
-{
- ASSERT(IsValid());
-
- size_t EncryptedLength = a_EncryptedMaxLength;
- int res = pk_encrypt(&m_Pk,
- a_PlainData, a_PlainLength, a_EncryptedData, &EncryptedLength, a_EncryptedMaxLength,
- ctr_drbg_random, m_CtrDrbg.GetInternal()
- );
- if (res != 0)
- {
- return res;
- }
- return (int)EncryptedLength;
-}
-
-
-
-
-
-
-int cPublicKey::ParsePublic(const void * a_Data, size_t a_NumBytes)
-{
- ASSERT(!IsValid()); // Cannot parse a second key
-
- return pk_parse_public_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes);
-}
-
-
-
-
-
-
-int cPublicKey::ParsePrivate(const void * a_Data, size_t a_NumBytes, const AString & a_Password)
-{
- ASSERT(!IsValid()); // Cannot parse a second key
-
- if (a_Password.empty())
- {
- return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, NULL, 0);
- }
- else
- {
- return pk_parse_key(
- &m_Pk,
- (const unsigned char *)a_Data, a_NumBytes,
- (const unsigned char *)a_Password.c_str(), a_Password.size()
- );
- }
-}
-
-
-
-
-
-bool cPublicKey::IsValid(void) const
-{
- return (pk_get_type(&m_Pk) != POLARSSL_PK_NONE);
-}
-
-
-
-
diff --git a/src/PolarSSL++/PublicKey.h b/src/PolarSSL++/PublicKey.h
deleted file mode 100644
index df52a4143..000000000
--- a/src/PolarSSL++/PublicKey.h
+++ /dev/null
@@ -1,76 +0,0 @@
-
-// PublicKey.h
-
-// Declares the cPublicKey class representing a RSA public key in PolarSSL
-
-
-
-
-
-#pragma once
-
-#include "CtrDrbgContext.h"
-#include "polarssl/pk.h"
-
-
-
-
-
-class cPublicKey
-{
- friend class cSslContext;
-
-public:
- /** Constructs an empty key instance. Before use, it needs to be filled by ParsePublic() or ParsePrivate() */
- cPublicKey(void);
-
- /** Constructs the public key out of the DER- or PEM-encoded pubkey data */
- cPublicKey(const AString & a_PublicKeyData);
-
- /** Constructs the private key out of the DER- or PEM-encoded privkey data, with the specified password.
- If a_Password is empty, no password is assumed. */
- cPublicKey(const AString & a_PrivateKeyData, const AString & a_Password);
-
- ~cPublicKey();
-
- /** Decrypts the data using the stored public key
- Both a_EncryptedData and a_DecryptedData must be at least bytes large.
- Returns the number of bytes decrypted, or negative number for error. */
- int Decrypt(const Byte * a_EncryptedData, size_t a_EncryptedLength, Byte * a_DecryptedData, size_t a_DecryptedMaxLength);
-
- /** Encrypts the data using the stored public key
- Both a_EncryptedData and a_DecryptedData must be at least bytes large.
- Returns the number of bytes decrypted, or negative number for error. */
- int Encrypt(const Byte * a_PlainData, size_t a_PlainLength, Byte * a_EncryptedData, size_t a_EncryptedMaxLength);
-
- /** Parses the specified data into a public key representation.
- The key can be DER- or PEM-encoded.
- Returns 0 on success, PolarSSL error code on failure. */
- int ParsePublic(const void * a_Data, size_t a_NumBytes);
-
- /** Parses the specified data into a private key representation.
- If a_Password is empty, no password is assumed.
- The key can be DER- or PEM-encoded.
- Returns 0 on success, PolarSSL error code on failure. */
- int ParsePrivate(const void * a_Data, size_t a_NumBytes, const AString & a_Password);
-
- /** Returns true if the contained key is valid. */
- bool IsValid(void) const;
-
-protected:
- /** The public key PolarSSL representation */
- pk_context m_Pk;
-
- /** The random generator used in encryption and decryption */
- cCtrDrbgContext m_CtrDrbg;
-
-
- /** Returns the internal context ptr. Only use in PolarSSL API calls. */
- pk_context * GetInternal(void) { return &m_Pk; }
-} ;
-
-typedef SharedPtr cPublicKeyPtr;
-
-
-
-
diff --git a/src/PolarSSL++/SslContext.cpp b/src/PolarSSL++/SslContext.cpp
index df0219610..bc397b655 100644
--- a/src/PolarSSL++/SslContext.cpp
+++ b/src/PolarSSL++/SslContext.cpp
@@ -115,7 +115,7 @@ void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cRsaPrivateKe
-void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cPublicKeyPtr & a_OwnCertPrivKey)
+void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cCryptoKeyPtr & a_OwnCertPrivKey)
{
ASSERT(m_IsValid); // Call Initialize() first
diff --git a/src/PolarSSL++/SslContext.h b/src/PolarSSL++/SslContext.h
index 273939b9f..a4ad1a345 100644
--- a/src/PolarSSL++/SslContext.h
+++ b/src/PolarSSL++/SslContext.h
@@ -11,7 +11,7 @@
#include "polarssl/ssl.h"
#include "../ByteBuffer.h"
-#include "PublicKey.h"
+#include "CryptoKey.h"
#include "RsaPrivateKey.h"
#include "X509Cert.h"
@@ -54,9 +54,8 @@ public:
void SetOwnCert(const cX509CertPtr & a_OwnCert, const cRsaPrivateKeyPtr & a_OwnCertPrivKey);
/** Sets the certificate to use as our own. Must be used when representing a server, optional when client.
- Must be called after Initialize().
- Despite the class name, a_OwnCertPrivKey is a PRIVATE key. */
- void SetOwnCert(const cX509CertPtr & a_OwnCert, const cPublicKeyPtr & a_OwnCertPrivKey);
+ Must be called after Initialize(). */
+ void SetOwnCert(const cX509CertPtr & a_OwnCert, const cCryptoKeyPtr & a_OwnCertPrivKey);
/** Sets a cert chain as the trusted cert store for this context. Must be called after Initialize().
Calling this will switch the context into strict cert verification mode.
@@ -107,11 +106,11 @@ protected:
/** The certificate that we present to the peer. */
cX509CertPtr m_OwnCert;
- /** Private key for m_OwnCert, if initialized from a cRsaPrivateKey */
+ /** Private key for m_OwnCert, if initialized from a cRsaPrivateKey. */
cRsaPrivateKeyPtr m_OwnCertPrivKey;
- /** Private key for m_OwnCert, if initialized from a cPublicKey. Despite the class name, this is a PRIVATE key. */
- cPublicKeyPtr m_OwnCertPrivKey2;
+ /** Private key for m_OwnCert, if initialized from a cCryptoKey. */
+ cCryptoKeyPtr m_OwnCertPrivKey2;
/** True if the SSL handshake has been completed. */
bool m_HasHandshaken;
--
cgit v1.2.3
From 772b57ca04b2dbe4ec163a8c2856f8af7bc5c2a5 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 18:00:10 +0200
Subject: Anvil saver pads data to 4K boundaries.
Fixes #524.
---
src/WorldStorage/WSSAnvil.cpp | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp
index 33f34728e..f33178173 100644
--- a/src/WorldStorage/WSSAnvil.cpp
+++ b/src/WorldStorage/WSSAnvil.cpp
@@ -2672,6 +2672,11 @@ bool cWSSAnvil::cMCAFile::SetChunkData(const cChunkCoords & a_Chunk, const AStri
return false;
}
+ // Add padding to 4K boundary:
+ size_t BytesWritten = a_Data.size() + MCA_CHUNK_HEADER_LENGTH;
+ static const char Padding[4095] = {0};
+ m_File.Write(Padding, 4096 - (BytesWritten % 4096));
+
// Store the header:
ChunkSize = (a_Data.size() + MCA_CHUNK_HEADER_LENGTH + 4095) / 4096; // Round data size *up* to nearest 4KB sector, make it a sector number
ASSERT(ChunkSize < 256);
--
cgit v1.2.3
From d9e5dbf16526aa102abdc818d3515928663a973c Mon Sep 17 00:00:00 2001
From: Mattes D
Date: Thu, 1 May 2014 18:06:23 +0200
Subject: Renamed PublicKey to CryptoKey in CMakeLists.txt
---
src/PolarSSL++/CMakeLists.txt | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/src/PolarSSL++/CMakeLists.txt b/src/PolarSSL++/CMakeLists.txt
index b0a592760..9a59cdb2c 100644
--- a/src/PolarSSL++/CMakeLists.txt
+++ b/src/PolarSSL++/CMakeLists.txt
@@ -1,4 +1,3 @@
-
cmake_minimum_required (VERSION 2.6)
project (MCServer)
@@ -11,8 +10,8 @@ set(SOURCES
BufferedSslContext.cpp
CallbackSslContext.cpp
CtrDrbgContext.cpp
+ CryptoKey.cpp
EntropyContext.cpp
- PublicKey.cpp
RsaPrivateKey.cpp
Sha1Checksum.cpp
SslContext.cpp
@@ -26,8 +25,8 @@ set(HEADERS
BufferedSslContext.h
CallbackSslContext.h
CtrDrbgContext.h
+ CryptoKey.h
EntropyContext.h
- PublicKey.h
RsaPrivateKey.h
SslContext.h
Sha1Checksum.h
--
cgit v1.2.3
From ed071538d56826a9c46ccc486f2bd9c5d30d3054 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Thu, 1 May 2014 09:47:22 -0700
Subject: Changed polarssl repo to point to cloned copy of polarssl
---
.gitmodules | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.gitmodules b/.gitmodules
index 2c7ec209b..2aaee3624 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -9,4 +9,4 @@
url = https://github.com/bearbin/transapi.git
[submodule "lib/polarssl"]
path = lib/polarssl
- url = https://github.com/polarssl/polarssl
+ url = https://github.com/mc-server/polarssl
--
cgit v1.2.3
From 9928698d6d602813eb2db5b9d494a1b5e5bb0f7f Mon Sep 17 00:00:00 2001
From: Tycho
Date: Thu, 1 May 2014 09:53:43 -0700
Subject: Merged change to enable testing to be disabled This is confirmed
upstream but is unlikely to get into the repository for several weeks
---
lib/polarssl | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lib/polarssl b/lib/polarssl
index 2cb1a0c40..1ed82759c 160000
--- a/lib/polarssl
+++ b/lib/polarssl
@@ -1 +1 @@
-Subproject commit 2cb1a0c4009ecf368ecc74eb428394e10f9e6d00
+Subproject commit 1ed82759c68f92c4acc7e3f33b850cf9f01c8aba
--
cgit v1.2.3
From 3e854bc5960dccbcecc32bf2f280f1fb04f67307 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 20:20:12 +0200
Subject: ProtoProxy: Renamed PublicKey to CryptoKey.
---
Tools/ProtoProxy/CMakeLists.txt | 4 ++--
Tools/ProtoProxy/Connection.cpp | 4 ++--
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/Tools/ProtoProxy/CMakeLists.txt b/Tools/ProtoProxy/CMakeLists.txt
index a136c95df..f0796363c 100644
--- a/Tools/ProtoProxy/CMakeLists.txt
+++ b/Tools/ProtoProxy/CMakeLists.txt
@@ -38,9 +38,9 @@ set(SHARED_SRC
../../src/MCLogger.cpp
../../src/PolarSSL++/AesCfb128Decryptor.cpp
../../src/PolarSSL++/AesCfb128Encryptor.cpp
+ ../../src/PolarSSL++/CryptoKey.cpp
../../src/PolarSSL++/CtrDrbgContext.cpp
../../src/PolarSSL++/EntropyContext.cpp
- ../../src/PolarSSL++/PublicKey.cpp
../../src/PolarSSL++/RsaPrivateKey.cpp
)
set(SHARED_HDR
@@ -50,9 +50,9 @@ set(SHARED_HDR
../../src/MCLogger.h
../../src/PolarSSL++/AesCfb128Decryptor.h
../../src/PolarSSL++/AesCfb128Encryptor.h
+ ../../src/PolarSSL++/CryptoKey.h
../../src/PolarSSL++/CtrDrbgContext.h
../../src/PolarSSL++/EntropyContext.h
- ../../src/PolarSSL++/PublicKey.h
../../src/PolarSSL++/RsaPrivateKey.h
)
set(SHARED_OSS_SRC
diff --git a/Tools/ProtoProxy/Connection.cpp b/Tools/ProtoProxy/Connection.cpp
index 26aed2206..c5916c1ca 100644
--- a/Tools/ProtoProxy/Connection.cpp
+++ b/Tools/ProtoProxy/Connection.cpp
@@ -7,7 +7,7 @@
#include "Connection.h"
#include "Server.h"
#include
-#include "PolarSSL++/PublicKey.h"
+#include "PolarSSL++/CryptoKey.h"
#ifdef _WIN32
#include // For _mkdir()
@@ -2900,7 +2900,7 @@ void cConnection::SendEncryptionKeyResponse(const AString & a_ServerPublicKey, c
Byte SharedSecret[16];
Byte EncryptedSecret[128];
memset(SharedSecret, 0, sizeof(SharedSecret)); // Use all zeroes for the initial secret
- cPublicKey PubKey(a_ServerPublicKey);
+ cCryptoKey PubKey(a_ServerPublicKey);
int res = PubKey.Encrypt(SharedSecret, sizeof(SharedSecret), EncryptedSecret, sizeof(EncryptedSecret));
if (res < 0)
{
--
cgit v1.2.3
From a2cffb0363e42f12019712297e764a269b6a7d9a Mon Sep 17 00:00:00 2001
From: Mattes D
Date: Thu, 1 May 2014 20:21:54 +0200
Subject: Fixed MSVC2013 compilation.
---
src/Globals.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Globals.h b/src/Globals.h
index a09819ce9..71e9191e4 100644
--- a/src/Globals.h
+++ b/src/Globals.h
@@ -272,7 +272,7 @@ template class SizeChecker;
#if (defined(_MSC_VER) && (_MSC_VER < 1600))
// MSVC before 2010 doesn't have std::shared_ptr, but has std::tr1::shared_ptr, defined in included earlier
#define SharedPtr std::tr1::shared_ptr
-#elif (__cplusplus >= 201103L)
+#elif (defined(_MSC_VER) || (__cplusplus >= 201103L))
// C++11 has std::shared_ptr in , included earlier
#define SharedPtr std::shared_ptr
#else
--
cgit v1.2.3
From 1929b46affd7e8ae98230faa726a896eef75cb16 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Thu, 1 May 2014 11:52:08 -0700
Subject: Disable polarssl tests by default
---
lib/polarssl.cmake | 1 +
1 file changed, 1 insertion(+)
diff --git a/lib/polarssl.cmake b/lib/polarssl.cmake
index 2a58e54c5..4a2af9dfd 100644
--- a/lib/polarssl.cmake
+++ b/lib/polarssl.cmake
@@ -2,6 +2,7 @@
if(NOT TARGET polarssl)
message("including polarssl")
if (SELF_TEST)
+ set(ENABLE_TESTING 0)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl)
else()
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl EXCLUDE_FROM_ALL)
--
cgit v1.2.3
From 47cc1a84e186f76f69ad432c081ae74ff6c80a6e Mon Sep 17 00:00:00 2001
From: Tycho
Date: Thu, 1 May 2014 11:57:07 -0700
Subject: Tests off by default take 2
---
lib/polarssl.cmake | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lib/polarssl.cmake b/lib/polarssl.cmake
index 4a2af9dfd..172a63729 100644
--- a/lib/polarssl.cmake
+++ b/lib/polarssl.cmake
@@ -2,7 +2,7 @@
if(NOT TARGET polarssl)
message("including polarssl")
if (SELF_TEST)
- set(ENABLE_TESTING 0)
+ set(ENABLE_TESTING OFF CACHE BOOL)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl)
else()
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl EXCLUDE_FROM_ALL)
--
cgit v1.2.3
From 8d6919f3b63338ec01eff15a3968b004bd3be132 Mon Sep 17 00:00:00 2001
From: Tycho
Date: Thu, 1 May 2014 12:05:11 -0700
Subject: Fixed polarssl programs included
---
lib/polarssl.cmake | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/lib/polarssl.cmake b/lib/polarssl.cmake
index 172a63729..91f0fa145 100644
--- a/lib/polarssl.cmake
+++ b/lib/polarssl.cmake
@@ -2,7 +2,8 @@
if(NOT TARGET polarssl)
message("including polarssl")
if (SELF_TEST)
- set(ENABLE_TESTING OFF CACHE BOOL)
+ set(ENABLE_TESTING OFF CACHE BOOL "Disable tests")
+ set(ENABLE_PROGRAMS OFF CACHE BOOL "Disable programs")
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl)
else()
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/polarssl/ ${CMAKE_CURRENT_BINARY_DIR}/lib/polarssl EXCLUDE_FROM_ALL)
--
cgit v1.2.3
From 9221b458989512e41f8502b56ed738d143599093 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 21:23:37 +0200
Subject: cSslContext has virtual destructor now.
---
src/PolarSSL++/SslContext.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/PolarSSL++/SslContext.h b/src/PolarSSL++/SslContext.h
index a4ad1a345..6b4f2c1e7 100644
--- a/src/PolarSSL++/SslContext.h
+++ b/src/PolarSSL++/SslContext.h
@@ -40,7 +40,7 @@ public:
/** Creates a new uninitialized context */
cSslContext(void);
- ~cSslContext();
+ virtual ~cSslContext();
/** Initializes the context for use as a server or client.
Returns 0 on success, PolarSSL error on failure. */
--
cgit v1.2.3
From b0056cdcf8a36efbed4b97414ebf5741b56a5895 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:02:25 +0200
Subject: Removed the explicit copy constructor for cItem.
The compiler generates an implicit one with the same contents and warns about it. The function left in for ToLua to generate the binding for it.
---
src/Item.h | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/src/Item.h b/src/Item.h
index 641c681db..8eb0a1f4e 100644
--- a/src/Item.h
+++ b/src/Item.h
@@ -73,6 +73,10 @@ public:
}
+ // The constructor is disabled in code, because the compiler generates it anyway,
+ // but it needs to stay because ToLua needs to generate the binding for it
+ #if 0
+
/** Creates an exact copy of the item */
cItem(const cItem & a_CopyFrom) :
m_ItemType (a_CopyFrom.m_ItemType),
@@ -85,6 +89,8 @@ public:
{
}
+ #endif
+
void Empty(void)
{
--
cgit v1.2.3
From 30e81156eb6de46d7a374c044e26b35d83af4244 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:02:45 +0200
Subject: Added a missing return statement.
---
src/RCONServer.cpp | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/RCONServer.cpp b/src/RCONServer.cpp
index fd4b26cab..cd5292ac3 100644
--- a/src/RCONServer.cpp
+++ b/src/RCONServer.cpp
@@ -206,6 +206,7 @@ bool cRCONServer::cConnection::DataReceived(const char * a_Data, size_t a_Size)
}
m_Buffer.erase(0, Length + 4);
} // while (m_Buffer.size() >= 14)
+ return false;
}
--
cgit v1.2.3
From e175ae551c5e1e8034648f950c016b6348d6bf09 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:41:18 +0200
Subject: Fixed warning in cBlockArea.
---
src/BlockArea.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/BlockArea.h b/src/BlockArea.h
index 4c4dfb8ff..6dba0f12e 100644
--- a/src/BlockArea.h
+++ b/src/BlockArea.h
@@ -294,7 +294,7 @@ public:
NIBBLETYPE * GetBlockMetas (void) const { return m_BlockMetas; } // NOTE: one byte per block!
NIBBLETYPE * GetBlockLight (void) const { return m_BlockLight; } // NOTE: one byte per block!
NIBBLETYPE * GetBlockSkyLight(void) const { return m_BlockSkyLight; } // NOTE: one byte per block!
- size_t GetBlockCount(void) const { return m_Size.x * m_Size.y * m_Size.z; }
+ size_t GetBlockCount(void) const { return (size_t)(m_Size.x * m_Size.y * m_Size.z); }
int MakeIndex(int a_RelX, int a_RelY, int a_RelZ) const;
protected:
--
cgit v1.2.3
From a6eba4ff8b007863eac20693db5dd859f0dcbc70 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:41:41 +0200
Subject: Fixed warning in cCallbackSslContext::cDataCallbacks.
---
src/PolarSSL++/CallbackSslContext.h | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/PolarSSL++/CallbackSslContext.h b/src/PolarSSL++/CallbackSslContext.h
index 4e4c1ed7f..3e6edc5f4 100644
--- a/src/PolarSSL++/CallbackSslContext.h
+++ b/src/PolarSSL++/CallbackSslContext.h
@@ -23,6 +23,9 @@ public:
class cDataCallbacks
{
public:
+ // Force a virtual destructor in descendants:
+ virtual ~cDataCallbacks() {}
+
/** Called when PolarSSL wants to read encrypted data from the SSL peer.
The returned value is the number of bytes received, or a PolarSSL error on failure.
The implementation can return POLARSSL_ERR_NET_WANT_READ or POLARSSL_ERR_NET_WANT_WRITE to indicate
--
cgit v1.2.3
From b6b86b7270ca3f44b0b2a24ffe8292e87e762713 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:43:37 +0200
Subject: Fixed warnings in FastNBT.
---
src/WorldStorage/FastNBT.h | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/WorldStorage/FastNBT.h b/src/WorldStorage/FastNBT.h
index 5e5af3ca3..bcf93228f 100644
--- a/src/WorldStorage/FastNBT.h
+++ b/src/WorldStorage/FastNBT.h
@@ -237,7 +237,7 @@ public:
{
ASSERT(m_Tags[(size_t)a_Tag].m_Type == TAG_String);
AString res;
- res.assign(m_Data + m_Tags[(size_t)a_Tag].m_DataStart, m_Tags[(size_t)a_Tag].m_DataLength);
+ res.assign(m_Data + m_Tags[(size_t)a_Tag].m_DataStart, (size_t)m_Tags[(size_t)a_Tag].m_DataLength);
return res;
}
@@ -245,7 +245,7 @@ public:
inline AString GetName(int a_Tag) const
{
AString res;
- res.assign(m_Data + m_Tags[(size_t)a_Tag].m_NameStart, m_Tags[(size_t)a_Tag].m_NameLength);
+ res.assign(m_Data + m_Tags[(size_t)a_Tag].m_NameStart, (size_t)m_Tags[(size_t)a_Tag].m_NameLength);
return res;
}
--
cgit v1.2.3
From a91129af4ac186eaceb5fbf044539c052c4c6cf8 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:44:52 +0200
Subject: Fixed warnings in cBlockArea.
---
src/BlockArea.cpp | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp
index 55e8d6849..e0ae2c5b6 100644
--- a/src/BlockArea.cpp
+++ b/src/BlockArea.cpp
@@ -2005,7 +2005,7 @@ void cBlockArea::ExpandBlockTypes(int a_SubMinX, int a_AddMaxX, int a_SubMinY, i
int NewSizeX = m_Size.x + a_SubMinX + a_AddMaxX;
int NewSizeY = m_Size.y + a_SubMinY + a_AddMaxY;
int NewSizeZ = m_Size.z + a_SubMinZ + a_AddMaxZ;
- size_t BlockCount = (size_t)NewSizeX * NewSizeY * NewSizeZ;
+ size_t BlockCount = (size_t)(NewSizeX * NewSizeY * NewSizeZ);
BLOCKTYPE * NewBlockTypes = new BLOCKTYPE[BlockCount];
memset(NewBlockTypes, 0, BlockCount * sizeof(BLOCKTYPE));
int OldIndex = 0;
@@ -2035,7 +2035,7 @@ void cBlockArea::ExpandNibbles(NIBBLEARRAY & a_Array, int a_SubMinX, int a_AddMa
int NewSizeX = m_Size.x + a_SubMinX + a_AddMaxX;
int NewSizeY = m_Size.y + a_SubMinY + a_AddMaxY;
int NewSizeZ = m_Size.z + a_SubMinZ + a_AddMaxZ;
- size_t BlockCount = (size_t)NewSizeX * NewSizeY * NewSizeZ;
+ size_t BlockCount = (size_t)(NewSizeX * NewSizeY * NewSizeZ);
NIBBLETYPE * NewNibbles = new NIBBLETYPE[BlockCount];
memset(NewNibbles, 0, BlockCount * sizeof(NIBBLETYPE));
int OldIndex = 0;
--
cgit v1.2.3
From a4d8c6d656da6b3b4c986361213bb65540a08e80 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:47:02 +0200
Subject: Fixed warning in BlockID.
---
src/BlockID.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/BlockID.cpp b/src/BlockID.cpp
index bf95d0798..bfe826f40 100644
--- a/src/BlockID.cpp
+++ b/src/BlockID.cpp
@@ -102,7 +102,7 @@ public:
return true;
}
- a_Item.m_ItemDamage = atoi(Split[1].c_str());
+ a_Item.m_ItemDamage = (short)atoi(Split[1].c_str());
if ((a_Item.m_ItemDamage == 0) && (Split[1] != "0"))
{
// Parsing the number failed
--
cgit v1.2.3
From fb173a756ca7c0cd9ebfde70e5a5af0a78faa884 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:54:22 +0200
Subject: Fixed warnings in cByteBuffer.
---
src/ByteBuffer.cpp | 26 +++++++++++++-------------
src/ByteBuffer.h | 2 +-
2 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/src/ByteBuffer.cpp b/src/ByteBuffer.cpp
index c27bc4cad..4de89f7c1 100644
--- a/src/ByteBuffer.cpp
+++ b/src/ByteBuffer.cpp
@@ -327,7 +327,7 @@ bool cByteBuffer::ReadBEShort(short & a_Value)
CheckValid();
NEEDBYTES(2);
ReadBuf(&a_Value, 2);
- a_Value = ntohs(a_Value);
+ a_Value = (short)ntohs((u_short)a_Value);
return true;
}
@@ -341,7 +341,7 @@ bool cByteBuffer::ReadBEInt(int & a_Value)
CheckValid();
NEEDBYTES(4);
ReadBuf(&a_Value, 4);
- a_Value = ntohl(a_Value);
+ a_Value = (int)ntohl((u_long)a_Value);
return true;
}
@@ -420,7 +420,7 @@ bool cByteBuffer::ReadBEUTF16String16(AString & a_Value)
ASSERT(!"Negative string length? Are you sure?");
return true;
}
- return ReadUTF16String(a_Value, Length);
+ return ReadUTF16String(a_Value, (size_t)Length);
}
@@ -438,7 +438,7 @@ bool cByteBuffer::ReadVarInt(UInt32 & a_Value)
{
NEEDBYTES(1);
ReadBuf(&b, 1);
- Value = Value | (((Int64)(b & 0x7f)) << Shift);
+ Value = Value | (((UInt32)(b & 0x7f)) << Shift);
Shift += 7;
} while ((b & 0x80) != 0);
a_Value = Value;
@@ -462,7 +462,7 @@ bool cByteBuffer::ReadVarUTF8String(AString & a_Value)
{
LOGWARNING("%s: String too large: %u (%u KiB)", __FUNCTION__, Size, Size / 1024);
}
- return ReadString(a_Value, (int)Size);
+ return ReadString(a_Value, (size_t)Size);
}
@@ -517,7 +517,7 @@ bool cByteBuffer::WriteBEShort(short a_Value)
CHECK_THREAD;
CheckValid();
PUTBYTES(2);
- short Converted = htons(a_Value);
+ u_short Converted = htons((u_short)a_Value);
return WriteBuf(&Converted, 2);
}
@@ -530,7 +530,7 @@ bool cByteBuffer::WriteBEInt(int a_Value)
CHECK_THREAD;
CheckValid();
PUTBYTES(4);
- int Converted = HostToNetwork4(&a_Value);
+ UInt32 Converted = HostToNetwork4(&a_Value);
return WriteBuf(&Converted, 4);
}
@@ -543,7 +543,7 @@ bool cByteBuffer::WriteBEInt64(Int64 a_Value)
CHECK_THREAD;
CheckValid();
PUTBYTES(8);
- Int64 Converted = HostToNetwork8(&a_Value);
+ UInt64 Converted = HostToNetwork8(&a_Value);
return WriteBuf(&Converted, 8);
}
@@ -556,7 +556,7 @@ bool cByteBuffer::WriteBEFloat(float a_Value)
CHECK_THREAD;
CheckValid();
PUTBYTES(4);
- int Converted = HostToNetwork4(&a_Value);
+ UInt32 Converted = HostToNetwork4(&a_Value);
return WriteBuf(&Converted, 4);
}
@@ -569,7 +569,7 @@ bool cByteBuffer::WriteBEDouble(double a_Value)
CHECK_THREAD;
CheckValid();
PUTBYTES(8);
- Int64 Converted = HostToNetwork8(&a_Value);
+ UInt64 Converted = HostToNetwork8(&a_Value);
return WriteBuf(&Converted, 8);
}
@@ -613,7 +613,7 @@ bool cByteBuffer::WriteVarInt(UInt32 a_Value)
// A 32-bit integer can be encoded by at most 5 bytes:
unsigned char b[5];
- int idx = 0;
+ size_t idx = 0;
do
{
b[idx] = (a_Value & 0x7f) | ((a_Value > 0x7f) ? 0x80 : 0x00);
@@ -632,7 +632,7 @@ bool cByteBuffer::WriteVarUTF8String(const AString & a_Value)
CHECK_THREAD;
CheckValid();
PUTBYTES(a_Value.size() + 1); // This is a lower-bound on the bytes that will be actually written. Fail early.
- bool res = WriteVarInt(a_Value.size());
+ bool res = WriteVarInt((UInt32)(a_Value.size()));
if (!res)
{
return false;
@@ -757,7 +757,7 @@ bool cByteBuffer::ReadString(AString & a_String, size_t a_Count)
-bool cByteBuffer::ReadUTF16String(AString & a_String, int a_NumChars)
+bool cByteBuffer::ReadUTF16String(AString & a_String, size_t a_NumChars)
{
// Reads 2 * a_NumChars bytes and interprets it as a UTF16 string, converting it into UTF8 string a_String
CHECK_THREAD;
diff --git a/src/ByteBuffer.h b/src/ByteBuffer.h
index 7656a5b13..929c93167 100644
--- a/src/ByteBuffer.h
+++ b/src/ByteBuffer.h
@@ -101,7 +101,7 @@ public:
bool ReadString(AString & a_String, size_t a_Count);
/// Reads 2 * a_NumChars bytes and interprets it as a UTF16-BE string, converting it into UTF8 string a_String
- bool ReadUTF16String(AString & a_String, int a_NumChars);
+ bool ReadUTF16String(AString & a_String, size_t a_NumChars);
/// Skips reading by a_Count bytes; returns false if not enough bytes in the ringbuffer
bool SkipRead(size_t a_Count);
--
cgit v1.2.3
From ed75d3a8364f360b213956c40c51729ea53f3616 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 22:58:58 +0200
Subject: Fixed warnings in ClientHandle.
---
src/ClientHandle.cpp | 4 ++--
src/Protocol/Protocol.h | 2 +-
src/Protocol/Protocol125.cpp | 2 +-
src/Protocol/Protocol125.h | 2 +-
src/Protocol/Protocol17x.cpp | 2 +-
src/Protocol/Protocol17x.h | 2 +-
src/Protocol/ProtocolRecognizer.cpp | 2 +-
src/Protocol/ProtocolRecognizer.h | 2 +-
8 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index 2362abe1e..7a4158491 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -1658,7 +1658,7 @@ void cClientHandle::SendData(const char * a_Data, size_t a_Size)
{
// There is a queued overflow. Append to it, then send as much from its front as possible
m_OutgoingDataOverflow.append(a_Data, a_Size);
- int CanFit = m_OutgoingData.GetFreeSpace();
+ size_t CanFit = m_OutgoingData.GetFreeSpace();
if (CanFit > 128)
{
// No point in moving the data over if it's not large enough - too much effort for too little an effect
@@ -2522,7 +2522,7 @@ void cClientHandle::SendWindowOpen(const cWindow & a_Window)
-void cClientHandle::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value)
+void cClientHandle::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value)
{
m_Protocol->SendWindowProperty(a_Window, a_Property, a_Value);
}
diff --git a/src/Protocol/Protocol.h b/src/Protocol/Protocol.h
index 2fbeef0fa..8f152ad37 100644
--- a/src/Protocol/Protocol.h
+++ b/src/Protocol/Protocol.h
@@ -123,7 +123,7 @@ public:
virtual void SendWholeInventory (const cWindow & a_Window) = 0;
virtual void SendWindowClose (const cWindow & a_Window) = 0;
virtual void SendWindowOpen (const cWindow & a_Window) = 0;
- virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) = 0;
+ virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) = 0;
/// Returns the ServerID used for authentication through session.minecraft.net
virtual AString GetAuthServerID(void) = 0;
diff --git a/src/Protocol/Protocol125.cpp b/src/Protocol/Protocol125.cpp
index 35ab72bfc..e7873cf7a 100644
--- a/src/Protocol/Protocol125.cpp
+++ b/src/Protocol/Protocol125.cpp
@@ -1175,7 +1175,7 @@ void cProtocol125::SendWindowOpen(const cWindow & a_Window)
-void cProtocol125::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value)
+void cProtocol125::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value)
{
cCSLock Lock(m_CSPacket);
WriteByte (PACKET_WINDOW_PROPERTY);
diff --git a/src/Protocol/Protocol125.h b/src/Protocol/Protocol125.h
index 89e64f386..423e58d67 100644
--- a/src/Protocol/Protocol125.h
+++ b/src/Protocol/Protocol125.h
@@ -96,7 +96,7 @@ public:
virtual void SendWholeInventory (const cWindow & a_Window) override;
virtual void SendWindowClose (const cWindow & a_Window) override;
virtual void SendWindowOpen (const cWindow & a_Window) override;
- virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override;
+ virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) override;
virtual AString GetAuthServerID(void) override;
diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp
index a6d566625..bc9aff0c0 100644
--- a/src/Protocol/Protocol17x.cpp
+++ b/src/Protocol/Protocol17x.cpp
@@ -1383,7 +1383,7 @@ void cProtocol172::SendWindowOpen(const cWindow & a_Window)
-void cProtocol172::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value)
+void cProtocol172::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value)
{
ASSERT(m_State == 3); // In game mode?
diff --git a/src/Protocol/Protocol17x.h b/src/Protocol/Protocol17x.h
index 3f9c93357..eed761a4a 100644
--- a/src/Protocol/Protocol17x.h
+++ b/src/Protocol/Protocol17x.h
@@ -128,7 +128,7 @@ public:
virtual void SendWholeInventory (const cWindow & a_Window) override;
virtual void SendWindowClose (const cWindow & a_Window) override;
virtual void SendWindowOpen (const cWindow & a_Window) override;
- virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override;
+ virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) override;
virtual AString GetAuthServerID(void) override { return m_AuthServerID; }
diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp
index 2ccb9f197..22dfe7c88 100644
--- a/src/Protocol/ProtocolRecognizer.cpp
+++ b/src/Protocol/ProtocolRecognizer.cpp
@@ -357,7 +357,7 @@ void cProtocolRecognizer::SendHealth(void)
-void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value)
+void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value)
{
ASSERT(m_Protocol != NULL);
m_Protocol->SendWindowProperty(a_Window, a_Property, a_Value);
diff --git a/src/Protocol/ProtocolRecognizer.h b/src/Protocol/ProtocolRecognizer.h
index 408109ef4..37f47379d 100644
--- a/src/Protocol/ProtocolRecognizer.h
+++ b/src/Protocol/ProtocolRecognizer.h
@@ -131,7 +131,7 @@ public:
virtual void SendWholeInventory (const cWindow & a_Window) override;
virtual void SendWindowClose (const cWindow & a_Window) override;
virtual void SendWindowOpen (const cWindow & a_Window) override;
- virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override;
+ virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) override;
virtual AString GetAuthServerID(void) override;
--
cgit v1.2.3
From e24bdc9328278b676c7acf83fd9f31b430561b98 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 23:03:23 +0200
Subject: More ClientHandle fixes.
---
src/ClientHandle.cpp | 4 ++--
src/ClientHandle.h | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index 7a4158491..4ed0d682f 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -716,7 +716,7 @@ void cClientHandle::UnregisterPluginChannels(const AStringVector & a_ChannelList
-void cClientHandle::HandleCommandBlockMessage(const char * a_Data, unsigned int a_Length)
+void cClientHandle::HandleCommandBlockMessage(const char * a_Data, size_t a_Length)
{
if (a_Length < 14)
{
@@ -2522,7 +2522,7 @@ void cClientHandle::SendWindowOpen(const cWindow & a_Window)
-void cClientHandle::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value)
+void cClientHandle::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value)
{
m_Protocol->SendWindowProperty(a_Window, a_Property, a_Value);
}
diff --git a/src/ClientHandle.h b/src/ClientHandle.h
index 9f8d44129..9fd17ac00 100644
--- a/src/ClientHandle.h
+++ b/src/ClientHandle.h
@@ -384,7 +384,7 @@ private:
void UnregisterPluginChannels(const AStringVector & a_ChannelList);
/** Handles the "MC|AdvCdm" plugin message */
- void HandleCommandBlockMessage(const char * a_Data, unsigned int a_Length);
+ void HandleCommandBlockMessage(const char * a_Data, size_t a_Length);
// cSocketThreads::cCallback overrides:
virtual void DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client
--
cgit v1.2.3
From cb07541029bbce8a2bd46a58850af20687588978 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 23:10:37 +0200
Subject: Fixed a warning in Noise.
---
src/Noise.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Noise.h b/src/Noise.h
index 62004503f..e605051b5 100644
--- a/src/Noise.h
+++ b/src/Noise.h
@@ -280,7 +280,7 @@ NOISE_DATATYPE cNoise::CubicInterpolate(NOISE_DATATYPE a_A, NOISE_DATATYPE a_B,
NOISE_DATATYPE cNoise::CosineInterpolate(NOISE_DATATYPE a_A, NOISE_DATATYPE a_B, NOISE_DATATYPE a_Pct)
{
const NOISE_DATATYPE ft = a_Pct * (NOISE_DATATYPE)3.1415927;
- const NOISE_DATATYPE f = (1 - cos(ft)) * (NOISE_DATATYPE)0.5;
+ const NOISE_DATATYPE f = (NOISE_DATATYPE)((NOISE_DATATYPE)(1 - cos(ft)) * (NOISE_DATATYPE)0.5);
return a_A * (1 - f) + a_B * f;
}
--
cgit v1.2.3
From d950c8346fe0c89594e871f014f449e595c97706 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 23:38:35 +0200
Subject: Fixed warnings in Lua helpers.
---
src/Bindings/LuaChunkStay.cpp | 2 +-
src/Bindings/LuaFunctions.h | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/Bindings/LuaChunkStay.cpp b/src/Bindings/LuaChunkStay.cpp
index db865cfa4..985a18a95 100644
--- a/src/Bindings/LuaChunkStay.cpp
+++ b/src/Bindings/LuaChunkStay.cpp
@@ -42,7 +42,7 @@ bool cLuaChunkStay::AddChunks(int a_ChunkCoordTableStackPos)
// Add each set of coords:
int NumChunks = luaL_getn(L, a_ChunkCoordTableStackPos);
- m_Chunks.reserve(NumChunks);
+ m_Chunks.reserve((size_t)NumChunks);
for (int idx = 1; idx <= NumChunks; idx++)
{
// Push the idx-th element of the array onto stack top, check that it's a table:
diff --git a/src/Bindings/LuaFunctions.h b/src/Bindings/LuaFunctions.h
index 4f9eab86d..629e2d77d 100644
--- a/src/Bindings/LuaFunctions.h
+++ b/src/Bindings/LuaFunctions.h
@@ -4,12 +4,12 @@
#include
// tolua_begin
-unsigned int GetTime()
+inline unsigned int GetTime()
{
return (unsigned int)time(0);
}
-std::string GetChar( std::string & a_Str, unsigned int a_Idx )
+inline std::string GetChar( std::string & a_Str, unsigned int a_Idx )
{
return std::string(1, a_Str[ a_Idx ]);
}
--
cgit v1.2.3
From 06da2c86b4b9408f8189eded7e302eb467522d31 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Thu, 1 May 2014 23:43:11 +0200
Subject: Fixed warnings in ManualBindings.
---
src/Bindings/ManualBindings.cpp | 40 ++++++++++++++++++++--------------------
1 file changed, 20 insertions(+), 20 deletions(-)
diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp
index b3f75aff1..10e560ac0 100644
--- a/src/Bindings/ManualBindings.cpp
+++ b/src/Bindings/ManualBindings.cpp
@@ -37,7 +37,7 @@
/****************************
* Better error reporting for Lua
**/
-int tolua_do_error(lua_State* L, const char * a_pMsg, tolua_Error * a_pToLuaError)
+static int tolua_do_error(lua_State* L, const char * a_pMsg, tolua_Error * a_pToLuaError)
{
// Retrieve current function name
lua_Debug entry;
@@ -57,7 +57,7 @@ int tolua_do_error(lua_State* L, const char * a_pMsg, tolua_Error * a_pToLuaErro
-int lua_do_error(lua_State* L, const char * a_pFormat, ...)
+static int lua_do_error(lua_State* L, const char * a_pFormat, ...)
{
// Retrieve current function name
lua_Debug entry;
@@ -235,7 +235,7 @@ static int tolua_Base64Decode(lua_State * tolua_S)
-cPluginLua * GetLuaPlugin(lua_State * L)
+static cPluginLua * GetLuaPlugin(lua_State * L)
{
// Get the plugin identification out of LuaState:
lua_getglobal(L, LUA_PLUGIN_INSTANCE_VAR_NAME);
@@ -1776,20 +1776,20 @@ static int tolua_cWorld_ChunkStay(lua_State * tolua_S)
-static int tolua_cPlayer_GetGroups(lua_State* tolua_S)
+static int tolua_cPlayer_GetGroups(lua_State * tolua_S)
{
- cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S, 1, NULL);
+ cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL);
const cPlayer::GroupList & AllGroups = self->GetGroups();
- lua_createtable(tolua_S, AllGroups.size(), 0);
+ lua_createtable(tolua_S, (int)AllGroups.size(), 0);
int newTable = lua_gettop(tolua_S);
int index = 1;
cPlayer::GroupList::const_iterator iter = AllGroups.begin();
- while(iter != AllGroups.end())
+ while (iter != AllGroups.end())
{
- const cGroup* Group = *iter;
- tolua_pushusertype( tolua_S, (void*)Group, "const cGroup" );
+ const cGroup * Group = *iter;
+ tolua_pushusertype(tolua_S, (void *)Group, "const cGroup");
lua_rawseti(tolua_S, newTable, index);
++iter;
++index;
@@ -1801,20 +1801,20 @@ static int tolua_cPlayer_GetGroups(lua_State* tolua_S)
-static int tolua_cPlayer_GetResolvedPermissions(lua_State* tolua_S)
+static int tolua_cPlayer_GetResolvedPermissions(lua_State * tolua_S)
{
- cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S, 1, NULL);
+ cPlayer * self = (cPlayer*) tolua_tousertype(tolua_S, 1, NULL);
cPlayer::StringList AllPermissions = self->GetResolvedPermissions();
- lua_createtable(tolua_S, AllPermissions.size(), 0);
+ lua_createtable(tolua_S, (int)AllPermissions.size(), 0);
int newTable = lua_gettop(tolua_S);
int index = 1;
cPlayer::StringList::iterator iter = AllPermissions.begin();
- while(iter != AllPermissions.end())
+ while (iter != AllPermissions.end())
{
- std::string& Permission = *iter;
- tolua_pushstring( tolua_S, Permission.c_str() );
+ std::string & Permission = *iter;
+ lua_pushlstring(tolua_S, Permission.c_str(), Permission.length());
lua_rawseti(tolua_S, newTable, index);
++iter;
++index;
@@ -2076,18 +2076,18 @@ static int tolua_get_HTTPRequest_FormData(lua_State* tolua_S)
static int tolua_cWebAdmin_GetPlugins(lua_State * tolua_S)
{
- cWebAdmin* self = (cWebAdmin*) tolua_tousertype(tolua_S, 1, NULL);
+ cWebAdmin * self = (cWebAdmin *)tolua_tousertype(tolua_S, 1, NULL);
const cWebAdmin::PluginList & AllPlugins = self->GetPlugins();
- lua_createtable(tolua_S, AllPlugins.size(), 0);
+ lua_createtable(tolua_S, (int)AllPlugins.size(), 0);
int newTable = lua_gettop(tolua_S);
int index = 1;
cWebAdmin::PluginList::const_iterator iter = AllPlugins.begin();
- while(iter != AllPlugins.end())
+ while (iter != AllPlugins.end())
{
- const cWebPlugin* Plugin = *iter;
- tolua_pushusertype( tolua_S, (void*)Plugin, "const cWebPlugin" );
+ const cWebPlugin * Plugin = *iter;
+ tolua_pushusertype(tolua_S, (void *)Plugin, "const cWebPlugin");
lua_rawseti(tolua_S, newTable, index);
++iter;
++index;
--
cgit v1.2.3
From 4d704255de1368d7d9912458053c2de14be1b5ac Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Fri, 2 May 2014 11:18:02 +0200
Subject: HOOK_DISCONNECT has cClientHandle as its first parameter.
Ref.: #655.
---
src/Bindings/Plugin.h | 2 +-
src/Bindings/PluginLua.cpp | 4 ++--
src/Bindings/PluginLua.h | 2 +-
src/Bindings/PluginManager.cpp | 4 ++--
src/Bindings/PluginManager.h | 2 +-
src/ClientHandle.cpp | 6 +++---
6 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/src/Bindings/Plugin.h b/src/Bindings/Plugin.h
index df0bd4dcc..0bd9270c4 100644
--- a/src/Bindings/Plugin.h
+++ b/src/Bindings/Plugin.h
@@ -56,7 +56,7 @@ public:
virtual bool OnChunkUnloading (cWorld * a_World, int a_ChunkX, int a_ChunkZ) = 0;
virtual bool OnCollectingPickup (cPlayer * a_Player, cPickup * a_Pickup) = 0;
virtual bool OnCraftingNoRecipe (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0;
- virtual bool OnDisconnect (cPlayer * a_Player, const AString & a_Reason) = 0;
+ virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) = 0;
virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split) = 0;
virtual bool OnExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0;
virtual bool OnExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0;
diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp
index cb55715a6..59708bf59 100644
--- a/src/Bindings/PluginLua.cpp
+++ b/src/Bindings/PluginLua.cpp
@@ -400,14 +400,14 @@ bool cPluginLua::OnCraftingNoRecipe(const cPlayer * a_Player, const cCraftingGri
-bool cPluginLua::OnDisconnect(cPlayer * a_Player, const AString & a_Reason)
+bool cPluginLua::OnDisconnect(cClientHandle & a_Client, const AString & a_Reason)
{
cCSLock Lock(m_CriticalSection);
bool res = false;
cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_DISCONNECT];
for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr)
{
- m_LuaState.Call((int)(**itr), a_Player, a_Reason, cLuaState::Return, res);
+ m_LuaState.Call((int)(**itr), &a_Client, a_Reason, cLuaState::Return, res);
if (res)
{
return true;
diff --git a/src/Bindings/PluginLua.h b/src/Bindings/PluginLua.h
index 59542d23a..3357dd87b 100644
--- a/src/Bindings/PluginLua.h
+++ b/src/Bindings/PluginLua.h
@@ -79,7 +79,7 @@ public:
virtual bool OnChunkUnloading (cWorld * a_World, int a_ChunkX, int a_ChunkZ) override;
virtual bool OnCollectingPickup (cPlayer * a_Player, cPickup * a_Pickup) override;
virtual bool OnCraftingNoRecipe (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override;
- virtual bool OnDisconnect (cPlayer * a_Player, const AString & a_Reason) override;
+ virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) override;
virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split) override;
virtual bool OnExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) override;
virtual bool OnExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) override;
diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp
index 6a5356c0b..aaccc606d 100644
--- a/src/Bindings/PluginManager.cpp
+++ b/src/Bindings/PluginManager.cpp
@@ -442,7 +442,7 @@ bool cPluginManager::CallHookCraftingNoRecipe(const cPlayer * a_Player, const cC
-bool cPluginManager::CallHookDisconnect(cPlayer * a_Player, const AString & a_Reason)
+bool cPluginManager::CallHookDisconnect(cClientHandle & a_Client, const AString & a_Reason)
{
HookMap::iterator Plugins = m_Hooks.find(HOOK_DISCONNECT);
if (Plugins == m_Hooks.end())
@@ -451,7 +451,7 @@ bool cPluginManager::CallHookDisconnect(cPlayer * a_Player, const AString & a_Re
}
for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr)
{
- if ((*itr)->OnDisconnect(a_Player, a_Reason))
+ if ((*itr)->OnDisconnect(a_Client, a_Reason))
{
return true;
}
diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h
index 512bc1351..58c1cebb4 100644
--- a/src/Bindings/PluginManager.h
+++ b/src/Bindings/PluginManager.h
@@ -172,7 +172,7 @@ public: // tolua_export
bool CallHookChunkUnloading (cWorld * a_World, int a_ChunkX, int a_ChunkZ);
bool CallHookCollectingPickup (cPlayer * a_Player, cPickup & a_Pickup);
bool CallHookCraftingNoRecipe (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe);
- bool CallHookDisconnect (cPlayer * a_Player, const AString & a_Reason);
+ bool CallHookDisconnect (cClientHandle & a_Client, const AString & a_Reason);
bool CallHookExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split); // If a_Player == NULL, it is a console cmd
bool CallHookExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData);
bool CallHookExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData);
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index 4ed0d682f..29213ca2d 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -1510,7 +1510,7 @@ void cClientHandle::HandleDisconnect(const AString & a_Reason)
{
LOGD("Received d/c packet from %s with reason \"%s\"", m_Username.c_str(), a_Reason.c_str());
- cRoot::Get()->GetPluginManager()->CallHookDisconnect(m_Player, a_Reason);
+ cRoot::Get()->GetPluginManager()->CallHookDisconnect(*this, a_Reason);
m_HasSentDC = true;
Destroy();
@@ -2689,9 +2689,9 @@ void cClientHandle::SocketClosed(void)
LOGD("Player %s @ %s disconnected", m_Username.c_str(), m_IPString.c_str());
- if (m_Username != "") // Ignore client pings
+ if (!m_Username.empty()) // Ignore client pings
{
- cRoot::Get()->GetPluginManager()->CallHookDisconnect(m_Player, "Player disconnected");
+ cRoot::Get()->GetPluginManager()->CallHookDisconnect(*this, "Player disconnected");
}
Destroy();
--
cgit v1.2.3
From 0cfa0c45610cbe5c7ae6a03034f81416699247c4 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Fri, 2 May 2014 12:23:01 +0200
Subject: APIDump: Improved error handling in API file loader.
---
MCServer/Plugins/APIDump/main_APIDump.lua | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/MCServer/Plugins/APIDump/main_APIDump.lua b/MCServer/Plugins/APIDump/main_APIDump.lua
index 52199740b..a25bab9cf 100644
--- a/MCServer/Plugins/APIDump/main_APIDump.lua
+++ b/MCServer/Plugins/APIDump/main_APIDump.lua
@@ -27,10 +27,14 @@ local function LoadAPIFiles(a_Folder, a_DstTable)
-- We only want .lua files from the folder:
if (cFile:IsFile(FileName) and fnam:match(".*%.lua$")) then
local TablesFn, Err = loadfile(FileName);
- if (TablesFn == nil) then
+ if (type(TablesFn) ~= "function") then
LOGWARNING("Cannot load API descriptions from " .. FileName .. ", Lua error '" .. Err .. "'.");
else
local Tables = TablesFn();
+ if (type(Tables) ~= "table") then
+ LOGWARNING("Cannot load API descriptions from " .. FileName .. ", returned object is not a table (" .. type(Tables) .. ").");
+ break
+ end
for k, cls in pairs(Tables) do
a_DstTable[k] = cls;
end
--
cgit v1.2.3
From 13452d3ab92c1cc12201caf60782fd7f7c4314f7 Mon Sep 17 00:00:00 2001
From: madmaxoft
Date: Fri, 2 May 2014 12:23:22 +0200
Subject: APIDump: Updated the OnDisconnect hook docs.
Ref.: #655.
---
MCServer/Plugins/APIDump/Hooks/OnDisconnect.lua | 24 +++++++++++++++++-------
1 file changed, 17 insertions(+), 7 deletions(-)
diff --git a/MCServer/Plugins/APIDump/Hooks/OnDisconnect.lua b/MCServer/Plugins/APIDump/Hooks/OnDisconnect.lua
index a3301a8c6..204cb63d2 100644
--- a/MCServer/Plugins/APIDump/Hooks/OnDisconnect.lua
+++ b/MCServer/Plugins/APIDump/Hooks/OnDisconnect.lua
@@ -2,23 +2,33 @@ return
{
HOOK_DISCONNECT =
{
- CalledWhen = "A player has explicitly disconnected.",
+ CalledWhen = [[
+ A client has disconnected, either by explicitly sending the disconnect packet (in older protocols) or
+ their connection was terminated
+ ]],
DefaultFnName = "OnDisconnect", -- also used as pagename
Desc = [[
- This hook is called when a client is about to be disconnected from the server, for whatever reason.
-
-
Note that this hook will be removed after <1.7 protocol support is removed, as it was originally a hook for
- the client sending the server a disconnect packet, which no longer happens.
+ This hook is called when a client has disconnected from the server, for whatever reason. It is also
+ called when the client sends the Disconnect packet (only in pre-1.7 protocols). This hook is not called
+ for server ping connections.
+
+ Note that the hook is called even for connections to players who failed to auth. In such a case there's
+ no {{cPlayer}} object associated with the client.