From ff18400535e617cb5eac86897bf400bd61848927 Mon Sep 17 00:00:00 2001 From: narroo Date: Mon, 28 Apr 2014 15:35:26 -0400 Subject: Added some E_META_* values to BlockID.h --- src/BlockID.h | 140 +++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 120 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index a227245aa..4949ac528 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -401,6 +401,14 @@ enum /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Block metas: + // E_BLOCK_BED metas: + E_BLOCK_BED_SOUTH = 0, + E_BLOCK_BED_WEST = 1, + E_BLOCK_BED_NORTH = 2, + E_BLOCK_BED_EAST = 3, + E_BLOCK_BED_OCCUPIED = 4, + E_BLOCK_BED_BED_HEAD = 8, + // E_BLOCK_BIG_FLOWER metas E_META_BIG_FLOWER_SUNFLOWER = 0, E_META_BIG_FLOWER_LILAC = 1, @@ -447,14 +455,17 @@ enum E_META_DROPSPENSER_FACING_XP = 5, // E_BLOCK_DOUBLE_STONE_SLAB metas: - E_META_DOUBLE_STONE_SLAB_STONE = 0, - E_META_DOUBLE_STONE_SLAB_SANDSTONE = 1, - E_META_DOUBLE_STONE_SLAB_WOODEN = 2, - E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, - E_META_DOUBLE_STONE_SLAB_BRICK = 4, - E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, - E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, - E_META_DOUBLE_STONE_SLAB_STONE_SECRET = 7, + E_META_DOUBLE_STONE_SLAB_STONE = 0, + E_META_DOUBLE_STONE_SLAB_SANDSTONE = 1, + E_META_DOUBLE_STONE_SLAB_WOODEN = 2, + E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, + E_META_DOUBLE_STONE_SLAB_BRICK = 4, + E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, + E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, + E_META_DOUBLE_STONE_SLAB_QUARTZ = 7, + E_META_DOUBLE_STONE_SLAB_SMOOTH_STONE = 8, + E_META_DOUBLE_STONE_SLAB_SMOOTH_SANDSTONE = 9, + E_META_DOUBLE_STONE_SLAB_TILE_QUARTZ = 10, // E_BLOCK_FLOWER metas E_META_FLOWER_POPPY = 0, @@ -483,6 +494,28 @@ enum E_META_LEAVES_CONIFER = 1, E_META_LEAVES_BIRCH = 2, E_META_LEAVES_JUNGLE = 3, + E_META_LEAVES_APPLE_NO_DECAY = 4, + E_META_LEAVES_CONIFER_NO_DECAY = 5, + E_META_LEAVES_BIRCH_NO_DECAY = 6, + E_META_LEAVES_JUNGLE_NO_DECAY = 7, + E_META_LEAVES_APPLE_CHECK_DECAY = 8, + E_META_LEAVES_CONIFER_CHECK_DECAY = 9, + E_META_LEAVES_BIRCH_CHECK_DECAY = 10, + E_META_LEAVES_JUNGLE_CHECK_DECAY = 11, + E_META_LEAVES_APPLE_NO_DECAY_AND_CHECK_DECAY = 12, + E_META_LEAVES_CONIFER_NO_DECAY_AND_CHECK_DECAY = 13, + E_META_LEAVES_BIRCH_NO_DECAY_AND_CHECK_DECAY = 14, + E_META_LEAVES_JUNGLE_NO_DECAY_AND_CHECK_DECAY = 15, + + // E_BLOCK_LEAVES meta cont. (Block ID 161): + E_META_LEAVES_ACACIA = 0, + E_META_LEAVES_DARK_OAK = 1, + E_META_LEAVES_ACACIA_NO_DECAY = 4, + E_META_LEAVES_DARK_OAK_NO_DECAY = 5, + E_META_LEAVES_ACACIA_CHECK_DECAY = 8, + E_META_LEAVES_DARK_OAK_CHECK_DECAY = 9, + E_META_LEAVES_ACACIA_NO_DECAY_CHECK_DECAY = 12, + E_META_LEAVES_DARK_OAK_NO_DECAY_CHECK_DECAY = 13, // E_BLOCK_LOG metas: E_META_LOG_APPLE = 0, @@ -498,11 +531,23 @@ enum E_META_NEW_LOG_ACACIA_WOOD = 0, E_META_NEW_LOG_DARK_OAK_WOOD = 1, + // E_BLOCK_PISTON metas: + E_META_PISTON_DOWN = 0, + E_META_PISTON_UP = 1, + E_META_PISTON_NORTH = 2, + E_META_PISTON_SOUTH = 3, + E_META_PISTON_WEST = 4, + E_META_PISTON_EAST = 5, + E_META_PISTON_HEAD_STICKY = 8, + E_META_PISTON_EXTENDED = 8, + // E_BLOCK_PLANKS metas: E_META_PLANKS_APPLE = 0, E_META_PLANKS_CONIFER = 1, E_META_PLANKS_BIRCH = 2, E_META_PLANKS_JUNGLE = 3, + E_META_PLANKS_ACACIA = 4, + E_META_PLANKS_DARK_OAK= 5, // E_BLOCK_(XXX_WEIGHTED)_PRESSURE_PLATE metas: E_META_PRESSURE_PLATE_RAISED = 0, @@ -611,15 +656,31 @@ enum E_META_STAINED_GLASS_PANE_RED = 14, E_META_STAINED_GLASS_PANE_BLACK = 15, + // E_BLOCK_STAIRS metas: + E_BLOCK_STAIRS_EAST = 0, + E_BLOCK_STAIRS_WEST = 1, + E_BLOCK_STAIRS_SOUTH = 2, + E_BLOCK_STAIRS_NORTH = 3, + E_BLOCK_STAIRS_UPSIDE_DOWN = 4, + + // E_BLOCK_STONE metas: + E_META_STONE_STONE = 0, + E_META_STONE_GRANITE = 1, + E_META_STONE_POLISHED_GRANITE = 2, + E_META_STONE_DIORITE = 3, + E_META_STONE_POLISHED_DIORITE = 4, + E_META_STONE_ANDESITE = 5, + E_META_STONE_POLISHED_ANDESITE = 6, + // E_BLOCK_STONE_SLAB metas: - E_META_STONE_SLAB_STONE = 0, - E_META_STONE_SLAB_SANDSTONE = 1, - E_META_STONE_SLAB_PLANKS = 2, - E_META_STONE_SLAB_COBBLESTONE = 3, - E_META_STONE_SLAB_BRICK = 4, - E_META_STONE_SLAB_STONE_BRICK = 5, - E_META_STONE_SLAB_NETHER_BRICK = 6, - E_META_STONE_SLAB_STONE_SECRET = 7, + E_META_STONE_SLAB_STONE = 0, + E_META_STONE_SLAB_SANDSTONE = 1, + E_META_STONE_SLAB_PLANKS = 2, + E_META_STONE_SLAB_COBBLESTONE = 3, + E_META_STONE_SLAB_BRICK = 4, + E_META_STONE_SLAB_STONE_BRICK = 5, + E_META_STONE_SLAB_NETHER_BRICK = 6, + E_META_STONE_SLAB_QUARTZ = 7, // E_BLOCK_STONE_BRICKS metas: E_META_STONE_BRICK_NORMAL = 0, @@ -628,9 +689,10 @@ enum E_META_STONE_BRICK_ORNAMENT = 3, // E_BLOCK_TALL_GRASS metas: - E_META_TALL_GRASS_DEAD_SHRUB = 0, - E_META_TALL_GRASS_GRASS = 1, - E_META_TALL_GRASS_FERN = 2, + E_META_TALL_GRASS_DEAD_SHRUB = 0, + E_META_TALL_GRASS_GRASS = 1, + E_META_TALL_GRASS_FERN = 2, + E_META_TALL_GRASS_BIOME = 3, // E_BLOCK_TORCH, E_BLOCK_REDSTONE_TORCH_OFF, E_BLOCK_REDSTONE_TORCH_ON metas: E_META_TORCH_EAST = 1, // east face of the block, pointing east @@ -642,7 +704,43 @@ enum E_META_TORCH_XP = 2, // Torch attached to the XP side of its block E_META_TORCH_ZM = 3, // Torch attached to the ZM side of its block E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block - + + // E_BLOCK_WOOD metas: + E_BLOCK_WOOD_OAK_UP_DOWN = 0, + E_BLOCK_WOOD_SPRUCE_UP_DOWN = 1, + E_BLOCK_WOOD_BIRCH_UP_DOWN = 2, + E_BLOCK_WOOD_JUNGLE_UP_DOWN = 3, + E_BLOCK_WOOD_OAK_EAST_WEST = 4, + E_BLOCK_WOOD_SPRUCE_EAST_WEST = 5, + E_BLOCK_WOOD_BIRCH_EAST_WEST = 6, + E_BLOCK_WOOD_JUNGLE_EAST_WEST = 7, + E_BLOCK_WOOD_OAK_NORTH_SOUTH = 8, + E_BLOCK_WOOD_SPRUCE_NORTH_SOUTH = 9, + E_BLOCK_WOOD_BIRCH_NORTH_SOUTH = 10, + E_BLOCK_WOOD_JUNGLE_NORTH_SOUTH = 11, + E_BLOCK_WOOD_OAK_BARK_ONLY = 12, + E_BLOCK_WOOD_SPRUCE_BARK_ONLY = 13, + E_BLOCK_WOOD_BIRCH_BARK_ONLY = 14, + E_BLOCK_WOOD_JUNGLE_BARK_ONLY = 15, + + // E_BLOCK_WOOD metas cont. (Block ID 162): + E_BLOCK_WOOD_ACACIA_UP_DOWN = 0, + E_BLOCK_WOOD_DARK_OAK_UP_DOWN = 1, + E_BLOCK_WOOD_ACACIA_UP_DOWN = 2, + E_BLOCK_WOOD_DARK_OAK_UP_DOWN = 3, + E_BLOCK_WOOD_ACACIA_EAST_WEST = 4, + E_BLOCK_WOOD_DARK_OAK_EAST_WEST = 5, + E_BLOCK_WOOD_ACACIA_EAST_WEST = 6, + E_BLOCK_WOOD_DARK_OAK_EAST_WEST = 7, + E_BLOCK_WOOD_ACACIA_NORTH_SOUTH = 8, + E_BLOCK_WOOD_DARK_OAK_NORTH_SOUTH = 9, + E_BLOCK_WOOD_ACACIA_NORTH_SOUTH = 10, + E_BLOCK_WOOD_DARK_OAK_NORTH_SOUTH = 11, + E_BLOCK_WOOD_ACACIA_BARK_ONLY = 12, + E_BLOCK_WOOD_DARK_OAK_BARK_ONLY = 13, + E_BLOCK_WOOD_ACACIA_BARK_ONLY = 14, + E_BLOCK_WOOD_DARK_OAK_BARK_ONLY = 15, + // E_BLOCK_WOODEN_DOUBLE_SLAB metas: E_META_WOODEN_DOUBLE_SLAB_APPLE = 0, E_META_WOODEN_DOUBLE_SLAB_CONIFER = 1, @@ -658,6 +756,8 @@ enum E_META_WOODEN_SLAB_JUNGLE = 3, E_META_WOODEN_SLAB_ACACIA = 4, E_META_WOODEN_SLAB_DARK_OAK = 5, + E_META_WOODEN_SLAB_RIGHT_SIDE_UP = 0, + E_META_WOODWN_SLAB_UPSIDE_DOWN = 8, // E_BLOCK_WOOL metas: E_META_WOOL_WHITE = 0, -- cgit v1.2.3 From f4fa3985b55a98d8c6a404df24bfd5a8ba5056c0 Mon Sep 17 00:00:00 2001 From: narroo Date: Mon, 28 Apr 2014 15:49:34 -0400 Subject: Fixed Formmating --- src/BlockID.h | 138 +++++++++++++++++++++++++++++----------------------------- 1 file changed, 69 insertions(+), 69 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 4949ac528..8cc3f6397 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -455,17 +455,17 @@ enum E_META_DROPSPENSER_FACING_XP = 5, // E_BLOCK_DOUBLE_STONE_SLAB metas: - E_META_DOUBLE_STONE_SLAB_STONE = 0, - E_META_DOUBLE_STONE_SLAB_SANDSTONE = 1, - E_META_DOUBLE_STONE_SLAB_WOODEN = 2, - E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, - E_META_DOUBLE_STONE_SLAB_BRICK = 4, - E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, - E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, - E_META_DOUBLE_STONE_SLAB_QUARTZ = 7, - E_META_DOUBLE_STONE_SLAB_SMOOTH_STONE = 8, - E_META_DOUBLE_STONE_SLAB_SMOOTH_SANDSTONE = 9, - E_META_DOUBLE_STONE_SLAB_TILE_QUARTZ = 10, + E_META_DOUBLE_STONE_SLAB_STONE = 0, + E_META_DOUBLE_STONE_SLAB_SANDSTON = 1, + E_META_DOUBLE_STONE_SLAB_WOODEN = 2, + E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, + E_META_DOUBLE_STONE_SLAB_BRICK = 4, + E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, + E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, + E_META_DOUBLE_STONE_SLAB_QUARTZ = 7, + E_META_DOUBLE_STONE_SLAB_SMOOTH_STONE = 8, + E_META_DOUBLE_STONE_SLAB_SMOOTH_SANDSTONE = 9, + E_META_DOUBLE_STONE_SLAB_TILE_QUARTZ = 10, // E_BLOCK_FLOWER metas E_META_FLOWER_POPPY = 0, @@ -508,14 +508,14 @@ enum E_META_LEAVES_JUNGLE_NO_DECAY_AND_CHECK_DECAY = 15, // E_BLOCK_LEAVES meta cont. (Block ID 161): - E_META_LEAVES_ACACIA = 0, - E_META_LEAVES_DARK_OAK = 1, - E_META_LEAVES_ACACIA_NO_DECAY = 4, - E_META_LEAVES_DARK_OAK_NO_DECAY = 5, - E_META_LEAVES_ACACIA_CHECK_DECAY = 8, - E_META_LEAVES_DARK_OAK_CHECK_DECAY = 9, - E_META_LEAVES_ACACIA_NO_DECAY_CHECK_DECAY = 12, - E_META_LEAVES_DARK_OAK_NO_DECAY_CHECK_DECAY = 13, + E_META_LEAVES_ACACIA = 0, + E_META_LEAVES_DARK_OAK = 1, + E_META_LEAVES_ACACIA_NO_DECAY = 4, + E_META_LEAVES_DARK_OAK_NO_DECAY = 5, + E_META_LEAVES_ACACIA_CHECK_DECAY = 8, + E_META_LEAVES_DARK_OAK_CHECK_DECAY = 9, + E_META_LEAVES_ACACIA_NO_DECAY_CHECK_DECAY = 12, + E_META_LEAVES_DARK_OAK_NO_DECAY_CHECK_DECAY = 13, // E_BLOCK_LOG metas: E_META_LOG_APPLE = 0, @@ -532,14 +532,14 @@ enum E_META_NEW_LOG_DARK_OAK_WOOD = 1, // E_BLOCK_PISTON metas: - E_META_PISTON_DOWN = 0, - E_META_PISTON_UP = 1, - E_META_PISTON_NORTH = 2, - E_META_PISTON_SOUTH = 3, - E_META_PISTON_WEST = 4, - E_META_PISTON_EAST = 5, - E_META_PISTON_HEAD_STICKY = 8, - E_META_PISTON_EXTENDED = 8, + E_META_PISTON_DOWN = 0, + E_META_PISTON_UP = 1, + E_META_PISTON_NORTH = 2, + E_META_PISTON_SOUTH = 3, + E_META_PISTON_WEST = 4, + E_META_PISTON_EAST = 5, + E_META_PISTON_HEAD_STICKY = 8, + E_META_PISTON_EXTENDED = 8, // E_BLOCK_PLANKS metas: E_META_PLANKS_APPLE = 0, @@ -657,30 +657,30 @@ enum E_META_STAINED_GLASS_PANE_BLACK = 15, // E_BLOCK_STAIRS metas: - E_BLOCK_STAIRS_EAST = 0, - E_BLOCK_STAIRS_WEST = 1, - E_BLOCK_STAIRS_SOUTH = 2, - E_BLOCK_STAIRS_NORTH = 3, - E_BLOCK_STAIRS_UPSIDE_DOWN = 4, + E_BLOCK_STAIRS_EAST = 0, + E_BLOCK_STAIRS_WEST = 1, + E_BLOCK_STAIRS_SOUTH = 2, + E_BLOCK_STAIRS_NORTH = 3, + E_BLOCK_STAIRS_UPSIDE_DOWN = 4, // E_BLOCK_STONE metas: - E_META_STONE_STONE = 0, - E_META_STONE_GRANITE = 1, - E_META_STONE_POLISHED_GRANITE = 2, - E_META_STONE_DIORITE = 3, - E_META_STONE_POLISHED_DIORITE = 4, - E_META_STONE_ANDESITE = 5, - E_META_STONE_POLISHED_ANDESITE = 6, + E_META_STONE_STONE = 0, + E_META_STONE_GRANITE = 1, + E_META_STONE_POLISHED_GRANITE = 2, + E_META_STONE_DIORITE = 3, + E_META_STONE_POLISHED_DIORITE = 4, + E_META_STONE_ANDESITE = 5, + E_META_STONE_POLISHED_ANDESITE = 6, // E_BLOCK_STONE_SLAB metas: - E_META_STONE_SLAB_STONE = 0, - E_META_STONE_SLAB_SANDSTONE = 1, - E_META_STONE_SLAB_PLANKS = 2, - E_META_STONE_SLAB_COBBLESTONE = 3, - E_META_STONE_SLAB_BRICK = 4, - E_META_STONE_SLAB_STONE_BRICK = 5, - E_META_STONE_SLAB_NETHER_BRICK = 6, - E_META_STONE_SLAB_QUARTZ = 7, + E_META_STONE_SLAB_STONE = 0, + E_META_STONE_SLAB_SANDSTONE = 1, + E_META_STONE_SLAB_PLANKS = 2, + E_META_STONE_SLAB_COBBLESTONE = 3, + E_META_STONE_SLAB_BRICK = 4, + E_META_STONE_SLAB_STONE_BRICK = 5, + E_META_STONE_SLAB_NETHER_BRICK = 6, + E_META_STONE_SLAB_QUARTZ = 7, // E_BLOCK_STONE_BRICKS metas: E_META_STONE_BRICK_NORMAL = 0, @@ -689,10 +689,10 @@ enum E_META_STONE_BRICK_ORNAMENT = 3, // E_BLOCK_TALL_GRASS metas: - E_META_TALL_GRASS_DEAD_SHRUB = 0, - E_META_TALL_GRASS_GRASS = 1, - E_META_TALL_GRASS_FERN = 2, - E_META_TALL_GRASS_BIOME = 3, + E_META_TALL_GRASS_DEAD_SHRUB = 0, + E_META_TALL_GRASS_GRASS = 1, + E_META_TALL_GRASS_FERN = 2, + E_META_TALL_GRASS_BIOME = 3, // E_BLOCK_TORCH, E_BLOCK_REDSTONE_TORCH_OFF, E_BLOCK_REDSTONE_TORCH_ON metas: E_META_TORCH_EAST = 1, // east face of the block, pointing east @@ -706,22 +706,22 @@ enum E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block // E_BLOCK_WOOD metas: - E_BLOCK_WOOD_OAK_UP_DOWN = 0, - E_BLOCK_WOOD_SPRUCE_UP_DOWN = 1, - E_BLOCK_WOOD_BIRCH_UP_DOWN = 2, - E_BLOCK_WOOD_JUNGLE_UP_DOWN = 3, - E_BLOCK_WOOD_OAK_EAST_WEST = 4, - E_BLOCK_WOOD_SPRUCE_EAST_WEST = 5, - E_BLOCK_WOOD_BIRCH_EAST_WEST = 6, - E_BLOCK_WOOD_JUNGLE_EAST_WEST = 7, - E_BLOCK_WOOD_OAK_NORTH_SOUTH = 8, - E_BLOCK_WOOD_SPRUCE_NORTH_SOUTH = 9, - E_BLOCK_WOOD_BIRCH_NORTH_SOUTH = 10, - E_BLOCK_WOOD_JUNGLE_NORTH_SOUTH = 11, - E_BLOCK_WOOD_OAK_BARK_ONLY = 12, - E_BLOCK_WOOD_SPRUCE_BARK_ONLY = 13, - E_BLOCK_WOOD_BIRCH_BARK_ONLY = 14, - E_BLOCK_WOOD_JUNGLE_BARK_ONLY = 15, + E_BLOCK_WOOD_OAK_UP_DOWN = 0, + E_BLOCK_WOOD_SPRUCE_UP_DOWN = 1, + E_BLOCK_WOOD_BIRCH_UP_DOWN = 2, + E_BLOCK_WOOD_JUNGLE_UP_DOWN = 3, + E_BLOCK_WOOD_OAK_EAST_WEST = 4, + E_BLOCK_WOOD_SPRUCE_EAST_WEST = 5, + E_BLOCK_WOOD_BIRCH_EAST_WEST = 6, + E_BLOCK_WOOD_JUNGLE_EAST_WEST = 7, + E_BLOCK_WOOD_OAK_NORTH_SOUTH = 8, + E_BLOCK_WOOD_SPRUCE_NORTH_SOUTH = 9, + E_BLOCK_WOOD_BIRCH_NORTH_SOUTH = 10, + E_BLOCK_WOOD_JUNGLE_NORTH_SOUTH = 11, + E_BLOCK_WOOD_OAK_BARK_ONLY = 12, + E_BLOCK_WOOD_SPRUCE_BARK_ONLY = 13, + E_BLOCK_WOOD_BIRCH_BARK_ONLY = 14, + E_BLOCK_WOOD_JUNGLE_BARK_ONLY = 15, // E_BLOCK_WOOD metas cont. (Block ID 162): E_BLOCK_WOOD_ACACIA_UP_DOWN = 0, @@ -756,8 +756,8 @@ enum E_META_WOODEN_SLAB_JUNGLE = 3, E_META_WOODEN_SLAB_ACACIA = 4, E_META_WOODEN_SLAB_DARK_OAK = 5, - E_META_WOODEN_SLAB_RIGHT_SIDE_UP = 0, - E_META_WOODWN_SLAB_UPSIDE_DOWN = 8, + E_META_WOODEN_SLAB_RIGHT_SIDE_UP = 0, + E_META_WOODWN_SLAB_UPSIDE_DOWN = 8, // E_BLOCK_WOOL metas: E_META_WOOL_WHITE = 0, -- cgit v1.2.3 From a1b3e51aba7346f1a4cd7a1555cc8b9cd73b59e0 Mon Sep 17 00:00:00 2001 From: narroo Date: Tue, 20 May 2014 11:10:22 -0400 Subject: Fixed some E_META_*** Names --- src/BlockID.h | 138 ++++++++++++++++++++++++++++------------------------------ 1 file changed, 67 insertions(+), 71 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 8cc3f6397..32943ea67 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -490,38 +490,34 @@ enum E_META_HOPPER_FACING_XP = 5, // E_BLOCK_LEAVES metas: - E_META_LEAVES_APPLE = 0, - E_META_LEAVES_CONIFER = 1, - E_META_LEAVES_BIRCH = 2, - E_META_LEAVES_JUNGLE = 3, - E_META_LEAVES_APPLE_NO_DECAY = 4, - E_META_LEAVES_CONIFER_NO_DECAY = 5, - E_META_LEAVES_BIRCH_NO_DECAY = 6, - E_META_LEAVES_JUNGLE_NO_DECAY = 7, - E_META_LEAVES_APPLE_CHECK_DECAY = 8, - E_META_LEAVES_CONIFER_CHECK_DECAY = 9, - E_META_LEAVES_BIRCH_CHECK_DECAY = 10, - E_META_LEAVES_JUNGLE_CHECK_DECAY = 11, - E_META_LEAVES_APPLE_NO_DECAY_AND_CHECK_DECAY = 12, - E_META_LEAVES_CONIFER_NO_DECAY_AND_CHECK_DECAY = 13, - E_META_LEAVES_BIRCH_NO_DECAY_AND_CHECK_DECAY = 14, - E_META_LEAVES_JUNGLE_NO_DECAY_AND_CHECK_DECAY = 15, + E_META_NEWLEAVES_APPLE = 0, + E_META_NEWLEAVES_CONIFER = 1, + E_META_NEWLEAVES_BIRCH = 2, + E_META_NEWLEAVES_JUNGLE = 3, + E_META_NEWLEAVES_APPLE_NO_DECAY = 4, + E_META_NEWLEAVES_CONIFER_NO_DECAY = 5, + E_META_NEWLEAVES_BIRCH_NO_DECAY = 6, + E_META_NEWLEAVES_JUNGLE_NO_DECAY = 7, + E_META_NEWLEAVES_APPLE_CHECK_DECAY = 8, + E_META_NEWLEAVES_CONIFER_CHECK_DECAY = 9, + E_META_NEWLEAVES_BIRCH_CHECK_DECAY = 10, + E_META_NEWLEAVES_JUNGLE_CHECK_DECAY = 11, // E_BLOCK_LEAVES meta cont. (Block ID 161): - E_META_LEAVES_ACACIA = 0, - E_META_LEAVES_DARK_OAK = 1, - E_META_LEAVES_ACACIA_NO_DECAY = 4, - E_META_LEAVES_DARK_OAK_NO_DECAY = 5, - E_META_LEAVES_ACACIA_CHECK_DECAY = 8, - E_META_LEAVES_DARK_OAK_CHECK_DECAY = 9, - E_META_LEAVES_ACACIA_NO_DECAY_CHECK_DECAY = 12, - E_META_LEAVES_DARK_OAK_NO_DECAY_CHECK_DECAY = 13, + E_META_NEWLEAVES_ACACIA = 0, + E_META_NEWLEAVES_DARK_OAK = 1, + E_META_NEWLEAVES_ACACIA_NO_DECAY = 4, + E_META_NEWLEAVES_DARK_OAK_NO_DECAY = 5, + E_META_NEWLEAVES_ACACIA_CHECK_DECAY = 8, + E_META_NEWLEAVES_DARK_OAK_CHECK_DECAY = 9, + E_META_NEWLEAVES_ACACIA_NO_DECAY_CHECK_DECAY = 12, + E_META_NEWLEAVES_DARK_OAK_NO_DECAY_CHECK_DECAY = 13, // E_BLOCK_LOG metas: - E_META_LOG_APPLE = 0, - E_META_LOG_CONIFER = 1, - E_META_LOG_BIRCH = 2, - E_META_LOG_JUNGLE = 3, + E_META_NEWLOG_APPLE = 0, + E_META_NEWLOG_CONIFER = 1, + E_META_NEWLOG_BIRCH = 2, + E_META_NEWLOG_JUNGLE = 3, // E_BLOCK_NEW_LEAVES metas E_META_NEW_LEAVES_ACACIA_WOOD = 0, @@ -534,10 +530,10 @@ enum // E_BLOCK_PISTON metas: E_META_PISTON_DOWN = 0, E_META_PISTON_UP = 1, - E_META_PISTON_NORTH = 2, - E_META_PISTON_SOUTH = 3, - E_META_PISTON_WEST = 4, - E_META_PISTON_EAST = 5, + E_META_PISTON_ZM = 2, + E_META_PISTON_ZP = 3, + E_META_PISTON_XM = 4, + E_META_PISTON_XP = 5, E_META_PISTON_HEAD_STICKY = 8, E_META_PISTON_EXTENDED = 8, @@ -657,10 +653,10 @@ enum E_META_STAINED_GLASS_PANE_BLACK = 15, // E_BLOCK_STAIRS metas: - E_BLOCK_STAIRS_EAST = 0, - E_BLOCK_STAIRS_WEST = 1, - E_BLOCK_STAIRS_SOUTH = 2, - E_BLOCK_STAIRS_NORTH = 3, + E_BLOCK_STAIRS_XP = 0, + E_BLOCK_STAIRS_XM = 1, + E_BLOCK_STAIRS_ZP = 2, + E_BLOCK_STAIRS_ZM = 3, E_BLOCK_STAIRS_UPSIDE_DOWN = 4, // E_BLOCK_STONE metas: @@ -705,41 +701,41 @@ enum E_META_TORCH_ZM = 3, // Torch attached to the ZM side of its block E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block - // E_BLOCK_WOOD metas: - E_BLOCK_WOOD_OAK_UP_DOWN = 0, - E_BLOCK_WOOD_SPRUCE_UP_DOWN = 1, - E_BLOCK_WOOD_BIRCH_UP_DOWN = 2, - E_BLOCK_WOOD_JUNGLE_UP_DOWN = 3, - E_BLOCK_WOOD_OAK_EAST_WEST = 4, - E_BLOCK_WOOD_SPRUCE_EAST_WEST = 5, - E_BLOCK_WOOD_BIRCH_EAST_WEST = 6, - E_BLOCK_WOOD_JUNGLE_EAST_WEST = 7, - E_BLOCK_WOOD_OAK_NORTH_SOUTH = 8, - E_BLOCK_WOOD_SPRUCE_NORTH_SOUTH = 9, - E_BLOCK_WOOD_BIRCH_NORTH_SOUTH = 10, - E_BLOCK_WOOD_JUNGLE_NORTH_SOUTH = 11, - E_BLOCK_WOOD_OAK_BARK_ONLY = 12, - E_BLOCK_WOOD_SPRUCE_BARK_ONLY = 13, - E_BLOCK_WOOD_BIRCH_BARK_ONLY = 14, - E_BLOCK_WOOD_JUNGLE_BARK_ONLY = 15, - - // E_BLOCK_WOOD metas cont. (Block ID 162): - E_BLOCK_WOOD_ACACIA_UP_DOWN = 0, - E_BLOCK_WOOD_DARK_OAK_UP_DOWN = 1, - E_BLOCK_WOOD_ACACIA_UP_DOWN = 2, - E_BLOCK_WOOD_DARK_OAK_UP_DOWN = 3, - E_BLOCK_WOOD_ACACIA_EAST_WEST = 4, - E_BLOCK_WOOD_DARK_OAK_EAST_WEST = 5, - E_BLOCK_WOOD_ACACIA_EAST_WEST = 6, - E_BLOCK_WOOD_DARK_OAK_EAST_WEST = 7, - E_BLOCK_WOOD_ACACIA_NORTH_SOUTH = 8, - E_BLOCK_WOOD_DARK_OAK_NORTH_SOUTH = 9, - E_BLOCK_WOOD_ACACIA_NORTH_SOUTH = 10, - E_BLOCK_WOOD_DARK_OAK_NORTH_SOUTH = 11, - E_BLOCK_WOOD_ACACIA_BARK_ONLY = 12, - E_BLOCK_WOOD_DARK_OAK_BARK_ONLY = 13, - E_BLOCK_WOOD_ACACIA_BARK_ONLY = 14, - E_BLOCK_WOOD_DARK_OAK_BARK_ONLY = 15, + // E_META_LOG metas: + E_META_NEWLOG_OAK_UP_DOWN = 0, + E_META_NEWLOG_SPRUCE_UP_DOWN = 1, + E_META_NEWLOG_BIRCH_UP_DOWN = 2, + E_META_NEWLOG_JUNGLE_UP_DOWN = 3, + E_META_NEWLOG_OAK_X = 4, + E_META_NEWLOG_SPRUCE_X = 5, + E_META_NEWLOG_BIRCH_X = 6, + E_META_NEWLOG_JUNGLE_X = 7, + E_META_NEWLOG_OAK_Z = 8, + E_META_NEWLOG_SPRUCE_Z = 9, + E_META_NEWLOG_BIRCH_Z = 10, + E_META_NEWLOG_JUNGLE_Z = 11, + E_META_NEWLOG_OAK_BARK_ONLY = 12, + E_META_NEWLOG_SPRUCE_BARK_ONLY = 13, + E_META_NEWLOG_BIRCH_BARK_ONLY = 14, + E_META_NEWLOG_JUNGLE_BARK_ONLY = 15, + + // E_META_NEWLOG metas cont. (Block ID 162): + E_META_NEWLOG_ACACIA_UP_DOWN = 0, + E_META_NEWLOG_DARK_OAK_UP_DOWN = 1, + E_META_NEWLOG_ACACIA_UP_DOWN = 2, + E_META_NEWLOG_DARK_OAK_UP_DOWN = 3, + E_META_NEWLOG_ACACIA_X = 4, + E_META_NEWLOG_DARK_OAK_X = 5, + E_META_NEWLOG_ACACIA_X = 6, + E_META_NEWLOG_DARK_OAK_X = 7, + E_META_NEWLOG_ACACIA_Z = 8, + E_META_NEWLOG_DARK_OAK_Z = 9, + E_META_NEWLOG_ACACIA_Z = 10, + E_META_NEWLOG_DARK_OAK_Z = 11, + E_META_NEWLOG_ACACIA_BARK_ONLY = 12, + E_META_NEWLOG_DARK_OAK_BARK_ONLY = 13, + E_META_NEWLOG_ACACIA_BARK_ONLY = 14, + E_META_NEWLOG_DARK_OAK_BARK_ONLY = 15, // E_BLOCK_WOODEN_DOUBLE_SLAB metas: E_META_WOODEN_DOUBLE_SLAB_APPLE = 0, -- cgit v1.2.3 From 6aa3c5ece86d864e4dac8f2632500bfc0e4dd89d Mon Sep 17 00:00:00 2001 From: narroo Date: Sat, 7 Jun 2014 20:24:31 -0400 Subject: Fixed E_META_...Typos in BlockID.h --- src/BlockID.h | 10 --- src/Blocks/BlockLeaves.h | 4 +- src/Generating/Trees.cpp | 156 +++++++++++++++++++++++------------------------ 3 files changed, 80 insertions(+), 90 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 32943ea67..4f6b1afcc 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -510,8 +510,6 @@ enum E_META_NEWLEAVES_DARK_OAK_NO_DECAY = 5, E_META_NEWLEAVES_ACACIA_CHECK_DECAY = 8, E_META_NEWLEAVES_DARK_OAK_CHECK_DECAY = 9, - E_META_NEWLEAVES_ACACIA_NO_DECAY_CHECK_DECAY = 12, - E_META_NEWLEAVES_DARK_OAK_NO_DECAY_CHECK_DECAY = 13, // E_BLOCK_LOG metas: E_META_NEWLOG_APPLE = 0, @@ -722,20 +720,12 @@ enum // E_META_NEWLOG metas cont. (Block ID 162): E_META_NEWLOG_ACACIA_UP_DOWN = 0, E_META_NEWLOG_DARK_OAK_UP_DOWN = 1, - E_META_NEWLOG_ACACIA_UP_DOWN = 2, - E_META_NEWLOG_DARK_OAK_UP_DOWN = 3, E_META_NEWLOG_ACACIA_X = 4, E_META_NEWLOG_DARK_OAK_X = 5, - E_META_NEWLOG_ACACIA_X = 6, - E_META_NEWLOG_DARK_OAK_X = 7, E_META_NEWLOG_ACACIA_Z = 8, E_META_NEWLOG_DARK_OAK_Z = 9, - E_META_NEWLOG_ACACIA_Z = 10, - E_META_NEWLOG_DARK_OAK_Z = 11, E_META_NEWLOG_ACACIA_BARK_ONLY = 12, E_META_NEWLOG_DARK_OAK_BARK_ONLY = 13, - E_META_NEWLOG_ACACIA_BARK_ONLY = 14, - E_META_NEWLOG_DARK_OAK_BARK_ONLY = 15, // E_BLOCK_WOODEN_DOUBLE_SLAB metas: E_META_WOODEN_DOUBLE_SLAB_APPLE = 0, diff --git a/src/Blocks/BlockLeaves.h b/src/Blocks/BlockLeaves.h index d21227b07..d9d1bdb7e 100644 --- a/src/Blocks/BlockLeaves.h +++ b/src/Blocks/BlockLeaves.h @@ -47,7 +47,7 @@ public: } // 1 % chance of dropping an apple, if the leaves' type is Apple Leaves - if ((a_BlockMeta & 3) == E_META_LEAVES_APPLE) + if ((a_BlockMeta & 3) == E_META_NEWLEAVES_APPLE) { if (rand.NextInt(101) == 0) { @@ -64,7 +64,7 @@ public: // 0.5% chance of dropping an apple, if the leaves' type is Apple Leaves: NIBBLETYPE Meta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); cFastRandom rand; - if (((Meta & 3) == E_META_LEAVES_APPLE) && (rand.NextInt(201) == 100)) + if (((Meta & 3) == E_META_NEWLEAVES_APPLE) && (rand.NextInt(201) == 100)) { cItems Drops; Drops.push_back(cItem(E_ITEM_RED_APPLE, 1, 0)); diff --git a/src/Generating/Trees.cpp b/src/Generating/Trees.cpp index 4909587b1..5a71cf13c 100644 --- a/src/Generating/Trees.cpp +++ b/src/Generating/Trees.cpp @@ -304,31 +304,31 @@ void GetSmallAppleTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a // Trunk: for (int i = 0; i < Height; i++) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_APPLE)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_APPLE)); } int Hei = a_BlockY + Height; // 2 BigO2 + corners layers: for (int i = 0; i < 2; i++) { - PushCoordBlocks (a_BlockX, Hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - PushCornerBlocks(a_BlockX, Hei, a_BlockZ, a_Seq, a_Noise, 0x5000000 - i * 0x10000000, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Hei, a_BlockZ, E_BLOCK_LOG, E_META_LOG_APPLE)); + PushCoordBlocks (a_BlockX, Hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + PushCornerBlocks(a_BlockX, Hei, a_BlockZ, a_Seq, a_Noise, 0x5000000 - i * 0x10000000, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Hei, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_APPLE)); Hei++; } // for i - 2* // Optional BigO1 + corners layer: if ((Random & 1) == 0) { - PushCoordBlocks (a_BlockX, Hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - PushCornerBlocks(a_BlockX, Hei, a_BlockZ, a_Seq, a_Noise, 0x6000000, a_OtherBlocks, 1, E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Hei, a_BlockZ, E_BLOCK_LOG, E_META_LOG_APPLE)); + PushCoordBlocks (a_BlockX, Hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + PushCornerBlocks(a_BlockX, Hei, a_BlockZ, a_Seq, a_Noise, 0x6000000, a_OtherBlocks, 1, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Hei, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_APPLE)); Hei++; } // Top plus: - PushCoordBlocks(a_BlockX, Hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, Hei, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_APPLE)); + PushCoordBlocks(a_BlockX, Hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, Hei, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE)); } @@ -355,25 +355,25 @@ void GetBirchTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Nois // The entire trunk, out of logs: for (int i = Height - 1; i >= 0; --i) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_BIRCH)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_BIRCH)); } int h = a_BlockY + Height; // Top layer - just the Plus: - PushCoordBlocks(a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_BIRCH)); // There's no log at this layer + PushCoordBlocks(a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH)); // There's no log at this layer h--; // Second layer - log, Plus and maybe Corners: - PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); - PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 1, E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); + PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); + PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 1, E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); h--; // Third and fourth layers - BigO2 and maybe 2*Corners: for (int Row = 0; Row < 2; Row++) { - PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); - PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x3fffffff + Row * 0x10000000, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); + PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); + PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x3fffffff + Row * 0x10000000, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); h--; } // for Row - 2* } @@ -411,25 +411,25 @@ void GetTallBirchTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_ // The entire trunk, out of logs: for (int i = Height - 1; i >= 0; --i) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_BIRCH)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_BIRCH)); } int h = a_BlockY + Height; // Top layer - just the Plus: - PushCoordBlocks(a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_BIRCH)); // There's no log at this layer + PushCoordBlocks(a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH)); // There's no log at this layer h--; // Second layer - log, Plus and maybe Corners: - PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); - PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 1, E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); + PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); + PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 1, E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); h--; // Third and fourth layers - BigO2 and maybe 2*Corners: for (int Row = 0; Row < 2; Row++) { - PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); - PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x3fffffff + Row * 0x10000000, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_LEAVES_BIRCH); + PushCoordBlocks (a_BlockX, h, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); + PushCornerBlocks(a_BlockX, h, a_BlockZ, a_Seq, a_Noise, 0x3fffffff + Row * 0x10000000, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_NEWLEAVES_BIRCH); h--; } // for Row - 2* } @@ -476,15 +476,15 @@ void GetSpruceTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noi // Clear trunk blocks: for (int i = 0; i < Height; i++) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); } Height += a_BlockY; // Optional size-1 bottom leaves layer: if ((MyRandom & 1) == 0) { - PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); + PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); Height++; } MyRandom >>= 1; @@ -500,30 +500,30 @@ void GetSpruceTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noi case 0: case 1: { - PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - PushCoordBlocks(a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); + PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + PushCoordBlocks(a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); Height += 2; break; } case 2: { - PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - PushCoordBlocks(a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); + PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + PushCoordBlocks(a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); Height += 2; break; } case 3: { - PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - PushCoordBlocks(a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - PushCoordBlocks(a_BlockX, Height + 2, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); - a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 2, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); + PushCoordBlocks(a_BlockX, Height, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + PushCoordBlocks(a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + PushCoordBlocks(a_BlockX, Height + 2, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, Height + 2, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); Height += 3; break; } @@ -534,17 +534,17 @@ void GetSpruceTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noi if ((MyRandom & 1) == 0) { // (0, 1, 0) top: - a_LogBlocks.push_back (sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); - PushCoordBlocks (a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_CONIFER)); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height + 2, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_CONIFER)); + a_LogBlocks.push_back (sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); + PushCoordBlocks (a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER)); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height + 2, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER)); } else { // (1, 0) top: - a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_CONIFER)); - PushCoordBlocks (a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_CONIFER)); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER)); + PushCoordBlocks (a_BlockX, Height + 1, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, Height + 1, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER)); } } @@ -574,16 +574,16 @@ void GetPineTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noise // The entire trunk, out of logs: for (int i = TrunkHeight; i >= 0; --i) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_CONIFER)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_CONIFER)); } int h = a_BlockY + TrunkHeight + 2; // Top layer - just a single leaves block: - a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_CONIFER)); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER)); h--; // One more layer is above the trunk, push the central leaves: - a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_CONIFER)); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, h, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER)); // Layers expanding in size, then collapsing again: // LOGD("Generating %d layers of pine leaves, SameSizeMax = %d", NumLeavesLayers, SameSizeMax); @@ -596,7 +596,7 @@ void GetPineTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noise break; } ASSERT((size_t)LayerSize < ARRAYCOUNT(BigOs)); - PushCoordBlocks(a_BlockX, h, a_BlockZ, a_OtherBlocks, BigOs[LayerSize].Coords, BigOs[LayerSize].Count, E_BLOCK_LEAVES, E_META_LEAVES_CONIFER); + PushCoordBlocks(a_BlockX, h, a_BlockZ, a_OtherBlocks, BigOs[LayerSize].Coords, BigOs[LayerSize].Count, E_BLOCK_LEAVES, E_META_NEWLEAVES_CONIFER); h--; } } @@ -623,7 +623,7 @@ void GetSwampTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Nois for (int i = 0; i < Height; i++) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_APPLE)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_APPLE)); } int hei = a_BlockY + Height - 2; @@ -633,17 +633,17 @@ void GetSwampTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Nois // The lower two leaves layers are BigO3 with log in the middle and possibly corners: for (int i = 0; i < 2; i++) { - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_LEAVES_APPLE); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); hei++; } // for i - 2* // The upper two leaves layers are BigO2 with leaves in the middle and possibly corners: for (int i = 0; i < 2; i++) { - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_LEAVES_APPLE); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_APPLE)); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE)); hei++; } // for i - 2* } @@ -657,15 +657,15 @@ void GetAppleBushImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Nois a_OtherBlocks.reserve(3 + ARRAYCOUNT(BigO2) + ARRAYCOUNT(BigO1)); int hei = a_BlockY; - a_LogBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LOG, E_META_LOG_JUNGLE)); - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_APPLE); + a_LogBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_JUNGLE)); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); hei++; - a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_APPLE)); - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_APPLE); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE)); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE); hei++; - a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_APPLE)); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_APPLE)); } @@ -709,10 +709,10 @@ void GetLargeJungleTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & for (int i = 0; i < Height; i++) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_JUNGLE)); - a_LogBlocks.push_back(sSetBlock(a_BlockX + 1, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_JUNGLE)); - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ + 1, E_BLOCK_LOG, E_META_LOG_JUNGLE)); - a_LogBlocks.push_back(sSetBlock(a_BlockX + 1, a_BlockY + i, a_BlockZ + 1, E_BLOCK_LOG, E_META_LOG_JUNGLE)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_JUNGLE)); + a_LogBlocks.push_back(sSetBlock(a_BlockX + 1, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_JUNGLE)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ + 1, E_BLOCK_LOG, E_META_NEWLOG_JUNGLE)); + a_LogBlocks.push_back(sSetBlock(a_BlockX + 1, a_BlockY + i, a_BlockZ + 1, E_BLOCK_LOG, E_META_NEWLOG_JUNGLE)); } int hei = a_BlockY + Height - 2; @@ -722,15 +722,15 @@ void GetLargeJungleTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & // The lower two leaves layers are BigO4 with log in the middle and possibly corners: for (int i = 0; i < 2; i++) { - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO4, ARRAYCOUNT(BigO4), E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); - PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO4, ARRAYCOUNT(BigO4), E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); + PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); hei++; } // for i - 2* // The top leaves layer is a BigO3 with leaves in the middle and possibly corners: - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); - PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE)); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); + PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE)); } @@ -762,7 +762,7 @@ void GetSmallJungleTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & for (int i = 0; i < Height; i++) { - a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_LOG_JUNGLE)); + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_LOG, E_META_NEWLOG_JUNGLE)); } int hei = a_BlockY + Height - 3; @@ -772,22 +772,22 @@ void GetSmallJungleTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & // The lower two leaves layers are BigO3 with log in the middle and possibly corners: for (int i = 0; i < 2; i++) { - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); - PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO3, ARRAYCOUNT(BigO3), E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); + PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 3, E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); hei++; } // for i - 2* // Two layers of BigO2 leaves, possibly with corners: for (int i = 0; i < 1; i++) { - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); - PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); + PushCornerBlocks(a_BlockX, hei, a_BlockZ, a_Seq, a_Noise, 0x5fffffff, a_OtherBlocks, 2, E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); hei++; } // for i - 2* // Top plus, all leaves: - PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE); - a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_LEAVES_JUNGLE)); + PushCoordBlocks(a_BlockX, hei, a_BlockZ, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE); + a_OtherBlocks.push_back(sSetBlock(a_BlockX, hei, a_BlockZ, E_BLOCK_LEAVES, E_META_NEWLEAVES_JUNGLE)); } -- cgit v1.2.3 From 0019d17a11e2e5cd8ec066a321b8636ed9c3e9a3 Mon Sep 17 00:00:00 2001 From: narroo Date: Wed, 2 Jul 2014 16:35:03 -0400 Subject: Spacing fixes and a few more BLOCK_META constants. --- src/BlockID.h | 283 +++++++++++++++++++++++++++++++--------------------------- 1 file changed, 152 insertions(+), 131 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 4f6b1afcc..655c8c712 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -401,13 +401,20 @@ enum /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Block metas: + // E_BLOCK_ANVIL metas + E_BLOCK_ANVIL_Z = 0, + E_BLOCK_ANVIL_X = 1, + E_BLOCK_ANVIL_NO_DAMAGE = 0, + E_BLOCK_ANVIL_LOW_DAMAGE = 4, + E_BLOCK_ANVIL_HIGH_DAMAGE = 8, + // E_BLOCK_BED metas: - E_BLOCK_BED_SOUTH = 0, - E_BLOCK_BED_WEST = 1, - E_BLOCK_BED_NORTH = 2, - E_BLOCK_BED_EAST = 3, - E_BLOCK_BED_OCCUPIED = 4, - E_BLOCK_BED_BED_HEAD = 8, + E_BLOCK_BED_ZP = 0, + E_BLOCK_BED_XM = 1, + E_BLOCK_BED_ZM = 2, + E_BLOCK_BED_XP = 3, + E_BLOCK_BED_OCCUPIED = 4, + E_BLOCK_BED_BED_HEAD = 8, // E_BLOCK_BIG_FLOWER metas E_META_BIG_FLOWER_SUNFLOWER = 0, @@ -417,6 +424,20 @@ enum E_META_BIG_FLOWER_ROSE_BUSH = 4, E_META_BIG_FLOWER_PEONY = 5, + // E_BLOCK_BREWING_STAND metas + E_META_BREWING_STAND_FILLED_SLOT_XP = 1, + E_META_BREWING_STAND_FILLED_SLOT_XM_ZP = 2, + E_META_BREWING_STAND_FILLED_SLOT_XM_ZM = 4, + + // E_BLOCK_BUTTON metas + E_BLOCK_BUTTON_YM = 0, + E_BLOCK_BUTTON_XP = 1, + E_BLOCK_BUTTON_XM = 2, + E_BLOCK_BUTTON_ZP = 3, + E_BLOCK_BUTTON_ZM = 4, + E_BLOCK_BUTTON_YP = 5, + E_BLOCK_BUTTON_PRESSED = 8, + // E_BLOCK_CARPET metas: E_META_CARPET_WHITE = 0, E_META_CARPET_ORANGE = 1, @@ -455,17 +476,17 @@ enum E_META_DROPSPENSER_FACING_XP = 5, // E_BLOCK_DOUBLE_STONE_SLAB metas: - E_META_DOUBLE_STONE_SLAB_STONE = 0, - E_META_DOUBLE_STONE_SLAB_SANDSTON = 1, - E_META_DOUBLE_STONE_SLAB_WOODEN = 2, - E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, - E_META_DOUBLE_STONE_SLAB_BRICK = 4, - E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, - E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, - E_META_DOUBLE_STONE_SLAB_QUARTZ = 7, - E_META_DOUBLE_STONE_SLAB_SMOOTH_STONE = 8, - E_META_DOUBLE_STONE_SLAB_SMOOTH_SANDSTONE = 9, - E_META_DOUBLE_STONE_SLAB_TILE_QUARTZ = 10, + E_META_DOUBLE_STONE_SLAB_STONE = 0, + E_META_DOUBLE_STONE_SLAB_SANDSTON = 1, + E_META_DOUBLE_STONE_SLAB_WOODEN = 2, + E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, + E_META_DOUBLE_STONE_SLAB_BRICK = 4, + E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, + E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, + E_META_DOUBLE_STONE_SLAB_QUARTZ = 7, + E_META_DOUBLE_STONE_SLAB_SMOOTH_STONE = 8, + E_META_DOUBLE_STONE_SLAB_SMOOTH_SANDSTONE = 9, + E_META_DOUBLE_STONE_SLAB_TILE_QUARTZ = 10, // E_BLOCK_FLOWER metas E_META_FLOWER_POPPY = 0, @@ -478,8 +499,8 @@ enum E_META_FLOWER_OXEYE_DAISY = 8, // E_BLOCK_JUKEBOX metas - E_META_JUKEBOX_OFF = 0, - E_META_JUKEBOX_ON = 1, + E_META_JUKEBOX_OFF = 0, + E_META_JUKEBOX_ON = 1, // E_BLOCK_HOPPER metas: E_META_HOPPER_FACING_YM = 0, @@ -490,26 +511,26 @@ enum E_META_HOPPER_FACING_XP = 5, // E_BLOCK_LEAVES metas: - E_META_NEWLEAVES_APPLE = 0, - E_META_NEWLEAVES_CONIFER = 1, - E_META_NEWLEAVES_BIRCH = 2, - E_META_NEWLEAVES_JUNGLE = 3, - E_META_NEWLEAVES_APPLE_NO_DECAY = 4, - E_META_NEWLEAVES_CONIFER_NO_DECAY = 5, - E_META_NEWLEAVES_BIRCH_NO_DECAY = 6, - E_META_NEWLEAVES_JUNGLE_NO_DECAY = 7, - E_META_NEWLEAVES_APPLE_CHECK_DECAY = 8, + E_META_NEWLEAVES_APPLE = 0, + E_META_NEWLEAVES_CONIFER = 1, + E_META_NEWLEAVES_BIRCH = 2, + E_META_NEWLEAVES_JUNGLE = 3, + E_META_NEWLEAVES_APPLE_NO_DECAY = 4, + E_META_NEWLEAVES_CONIFER_NO_DECAY = 5, + E_META_NEWLEAVES_BIRCH_NO_DECAY = 6, + E_META_NEWLEAVES_JUNGLE_NO_DECAY = 7, + E_META_NEWLEAVES_APPLE_CHECK_DECAY = 8, E_META_NEWLEAVES_CONIFER_CHECK_DECAY = 9, - E_META_NEWLEAVES_BIRCH_CHECK_DECAY = 10, - E_META_NEWLEAVES_JUNGLE_CHECK_DECAY = 11, + E_META_NEWLEAVES_BIRCH_CHECK_DECAY = 10, + E_META_NEWLEAVES_JUNGLE_CHECK_DECAY = 11, // E_BLOCK_LEAVES meta cont. (Block ID 161): - E_META_NEWLEAVES_ACACIA = 0, - E_META_NEWLEAVES_DARK_OAK = 1, + E_META_NEWLEAVES_ACACIA = 0, + E_META_NEWLEAVES_DARK_OAK = 1, E_META_NEWLEAVES_ACACIA_NO_DECAY = 4, E_META_NEWLEAVES_DARK_OAK_NO_DECAY = 5, - E_META_NEWLEAVES_ACACIA_CHECK_DECAY = 8, - E_META_NEWLEAVES_DARK_OAK_CHECK_DECAY = 9, + E_META_NEWLEAVES_ACACIA_CHECK_DECAY = 8, + E_META_NEWLEAVES_DARK_OAK_CHECK_DECAY = 9, // E_BLOCK_LOG metas: E_META_NEWLOG_APPLE = 0, @@ -522,47 +543,47 @@ enum E_META_NEW_LEAVES_DARK_OAK_WOOD = 1, // E_BLOCK_NEW_LOG metas - E_META_NEW_LOG_ACACIA_WOOD = 0, - E_META_NEW_LOG_DARK_OAK_WOOD = 1, + E_META_NEW_LOG_ACACIA_WOOD = 0, + E_META_NEW_LOG_DARK_OAK_WOOD = 1, // E_BLOCK_PISTON metas: - E_META_PISTON_DOWN = 0, - E_META_PISTON_UP = 1, - E_META_PISTON_ZM = 2, - E_META_PISTON_ZP = 3, - E_META_PISTON_XM = 4, - E_META_PISTON_XP = 5, - E_META_PISTON_HEAD_STICKY = 8, - E_META_PISTON_EXTENDED = 8, + E_META_PISTON_DOWN = 0, + E_META_PISTON_U = 1, + E_META_PISTON_ZM = 2, + E_META_PISTON_ZP = 3, + E_META_PISTON_XM = 4, + E_META_PISTON_XP = 5, + E_META_PISTON_HEAD_STICKY = 8, + E_META_PISTON_EXTENDED = 8, // E_BLOCK_PLANKS metas: - E_META_PLANKS_APPLE = 0, - E_META_PLANKS_CONIFER = 1, - E_META_PLANKS_BIRCH = 2, - E_META_PLANKS_JUNGLE = 3, - E_META_PLANKS_ACACIA = 4, - E_META_PLANKS_DARK_OAK= 5, + E_META_PLANKS_APPLE = 0, + E_META_PLANKS_CONIFER = 1, + E_META_PLANKS_BIRCH = 2, + E_META_PLANKS_JUNGLE = 3, + E_META_PLANKS_ACACIA = 4, + E_META_PLANKS_DARK_OAK = 5, // E_BLOCK_(XXX_WEIGHTED)_PRESSURE_PLATE metas: - E_META_PRESSURE_PLATE_RAISED = 0, + E_META_PRESSURE_PLATE_RAISED = 0, E_META_PRESSURE_PLATE_DEPRESSED = 1, // E_BLOCK_QUARTZ_BLOCK metas: - E_META_QUARTZ_NORMAL = 0, + E_META_QUARTZ_NORMAL = 0, E_META_QUARTZ_CHISELLED = 1, - E_META_QUARTZ_PILLAR = 2, + E_META_QUARTZ_PILLAR = 2, // E_BLOCK_RAIL metas - E_META_RAIL_ZM_ZP = 0, - E_META_RAIL_XM_XP = 1, - E_META_RAIL_ASCEND_XP = 2, - E_META_RAIL_ASCEND_XM = 3, - E_META_RAIL_ASCEND_ZM = 4, - E_META_RAIL_ASCEND_ZP = 5, - E_META_RAIL_CURVED_ZP_XP = 6, - E_META_RAIL_CURVED_ZP_XM = 7, - E_META_RAIL_CURVED_ZM_XM = 8, - E_META_RAIL_CURVED_ZM_XP = 9, + E_META_RAIL_ZM_ZP = 0, + E_META_RAIL_XM_XP = 1, + E_META_RAIL_ASCEND_XP = 2, + E_META_RAIL_ASCEND_XM = 3, + E_META_RAIL_ASCEND_ZM = 4, + E_META_RAIL_ASCEND_ZP = 5, + E_META_RAIL_CURVED_ZP_XP = 6, + E_META_RAIL_CURVED_ZP_XM = 7, + E_META_RAIL_CURVED_ZM_XM = 8, + E_META_RAIL_CURVED_ZM_XP = 9, // E_BLOCK_SAND metas: E_META_SAND_NORMAL = 0, @@ -651,42 +672,42 @@ enum E_META_STAINED_GLASS_PANE_BLACK = 15, // E_BLOCK_STAIRS metas: - E_BLOCK_STAIRS_XP = 0, - E_BLOCK_STAIRS_XM = 1, - E_BLOCK_STAIRS_ZP = 2, - E_BLOCK_STAIRS_ZM = 3, + E_BLOCK_STAIRS_XP = 0, + E_BLOCK_STAIRS_XM = 1, + E_BLOCK_STAIRS_ZP = 2, + E_BLOCK_STAIRS_ZM = 3, E_BLOCK_STAIRS_UPSIDE_DOWN = 4, // E_BLOCK_STONE metas: - E_META_STONE_STONE = 0, - E_META_STONE_GRANITE = 1, - E_META_STONE_POLISHED_GRANITE = 2, - E_META_STONE_DIORITE = 3, - E_META_STONE_POLISHED_DIORITE = 4, - E_META_STONE_ANDESITE = 5, - E_META_STONE_POLISHED_ANDESITE = 6, + E_META_STONE_STONE = 0, + E_META_STONE_GRANITE = 1, + E_META_STONE_POLISHED_GRANITE = 2, + E_META_STONE_DIORITE = 3, + E_META_STONE_POLISHED_DIORITE = 4, + E_META_STONE_ANDESITE = 5, + E_META_STONE_POLISHED_ANDESITE = 6, // E_BLOCK_STONE_SLAB metas: - E_META_STONE_SLAB_STONE = 0, - E_META_STONE_SLAB_SANDSTONE = 1, - E_META_STONE_SLAB_PLANKS = 2, - E_META_STONE_SLAB_COBBLESTONE = 3, - E_META_STONE_SLAB_BRICK = 4, - E_META_STONE_SLAB_STONE_BRICK = 5, - E_META_STONE_SLAB_NETHER_BRICK = 6, - E_META_STONE_SLAB_QUARTZ = 7, + E_META_STONE_SLAB_STONE = 0, + E_META_STONE_SLAB_SANDSTONE = 1, + E_META_STONE_SLAB_PLANKS = 2, + E_META_STONE_SLAB_COBBLESTONE = 3, + E_META_STONE_SLAB_BRICK = 4, + E_META_STONE_SLAB_STONE_BRICK = 5, + E_META_STONE_SLAB_NETHER_BRICK = 6, + E_META_STONE_SLAB_QUARTZ = 7, // E_BLOCK_STONE_BRICKS metas: - E_META_STONE_BRICK_NORMAL = 0, - E_META_STONE_BRICK_MOSSY = 1, - E_META_STONE_BRICK_CRACKED = 2, - E_META_STONE_BRICK_ORNAMENT = 3, + E_META_STONE_BRICK_NORMAL = 0, + E_META_STONE_BRICK_MOSSY = 1, + E_META_STONE_BRICK_CRACKED = 2, + E_META_STONE_BRICK_ORNAMENT = 3, // E_BLOCK_TALL_GRASS metas: - E_META_TALL_GRASS_DEAD_SHRUB = 0, - E_META_TALL_GRASS_GRASS = 1, - E_META_TALL_GRASS_FERN = 2, - E_META_TALL_GRASS_BIOME = 3, + E_META_TALL_GRASS_DEAD_SHRUB = 0, + E_META_TALL_GRASS_GRASS = 1, + E_META_TALL_GRASS_FERN = 2, + E_META_TALL_GRASS_BIOME = 3, // E_BLOCK_TORCH, E_BLOCK_REDSTONE_TORCH_OFF, E_BLOCK_REDSTONE_TORCH_ON metas: E_META_TORCH_EAST = 1, // east face of the block, pointing east @@ -694,56 +715,56 @@ enum E_META_TORCH_SOUTH = 3, E_META_TORCH_NORTH = 4, E_META_TORCH_FLOOR = 5, - E_META_TORCH_XM = 1, // Torch attached to the XM side of its block - E_META_TORCH_XP = 2, // Torch attached to the XP side of its block - E_META_TORCH_ZM = 3, // Torch attached to the ZM side of its block - E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block + E_META_TORCH_XM = 1, // Torch attached to the XM side of its block + E_META_TORCH_XP = 2, // Torch attached to the XP side of its block + E_META_TORCH_ZM = 3, // Torch attached to the ZM side of its block + E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block // E_META_LOG metas: - E_META_NEWLOG_OAK_UP_DOWN = 0, - E_META_NEWLOG_SPRUCE_UP_DOWN = 1, - E_META_NEWLOG_BIRCH_UP_DOWN = 2, - E_META_NEWLOG_JUNGLE_UP_DOWN = 3, - E_META_NEWLOG_OAK_X = 4, - E_META_NEWLOG_SPRUCE_X = 5, - E_META_NEWLOG_BIRCH_X = 6, - E_META_NEWLOG_JUNGLE_X = 7, - E_META_NEWLOG_OAK_Z = 8, - E_META_NEWLOG_SPRUCE_Z = 9, - E_META_NEWLOG_BIRCH_Z = 10, - E_META_NEWLOG_JUNGLE_Z = 11, - E_META_NEWLOG_OAK_BARK_ONLY = 12, - E_META_NEWLOG_SPRUCE_BARK_ONLY = 13, - E_META_NEWLOG_BIRCH_BARK_ONLY = 14, - E_META_NEWLOG_JUNGLE_BARK_ONLY = 15, + E_META_NEWLOG_OAK_UP_DOWN = 0, + E_META_NEWLOG_SPRUCE_UP_DOWN = 1, + E_META_NEWLOG_BIRCH_UP_DOWN = 2, + E_META_NEWLOG_JUNGLE_UP_DOWN = 3, + E_META_NEWLOG_OAK_X = 4, + E_META_NEWLOG_SPRUCE_X = 5, + E_META_NEWLOG_BIRCH_X = 6, + E_META_NEWLOG_JUNGLE_X = 7, + E_META_NEWLOG_OAK_Z = 8, + E_META_NEWLOG_SPRUCE_Z = 9, + E_META_NEWLOG_BIRCH_Z = 10, + E_META_NEWLOG_JUNGLE_Z = 11, + E_META_NEWLOG_OAK_BARK_ONLY = 12, + E_META_NEWLOG_SPRUCE_BARK_ONLY = 13, + E_META_NEWLOG_BIRCH_BARK_ONLY = 14, + E_META_NEWLOG_JUNGLE_BARK_ONLY = 15, // E_META_NEWLOG metas cont. (Block ID 162): - E_META_NEWLOG_ACACIA_UP_DOWN = 0, - E_META_NEWLOG_DARK_OAK_UP_DOWN = 1, - E_META_NEWLOG_ACACIA_X = 4, - E_META_NEWLOG_DARK_OAK_X = 5, - E_META_NEWLOG_ACACIA_Z = 8, - E_META_NEWLOG_DARK_OAK_Z = 9, - E_META_NEWLOG_ACACIA_BARK_ONLY = 12, + E_META_NEWLOG_ACACIA_UP_DOWN = 0, + E_META_NEWLOG_DARK_OAK_UP_DOWN = 1, + E_META_NEWLOG_ACACIA_X = 4, + E_META_NEWLOG_DARK_OAK_X = 5, + E_META_NEWLOG_ACACIA_Z = 8, + E_META_NEWLOG_DARK_OAK_Z = 9, + E_META_NEWLOG_ACACIA_BARK_ONLY = 12, E_META_NEWLOG_DARK_OAK_BARK_ONLY = 13, // E_BLOCK_WOODEN_DOUBLE_SLAB metas: - E_META_WOODEN_DOUBLE_SLAB_APPLE = 0, - E_META_WOODEN_DOUBLE_SLAB_CONIFER = 1, - E_META_WOODEN_DOUBLE_SLAB_BIRCH = 2, - E_META_WOODEN_DOUBLE_SLAB_JUNGLE = 3, - E_META_WOODEN_DOUBLE_SLAB_ACACIA = 4, - E_META_WOODEN_DOUBLE_SLAB_DARK_OAK = 5, + E_META_WOODEN_DOUBLE_SLAB_APPLE = 0, + E_META_WOODEN_DOUBLE_SLAB_CONIFER = 1, + E_META_WOODEN_DOUBLE_SLAB_BIRCH = 2, + E_META_WOODEN_DOUBLE_SLAB_JUNGLE = 3, + E_META_WOODEN_DOUBLE_SLAB_ACACIA = 4, + E_META_WOODEN_DOUBLE_SLAB_DARK_OAK = 5, // E_BLOCK_WOODEN_SLAB metas: - E_META_WOODEN_SLAB_APPLE = 0, - E_META_WOODEN_SLAB_CONIFER = 1, - E_META_WOODEN_SLAB_BIRCH = 2, - E_META_WOODEN_SLAB_JUNGLE = 3, - E_META_WOODEN_SLAB_ACACIA = 4, - E_META_WOODEN_SLAB_DARK_OAK = 5, - E_META_WOODEN_SLAB_RIGHT_SIDE_UP = 0, - E_META_WOODWN_SLAB_UPSIDE_DOWN = 8, + E_META_WOODEN_SLAB_APPLE = 0, + E_META_WOODEN_SLAB_CONIFER = 1, + E_META_WOODEN_SLAB_BIRCH = 2, + E_META_WOODEN_SLAB_JUNGLE = 3, + E_META_WOODEN_SLAB_ACACIA = 4, + E_META_WOODEN_SLAB_DARK_OAK = 5, + E_META_WOODEN_SLAB_RIGHT_SIDE_UP = 0, + E_META_WOODWN_SLAB_UPSIDE_DOWN = 8, // E_BLOCK_WOOL metas: E_META_WOOL_WHITE = 0, -- cgit v1.2.3 From 12012d0c80fbee12de7e842b7976af6973960c45 Mon Sep 17 00:00:00 2001 From: archshift Date: Tue, 29 Jul 2014 13:14:48 -0700 Subject: Renamed NEWLEAVES and NEWLOG to LEAVES and LOG. --- src/BlockID.h | 68 +++++++++++++++++++++++++++++------------------------------ 1 file changed, 34 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 9334b7310..b78c09f9c 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -512,18 +512,18 @@ enum E_META_HOPPER_FACING_XP = 5, // E_BLOCK_LEAVES metas: - E_META_NEWLEAVES_APPLE = 0, - E_META_NEWLEAVES_CONIFER = 1, - E_META_NEWLEAVES_BIRCH = 2, - E_META_NEWLEAVES_JUNGLE = 3, - E_META_NEWLEAVES_APPLE_NO_DECAY = 4, - E_META_NEWLEAVES_CONIFER_NO_DECAY = 5, - E_META_NEWLEAVES_BIRCH_NO_DECAY = 6, - E_META_NEWLEAVES_JUNGLE_NO_DECAY = 7, - E_META_NEWLEAVES_APPLE_CHECK_DECAY = 8, - E_META_NEWLEAVES_CONIFER_CHECK_DECAY = 9, - E_META_NEWLEAVES_BIRCH_CHECK_DECAY = 10, - E_META_NEWLEAVES_JUNGLE_CHECK_DECAY = 11, + E_META_LEAVES_APPLE = 0, + E_META_LEAVES_CONIFER = 1, + E_META_LEAVES_BIRCH = 2, + E_META_LEAVES_JUNGLE = 3, + E_META_LEAVES_APPLE_NO_DECAY = 4, + E_META_LEAVES_CONIFER_NO_DECAY = 5, + E_META_LEAVES_BIRCH_NO_DECAY = 6, + E_META_LEAVES_JUNGLE_NO_DECAY = 7, + E_META_LEAVES_APPLE_CHECK_DECAY = 8, + E_META_LEAVES_CONIFER_CHECK_DECAY = 9, + E_META_LEAVES_BIRCH_CHECK_DECAY = 10, + E_META_LEAVES_JUNGLE_CHECK_DECAY = 11, // E_BLOCK_LEAVES meta cont. (Block ID 161): E_META_NEWLEAVES_ACACIA = 0, @@ -534,10 +534,10 @@ enum E_META_NEWLEAVES_DARK_OAK_CHECK_DECAY = 9, // E_BLOCK_LOG metas: - E_META_NEWLOG_APPLE = 0, - E_META_NEWLOG_CONIFER = 1, - E_META_NEWLOG_BIRCH = 2, - E_META_NEWLOG_JUNGLE = 3, + E_META_LOG_APPLE = 0, + E_META_LOG_CONIFER = 1, + E_META_LOG_BIRCH = 2, + E_META_LOG_JUNGLE = 3, // E_BLOCK_NEW_LEAVES metas E_META_NEW_LEAVES_ACACIA_WOOD = 0, @@ -722,24 +722,24 @@ enum E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block // E_META_LOG metas: - E_META_NEWLOG_OAK_UP_DOWN = 0, - E_META_NEWLOG_SPRUCE_UP_DOWN = 1, - E_META_NEWLOG_BIRCH_UP_DOWN = 2, - E_META_NEWLOG_JUNGLE_UP_DOWN = 3, - E_META_NEWLOG_OAK_X = 4, - E_META_NEWLOG_SPRUCE_X = 5, - E_META_NEWLOG_BIRCH_X = 6, - E_META_NEWLOG_JUNGLE_X = 7, - E_META_NEWLOG_OAK_Z = 8, - E_META_NEWLOG_SPRUCE_Z = 9, - E_META_NEWLOG_BIRCH_Z = 10, - E_META_NEWLOG_JUNGLE_Z = 11, - E_META_NEWLOG_OAK_BARK_ONLY = 12, - E_META_NEWLOG_SPRUCE_BARK_ONLY = 13, - E_META_NEWLOG_BIRCH_BARK_ONLY = 14, - E_META_NEWLOG_JUNGLE_BARK_ONLY = 15, - - // E_META_NEWLOG metas cont. (Block ID 162): + E_META_LOG_OAK_UP_DOWN = 0, + E_META_LOG_SPRUCE_UP_DOWN = 1, + E_META_LOG_BIRCH_UP_DOWN = 2, + E_META_LOG_JUNGLE_UP_DOWN = 3, + E_META_LOG_OAK_X = 4, + E_META_LOG_SPRUCE_X = 5, + E_META_LOG_BIRCH_X = 6, + E_META_LOG_JUNGLE_X = 7, + E_META_LOG_OAK_Z = 8, + E_META_LOG_SPRUCE_Z = 9, + E_META_LOG_BIRCH_Z = 10, + E_META_LOG_JUNGLE_Z = 11, + E_META_LOG_OAK_BARK_ONLY = 12, + E_META_LOG_SPRUCE_BARK_ONLY = 13, + E_META_LOG_BIRCH_BARK_ONLY = 14, + E_META_LOG_JUNGLE_BARK_ONLY = 15, + + // E_META_LOG metas cont. (Block ID 162): E_META_NEWLOG_ACACIA_UP_DOWN = 0, E_META_NEWLOG_DARK_OAK_UP_DOWN = 1, E_META_NEWLOG_ACACIA_X = 4, -- cgit v1.2.3 From 3e741134279e02d204a8d4638f2d46dfbf814d0c Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Fri, 12 Sep 2014 23:18:02 +0100 Subject: Implemented Chest Minecarts --- src/BlockEntities/BlockEntityWithItems.h | 2 +- src/BlockEntities/ChestEntity.cpp | 1 - src/BlockEntities/DispenserEntity.cpp | 1 - src/BlockEntities/DropSpenserEntity.cpp | 1 - src/BlockEntities/DropperEntity.cpp | 1 - src/BlockEntities/EnderChestEntity.h | 2 +- src/BlockEntities/FurnaceEntity.cpp | 1 - src/Entities/Minecart.cpp | 41 +++++++++++++++---- src/Entities/Minecart.h | 40 +++++++++++++----- src/UI/SlotArea.cpp | 35 ++++++++++++++++ src/UI/SlotArea.h | 14 +++++++ src/UI/Window.cpp | 30 ++++++++++++++ src/UI/Window.h | 15 +++++++ src/UI/WindowOwner.h | 69 +------------------------------- src/WorldStorage/NBTChunkSerializer.cpp | 2 +- 15 files changed, 161 insertions(+), 94 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/BlockEntityWithItems.h b/src/BlockEntities/BlockEntityWithItems.h index 5f1639d45..c19958e8d 100644 --- a/src/BlockEntities/BlockEntityWithItems.h +++ b/src/BlockEntities/BlockEntityWithItems.h @@ -23,7 +23,7 @@ class cBlockEntityWithItems : // tolua_end // tolua doesn't seem to support multiple inheritance? , public cItemGrid::cListener - , public cBlockEntityWindowOwner + , public cWindowOwner // tolua_begin { typedef cBlockEntity super; diff --git a/src/BlockEntities/ChestEntity.cpp b/src/BlockEntities/ChestEntity.cpp index 21e1f6ba2..13831b64a 100644 --- a/src/BlockEntities/ChestEntity.cpp +++ b/src/BlockEntities/ChestEntity.cpp @@ -15,7 +15,6 @@ cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_ super(a_Type, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), m_NumActivePlayers(0) { - cBlockEntityWindowOwner::SetBlockEntity(this); } diff --git a/src/BlockEntities/DispenserEntity.cpp b/src/BlockEntities/DispenserEntity.cpp index c02c68afa..649107dbb 100644 --- a/src/BlockEntities/DispenserEntity.cpp +++ b/src/BlockEntities/DispenserEntity.cpp @@ -17,7 +17,6 @@ cDispenserEntity::cDispenserEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : super(E_BLOCK_DISPENSER, a_BlockX, a_BlockY, a_BlockZ, a_World) { - SetBlockEntity(this); // cBlockEntityWindowOwner } diff --git a/src/BlockEntities/DropSpenserEntity.cpp b/src/BlockEntities/DropSpenserEntity.cpp index dc38e3e9b..c11a8c796 100644 --- a/src/BlockEntities/DropSpenserEntity.cpp +++ b/src/BlockEntities/DropSpenserEntity.cpp @@ -19,7 +19,6 @@ cDropSpenserEntity::cDropSpenserEntity(BLOCKTYPE a_BlockType, int a_BlockX, int m_ShouldDropSpense(false), m_IsPowered(false) { - SetBlockEntity(this); // cBlockEntityWindowOwner } diff --git a/src/BlockEntities/DropperEntity.cpp b/src/BlockEntities/DropperEntity.cpp index 5d4a8ad97..8f9ef210d 100644 --- a/src/BlockEntities/DropperEntity.cpp +++ b/src/BlockEntities/DropperEntity.cpp @@ -15,7 +15,6 @@ cDropperEntity::cDropperEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : super(E_BLOCK_DROPPER, a_BlockX, a_BlockY, a_BlockZ, a_World) { - SetBlockEntity(this); // cBlockEntityWindowOwner } diff --git a/src/BlockEntities/EnderChestEntity.h b/src/BlockEntities/EnderChestEntity.h index ed178f6fc..0715e9a29 100644 --- a/src/BlockEntities/EnderChestEntity.h +++ b/src/BlockEntities/EnderChestEntity.h @@ -12,7 +12,7 @@ // tolua_begin class cEnderChestEntity : public cBlockEntity, - public cBlockEntityWindowOwner + public cWindowOwner { typedef cBlockEntity super; diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index 72fd7f2b3..d2ffd643b 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -36,7 +36,6 @@ cFurnaceEntity::cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY m_LastProgressFuel(0), m_LastProgressCook(0) { - cBlockEntityWindowOwner::SetBlockEntity(this); m_Contents.AddListener(*this); } diff --git a/src/Entities/Minecart.cpp b/src/Entities/Minecart.cpp index 1501eea84..a3927298e 100644 --- a/src/Entities/Minecart.cpp +++ b/src/Entities/Minecart.cpp @@ -1103,29 +1103,54 @@ void cRideableMinecart::OnRightClicked(cPlayer & a_Player) // cMinecartWithChest: cMinecartWithChest::cMinecartWithChest(double a_X, double a_Y, double a_Z) : - super(mpChest, a_X, a_Y, a_Z) + super(mpChest, a_X, a_Y, a_Z), + m_Contents(ContentsWidth, ContentsHeight) { + m_Contents.AddListener(*this); } -void cMinecartWithChest::SetSlot(size_t a_Idx, const cItem & a_Item) +void cMinecartWithChest::OnRightClicked(cPlayer & a_Player) { - ASSERT(a_Idx < ARRAYCOUNT(m_Items)); - - m_Items[a_Idx] = a_Item; + // If the window is not created, open it anew: + cWindow * Window = GetWindow(); + if (Window == NULL) + { + OpenNewWindow(); + Window = GetWindow(); + } + + // Open the window for the player: + if (Window != NULL) + { + if (a_Player.GetWindow() != Window) + { + a_Player.OpenWindow(Window); + } + } } -void cMinecartWithChest::OnRightClicked(cPlayer & a_Player) +void cMinecartWithChest::OpenNewWindow() +{ + OpenWindow(new cMinecartWithChestWindow(this)); +} + + + + + +void cMinecartWithChest::Destroyed() { - // Show the chest UI window to the player - // TODO + cItems Pickups; + m_Contents.CopyToItems(Pickups); + GetWorld()->SpawnItemPickups(Pickups, GetPosX(), GetPosY() + 1, GetPosZ(), 4); } diff --git a/src/Entities/Minecart.h b/src/Entities/Minecart.h index 410d3c77d..f77a171ba 100644 --- a/src/Entities/Minecart.h +++ b/src/Entities/Minecart.h @@ -10,6 +10,7 @@ #pragma once #include "Entity.h" +#include "../UI/WindowOwner.h" @@ -108,27 +109,46 @@ protected: class cMinecartWithChest : - public cMinecart + public cMinecart, + public cItemGrid::cListener, + public cWindowOwner { typedef cMinecart super; public: CLASS_PROTODEF(cMinecartWithChest) - /// Number of item slots in the chest - static const int NumSlots = 9 * 3; - cMinecartWithChest(double a_X, double a_Y, double a_Z); + + enum + { + ContentsHeight = 3, + ContentsWidth = 9, + }; - const cItem & GetSlot(int a_Idx) const { return m_Items[a_Idx]; } - cItem & GetSlot(int a_Idx) { return m_Items[a_Idx]; } - - void SetSlot(size_t a_Idx, const cItem & a_Item); + const cItem & GetSlot(int a_Idx) const { return m_Contents.GetSlot(a_Idx); } + void SetSlot(size_t a_Idx, const cItem & a_Item) { m_Contents.SetSlot(a_Idx, a_Item); } protected: + cItemGrid m_Contents; + void OpenNewWindow(void); + virtual void Destroyed() override; - /// The chest contents: - cItem m_Items[NumSlots]; + // cItemGrid::cListener overrides: + virtual void OnSlotChanged(cItemGrid * a_Grid, int a_SlotNum) + { + UNUSED(a_SlotNum); + ASSERT(a_Grid == &m_Contents); + if (m_World != NULL) + { + if (GetWindow() != NULL) + { + GetWindow()->BroadcastWholeWindow(); + } + + m_World->MarkChunkDirty(GetChunkX(), GetChunkZ()); + } + } // cEntity overrides: virtual void OnRightClicked(cPlayer & a_Player) override; diff --git a/src/UI/SlotArea.cpp b/src/UI/SlotArea.cpp index b4facb2d3..999bed989 100644 --- a/src/UI/SlotArea.cpp +++ b/src/UI/SlotArea.cpp @@ -10,6 +10,7 @@ #include "../BlockEntities/DropSpenserEntity.h" #include "../BlockEntities/EnderChestEntity.h" #include "../BlockEntities/FurnaceEntity.h" +#include "../Entities/Minecart.h" #include "../Items/ItemHandler.h" #include "Window.h" #include "../CraftingRecipes.h" @@ -1919,6 +1920,40 @@ void cSlotAreaFurnace::HandleSmeltItem(const cItem & a_Result, cPlayer & a_Playe +//////////////////////////////////////////////////////////////////////////////// +// cSlotAreaMinecartWithChest: + +cSlotAreaMinecartWithChest::cSlotAreaMinecartWithChest(cMinecartWithChest * a_Chest, cWindow & a_ParentWindow) : + cSlotArea(27, a_ParentWindow), + m_Chest(a_Chest) +{ +} + + + + + +const cItem * cSlotAreaMinecartWithChest::GetSlot(int a_SlotNum, cPlayer & a_Player) const +{ + // a_SlotNum ranges from 0 to 26, use that to index the minecart chest entity's inventory directly: + UNUSED(a_Player); + return &(m_Chest->GetSlot(a_SlotNum)); +} + + + + + +void cSlotAreaMinecartWithChest::SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) +{ + UNUSED(a_Player); + m_Chest->SetSlot(a_SlotNum, a_Item); +} + + + + + //////////////////////////////////////////////////////////////////////////////// // cSlotAreaInventoryBase: diff --git a/src/UI/SlotArea.h b/src/UI/SlotArea.h index 6bbc87b76..0a35527d1 100644 --- a/src/UI/SlotArea.h +++ b/src/UI/SlotArea.h @@ -20,6 +20,7 @@ class cChestEntity; class cDropSpenserEntity; class cEnderChestEntity; class cFurnaceEntity; +class cMinecartWithChest; class cCraftingRecipe; class cEnchantingWindow; class cWorld; @@ -455,3 +456,16 @@ protected: + +class cSlotAreaMinecartWithChest : + public cSlotArea +{ +public: + cSlotAreaMinecartWithChest(cMinecartWithChest * a_ChestCart, cWindow & a_ParentWindow); + + virtual const cItem * GetSlot(int a_SlotNum, cPlayer & a_Player) const override; + virtual void SetSlot(int a_SlotNum, cPlayer & a_Player, const cItem & a_Item) override; + +protected: + cMinecartWithChest * m_Chest; +}; \ No newline at end of file diff --git a/src/UI/Window.cpp b/src/UI/Window.cpp index 66900269f..fd80a017d 100644 --- a/src/UI/Window.cpp +++ b/src/UI/Window.cpp @@ -14,6 +14,7 @@ #include "../BlockEntities/DropSpenserEntity.h" #include "../BlockEntities/EnderChestEntity.h" #include "../BlockEntities/HopperEntity.h" +#include "../Entities/Minecart.h" #include "../Root.h" #include "../Bindings/PluginManager.h" @@ -1047,6 +1048,34 @@ cChestWindow::~cChestWindow() +//////////////////////////////////////////////////////////////////////////////// +// cMinecartWithChestWindow: + +cMinecartWithChestWindow::cMinecartWithChestWindow(cMinecartWithChest * a_ChestCart) : + cWindow(wtChest, "Minecart with Chest"), + m_ChestCart(a_ChestCart) +{ + m_ShouldDistributeToHotbarFirst = false; + m_SlotAreas.push_back(new cSlotAreaMinecartWithChest(a_ChestCart, *this)); + m_SlotAreas.push_back(new cSlotAreaInventory(*this)); + m_SlotAreas.push_back(new cSlotAreaHotBar(*this)); + + a_ChestCart->GetWorld()->BroadcastSoundEffect("random.chestopen", a_ChestCart->GetPosX(), a_ChestCart->GetPosY(), a_ChestCart->GetPosZ(), 1, 1); +} + + + + + +cMinecartWithChestWindow::~cMinecartWithChestWindow() +{ + m_ChestCart->GetWorld()->BroadcastSoundEffect("random.chestclosed", m_ChestCart->GetPosX(), m_ChestCart->GetPosY(), m_ChestCart->GetPosZ(), 1, 1); +} + + + + + //////////////////////////////////////////////////////////////////////////////// // cDropSpenserWindow: @@ -1073,6 +1102,7 @@ cEnderChestWindow::cEnderChestWindow(cEnderChestEntity * a_EnderChest) : m_BlockY(a_EnderChest->GetPosY()), m_BlockZ(a_EnderChest->GetPosZ()) { + m_ShouldDistributeToHotbarFirst = false; m_SlotAreas.push_back(new cSlotAreaEnderChest(a_EnderChest, *this)); m_SlotAreas.push_back(new cSlotAreaInventory(*this)); m_SlotAreas.push_back(new cSlotAreaHotBar(*this)); diff --git a/src/UI/Window.h b/src/UI/Window.h index 3d860407f..f47cf4b99 100644 --- a/src/UI/Window.h +++ b/src/UI/Window.h @@ -23,6 +23,7 @@ class cDropSpenserEntity; class cEnderChestEntity; class cFurnaceEntity; class cHopperEntity; +class cMinecartWithChest; class cBeaconEntity; class cSlotArea; class cSlotAreaAnvil; @@ -360,6 +361,20 @@ protected: +class cMinecartWithChestWindow : + public cWindow +{ +public: + cMinecartWithChestWindow(cMinecartWithChest * a_ChestCart); + ~cMinecartWithChestWindow(); +private: + cMinecartWithChest * m_ChestCart; +}; + + + + + class cEnderChestWindow : public cWindow { diff --git a/src/UI/WindowOwner.h b/src/UI/WindowOwner.h index 7a7941e37..a8be3e6cb 100644 --- a/src/UI/WindowOwner.h +++ b/src/UI/WindowOwner.h @@ -52,77 +52,10 @@ public: { return m_Window; } - - /// Returns the block position at which the element owning the window is - virtual void GetBlockPos(int & a_BlockX, int & a_BlockY, int & a_BlockZ) = 0; private: cWindow * m_Window; -} ; - - - - - -/** -Window owner that is associated with a block entity (chest, furnace, ...) -*/ -class cBlockEntityWindowOwner : - public cWindowOwner -{ -public: - cBlockEntityWindowOwner(void) : - m_BlockEntity(NULL) - { - } - - void SetBlockEntity(cBlockEntity * a_BlockEntity) - { - m_BlockEntity = a_BlockEntity; - } - - virtual void GetBlockPos(int & a_BlockX, int & a_BlockY, int & a_BlockZ) override - { - a_BlockX = m_BlockEntity->GetPosX(); - a_BlockY = m_BlockEntity->GetPosY(); - a_BlockZ = m_BlockEntity->GetPosZ(); - } - -private: - cBlockEntity * m_BlockEntity; -} ; - - - - - -/** -Window owner that is associated with an entity (chest minecart) -*/ -class cEntityWindowOwner : - public cWindowOwner -{ -public: - cEntityWindowOwner(void) : - m_Entity(NULL) - { - } - - void SetEntity(cEntity * a_Entity) - { - m_Entity = a_Entity; - } - - virtual void GetBlockPos(int & a_BlockX, int & a_BlockY, int & a_BlockZ) override - { - a_BlockX = (int)floor(m_Entity->GetPosX() + 0.5); - a_BlockY = (int)floor(m_Entity->GetPosY() + 0.5); - a_BlockZ = (int)floor(m_Entity->GetPosZ() + 0.5); - } - -private: - cEntity * m_Entity; -} ; +}; diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp index 68e541eba..963e016d6 100644 --- a/src/WorldStorage/NBTChunkSerializer.cpp +++ b/src/WorldStorage/NBTChunkSerializer.cpp @@ -738,7 +738,7 @@ void cNBTChunkSerializer::AddItemFrameEntity(cItemFrame * a_ItemFrame) void cNBTChunkSerializer::AddMinecartChestContents(cMinecartWithChest * a_Minecart) { m_Writer.BeginList("Items", TAG_Compound); - for (int i = 0; i < cMinecartWithChest::NumSlots; i++) + for (int i = 0; i < cMinecartWithChest::ContentsHeight * cMinecartWithChest::ContentsWidth; i++) { const cItem & Item = a_Minecart->GetSlot(i); if (Item.IsEmpty()) -- cgit v1.2.3 From a8c7dadfd72e95e55a2773a69c796c087f95cfbb Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sat, 13 Sep 2014 11:14:17 +0100 Subject: Added newlines --- src/UI/SlotArea.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/UI/SlotArea.h b/src/UI/SlotArea.h index 0a35527d1..35743908a 100644 --- a/src/UI/SlotArea.h +++ b/src/UI/SlotArea.h @@ -468,4 +468,8 @@ public: protected: cMinecartWithChest * m_Chest; -}; \ No newline at end of file +}; + + + + -- cgit v1.2.3 From bc37b895bca7591e5fc9945bea54d9cac6a1deeb Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sat, 13 Sep 2014 11:15:16 +0100 Subject: e.t.c. -> etc. etcetera, not egg tray conglomerate :P --- src/UI/SlotArea.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/UI/SlotArea.h b/src/UI/SlotArea.h index 35743908a..1eeeb9836 100644 --- a/src/UI/SlotArea.h +++ b/src/UI/SlotArea.h @@ -449,7 +449,7 @@ protected: // cItemGrid::cListener overrides: virtual void OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) override; - /// Called after an item has been smelted to handle statistics e.t.c. + /// Called after an item has been smelted to handle statistics etc. void HandleSmeltItem(const cItem & a_Result, cPlayer & a_Player); } ; -- cgit v1.2.3 From 30f9a4d3abf9cf7f2b7b9f38d46bbb497e8f6b93 Mon Sep 17 00:00:00 2001 From: Masy98 Date: Sat, 27 Sep 2014 14:19:45 +0200 Subject: Fixed convertToPickups for doors --- src/Blocks/BlockDoor.h | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockDoor.h b/src/Blocks/BlockDoor.h index b2f9e4dcd..af6eee290 100644 --- a/src/Blocks/BlockDoor.h +++ b/src/Blocks/BlockDoor.h @@ -55,7 +55,44 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - a_Pickups.push_back(cItem((m_BlockType == E_BLOCK_WOODEN_DOOR) ? E_ITEM_WOODEN_DOOR : E_ITEM_IRON_DOOR, 1, 0)); + switch (m_BlockType) + { + case E_BLOCK_WOODEN_DOOR: + { + a_Pickups.Add(E_ITEM_WOODEN_DOOR); + break; + } + case E_BLOCK_ACACIA_DOOR: + { + a_Pickups.Add(E_ITEM_ACACIA_DOOR); + break; + } + case E_BLOCK_BIRCH_DOOR: + { + a_Pickups.Add(E_ITEM_BIRCH_DOOR); + break; + } + case E_BLOCK_DARK_OAK_DOOR: + { + a_Pickups.Add(E_ITEM_DARK_OAK_DOOR); + break; + } + case E_BLOCK_JUNGLE_DOOR: + { + a_Pickups.Add(E_ITEM_JUNGLE_DOOR); + break; + } + case E_BLOCK_SPRUCE_DOOR: + { + a_Pickups.Add(E_ITEM_SPRUCE_DOOR); + break; + } + case E_BLOCK_IRON_DOOR: + { + a_Pickups.Add(E_ITEM_IRON_DOOR); + break; + } + } } -- cgit v1.2.3 From 485bac281880e5828a8359b0197608f9bb964bb7 Mon Sep 17 00:00:00 2001 From: Masy98 Date: Sat, 27 Sep 2014 14:23:58 +0200 Subject: Fixed convertToPickups for fence gates --- src/Blocks/BlockFenceGate.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockFenceGate.h b/src/Blocks/BlockFenceGate.h index 3041dd46c..b5c1323bd 100644 --- a/src/Blocks/BlockFenceGate.h +++ b/src/Blocks/BlockFenceGate.h @@ -19,7 +19,7 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - a_Pickups.Add(E_BLOCK_FENCE_GATE, 1, 0); // Reset meta to zero + a_Pickups.Add(m_BlockType, 1, 0); // Reset meta to zero } -- cgit v1.2.3 From 6dd47e783af33cc7eecaf1837899c213bc09f954 Mon Sep 17 00:00:00 2001 From: Masy98 Date: Sat, 27 Sep 2014 15:11:35 +0200 Subject: Added default value to switch and spruce gate to fence gate handler --- src/Blocks/BlockDoor.h | 5 +++++ src/Blocks/BlockHandler.cpp | 1 + 2 files changed, 6 insertions(+) (limited to 'src') diff --git a/src/Blocks/BlockDoor.h b/src/Blocks/BlockDoor.h index af6eee290..0ff8bcfc8 100644 --- a/src/Blocks/BlockDoor.h +++ b/src/Blocks/BlockDoor.h @@ -92,6 +92,11 @@ public: a_Pickups.Add(E_ITEM_IRON_DOOR); break; } + default: + { + ASSERT(!"Unhandled door type!"); + break; + } } } diff --git a/src/Blocks/BlockHandler.cpp b/src/Blocks/BlockHandler.cpp index 7bfff0545..ff0b201e7 100644 --- a/src/Blocks/BlockHandler.cpp +++ b/src/Blocks/BlockHandler.cpp @@ -294,6 +294,7 @@ cBlockHandler * cBlockHandler::CreateBlockHandler(BLOCKTYPE a_BlockType) case E_BLOCK_SIGN_POST: return new cBlockSignPostHandler (a_BlockType); case E_BLOCK_SNOW: return new cBlockSnowHandler (a_BlockType); case E_BLOCK_SPRUCE_DOOR: return new cBlockDoorHandler (a_BlockType); + case E_BLOCK_SPRUCE_FENCE_GATE: return new cBlockFenceGateHandler (a_BlockType); case E_BLOCK_SPRUCE_WOOD_STAIRS: return new cBlockStairsHandler (a_BlockType); case E_BLOCK_STAINED_GLASS: return new cBlockGlassHandler (a_BlockType); case E_BLOCK_STAINED_GLASS_PANE: return new cBlockGlassHandler (a_BlockType); -- cgit v1.2.3 From 72c087cfd335b015139cb73ae78f74105d855cf0 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sat, 27 Sep 2014 14:28:14 +0100 Subject: Dropped support for <1.7.x --- src/ClientHandle.cpp | 14 - src/ClientHandle.h | 1 - src/Protocol/CMakeLists.txt | 10 - src/Protocol/Protocol.h | 101 +- src/Protocol/Protocol125.cpp | 2175 ----------------------------------- src/Protocol/Protocol125.h | 185 --- src/Protocol/Protocol132.cpp | 880 -------------- src/Protocol/Protocol132.h | 115 -- src/Protocol/Protocol14x.cpp | 265 ----- src/Protocol/Protocol14x.h | 63 - src/Protocol/Protocol15x.cpp | 209 ---- src/Protocol/Protocol15x.h | 42 - src/Protocol/Protocol16x.cpp | 312 ----- src/Protocol/Protocol16x.h | 78 -- src/Protocol/Protocol17x.cpp | 14 - src/Protocol/Protocol17x.h | 3 - src/Protocol/Protocol18x.cpp | 14 - src/Protocol/Protocol18x.h | 3 - src/Protocol/ProtocolRecognizer.cpp | 205 +--- src/Protocol/ProtocolRecognizer.h | 32 +- src/Root.cpp | 12 - src/Root.h | 6 - 22 files changed, 6 insertions(+), 4733 deletions(-) delete mode 100644 src/Protocol/Protocol125.cpp delete mode 100644 src/Protocol/Protocol125.h delete mode 100644 src/Protocol/Protocol132.cpp delete mode 100644 src/Protocol/Protocol132.h delete mode 100644 src/Protocol/Protocol14x.cpp delete mode 100644 src/Protocol/Protocol14x.h delete mode 100644 src/Protocol/Protocol15x.cpp delete mode 100644 src/Protocol/Protocol15x.h delete mode 100644 src/Protocol/Protocol16x.cpp delete mode 100644 src/Protocol/Protocol16x.h (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 878d309c9..9858aa991 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -1741,20 +1741,6 @@ void cClientHandle::HandleRespawn(void) -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(*this, a_Reason); - - m_HasSentDC = true; - Destroy(); -} - - - - - void cClientHandle::HandleKeepAlive(int a_KeepAliveID) { if (a_KeepAliveID == m_PingID) diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 0a936a2ca..10cf6ae28 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -239,7 +239,6 @@ public: void HandleAnimation (char a_Animation); void HandleChat (const AString & a_Message); void HandleCreativeInventory(short a_SlotNum, const cItem & a_HeldItem); - void HandleDisconnect (const AString & a_Reason); void HandleEntityCrouch (int a_EntityID, bool a_IsCrouching); void HandleEntityLeaveBed (int a_EntityID); void HandleEntitySprinting (int a_EntityID, bool a_IsSprinting); diff --git a/src/Protocol/CMakeLists.txt b/src/Protocol/CMakeLists.txt index 5426c58fa..7c97e67bc 100644 --- a/src/Protocol/CMakeLists.txt +++ b/src/Protocol/CMakeLists.txt @@ -8,11 +8,6 @@ SET (SRCS Authenticator.cpp ChunkDataSerializer.cpp MojangAPI.cpp - Protocol125.cpp - Protocol132.cpp - Protocol14x.cpp - Protocol15x.cpp - Protocol16x.cpp Protocol17x.cpp Protocol18x.cpp ProtocolRecognizer.cpp) @@ -22,11 +17,6 @@ SET (HDRS ChunkDataSerializer.h MojangAPI.h Protocol.h - Protocol125.h - Protocol132.h - Protocol14x.h - Protocol15x.h - Protocol16x.h Protocol17x.h Protocol18x.h ProtocolRecognizer.h) diff --git a/src/Protocol/Protocol.h b/src/Protocol/Protocol.h index b2ee92918..7225f663d 100644 --- a/src/Protocol/Protocol.h +++ b/src/Protocol/Protocol.h @@ -138,108 +138,9 @@ public: protected: cClientHandle * m_Client; cCriticalSection m_CSPacket; // Each SendXYZ() function must acquire this CS in order to send the whole packet at once - + /// A generic data-sending routine, all outgoing packet data needs to be routed through this so that descendants may override it virtual void SendData(const char * a_Data, size_t a_Size) = 0; - - /// Called after writing each packet, enables descendants to flush their buffers - virtual void Flush(void) {} - - // Helpers for writing partial packet data, write using SendData() - void WriteByte(Byte a_Value) - { - SendData((const char *)&a_Value, 1); - } - - void WriteChar(char a_Value) - { - SendData(&a_Value, 1); - } - - void WriteShort(short a_Value) - { - u_short Value = htons((u_short)a_Value); - SendData((const char *)&Value, 2); - } - - /* - void WriteShort(unsigned short a_Value) - { - a_Value = htons(a_Value); - SendData((const char *)&a_Value, 2); - } - */ - - void WriteInt(int a_Value) - { - u_long Value = htonl((u_long)a_Value); - SendData((const char *)&Value, 4); - } - - void WriteUInt(unsigned int a_Value) - { - a_Value = htonl(a_Value); - SendData((const char *)&a_Value, 4); - } - - void WriteInt64 (Int64 a_Value) - { - UInt64 Value = HostToNetwork8(&a_Value); - SendData((const char *)&Value, 8); - } - - void WriteFloat (float a_Value) - { - UInt32 val = HostToNetwork4(&a_Value); - SendData((const char *)&val, 4); - } - - void WriteDouble(double a_Value) - { - UInt64 val = HostToNetwork8(&a_Value); - SendData((const char *)&val, 8); - } - - void WriteString(const AString & a_Value) - { - AString UTF16; - UTF8ToRawBEUTF16(a_Value.c_str(), a_Value.length(), UTF16); - WriteShort((short)(UTF16.size() / 2)); - SendData(UTF16.data(), UTF16.size()); - } - - void WriteBool(bool a_Value) - { - WriteByte(a_Value ? 1 : 0); - } - - void WriteVectorI(const Vector3i & a_Vector) - { - WriteInt(a_Vector.x); - WriteInt(a_Vector.y); - WriteInt(a_Vector.z); - } - - void WriteVarInt(UInt32 a_Value) - { - // A 32-bit integer can be encoded by at most 5 bytes: - unsigned char b[5]; - size_t idx = 0; - do - { - b[idx] = (a_Value & 0x7f) | ((a_Value > 0x7f) ? 0x80 : 0x00); - a_Value = a_Value >> 7; - idx++; - } while (a_Value > 0); - - SendData((const char *)b, idx); - } - - void WriteVarUTF8String(const AString & a_String) - { - WriteVarInt((UInt32)a_String.size()); - SendData(a_String.data(), a_String.size()); - } } ; diff --git a/src/Protocol/Protocol125.cpp b/src/Protocol/Protocol125.cpp deleted file mode 100644 index 369a35e18..000000000 --- a/src/Protocol/Protocol125.cpp +++ /dev/null @@ -1,2175 +0,0 @@ - -// Protocol125.cpp - -// Implements the cProtocol125 class representing the release 1.2.5 protocol (#29) -/* -Documentation: - - protocol: http://wiki.vg/wiki/index.php?title=Protocol&oldid=2513 - - session handling: http://wiki.vg/wiki/index.php?title=Session&oldid=2262 - - slot format: http://wiki.vg/wiki/index.php?title=Slot_Data&oldid=2152 -*/ - -#include "Globals.h" - -#include "Protocol125.h" - -#include "../ClientHandle.h" -#include "../World.h" -#include "ChunkDataSerializer.h" -#include "../Entities/Entity.h" -#include "../Entities/ExpOrb.h" -#include "../Mobs/Monster.h" -#include "../Entities/Pickup.h" -#include "../Entities/Player.h" -#include "../ChatColor.h" -#include "../UI/Window.h" -#include "../Root.h" -#include "../Server.h" - -#include "../Entities/ArrowEntity.h" -#include "../Entities/Minecart.h" -#include "../Entities/FallingBlock.h" - -#include "../Mobs/IncludeAllMonsters.h" - -#include "../CompositeChat.h" - - - - - -enum -{ - PACKET_KEEP_ALIVE = 0x00, - PACKET_LOGIN = 0x01, - PACKET_HANDSHAKE = 0x02, - PACKET_CHAT = 0x03, - PACKET_UPDATE_TIME = 0x04, - PACKET_ENTITY_EQUIPMENT = 0x05, - PACKET_USE_ENTITY = 0x07, - PACKET_UPDATE_HEALTH = 0x08, - PACKET_RESPAWN = 0x09, - PACKET_PLAYER_ON_GROUND = 0x0a, - PACKET_PLAYER_POS = 0x0b, - PACKET_PLAYER_LOOK = 0x0c, - PACKET_PLAYER_MOVE_LOOK = 0x0d, - PACKET_BLOCK_DIG = 0x0e, - PACKET_BLOCK_PLACE = 0x0f, - PACKET_SLOT_SELECTED = 0x10, - PACKET_USE_BED = 0x11, - PACKET_ANIMATION = 0x12, - PACKET_PACKET_ENTITY_ACTION = 0x13, - PACKET_PLAYER_SPAWN = 0x14, - PACKET_PICKUP_SPAWN = 0x15, - PACKET_COLLECT_PICKUP = 0x16, - PACKET_SPAWN_OBJECT = 0x17, - PACKET_SPAWN_MOB = 0x18, - PACKET_ENTITY_VELOCITY = 0x1c, - PACKET_DESTROY_ENTITY = 0x1d, - PACKET_ENTITY = 0x1e, - PACKET_ENT_REL_MOVE = 0x1f, - PACKET_ENT_LOOK = 0x20, - PACKET_ENT_REL_MOVE_LOOK = 0x21, - PACKET_ENT_TELEPORT = 0x22, - PACKET_ENT_HEAD_LOOK = 0x23, - PACKET_ENT_STATUS = 0x26, - PACKET_ATTACH_ENTITY = 0x27, - PACKET_METADATA = 0x28, - PACKET_ENTITY_EFFECT = 0x29, - PACKET_SPAWN_EXPERIENCE_ORB = 0x1A, - PACKET_REMOVE_ENTITY_EFFECT = 0x2a, - PACKET_EXPERIENCE = 0x2b, - PACKET_PRE_CHUNK = 0x32, - PACKET_MAP_CHUNK = 0x33, - PACKET_MULTI_BLOCK = 0x34, - PACKET_BLOCK_CHANGE = 0x35, - PACKET_BLOCK_ACTION = 0x36, - PACKET_EXPLOSION = 0x3C, - PACKET_SOUND_EFFECT = 0x3e, - PACKET_SOUND_PARTICLE_EFFECT = 0x3d, - PACKET_CHANGE_GAME_STATE = 0x46, - PACKET_THUNDERBOLT = 0x47, - PACKET_WINDOW_OPEN = 0x64, - PACKET_WINDOW_CLOSE = 0x65, - PACKET_WINDOW_CLICK = 0x66, - PACKET_INVENTORY_SLOT = 0x67, - PACKET_INVENTORY_WHOLE = 0x68, - PACKET_WINDOW_PROPERTY = 0x69, - PACKET_CREATIVE_INVENTORY_ACTION = 0x6B, - PACKET_ENCHANT_ITEM = 0x6C, - PACKET_UPDATE_SIGN = 0x82, - PACKET_ITEM_DATA = 0x83, - PACKET_INCREMENT_STATISTIC = 0xC8, - PACKET_PLAYER_LIST_ITEM = 0xC9, - PACKET_PLAYER_ABILITIES = 0xca, - PACKET_PLUGIN_MESSAGE = 0xfa, - PACKET_PING = 0xfe, - PACKET_DISCONNECT = 0xff -} ; - - - - - -#define HANDLE_PACKET_READ(Proc, Type, Var) \ - Type Var; \ - { \ - if (!m_ReceivedData.Proc(Var)) \ - { \ - m_ReceivedData.CheckValid(); \ - return PARSE_INCOMPLETE; \ - } \ - m_ReceivedData.CheckValid(); \ - } - - - - -typedef unsigned char Byte; - - - - - -cProtocol125::cProtocol125(cClientHandle * a_Client) : - super(a_Client), - m_ReceivedData(32 KiB), - m_LastSentDimension(dimNotSet) -{ -} - - - - - -void cProtocol125::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_Vehicle) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ATTACH_ENTITY); - WriteInt(a_Entity.GetUniqueID()); - WriteInt((a_Vehicle == NULL) ? -1 : a_Vehicle->GetUniqueID()); - Flush(); -} - - - - - -void cProtocol125::SendBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType) -{ - UNUSED(a_BlockType); - - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_BLOCK_ACTION); - WriteInt (a_BlockX); - WriteShort((short)a_BlockY); - WriteInt (a_BlockZ); - WriteChar (a_Byte1); - WriteChar (a_Byte2); - Flush(); -} - - - - - -void cProtocol125::SendBlockBreakAnim(int a_entityID, int a_BlockX, int a_BlockY, int a_BlockZ, char stage) -{ - // Not supported in this protocol version -} - - - - - -void cProtocol125::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_BLOCK_CHANGE); - WriteInt (a_BlockX); - WriteByte((unsigned char)a_BlockY); - WriteInt (a_BlockZ); - WriteByte(a_BlockType); - WriteByte(a_BlockMeta); - Flush(); -} - - - - - -void cProtocol125::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSetBlockVector & a_Changes) -{ - cCSLock Lock(m_CSPacket); - if (a_Changes.size() == 1) - { - // Special packet for single-block changes - const sSetBlock & blk = a_Changes.front(); - SendBlockChange(a_ChunkX * cChunkDef::Width + blk.x, blk.y, a_ChunkZ * cChunkDef::Width + blk.z, blk.BlockType, blk.BlockMeta); - return; - } - - WriteByte (PACKET_MULTI_BLOCK); - WriteInt (a_ChunkX); - WriteInt (a_ChunkZ); - WriteShort((short)a_Changes.size()); - WriteUInt ((UInt32)(4 * a_Changes.size())); - for (sSetBlockVector::const_iterator itr = a_Changes.begin(), end = a_Changes.end(); itr != end; ++itr) - { - UInt32 Coords = ((UInt32)itr->y) | ((UInt32)(itr->z << 8)) | ((UInt32)(itr->x << 12)); - UInt32 Blocks = ((UInt32)itr->BlockMeta) | ((UInt32)(itr->BlockType << 4)); - WriteUInt(Coords << 16 | Blocks); - } - Flush(); -} - - - - - -void cProtocol125::SendChat(const AString & a_Message) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_CHAT); - WriteString(a_Message); - Flush(); -} - - - - - -void cProtocol125::SendChat(const cCompositeChat & a_Message) -{ - // This version doesn't support composite messages, just extract each part's text and use it: - - // Send the message: - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_CHAT); - WriteString(a_Message.ExtractText()); - Flush(); -} - - - - - -void cProtocol125::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) -{ - cCSLock Lock(m_CSPacket); - - // Send the pre-chunk: - SendPreChunk(a_ChunkX, a_ChunkZ, true); - - // Send the chunk data: - AString Serialized = a_Serializer.Serialize(cChunkDataSerializer::RELEASE_1_2_5, a_ChunkX, a_ChunkZ); - WriteByte(PACKET_MAP_CHUNK); - WriteInt (a_ChunkX); - WriteInt (a_ChunkZ); - SendData(Serialized.data(), Serialized.size()); - Flush(); -} - - - - - -void cProtocol125::SendCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_COLLECT_PICKUP); - WriteInt (a_Entity.GetUniqueID()); - WriteInt (a_Player.GetUniqueID()); - Flush(); -} - - - - - -void cProtocol125::SendDestroyEntity(const cEntity & a_Entity) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_DESTROY_ENTITY); - WriteInt (a_Entity.GetUniqueID()); - Flush(); -} - - - - - -void cProtocol125::SendDisconnect(const AString & a_Reason) -{ - cCSLock Lock(m_CSPacket); - WriteByte ((unsigned char)PACKET_DISCONNECT); - WriteString(a_Reason); - Flush(); -} - - - - - -void cProtocol125::SendEditSign(int a_BlockX, int a_BlockY, int a_BlockZ) -{ - // This protocol version doesn't support this packet, sign editor is invoked by the client automatically - UNUSED(a_BlockX); - UNUSED(a_BlockY); - UNUSED(a_BlockZ); -} - - - - - -void cProtocol125::SendEntityEffect(const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_ENTITY_EFFECT); - WriteInt (a_Entity.GetUniqueID()); - WriteByte ((Byte)a_EffectID); - WriteByte ((Byte)a_Amplifier); - WriteShort(a_Duration); - Flush(); -} - - - - - -void cProtocol125::SendEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_ENTITY_EQUIPMENT); - WriteInt (a_Entity.GetUniqueID()); - WriteShort(a_SlotNum); - WriteShort(a_Item.m_ItemType); - WriteShort(a_Item.m_ItemDamage); - Flush(); -} - - - - - -void cProtocol125::SendEntityHeadLook(const cEntity & a_Entity) -{ - ASSERT(a_Entity.GetUniqueID() != m_Client->GetPlayer()->GetUniqueID()); // Must not send for self - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ENT_HEAD_LOOK); - WriteInt (a_Entity.GetUniqueID()); - WriteChar((char)((a_Entity.GetHeadYaw() / 360.f) * 256)); - Flush(); -} - - - - - -void cProtocol125::SendEntityLook(const cEntity & a_Entity) -{ - ASSERT(a_Entity.GetUniqueID() != m_Client->GetPlayer()->GetUniqueID()); // Must not send for self - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ENT_LOOK); - WriteInt (a_Entity.GetUniqueID()); - WriteChar((char)((a_Entity.GetYaw() / 360.f) * 256)); - WriteChar((char)((a_Entity.GetPitch() / 360.f) * 256)); - Flush(); -} - - - - - -void cProtocol125::SendEntityMetadata(const cEntity & a_Entity) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_METADATA); - WriteInt (a_Entity.GetUniqueID()); - - WriteCommonMetadata(a_Entity); - if (a_Entity.IsMob()) - { - WriteMobMetadata(((const cMonster &)a_Entity)); - } - else - { - WriteEntityMetadata(a_Entity); - } - WriteByte(0x7f); - - Flush(); -} - - - - - -void cProtocol125::SendEntityProperties(const cEntity & a_Entity) -{ - // Not supported in this protocol version -} - - - - - -void cProtocol125::SendEntityRelMove(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) -{ - ASSERT(a_Entity.GetUniqueID() != m_Client->GetPlayer()->GetUniqueID()); // Must not send for self - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ENT_REL_MOVE); - WriteInt (a_Entity.GetUniqueID()); - WriteChar(a_RelX); - WriteChar(a_RelY); - WriteChar(a_RelZ); - Flush(); -} - - - - - -void cProtocol125::SendEntityRelMoveLook(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) -{ - ASSERT(a_Entity.GetUniqueID() != m_Client->GetPlayer()->GetUniqueID()); // Must not send for self - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ENT_REL_MOVE_LOOK); - WriteInt (a_Entity.GetUniqueID()); - WriteChar(a_RelX); - WriteChar(a_RelY); - WriteChar(a_RelZ); - WriteChar((char)((a_Entity.GetYaw() / 360.f) * 256)); - WriteChar((char)((a_Entity.GetPitch() / 360.f) * 256)); - Flush(); -} - - - - - -void cProtocol125::SendEntityStatus(const cEntity & a_Entity, char a_Status) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ENT_STATUS); - WriteInt (a_Entity.GetUniqueID()); - WriteChar(a_Status); - Flush(); -} - - - - - -void cProtocol125::SendEntityVelocity(const cEntity & a_Entity) -{ - ASSERT(a_Entity.GetUniqueID() != m_Client->GetPlayer()->GetUniqueID()); // Must not send for self - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ENTITY_VELOCITY); - WriteInt (a_Entity.GetUniqueID()); - WriteShort((short) (a_Entity.GetSpeedX() * 400)); // 400 = 8000 / 20 - WriteShort((short) (a_Entity.GetSpeedY() * 400)); - WriteShort((short) (a_Entity.GetSpeedZ() * 400)); - Flush(); -} - - - - - -void cProtocol125::SendExplosion(double a_BlockX, double a_BlockY, double a_BlockZ, float a_Radius, const cVector3iArray & a_BlocksAffected, const Vector3d & a_PlayerMotion) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_EXPLOSION); - WriteDouble (a_BlockX); - WriteDouble (a_BlockY); - WriteDouble (a_BlockZ); - WriteFloat (a_Radius); - WriteInt ((Int32)a_BlocksAffected.size()); - int BlockX = (int)a_BlockX; - int BlockY = (int)a_BlockY; - int BlockZ = (int)a_BlockZ; - for (cVector3iArray::const_iterator itr = a_BlocksAffected.begin(); itr != a_BlocksAffected.end(); ++itr) - { - WriteByte((Byte)(itr->x - BlockX)); - WriteByte((Byte)(itr->y - BlockY)); - WriteByte((Byte)(itr->z - BlockZ)); - } - WriteFloat((float)a_PlayerMotion.x); - WriteFloat((float)a_PlayerMotion.y); - WriteFloat((float)a_PlayerMotion.z); - Flush(); -} - - - - - -void cProtocol125::SendGameMode(eGameMode a_GameMode) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_CHANGE_GAME_STATE); - WriteByte(3); - WriteChar((char)a_GameMode); - Flush(); -} - - - - - -void cProtocol125::SendHandshake(const AString & a_ConnectionHash) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_HANDSHAKE); - WriteString(a_ConnectionHash); - Flush(); -} - - - - - -void cProtocol125::SendHealth(void) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_UPDATE_HEALTH); - cPlayer * Player = m_Client->GetPlayer(); - WriteShort((short)Player->GetHealth()); - WriteShort((short)Player->GetFoodLevel()); - WriteFloat((float)Player->GetFoodSaturationLevel()); - Flush(); -} - - - - - -void cProtocol125::SendInventorySlot(char a_WindowID, short a_SlotNum, const cItem & a_Item) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_INVENTORY_SLOT); - WriteChar (a_WindowID); - WriteShort(a_SlotNum); - WriteItem (a_Item); - Flush(); -} - - - - - -void cProtocol125::SendKeepAlive(int a_PingID) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_KEEP_ALIVE); - WriteInt (a_PingID); - Flush(); -} - - - - - -void cProtocol125::SendLogin(const cPlayer & a_Player, const cWorld & a_World) -{ - UNUSED(a_World); - cCSLock Lock(m_CSPacket); - - WriteByte (PACKET_LOGIN); - WriteInt (a_Player.GetUniqueID()); // EntityID of the player - WriteString(""); // Username, not used - WriteString("default"); // Level type - WriteInt ((int)a_Player.GetGameMode()); - WriteInt ((int)(a_World.GetDimension())); - WriteByte (2); // TODO: Difficulty - WriteByte (0); // Unused - WriteByte (60); // Client list width or something - Flush(); - m_LastSentDimension = a_World.GetDimension(); -} - - - - - -void cProtocol125::SendLoginSuccess(void) -{ - // Not supported in this protocol version -} - - - - - -void cProtocol125::SendMapColumn(int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length, unsigned int m_Scale) -{ - cCSLock Lock(m_CSPacket); - - WriteByte (PACKET_ITEM_DATA); - WriteShort(E_ITEM_MAP); - WriteShort((short)a_ID); - WriteShort((short)(3 + a_Length)); - - WriteByte(0); - WriteChar((char)a_X); - WriteChar((char)a_Y); - - SendData((const char *)a_Colors, a_Length); - - Flush(); -} - - - - - -void cProtocol125::SendMapDecorators(int a_ID, const cMapDecoratorList & a_Decorators, unsigned int m_Scale) -{ - cCSLock Lock(m_CSPacket); - - WriteByte (PACKET_ITEM_DATA); - WriteShort(E_ITEM_MAP); - WriteShort((short)a_ID); - WriteShort((short)(1 + (3 * a_Decorators.size()))); - - WriteByte(1); - - for (cMapDecoratorList::const_iterator it = a_Decorators.begin(); it != a_Decorators.end(); ++it) - { - WriteByte((Byte)(it->GetType() << 4) | (it->GetRot() & 0xf)); - WriteByte((Byte)it->GetPixelX()); - WriteByte((Byte)it->GetPixelZ()); - } - - Flush(); -} - - - - - - -void cProtocol125::SendMapInfo(int a_ID, unsigned int a_Scale) -{ - // This protocol doesn't support such message - UNUSED(a_ID); - UNUSED(a_Scale); -} - - - - - -void cProtocol125::SendPickupSpawn(const cPickup & a_Pickup) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_PICKUP_SPAWN); - WriteInt (a_Pickup.GetUniqueID()); - const cItem & Item = a_Pickup.GetItem(); - WriteShort (Item.m_ItemType); - WriteChar (Item.m_ItemCount); - WriteShort (Item.m_ItemDamage); - WriteVectorI((Vector3i)(a_Pickup.GetPosition() * 32)); - WriteByte ((char)(a_Pickup.GetSpeedX() * 8)); - WriteByte ((char)(a_Pickup.GetSpeedY() * 8)); - WriteByte ((char)(a_Pickup.GetSpeedZ() * 8)); - Flush(); -} - - - - - -void cProtocol125::SendEntityAnimation(const cEntity & a_Entity, char a_Animation) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ANIMATION); - WriteInt (a_Entity.GetUniqueID()); - WriteChar(a_Animation); - Flush(); -} - - - - - -void cProtocol125::SendParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount) -{ - // Not supported by this protocol version -} - - - - - -void cProtocol125::SendPaintingSpawn(const cPainting & a_Painting) -{ - // Not implemented in this protocol version - UNUSED(a_Painting); -} - - - - - -void cProtocol125::SendPlayerListAddPlayer(const cPlayer & a_Player) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_PLAYER_LIST_ITEM); - WriteString(a_Player.GetPlayerListName()); - WriteBool (true); - WriteShort (a_Player.GetClientHandle()->GetPing()); - Flush(); -} - - - - - -void cProtocol125::SendPlayerListRemovePlayer(const cPlayer & a_Player) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_PLAYER_LIST_ITEM); - WriteString(a_Player.GetPlayerListName()); - WriteBool (false); - WriteShort (0); - Flush(); -} - - - - - -void cProtocol125::SendPlayerListUpdateGameMode(const cPlayer & a_Player) -{ - // Not implemented in this protocol version - UNUSED(a_Player); -} - - - - - -void cProtocol125::SendPlayerListUpdatePing(const cPlayer & a_Player) -{ - // It is a simple add player packet in this protocol. - SendPlayerListAddPlayer(a_Player); -} - - - - - -void cProtocol125::SendPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName) -{ - // Not implemented in this protocol version - UNUSED(a_Player); - UNUSED(a_CustomName); -} - - - - - -void cProtocol125::SendPlayerMaxSpeed(void) -{ - // Not supported by this protocol version -} - - - - - -void cProtocol125::SendPlayerMoveLook(void) -{ - cCSLock Lock(m_CSPacket); - - /* - LOGD("Sending PlayerMoveLook: {%0.2f, %0.2f, %0.2f}, stance %0.2f, OnGround: %d", - m_Player->GetPosX(), m_Player->GetPosY(), m_Player->GetPosZ(), m_Player->GetStance(), m_Player->IsOnGround() ? 1 : 0 - ); - */ - - WriteByte(PACKET_PLAYER_MOVE_LOOK); - cPlayer * Player = m_Client->GetPlayer(); - WriteDouble(Player->GetPosX()); - WriteDouble(Player->GetStance() + 0.03); // Add a small amount so that the player doesn't start inside a block - WriteDouble(Player->GetPosY() + 0.03); // Add a small amount so that the player doesn't start inside a block - WriteDouble(Player->GetPosZ()); - WriteFloat ((float)(Player->GetYaw())); - WriteFloat ((float)(Player->GetPitch())); - WriteBool (Player->IsOnGround()); - Flush(); -} - - - - - -void cProtocol125::SendPlayerPosition(void) -{ - cCSLock Lock(m_CSPacket); - LOGD("Ignore send PlayerPos"); // PlayerPos is a C->S packet only now -} - - - - - -void cProtocol125::SendPlayerSpawn(const cPlayer & a_Player) -{ - const cItem & HeldItem = a_Player.GetEquippedItem(); - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_PLAYER_SPAWN); - WriteInt (a_Player.GetUniqueID()); - if (a_Player.HasCustomName()) - { - WriteString(a_Player.GetCustomName()); - } - else - { - WriteString(a_Player.GetName()); - } - WriteInt ((int)(a_Player.GetPosX() * 32)); - WriteInt ((int)(a_Player.GetPosY() * 32)); - WriteInt ((int)(a_Player.GetPosZ() * 32)); - WriteChar ((char)((a_Player.GetYaw() / 360.f) * 256)); - WriteChar ((char)((a_Player.GetPitch() / 360.f) * 256)); - WriteShort (HeldItem.IsEmpty() ? 0 : HeldItem.m_ItemType); - Flush(); -} - - - - - -void cProtocol125::SendPluginMessage(const AString & a_Channel, const AString & a_Message) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_PLUGIN_MESSAGE); - WriteString(a_Channel); - WriteShort((short)a_Message.size()); - SendData(a_Message.data(), a_Message.size()); - Flush(); -} - - - - - -void cProtocol125::SendRemoveEntityEffect(const cEntity & a_Entity, int a_EffectID) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_REMOVE_ENTITY_EFFECT); - WriteInt (a_Entity.GetUniqueID()); - WriteChar((char)a_EffectID); - Flush(); -} - - - - - -void cProtocol125::SendRespawn(eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks) -{ - cCSLock Lock(m_CSPacket); - if ((m_LastSentDimension == a_Dimension) && !a_ShouldIgnoreDimensionChecks) - { - // Must not send a respawn for the world with the same dimension, the client goes cuckoo if we do (unless we are respawning from death) - return; - } - cPlayer * Player = m_Client->GetPlayer(); - WriteByte (PACKET_RESPAWN); - WriteInt ((int)(a_Dimension)); - WriteByte (2); // TODO: Difficulty; 2 = Normal - WriteChar ((char)Player->GetGameMode()); - WriteShort (256); // Current world height - WriteString("default"); - Flush(); - m_LastSentDimension = a_Dimension; -} - - - - - -void cProtocol125::SendExperience(void) -{ - cCSLock Lock(m_CSPacket); - cPlayer * Player = m_Client->GetPlayer(); - WriteByte (PACKET_EXPERIENCE); - WriteFloat (Player->GetXpPercentage()); - WriteShort (Player->GetXpLevel()); - WriteShort (Player->GetCurrentXp()); - Flush(); -} - - - - - -void cProtocol125::SendExperienceOrb(const cExpOrb & a_ExpOrb) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_SPAWN_EXPERIENCE_ORB); - WriteInt(a_ExpOrb.GetUniqueID()); - WriteInt((int) a_ExpOrb.GetPosX()); - WriteInt((int) a_ExpOrb.GetPosY()); - WriteInt((int) a_ExpOrb.GetPosZ()); - WriteShort((short)a_ExpOrb.GetReward()); - Flush(); -} - - - - - -void cProtocol125::SendScoreboardObjective(const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) -{ - // This protocol version doesn't support such message - UNUSED(a_Name); - UNUSED(a_DisplayName); - UNUSED(a_Mode); -} - - - - - -void cProtocol125::SendSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch) -{ - // Not needed in this protocol version -} - - - - - -void cProtocol125::SendSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) -{ - // Not implemented in this protocol version -} - - - - - -void cProtocol125::SendSpawnFallingBlock(const cFallingBlock & a_FallingBlock) -{ - // This protocol version implements falling blocks using the spawn object / vehicle packet: - SendSpawnObject(a_FallingBlock, 70, a_FallingBlock.GetBlockType(), 0, 0); -} - - - - - -void cProtocol125::SendSpawnMob(const cMonster & a_Mob) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_SPAWN_MOB); - WriteInt (a_Mob.GetUniqueID()); - WriteByte ((Byte)a_Mob.GetMobType()); - WriteVectorI((Vector3i)(a_Mob.GetPosition() * 32)); - WriteByte (0); - WriteByte (0); - WriteByte (0); - - WriteCommonMetadata(a_Mob); - WriteMobMetadata(a_Mob); - WriteByte(0x7f); - - Flush(); -} - - - - - -void cProtocol125::SendSpawnObject(const cEntity & a_Entity, char a_ObjectType, int a_ObjectData, Byte a_Yaw, Byte a_Pitch) -{ - UNUSED(a_Yaw); - UNUSED(a_Pitch); - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_SPAWN_OBJECT); - WriteInt (a_Entity.GetUniqueID()); - WriteChar(a_ObjectType); - WriteInt ((int)(a_Entity.GetPosX() * 32)); - WriteInt ((int)(a_Entity.GetPosY() * 32)); - WriteInt ((int)(a_Entity.GetPosZ() * 32)); - WriteByte(a_Pitch); - WriteByte(a_Yaw); - WriteInt (a_ObjectData); - if (a_ObjectData != 0) - { - WriteShort((short)(a_Entity.GetSpeedX() * 400)); - WriteShort((short)(a_Entity.GetSpeedY() * 400)); - WriteShort((short)(a_Entity.GetSpeedZ() * 400)); - } - Flush(); -} - - - - - -void cProtocol125::SendSpawnVehicle(const cEntity & a_Vehicle, char a_VehicleType, char a_VehicleSubType) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_SPAWN_OBJECT); - WriteInt (a_Vehicle.GetUniqueID()); - WriteChar (a_VehicleType); - WriteInt ((int)(a_Vehicle.GetPosX() * 32)); - WriteInt ((int)(a_Vehicle.GetPosY() * 32)); - WriteInt ((int)(a_Vehicle.GetPosZ() * 32)); - WriteByte ((Byte)((a_Vehicle.GetPitch() / 360.f) * 256)); - WriteByte ((Byte)((a_Vehicle.GetYaw() / 360.f) * 256)); - WriteInt (a_VehicleSubType); - if (a_VehicleSubType != 0) - { - WriteShort((short)(a_Vehicle.GetSpeedX() * 400)); - WriteShort((short)(a_Vehicle.GetSpeedY() * 400)); - WriteShort((short)(a_Vehicle.GetSpeedZ() * 400)); - } - Flush(); -} - - - - - -void cProtocol125::SendStatistics(const cStatManager & a_Manager) -{ - /* NOTE: - Versions prior to minecraft 1.7 use an incremental statistic sync - method. The current setup does not allow us to implement that, because - of performance considerations. - */ -#if 0 - for (unsigned int i = 0; i < (unsigned int)statCount; ++i) - { - StatValue Value = m_Manager->GetValue((eStatistic) i); - - unsigned int StatID = cStatInfo::GetID((eStatistic) i); - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_INCREMENT_STATISTIC); - WriteInt(StatID); - WriteByte(Value); /* Can overflow! */ - Flush(); - } -#endif -} - - - - - -void cProtocol125::SendTabCompletionResults(const AStringVector & a_Results) -{ - // This protocol version doesn't support tab completion - UNUSED(a_Results); -} - - - - - -void cProtocol125::SendTeleportEntity(const cEntity & a_Entity) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_ENT_TELEPORT); - WriteInt (a_Entity.GetUniqueID()); - WriteInt ((int)(floor(a_Entity.GetPosX() * 32))); - WriteInt ((int)(floor(a_Entity.GetPosY() * 32))); - WriteInt ((int)(floor(a_Entity.GetPosZ() * 32))); - WriteChar ((char)((a_Entity.GetYaw() / 360.f) * 256)); - WriteChar ((char)((a_Entity.GetPitch() / 360.f) * 256)); - Flush(); -} - - - - - -void cProtocol125::SendThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_THUNDERBOLT); - WriteInt (0x7fffffff); // Entity ID of the thunderbolt; we use a constant one - WriteBool(true); // Unknown bool - WriteInt (a_BlockX * 32); - WriteInt (a_BlockY * 32); - WriteInt (a_BlockZ * 32); - Flush(); -} - - - - - -void cProtocol125::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle) -{ - // This protocol doesn't support a_DoDaylightCycle on false. - UNUSED(a_DoDaylightCycle); - - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_UPDATE_TIME); - // Use a_WorldAge for daycount, and a_TimeOfDay for the proper time of day: - WriteInt64((24000 * (a_WorldAge / 24000)) + (a_TimeOfDay % 24000)); - Flush(); -} - - - - - -void cProtocol125::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) -{ - cCSLock Lock(m_CSPacket); - SendPreChunk(a_ChunkX, a_ChunkZ, false); -} - - - - - -void cProtocol125::SendUpdateSign( - int a_BlockX, int a_BlockY, int a_BlockZ, - const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4 -) -{ - cCSLock Lock(m_CSPacket); - WriteByte ((unsigned char)PACKET_UPDATE_SIGN); - WriteInt (a_BlockX); - WriteShort ((short)a_BlockY); - WriteInt (a_BlockZ); - WriteString(a_Line1); - WriteString(a_Line2); - WriteString(a_Line3); - WriteString(a_Line4); - Flush(); -} - - - - - -void cProtocol125::SendUseBed(const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_USE_BED); - WriteInt (a_Entity.GetUniqueID()); - WriteByte(0); // Unknown byte only 0 has been observed - WriteInt (a_BlockX); - WriteByte((Byte)a_BlockY); - WriteInt (a_BlockZ); - Flush(); -} - - - - - -void cProtocol125::SendWeather(eWeather a_Weather) -{ - cCSLock Lock(m_CSPacket); - switch (a_Weather) - { - case eWeather_Sunny: - { - WriteByte(PACKET_CHANGE_GAME_STATE); - WriteByte(2); // Stop rain - WriteByte(0); // Unused - Flush(); - break; - } - - case eWeather_Rain: - case eWeather_ThunderStorm: - { - WriteByte(PACKET_CHANGE_GAME_STATE); - WriteByte(1); // Begin rain - WriteByte(0); // Unused - Flush(); - break; - } - } -} - - - - - -void cProtocol125::SendWholeInventory(const cWindow & a_Window) -{ - cCSLock Lock(m_CSPacket); - cItems Slots; - a_Window.GetSlots(*(m_Client->GetPlayer()), Slots); - SendWindowSlots(a_Window.GetWindowID(), (int)Slots.size(), &(Slots[0])); -} - - - - - -void cProtocol125::SendWindowClose(const cWindow & a_Window) -{ - if (a_Window.GetWindowType() == cWindow::wtInventory) - { - // Do not send inventory-window-close - return; - } - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_WINDOW_CLOSE); - WriteChar(a_Window.GetWindowID()); - Flush(); -} - - - - - -void cProtocol125::SendWindowOpen(const cWindow & a_Window) -{ - if (a_Window.GetWindowType() < 0) - { - // Do not send for inventory windows - return; - } - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_WINDOW_OPEN); - WriteChar (a_Window.GetWindowID()); - WriteByte ((Byte)a_Window.GetWindowType()); - WriteString(a_Window.GetWindowTitle()); - WriteByte ((Byte)a_Window.GetNumNonInventorySlots()); - Flush(); -} - - - - - -void cProtocol125::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_WINDOW_PROPERTY); - WriteChar (a_Window.GetWindowID()); - WriteShort(a_Property); - WriteShort(a_Value); - Flush(); -} - - - - - -AString cProtocol125::GetAuthServerID(void) -{ - // http://wiki.vg/wiki/index.php?title=Session&oldid=2262 - // The server generates a random hash and that is used for all clients, unmodified - return cRoot::Get()->GetServer()->GetServerID(); -} - - - - - -void cProtocol125::SendData(const char * a_Data, size_t a_Size) -{ - m_Client->SendData(a_Data, a_Size); -} - - - - - -void cProtocol125::DataReceived(const char * a_Data, size_t a_Size) -{ - if (!m_ReceivedData.Write(a_Data, a_Size)) - { - // Too much data in the incoming queue, report to caller: - m_Client->PacketBufferFull(); - return; - } - - // Parse and handle all complete packets in m_ReceivedData: - while (m_ReceivedData.CanReadBytes(1)) - { - unsigned char PacketType; - m_ReceivedData.ReadByte(PacketType); - switch (ParsePacket(PacketType)) - { - case PARSE_UNKNOWN: - { - // An unknown packet has been received, notify the client and abort: - m_Client->PacketUnknown(PacketType); - return; - } - case PARSE_ERROR: - { - // An error occurred while parsing a known packet, notify the client and abort: - m_Client->PacketError(PacketType); - return; - } - case PARSE_INCOMPLETE: - { - // Incomplete packet, bail out and process with the next batch of data - m_ReceivedData.ResetRead(); - return; - } - default: - { - // Packet successfully parsed, commit the read data and try again one more packet - m_ReceivedData.CommitRead(); - break; - } - } - } -} - - - - - -int cProtocol125::ParsePacket(unsigned char a_PacketType) -{ - switch (a_PacketType) - { - default: return PARSE_UNKNOWN; - case PACKET_ANIMATION: return ParseArmAnim(); - case PACKET_BLOCK_DIG: return ParseBlockDig(); - case PACKET_BLOCK_PLACE: return ParseBlockPlace(); - case PACKET_CHAT: return ParseChat(); - case PACKET_CREATIVE_INVENTORY_ACTION: return ParseCreativeInventoryAction(); - case PACKET_DISCONNECT: return ParseDisconnect(); - case PACKET_HANDSHAKE: return ParseHandshake(); - case PACKET_KEEP_ALIVE: return ParseKeepAlive(); - case PACKET_LOGIN: return ParseLogin(); - case PACKET_PACKET_ENTITY_ACTION: return ParseEntityAction(); - case PACKET_PING: return ParsePing(); - case PACKET_PLAYER_ABILITIES: return ParsePlayerAbilities(); - case PACKET_PLAYER_LOOK: return ParsePlayerLook(); - case PACKET_PLAYER_MOVE_LOOK: return ParsePlayerMoveLook(); - case PACKET_PLAYER_ON_GROUND: return ParsePlayerOnGround(); - case PACKET_PLAYER_POS: return ParsePlayerPosition(); - case PACKET_PLUGIN_MESSAGE: return ParsePluginMessage(); - case PACKET_RESPAWN: return ParseRespawn(); - case PACKET_SLOT_SELECTED: return ParseSlotSelected(); - case PACKET_UPDATE_SIGN: return ParseUpdateSign(); - case PACKET_USE_ENTITY: return ParseUseEntity(); - case PACKET_ENCHANT_ITEM: return ParseEnchantItem(); - case PACKET_WINDOW_CLICK: return ParseWindowClick(); - case PACKET_WINDOW_CLOSE: return ParseWindowClose(); - } -} - - - - - -int cProtocol125::ParseArmAnim(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, EntityID); - HANDLE_PACKET_READ(ReadChar, char, Animation); - m_Client->HandleAnimation(Animation); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseBlockDig(void) -{ - HANDLE_PACKET_READ(ReadChar, char, Status); - HANDLE_PACKET_READ(ReadBEInt, int, PosX); - HANDLE_PACKET_READ(ReadByte, Byte, PosY); - HANDLE_PACKET_READ(ReadBEInt, int, PosZ); - HANDLE_PACKET_READ(ReadChar, char, BlockFace); - m_Client->HandleLeftClick(PosX, PosY, PosZ, static_cast(BlockFace), Status); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseBlockPlace(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, PosX); - HANDLE_PACKET_READ(ReadByte, Byte, PosY); - HANDLE_PACKET_READ(ReadBEInt, int, PosZ); - HANDLE_PACKET_READ(ReadChar, char, BlockFace); - - cItem HeldItem; - int res = ParseItem(HeldItem); - if (res < 0) - { - return res; - } - - // 1.2.5 didn't have any cursor position, so use 8, 8, 8, so that halfslabs and stairs work correctly and the special value is recognizable. - m_Client->HandleRightClick(PosX, PosY, PosZ, static_cast(BlockFace), 8, 8, 8, HeldItem); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseChat(void) -{ - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Message); - m_Client->HandleChat(Message); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseCreativeInventoryAction(void) -{ - HANDLE_PACKET_READ(ReadBEShort, short, SlotNum); - cItem HeldItem; - int res = ParseItem(HeldItem); - if (res < 0) - { - return res; - } - m_Client->HandleCreativeInventory(SlotNum, HeldItem); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseDisconnect(void) -{ - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Reason); - m_Client->HandleDisconnect(Reason); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseEntityAction(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, EntityID); - HANDLE_PACKET_READ(ReadChar, char, ActionID); - - switch (ActionID) - { - case 1: m_Client->HandleEntityCrouch(EntityID, true); break; // Crouch - case 2: m_Client->HandleEntityCrouch(EntityID, false); break; // Uncrouch - case 3: m_Client->HandleEntityLeaveBed(EntityID); break; // Leave Bed - case 4: m_Client->HandleEntitySprinting(EntityID, true); break; // Start sprinting - case 5: m_Client->HandleEntitySprinting(EntityID, false); break; // Stop sprinting - } - - return PARSE_OK; -} - - - - - -int cProtocol125::ParseHandshake(void) -{ - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Username); - - AStringVector UserData = StringSplit(Username, ";"); // "FakeTruth;localhost:25565" - if (UserData.empty()) - { - m_Client->Kick("Did not receive username"); - return PARSE_OK; - } - m_Username = UserData[0]; - - LOGD("HANDSHAKE %s", Username.c_str()); - - if (!m_Client->HandleHandshake( m_Username)) - { - return PARSE_OK; // Player is not allowed into the server - } - - SendHandshake(cRoot::Get()->GetServer()->GetServerID()); - LOGD("User \"%s\" was sent a handshake response", m_Username.c_str()); - - return PARSE_OK; -} - - - - - -int cProtocol125::ParseKeepAlive(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, KeepAliveID); - m_Client->HandleKeepAlive(KeepAliveID); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseLogin(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, ProtocolVersion); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Username); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, LevelType); - HANDLE_PACKET_READ(ReadBEInt, int, ServerMode); - HANDLE_PACKET_READ(ReadBEInt, int, Dimension); - HANDLE_PACKET_READ(ReadChar, char, Difficulty); - HANDLE_PACKET_READ(ReadByte, Byte, WorldHeight); - HANDLE_PACKET_READ(ReadByte, Byte, MaxPlayers); - - if (ProtocolVersion < 29) - { - m_Client->Kick("Your client is outdated!"); - return PARSE_OK; - } - else if (ProtocolVersion > 29) - { - m_Client->Kick("Your client version is higher than the server!"); - return PARSE_OK; - } - - if (m_Username.compare(Username) != 0) - { - LOGWARNING("Login Username (\"%s\") does not match Handshake username (\"%s\") for client @ \"%s\", kicking", - Username.c_str(), - m_Username.c_str(), - m_Client->GetIPString().c_str() - ); - m_Client->Kick("Hacked client"); // Don't tell them why we don't want them - return PARSE_OK; - } - - m_Client->HandleLogin(ProtocolVersion, Username); - return PARSE_OK; -} - - - - - -int cProtocol125::ParsePing(void) -{ - // Packet has no more data - m_Client->HandlePing(); - return PARSE_OK; -} - - - - - - -int cProtocol125::ParsePlayerAbilities(void) -{ - HANDLE_PACKET_READ(ReadBool, bool, Invulnerable); - HANDLE_PACKET_READ(ReadBool, bool, IsFlying); - HANDLE_PACKET_READ(ReadBool, bool, CanFly); - HANDLE_PACKET_READ(ReadBool, bool, InstaMine); - // TODO: m_Client->HandlePlayerAbilities(...); - return PARSE_OK; -} - - - - - -int cProtocol125::ParsePlayerLook(void) -{ - HANDLE_PACKET_READ(ReadBEFloat, float, Rotation); - HANDLE_PACKET_READ(ReadBEFloat, float, Pitch); - HANDLE_PACKET_READ(ReadBool, bool, IsOnGround); - m_Client->HandlePlayerLook(Rotation, Pitch, IsOnGround); - return PARSE_OK; -} - - - - - -int cProtocol125::ParsePlayerMoveLook(void) -{ - HANDLE_PACKET_READ(ReadBEDouble, double, PosX); - HANDLE_PACKET_READ(ReadBEDouble, double, PosY); - HANDLE_PACKET_READ(ReadBEDouble, double, Stance); - HANDLE_PACKET_READ(ReadBEDouble, double, PosZ); - HANDLE_PACKET_READ(ReadBEFloat, float, Rotation); - HANDLE_PACKET_READ(ReadBEFloat, float, Pitch); - HANDLE_PACKET_READ(ReadBool, bool, IsOnGround); - // LOGD("Recv PML: {%0.2f, %0.2f, %0.2f}, Stance %0.2f, Gnd: %d", PosX, PosY, PosZ, Stance, IsOnGround ? 1 : 0); - m_Client->HandlePlayerMoveLook(PosX, PosY, PosZ, Stance, Rotation, Pitch, IsOnGround); - return PARSE_OK; -} - - - - - -int cProtocol125::ParsePlayerOnGround(void) -{ - HANDLE_PACKET_READ(ReadBool, bool, IsOnGround); - // TODO: m_Client->HandleFlying(IsOnGround); - return PARSE_OK; -} - - - - - -int cProtocol125::ParsePlayerPosition(void) -{ - HANDLE_PACKET_READ(ReadBEDouble, double, PosX); - HANDLE_PACKET_READ(ReadBEDouble, double, PosY); - HANDLE_PACKET_READ(ReadBEDouble, double, Stance); - HANDLE_PACKET_READ(ReadBEDouble, double, PosZ); - HANDLE_PACKET_READ(ReadBool, bool, IsOnGround); - m_Client->HandlePlayerPos(PosX, PosY, PosZ, Stance, IsOnGround); - return PARSE_OK; -} - - - - - -int cProtocol125::ParsePluginMessage(void) -{ - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, ChannelName); - HANDLE_PACKET_READ(ReadBEShort, short, Length); - AString Data; - if (!m_ReceivedData.ReadString(Data, (size_t)Length)) - { - m_ReceivedData.CheckValid(); - return PARSE_INCOMPLETE; - } - m_ReceivedData.CheckValid(); - - // TODO: Process the data - LOGD("Received %d bytes of plugin data on channel \"%s\".", Length, ChannelName.c_str()); - - return PARSE_OK; -} - - - - - -int cProtocol125::ParseRespawn(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, Dimension); - HANDLE_PACKET_READ(ReadChar, char, Difficulty); - HANDLE_PACKET_READ(ReadChar, char, CreativeMode); - HANDLE_PACKET_READ(ReadBEShort, short, WorldHeight); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, LevelType); - m_Client->HandleRespawn(); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseSlotSelected(void) -{ - HANDLE_PACKET_READ(ReadBEShort, short, SlotNum); - m_Client->HandleSlotSelected(SlotNum); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseUpdateSign(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, BlockX); - HANDLE_PACKET_READ(ReadBEShort, short, BlockY); - HANDLE_PACKET_READ(ReadBEInt, int, BlockZ); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Line1); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Line2); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Line3); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Line4); - m_Client->HandleUpdateSign(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseUseEntity(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, SourceEntityID); - HANDLE_PACKET_READ(ReadBEInt, int, TargetEntityID); - HANDLE_PACKET_READ(ReadBool, bool, IsLeftClick); - m_Client->HandleUseEntity(TargetEntityID, IsLeftClick); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseEnchantItem(void) -{ - HANDLE_PACKET_READ(ReadByte, Byte, WindowID); - HANDLE_PACKET_READ(ReadByte, Byte, Enchantment); - - m_Client->HandleEnchantItem(WindowID, Enchantment); - - return PARSE_OK; -} - - - - - -int cProtocol125::ParseWindowClick(void) -{ - HANDLE_PACKET_READ(ReadChar, char, WindowID); - HANDLE_PACKET_READ(ReadBEShort, short, SlotNum); - HANDLE_PACKET_READ(ReadBool, bool, IsRightClick); - HANDLE_PACKET_READ(ReadBEShort, short, TransactionID); - HANDLE_PACKET_READ(ReadBool, bool, IsShiftPressed); - cItem HeldItem; - int res = ParseItem(HeldItem); - if (res < 0) - { - return res; - } - - // Convert IsShiftPressed, IsRightClick, SlotNum and HeldItem into eClickAction used in the newer protocols: - eClickAction Action; - if (IsRightClick) - { - if (IsShiftPressed) - { - Action = caShiftRightClick; - } - else - { - if (SlotNum == -999) - { - Action = (HeldItem.IsEmpty()) ? caRightClickOutsideHoldNothing : caRightClickOutside; - } - else - { - Action = caRightClick; - } - } - } - else - { - // IsLeftClick - if (IsShiftPressed) - { - Action = caShiftLeftClick; - } - else - { - if (SlotNum == -999) - { - Action = (HeldItem.IsEmpty()) ? caLeftClickOutsideHoldNothing : caRightClickOutside; - } - else - { - Action = caLeftClick; - } - } - } - m_Client->HandleWindowClick(WindowID, SlotNum, Action, HeldItem); - return PARSE_OK; -} - - - - - -int cProtocol125::ParseWindowClose(void) -{ - HANDLE_PACKET_READ(ReadChar, char, WindowID); - m_Client->HandleWindowClose(WindowID); - return PARSE_OK; -} - - - - - -void cProtocol125::SendPreChunk(int a_ChunkX, int a_ChunkZ, bool a_ShouldLoad) -{ - WriteByte(PACKET_PRE_CHUNK); - WriteInt (a_ChunkX); - WriteInt (a_ChunkZ); - WriteBool(a_ShouldLoad); - Flush(); -} - - - - - -void cProtocol125::SendWindowSlots(char a_WindowID, int a_NumItems, const cItem * a_Items) -{ - WriteByte (PACKET_INVENTORY_WHOLE); - WriteChar (a_WindowID); - WriteShort((short)a_NumItems); - - for (int j = 0; j < a_NumItems; j++) - { - WriteItem(a_Items[j]); - } - Flush(); -} - - - - - -void cProtocol125::WriteItem(const cItem & a_Item) -{ - short ItemType = a_Item.m_ItemType; - ASSERT(ItemType >= -1); // Check validity of packets in debug runtime - if (ItemType <= 0) - { - // Fix, to make sure no invalid values are sent. - ItemType = -1; - } - - WriteShort(ItemType); - if (a_Item.IsEmpty()) - { - return; - } - - WriteChar (a_Item.m_ItemCount); - WriteShort(a_Item.m_ItemDamage); - - if (cItem::IsEnchantable(a_Item.m_ItemType)) - { - // TODO: Implement enchantments - WriteShort(-1); - } -} - - - - - -int cProtocol125::ParseItem(cItem & a_Item) -{ - HANDLE_PACKET_READ(ReadBEShort, short, ItemType); - - if (ItemType <= -1) - { - a_Item.Empty(); - return PARSE_OK; - } - a_Item.m_ItemType = ItemType; - - HANDLE_PACKET_READ(ReadChar, char, ItemCount); - HANDLE_PACKET_READ(ReadBEShort, short, ItemDamage); - a_Item.m_ItemCount = ItemCount; - a_Item.m_ItemDamage = ItemDamage; - if (ItemCount <= 0) - { - a_Item.Empty(); - } - - if (!cItem::IsEnchantable(ItemType)) - { - return PARSE_OK; - } - - HANDLE_PACKET_READ(ReadBEShort, short, EnchantNumBytes); - - if (EnchantNumBytes <= 0) - { - return PARSE_OK; - } - - // TODO: Enchantment not implemented yet! - if (!m_ReceivedData.SkipRead((size_t)EnchantNumBytes)) - { - return PARSE_INCOMPLETE; - } - - return PARSE_OK; -} - - - - - -void cProtocol125::WriteCommonMetadata(const cEntity & a_Entity) -{ - Byte CommonMetadata = 0; - - if (a_Entity.IsOnFire()) - { - CommonMetadata |= 0x1; - } - if (a_Entity.IsCrouched()) - { - CommonMetadata |= 0x2; - } - if (a_Entity.IsRiding()) - { - CommonMetadata |= 0x4; - } - if (a_Entity.IsSprinting()) - { - CommonMetadata |= 0x8; - } - if (a_Entity.IsRclking()) - { - CommonMetadata |= 0x10; - } - if (a_Entity.IsInvisible()) - { - CommonMetadata |= 0x20; - } - - WriteByte(0x0); - WriteByte(CommonMetadata); -} - - - - - -void cProtocol125::WriteEntityMetadata(const cEntity & a_Entity) -{ - if (a_Entity.IsMinecart()) - { - WriteByte(0x51); - // No idea how Mojang makes their carts shakey shakey, so here is a complicated one-liner expression that does something similar - WriteInt( (((a_Entity.GetMaxHealth() / 2) - (a_Entity.GetHealth() - (a_Entity.GetMaxHealth() / 2))) * ((const cMinecart &)a_Entity).LastDamage()) * 4); - WriteByte(0x52); - WriteInt(1); // Shaking direction, doesn't seem to affect anything - WriteByte(0x73); - WriteFloat((float)(((const cMinecart &)a_Entity).LastDamage() + 10)); // Damage taken / shake effect multiplyer - - if (((cMinecart &)a_Entity).GetPayload() == cMinecart::mpFurnace) - { - WriteByte(0x10); - WriteByte(((const cMinecartWithFurnace &)a_Entity).IsFueled() ? 1 : 0); // Fueled? - } - } - else if ((a_Entity.IsProjectile() && ((cProjectileEntity &)a_Entity).GetProjectileKind() == cProjectileEntity::pkArrow)) - { - WriteByte(0x10); - WriteByte(((const cArrowEntity &)a_Entity).IsCritical() ? 1 : 0); // Critical hitting arrow? - } -} - - - - - -void cProtocol125::WriteMobMetadata(const cMonster & a_Mob) -{ - switch (a_Mob.GetMobType()) - { - case mtCreeper: - { - WriteByte(0x10); - WriteChar(((const cCreeper &)a_Mob).IsBlowing() ? 1 : -1); // Blowing up? - WriteByte(0x11); - WriteByte(((const cCreeper &)a_Mob).IsCharged() ? 1 : 0); // Lightning-charged? - break; - } - case mtBat: - { - WriteByte(0x10); - WriteByte(((const cBat &)a_Mob).IsHanging() ? 1 : 0); // Upside down? - break; - } - case mtPig: - { - WriteByte(0x10); - WriteByte(((const cPig &)a_Mob).IsSaddled() ? 1 : 0); // Saddled? - break; - } - case mtVillager: - { - WriteByte(0x50); - WriteInt(((const cVillager &)a_Mob).GetVilType()); // What sort of TESTIFICATE? - break; - } - case mtZombie: - { - WriteByte(0xC); - WriteByte(((const cZombie &)a_Mob).IsBaby() ? 1 : 0); // Baby zombie? - WriteByte(0xD); - WriteByte(((const cZombie &)a_Mob).IsVillagerZombie() ? 1 : 0); // Converted zombie? - WriteByte(0xE); - WriteByte(((const cZombie &)a_Mob).IsConverting() ? 1 : 0); // Converted-but-converting-back zombllager? - break; - } - case mtGhast: - { - WriteByte(0x10); - WriteByte(((const cGhast &)a_Mob).IsCharging()); // About to spit a flameball? - break; - } - case mtWolf: - { - Byte WolfStatus = 0; - if (((const cWolf &)a_Mob).IsSitting()) - { - WolfStatus |= 0x1; - } - if (((const cWolf &)a_Mob).IsAngry()) - { - WolfStatus |= 0x2; - } - if (((const cWolf &)a_Mob).IsTame()) - { - WolfStatus |= 0x4; - } - WriteByte(0x10); - WriteByte(WolfStatus); - - WriteByte(0x72); - WriteFloat((float)(a_Mob.GetHealth())); // Tail health-o-meter (only shown when tamed, by the way) - WriteByte(0x13); - WriteByte(((const cWolf &)a_Mob).IsBegging() ? 1 : 0); // Ultra cute mode? - break; - } - case mtSheep: - { - // [1](1111) - // [] = Is sheared? () = Color, from 0 to 15 - - WriteByte(0x10); - Byte SheepMetadata = 0; - SheepMetadata = (Byte)((const cSheep &)a_Mob).GetFurColor(); - - if (((const cSheep &)a_Mob).IsSheared()) - { - SheepMetadata |= 0x16; - } - WriteByte(SheepMetadata); - break; - } - case mtEnderman: - { - WriteByte(0x10); - WriteByte((Byte)(((const cEnderman &)a_Mob).GetCarriedBlock())); // Block that he stole from your house - WriteByte(0x11); - WriteByte((Byte)(((const cEnderman &)a_Mob).GetCarriedMeta())); // Meta of block that he stole from your house - WriteByte(0x12); - WriteByte(((const cEnderman &)a_Mob).IsScreaming() ? 1 : 0); // Screaming at your face? - break; - } - case mtSkeleton: - { - WriteByte(0xD); - WriteByte(((const cSkeleton &)a_Mob).IsWither() ? 1 : 0); // It's a skeleton, but it's not - break; - } - case mtWitch: - { - WriteByte(0x15); - WriteByte(((const cWitch &)a_Mob).IsAngry() ? 1 : 0); // Aggravated? Doesn't seem to do anything - break; - } - case mtWither: - { - WriteByte(0x54); // Int at index 20 - WriteInt((Int32)((const cWither &)a_Mob).GetWitherInvulnerableTicks()); - WriteByte(0x66); // Float at index 6 - WriteFloat((float)(a_Mob.GetHealth())); - break; - } - case mtSlime: - case mtMagmaCube: - { - WriteByte(0x10); - if (a_Mob.GetMobType() == mtSlime) - { - WriteByte((Byte)((const cSlime &)a_Mob).GetSize()); // Size of slime - HEWGE, meh, cute BABBY SLIME - } - else - { - WriteByte((Byte)((const cMagmaCube &)a_Mob).GetSize()); // Size of slime - HEWGE, meh, cute BABBY SLIME - } - break; - } - case mtHorse: - { - int Flags = 0; - if (((const cHorse &)a_Mob).IsTame()) - { - Flags |= 0x2; - } - if (((const cHorse &)a_Mob).IsSaddled()) - { - Flags |= 0x4; - } - if (((const cHorse &)a_Mob).IsChested()) - { - Flags |= 0x8; - } - if (((const cHorse &)a_Mob).IsBaby()) - { - Flags |= 0x10; // IsBred flag, according to wiki.vg - don't think it does anything in multiplayer - } - if (((const cHorse &)a_Mob).IsEating()) - { - Flags |= 0x20; - } - if (((const cHorse &)a_Mob).IsRearing()) - { - Flags |= 0x40; - } - if (((const cHorse &)a_Mob).IsMthOpen()) - { - Flags |= 0x80; - } - WriteByte(0x50); - WriteInt(Flags); - - WriteByte(0x13); - WriteByte((Byte)((const cHorse &)a_Mob).GetHorseType()); // Type of horse (donkey, chestnut, etc.) - - WriteByte(0x54); - int Appearance = 0; - Appearance = ((const cHorse &)a_Mob).GetHorseColor(); // Mask FF - Appearance |= ((const cHorse &)a_Mob).GetHorseStyle() * 256; // Mask FF00, so multiply by 256 - WriteInt(Appearance); - - WriteByte(0x56); - WriteInt(((const cHorse &)a_Mob).GetHorseArmour()); // Horshey armour - break; - } - default: - { - break; - } - } -} - - - - diff --git a/src/Protocol/Protocol125.h b/src/Protocol/Protocol125.h deleted file mode 100644 index 3ea116c3b..000000000 --- a/src/Protocol/Protocol125.h +++ /dev/null @@ -1,185 +0,0 @@ - -// Protocol125.h - -// Interfaces to the cProtocol125 class representing the release 1.2.5 protocol (#29) - - - - - -#pragma once - -#include "Protocol.h" -#include "../ByteBuffer.h" -#include "../Entities/Painting.h" - - - - - -class cProtocol125 : - public cProtocol -{ - typedef cProtocol super; -public: - cProtocol125(cClientHandle * a_Client); - - /// Called when client sends some data: - virtual void DataReceived(const char * a_Data, size_t a_Size) override; - - /// Sending stuff to clients (alphabetically sorted): - virtual void SendAttachEntity (const cEntity & a_Entity, const cEntity * a_Vehicle) override; - virtual void SendBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType) override; - virtual void SendBlockBreakAnim (int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage) override; - virtual void SendBlockChange (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) override; - virtual void SendBlockChanges (int a_ChunkX, int a_ChunkZ, const sSetBlockVector & a_Changes) override; - virtual void SendChat (const AString & a_Message) override; - virtual void SendChat (const cCompositeChat & a_Message) override; - virtual void SendChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) override; - virtual void SendCollectEntity (const cEntity & a_Entity, const cPlayer & a_Player) override; - virtual void SendDestroyEntity (const cEntity & a_Entity) override; - virtual void SendDisconnect (const AString & a_Reason) override; - virtual void SendEditSign (int a_BlockX, int a_BlockY, int a_BlockZ) override; ///< Request the client to open up the sign editor for the sign (1.6+) - virtual void SendEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration) override; - virtual void SendEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item) override; - virtual void SendEntityHeadLook (const cEntity & a_Entity) override; - virtual void SendEntityLook (const cEntity & a_Entity) override; - virtual void SendEntityMetadata (const cEntity & a_Entity) override; - virtual void SendEntityProperties (const cEntity & a_Entity) override; - virtual void SendEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) override; - virtual void SendEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) override; - virtual void SendEntityStatus (const cEntity & a_Entity, char a_Status) override; - virtual void SendEntityVelocity (const cEntity & a_Entity) override; - virtual void SendExplosion (double a_BlockX, double a_BlockY, double a_BlockZ, float a_Radius, const cVector3iArray & a_BlocksAffected, const Vector3d & a_PlayerMotion) override; - virtual void SendGameMode (eGameMode a_GameMode) override; - virtual void SendHealth (void) override; - virtual void SendInventorySlot (char a_WindowID, short a_SlotNum, const cItem & a_Item) override; - virtual void SendKeepAlive (int a_PingID) override; - virtual void SendLogin (const cPlayer & a_Player, const cWorld & a_World) override; - virtual void SendLoginSuccess (void) override; - virtual void SendMapColumn (int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length, unsigned int m_Scale) override; - virtual void SendMapDecorators (int a_ID, const cMapDecoratorList & a_Decorators, unsigned int m_Scale) override; - virtual void SendMapInfo (int a_ID, unsigned int a_Scale) override; - virtual void SendParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount) override; - virtual void SendPaintingSpawn (const cPainting & a_Painting) override; - virtual void SendPickupSpawn (const cPickup & a_Pickup) override; - virtual void SendPlayerAbilities (void) override {} // This protocol doesn't support such message - virtual void SendEntityAnimation (const cEntity & a_Entity, char a_Animation) override; - virtual void SendPlayerListAddPlayer (const cPlayer & a_Player) override; - virtual void SendPlayerListRemovePlayer (const cPlayer & a_Player) override; - virtual void SendPlayerListUpdateGameMode (const cPlayer & a_Player) override; - virtual void SendPlayerListUpdatePing (const cPlayer & a_Player) override; - virtual void SendPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName) override; - virtual void SendPlayerMaxSpeed (void) override; - virtual void SendPlayerMoveLook (void) override; - virtual void SendPlayerPosition (void) override; - virtual void SendPlayerSpawn (const cPlayer & a_Player) override; - virtual void SendPluginMessage (const AString & a_Channel, const AString & a_Message) override; - virtual void SendRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID) override; - virtual void SendRespawn (eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks) override; - virtual void SendExperience (void) override; - virtual void SendExperienceOrb (const cExpOrb & a_ExpOrb) override; - virtual void SendScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) override; - virtual void SendScoreUpdate (const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode) override {} // This protocol doesn't support such message - virtual void SendDisplayObjective (const AString & a_Objective, cScoreboard::eDisplaySlot a_Display) override {} // This protocol doesn't support such message - virtual void SendSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch) override; - virtual void SendSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) override; - virtual void SendSpawnFallingBlock (const cFallingBlock & a_FallingBlock) override; - virtual void SendSpawnMob (const cMonster & a_Mob) override; - virtual void SendSpawnObject (const cEntity & a_Entity, char a_ObjectType, int a_ObjectData, Byte a_Yaw, Byte a_Pitch) override; - virtual void SendSpawnVehicle (const cEntity & a_Vehicle, char a_VehicleType, char a_VehicleSubType) override; - virtual void SendStatistics (const cStatManager & a_Manager) override; - virtual void SendTabCompletionResults (const AStringVector & a_Results) override; - virtual void SendTeleportEntity (const cEntity & a_Entity) override; - virtual void SendThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ) override; - virtual void SendTimeUpdate (Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle) override; - virtual void SendUnloadChunk (int a_ChunkX, int a_ChunkZ) override; - virtual void SendUpdateBlockEntity (cBlockEntity & a_BlockEntity) override {} - virtual void SendUpdateSign (int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4) override; - virtual void SendUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) override; - virtual void SendWeather (eWeather a_Weather) override; - 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, int a_Property, int a_Value) override; - - virtual AString GetAuthServerID(void) override; - -protected: - /// Results of packet-parsing: - enum eParseResult - { - PARSE_OK = 1, - PARSE_ERROR = -1, - PARSE_UNKNOWN = -2, - PARSE_INCOMPLETE = -3, - } ; - - cByteBuffer m_ReceivedData; ///< Buffer for the received data - - AString m_Username; ///< Stored in ParseHandshake(), compared to Login username - - /** The dimension that was last sent to a player in a Respawn or Login packet. - Used to avoid Respawning into the same dimension, which confuses the client. */ - eDimension m_LastSentDimension; - - virtual void SendData(const char * a_Data, size_t a_Size) override; - - /// Sends the Handshake packet - void SendHandshake(const AString & a_ConnectionHash); - - /// Parse the packet of the specified type from m_ReceivedData (switch into ParseXYZ()) - virtual int ParsePacket(unsigned char a_PacketType); - - // Specific packet parsers: - virtual int ParseArmAnim (void); - virtual int ParseBlockDig (void); - virtual int ParseBlockPlace (void); - virtual int ParseChat (void); - virtual int ParseCreativeInventoryAction(void); - virtual int ParseDisconnect (void); - virtual int ParseEntityAction (void); - virtual int ParseHandshake (void); - virtual int ParseKeepAlive (void); - virtual int ParseLogin (void); - virtual int ParsePing (void); - virtual int ParsePlayerAbilities (void); - virtual int ParsePlayerLook (void); - virtual int ParsePlayerMoveLook (void); - virtual int ParsePlayerOnGround (void); - virtual int ParsePlayerPosition (void); - virtual int ParsePluginMessage (void); - virtual int ParseRespawn (void); - virtual int ParseSlotSelected (void); - virtual int ParseUpdateSign (void); - virtual int ParseUseEntity (void); - virtual int ParseEnchantItem (void); - virtual int ParseWindowClick (void); - virtual int ParseWindowClose (void); - - // Utility functions: - /// Writes a "pre-chunk" packet - void SendPreChunk(int a_ChunkX, int a_ChunkZ, bool a_ShouldLoad); - - /// Writes a "set window items" packet with the specified params - void SendWindowSlots(char a_WindowID, int a_NumItems, const cItem * a_Items); - - /// Writes one item, "slot" as the protocol wiki calls it - virtual void WriteItem(const cItem & a_Item); - - /// Parses one item, "slot" as the protocol wiki calls it, from m_ReceivedData; returns the usual ParsePacket() codes - virtual int ParseItem(cItem & a_Item); - - /// Writes the COMMON entity metadata - void WriteCommonMetadata(const cEntity & a_Entity); - - /// Writes normal entity metadata - void WriteEntityMetadata(const cEntity & a_Entity); - - /// Writes mobile entity metadata - void WriteMobMetadata(const cMonster & a_Mob); -} ; - - - - diff --git a/src/Protocol/Protocol132.cpp b/src/Protocol/Protocol132.cpp deleted file mode 100644 index 63a15c082..000000000 --- a/src/Protocol/Protocol132.cpp +++ /dev/null @@ -1,880 +0,0 @@ - -// Protocol132.cpp - -// Implements the cProtocol132 class representing the release 1.3.2 protocol (#39) - -#include "Globals.h" -#include "ChunkDataSerializer.h" -#include "Protocol132.h" -#include "../Root.h" -#include "../Server.h" -#include "../World.h" -#include "../ClientHandle.h" -#include "../Item.h" -#include "../Entities/Player.h" -#include "../Mobs/Monster.h" -#include "../UI/Window.h" -#include "../Entities/Pickup.h" -#include "../WorldStorage/FastNBT.h" -#include "../WorldStorage/EnchantmentSerializer.h" -#include "../StringCompression.h" -#include "PolarSSL++/Sha1Checksum.h" - - - - - -#define HANDLE_PACKET_READ(Proc, Type, Var) \ - Type Var; \ - { \ - if (!m_ReceivedData.Proc(Var)) \ - { \ - m_ReceivedData.CheckValid(); \ - return PARSE_INCOMPLETE; \ - } \ - m_ReceivedData.CheckValid(); \ - } - - - - - -const int MAX_ENC_LEN = 512; // Maximum size of the encrypted message; should be 128, but who knows... - - - - - -enum -{ - PACKET_KEEP_ALIVE = 0x00, - PACKET_LOGIN = 0x01, - PACKET_ENTITY_EQUIPMENT = 0x05, - PACKET_COMPASS = 0x06, - PACKET_PLAYER_SPAWN = 0x14, - PACKET_COLLECT_PICKUP = 0x16, - PACKET_SPAWN_MOB = 0x18, - PACKET_DESTROY_ENTITIES = 0x1d, - PACKET_CHUNK_DATA = 0x33, - PACKET_BLOCK_CHANGE = 0x35, - PACKET_BLOCK_ACTION = 0x36, - PACKET_BLOCK_BREAK_ANIM = 0x37, - PACKET_SOUND_EFFECT = 0x3e, - PACKET_SOUND_PARTICLE_EFFECT = 0x3d, - PACKET_TAB_COMPLETION = 0xcb, - PACKET_LOCALE_VIEW_DISTANCE = 0xcc, - PACKET_CLIENT_STATUSES = 0xcd, - PACKET_ENCRYPTION_KEY_RESP = 0xfc, -} ; - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cProtocol132: - -cProtocol132::cProtocol132(cClientHandle * a_Client) : - super(a_Client), - m_IsEncrypted(false) -{ -} - - - - - -cProtocol132::~cProtocol132() -{ - if (!m_DataToSend.empty()) - { - LOGD("There are " SIZE_T_FMT " unsent bytes while deleting cProtocol132", m_DataToSend.size()); - } -} - - - - - -void cProtocol132::DataReceived(const char * a_Data, size_t a_Size) -{ - if (m_IsEncrypted) - { - Byte Decrypted[512]; - while (a_Size > 0) - { - size_t NumBytes = (a_Size > sizeof(Decrypted)) ? sizeof(Decrypted) : a_Size; - m_Decryptor.ProcessData(Decrypted, (Byte *)a_Data, NumBytes); - super::DataReceived((const char *)Decrypted, NumBytes); - a_Size -= NumBytes; - a_Data += NumBytes; - } - } - else - { - super::DataReceived(a_Data, a_Size); - } -} - - - - - -void cProtocol132::SendBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_BLOCK_ACTION); - WriteInt (a_BlockX); - WriteShort((short)a_BlockY); - WriteInt (a_BlockZ); - WriteChar (a_Byte1); - WriteChar (a_Byte2); - WriteShort(a_BlockType); - Flush(); -} - - - - - -void cProtocol132::SendBlockBreakAnim(int a_entityID, int a_BlockX, int a_BlockY, int a_BlockZ, char stage) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_BLOCK_BREAK_ANIM); - WriteInt (a_entityID); - WriteInt (a_BlockX); - WriteInt (a_BlockY); - WriteInt (a_BlockZ); - WriteChar (stage); - Flush(); -} - - - - - -void cProtocol132::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_BLOCK_CHANGE); - WriteInt (a_BlockX); - WriteByte ((unsigned char)a_BlockY); - WriteInt (a_BlockZ); - WriteShort(a_BlockType); - WriteByte (a_BlockMeta); - Flush(); -} - - - - - -void cProtocol132::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) -{ - cCSLock Lock(m_CSPacket); - - // Pre-chunk not used in 1.3.2. Finally. - - // Send the chunk data: - AString Serialized = a_Serializer.Serialize(cChunkDataSerializer::RELEASE_1_3_2, a_ChunkX, a_ChunkZ); - WriteByte(PACKET_CHUNK_DATA); - WriteInt (a_ChunkX); - WriteInt (a_ChunkZ); - SendData(Serialized.data(), Serialized.size()); - Flush(); -} - - - - - -void cProtocol132::SendCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_COLLECT_PICKUP); - WriteInt (a_Entity.GetUniqueID()); - WriteInt (a_Player.GetUniqueID()); - Flush(); -} - - - - - -void cProtocol132::SendDestroyEntity(const cEntity & a_Entity) -{ - if (a_Entity.GetUniqueID() == m_Client->GetPlayer()->GetUniqueID()) - { - // Do not send "destroy self" to the client, the client would crash (FS #254) - return; - } - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_DESTROY_ENTITIES); - WriteByte(1); // entity count - WriteInt (a_Entity.GetUniqueID()); - Flush(); -} - - - - - -void cProtocol132::SendEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_ENTITY_EQUIPMENT); - WriteInt (a_Entity.GetUniqueID()); - WriteShort(a_SlotNum); - WriteItem (a_Item); - Flush(); -} - - - - - -void cProtocol132::SendLogin(const cPlayer & a_Player, const cWorld & a_World) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_LOGIN); - WriteInt (a_Player.GetUniqueID()); // EntityID of the player - WriteString("default"); // Level type - WriteByte ((Byte)a_Player.GetGameMode()); - WriteByte ((Byte)(a_World.GetDimension())); - WriteByte (2); // TODO: Difficulty - WriteByte (0); // Unused, used to be world height - WriteByte (8); // Client list width or something - Flush(); - m_LastSentDimension = a_World.GetDimension(); - SendCompass(a_World); -} - - - - - -void cProtocol132::SendPlayerSpawn(const cPlayer & a_Player) -{ - const cItem & HeldItem = a_Player.GetEquippedItem(); - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_PLAYER_SPAWN); - WriteInt (a_Player.GetUniqueID()); - if (a_Player.HasCustomName()) - { - WriteString(a_Player.GetCustomName()); - } - else - { - WriteString(a_Player.GetName()); - } - WriteInt ((int)(a_Player.GetPosX() * 32)); - WriteInt ((int)(a_Player.GetPosY() * 32)); - WriteInt ((int)(a_Player.GetPosZ() * 32)); - WriteChar ((char)((a_Player.GetYaw() / 360.f) * 256)); - WriteChar ((char)((a_Player.GetPitch() / 360.f) * 256)); - WriteShort (HeldItem.IsEmpty() ? 0 : HeldItem.m_ItemType); - // Player metadata: just use a default metadata value, since the client doesn't like starting without any metadata: - WriteByte (0); // Index 0, byte (flags) - WriteByte (0); // Flags, empty - WriteByte (0x7f); // End of metadata - Flush(); -} - - - - - -void cProtocol132::SendSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_SOUND_EFFECT); - WriteString (a_SoundName); - WriteInt ((int)(a_X * 8.0)); - WriteInt ((int)(a_Y * 8.0)); - WriteInt ((int)(a_Z * 8.0)); - WriteFloat (a_Volume); - WriteChar ((char)(a_Pitch * 63.0f)); - Flush(); -} - - - - - -void cProtocol132::SendSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_SOUND_PARTICLE_EFFECT); - WriteInt (a_EffectID); - WriteInt (a_SrcX); - WriteByte((Byte)a_SrcY); - WriteInt (a_SrcZ); - WriteInt (a_Data); - Flush(); -} - - - - - -void cProtocol132::SendSpawnMob(const cMonster & a_Mob) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_SPAWN_MOB); - WriteInt (a_Mob.GetUniqueID()); - WriteByte ((Byte)a_Mob.GetMobType()); - WriteVectorI((Vector3i)(a_Mob.GetPosition() * 32)); - WriteByte ((Byte)((a_Mob.GetYaw() / 360.f) * 256)); - WriteByte ((Byte)((a_Mob.GetPitch() / 360.f) * 256)); - WriteByte ((Byte)((a_Mob.GetHeadYaw() / 360.f) * 256)); - WriteShort ((short)(a_Mob.GetSpeedX() * 400)); - WriteShort ((short)(a_Mob.GetSpeedY() * 400)); - WriteShort ((short)(a_Mob.GetSpeedZ() * 400)); - - WriteCommonMetadata(a_Mob); - WriteMobMetadata(a_Mob); - WriteByte(0x7f); - - Flush(); -} - - - - - -void cProtocol132::SendTabCompletionResults(const AStringVector & a_Results) -{ - if (a_Results.empty()) - { - // No results to send - return; - } - - AString Serialized(a_Results[0]); - for (AStringVector::const_iterator itr = a_Results.begin() + 1, end = a_Results.end(); itr != end; ++itr) - { - Serialized.push_back(0); - Serialized.append(*itr); - } // for itr - a_Results[] - - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_TAB_COMPLETION); - WriteString(Serialized); - Flush(); -} - - - - - -void cProtocol132::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) -{ - // Unloading the chunk is done by sending a "map chunk" packet - // with IncludeInitialize set to true and primary bitmap set to 0: - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_CHUNK_DATA); - WriteInt (a_ChunkX); - WriteInt (a_ChunkZ); - WriteBool(true); // IncludeInitialize - WriteShort(0); // Primary bitmap - WriteShort(0); // Add bitmap - WriteInt(0); - Flush(); -} - - - - - -void cProtocol132::SendWholeInventory(const cWindow & a_Window) -{ - // 1.3.2 requires player inventory slots to be sent as SetSlot packets, - // otherwise it sometimes fails to update the window - - // Send the entire window: - super::SendWholeInventory(a_Window); - - // Send the player inventory and hotbar: - cPlayer * Player = m_Client->GetPlayer(); - const cInventory & Inventory = Player->GetInventory(); - int BaseOffset = a_Window.GetNumSlots() - (cInventory::invNumSlots - cInventory::invInventoryOffset); // Number of non-inventory slots - char WindowID = a_Window.GetWindowID(); - for (short i = 0; i < cInventory::invInventoryCount; i++) - { - SendInventorySlot(WindowID, BaseOffset + i, Inventory.GetInventorySlot(i)); - } // for i - Inventory[] - BaseOffset += cInventory::invInventoryCount; - for (short i = 0; i < cInventory::invHotbarCount; i++) - { - SendInventorySlot(WindowID, BaseOffset + i, Inventory.GetHotbarSlot(i)); - } // for i - Hotbar[] - - // Send even the item being dragged: - SendInventorySlot(-1, -1, Player->GetDraggingItem()); -} - - - - - -AString cProtocol132::GetAuthServerID(void) -{ - // http://wiki.vg/wiki/index.php?title=Session&oldid=2615 - // Server uses SHA1 to mix ServerID, Client secret and server public key together - // The mixing is done in StartEncryption, the result is in m_AuthServerID - - return m_AuthServerID; -} - - - - - -int cProtocol132::ParsePacket(unsigned char a_PacketType) -{ - switch (a_PacketType) - { - default: return super::ParsePacket(a_PacketType); // off-load previously known packets into cProtocol125 - case PACKET_CLIENT_STATUSES: return ParseClientStatuses(); - case PACKET_ENCRYPTION_KEY_RESP: return ParseEncryptionKeyResponse(); - case PACKET_LOCALE_VIEW_DISTANCE: return ParseLocaleViewDistance(); - case PACKET_TAB_COMPLETION: return ParseTabCompletion(); - } -} - - - - - -int cProtocol132::ParseBlockPlace(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, PosX); - HANDLE_PACKET_READ(ReadByte, Byte, PosY); - HANDLE_PACKET_READ(ReadBEInt, int, PosZ); - HANDLE_PACKET_READ(ReadChar, char, BlockFace); - - cItem HeldItem; - int res = ParseItem(HeldItem); - if (res < 0) - { - return res; - } - - HANDLE_PACKET_READ(ReadChar, char, CursorX); - HANDLE_PACKET_READ(ReadChar, char, CursorY); - HANDLE_PACKET_READ(ReadChar, char, CursorZ); - - m_Client->HandleRightClick(PosX, PosY, PosZ, static_cast(BlockFace), CursorX, CursorY, CursorZ, HeldItem); - return PARSE_OK; -} - - - - - -int cProtocol132::ParseHandshake(void) -{ - HANDLE_PACKET_READ(ReadByte, Byte, ProtocolVersion); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Username); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, ServerHost); - HANDLE_PACKET_READ(ReadBEInt, int, ServerPort); - m_Username = Username; - - if (!m_Client->HandleHandshake( m_Username)) - { - return PARSE_OK; // Player is not allowed into the server - } - - // Send a 0xfd Encryption Key Request http://wiki.vg/Protocol#0xFD - SendEncryptionKeyRequest(); - - return PARSE_OK; -} - - - - - -int cProtocol132::ParseClientStatuses(void) -{ - HANDLE_PACKET_READ(ReadByte, Byte, Status); - if ((Status & 1) == 0) - { - m_Client->HandleLogin(39, m_Username); - } - else - { - m_Client->HandleRespawn(); - } - return PARSE_OK; -} - - - - - -int cProtocol132::ParseEncryptionKeyResponse(void) -{ - // Read the encryption key: - HANDLE_PACKET_READ(ReadBEShort, short, EncKeyLength); - if (EncKeyLength > MAX_ENC_LEN) - { - LOGD("Too long encryption key"); - m_Client->Kick("Hacked client"); - return PARSE_OK; - } - AString EncKey; - if (!m_ReceivedData.ReadString(EncKey, (size_t)EncKeyLength)) - { - return PARSE_INCOMPLETE; - } - - // Read the encryption nonce: - HANDLE_PACKET_READ(ReadBEShort, short, EncNonceLength); - AString EncNonce; - if (!m_ReceivedData.ReadString(EncNonce, (size_t)EncNonceLength)) - { - return PARSE_INCOMPLETE; - } - if (EncNonceLength > MAX_ENC_LEN) - { - LOGD("Too long encryption nonce"); - m_Client->Kick("Hacked client"); - return PARSE_OK; - } - - HandleEncryptionKeyResponse(EncKey, EncNonce); - return PARSE_OK; -} - - - - - -int cProtocol132::ParseLocaleViewDistance(void) -{ - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Locale); - HANDLE_PACKET_READ(ReadChar, char, ViewDistance); - HANDLE_PACKET_READ(ReadChar, char, ChatFlags); - HANDLE_PACKET_READ(ReadChar, char, ClientDifficulty); - m_Client->SetLocale(Locale); - // TODO: m_Client->HandleViewDistance(ViewDistance); - // TODO: m_Client->HandleChatFlags(ChatFlags); - // Ignoring client difficulty - return PARSE_OK; -} - - - - - -int cProtocol132::ParseLogin(void) -{ - // Login packet not used in 1.3.2 - return PARSE_ERROR; -} - - - - - -int cProtocol132::ParsePlayerAbilities(void) -{ - HANDLE_PACKET_READ(ReadBool, bool, Flags); - HANDLE_PACKET_READ(ReadChar, char, FlyingSpeed); - HANDLE_PACKET_READ(ReadChar, char, WalkingSpeed); - // TODO: m_Client->HandlePlayerAbilities(...); - return PARSE_OK; -} - - - - - -int cProtocol132::ParseTabCompletion(void) -{ - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Text); - m_Client->HandleTabCompletion(Text); - return PARSE_OK; -} - - - - - -void cProtocol132::SendData(const char * a_Data, size_t a_Size) -{ - m_DataToSend.append(a_Data, a_Size); -} - - - - - -void cProtocol132::Flush(void) -{ - ASSERT(m_CSPacket.IsLockedByCurrentThread()); // Did all packets lock the CS properly? - - if (m_DataToSend.empty()) - { - LOGD("Flushing empty"); - return; - } - const char * Data = m_DataToSend.data(); - size_t Size = m_DataToSend.size(); - if (m_IsEncrypted) - { - Byte Encrypted[8192]; // Larger buffer, we may be sending lots of data (chunks) - while (Size > 0) - { - size_t NumBytes = (Size > sizeof(Encrypted)) ? sizeof(Encrypted) : Size; - m_Encryptor.ProcessData(Encrypted, (Byte *)Data, NumBytes); - super::SendData((const char *)Encrypted, NumBytes); - Size -= NumBytes; - Data += NumBytes; - } - } - else - { - super::SendData(Data, Size); - } - m_DataToSend.clear(); -} - - - - - -void cProtocol132::WriteItem(const cItem & a_Item) -{ - short ItemType = a_Item.m_ItemType; - ASSERT(ItemType >= -1); // Check validity of packets in debug runtime - if (ItemType <= 0) - { - // Fix, to make sure no invalid values are sent. - ItemType = -1; - } - - if (a_Item.IsEmpty()) - { - WriteShort(-1); - return; - } - - WriteShort(ItemType); - WriteChar (a_Item.m_ItemCount); - WriteShort(a_Item.m_ItemDamage); - - if (a_Item.m_Enchantments.IsEmpty()) - { - WriteShort(-1); - return; - } - - // Send the enchantments: - cFastNBTWriter Writer; - const char * TagName = (a_Item.m_ItemType == E_ITEM_BOOK) ? "StoredEnchantments" : "ench"; - EnchantmentSerializer::WriteToNBTCompound(a_Item.m_Enchantments, Writer, TagName); - Writer.Finish(); - AString Compressed; - CompressStringGZIP(Writer.GetResult().data(), Writer.GetResult().size(), Compressed); - WriteShort((short)Compressed.size()); - SendData(Compressed.data(), Compressed.size()); -} - - - - - -int cProtocol132::ParseItem(cItem & a_Item) -{ - HANDLE_PACKET_READ(ReadBEShort, short, ItemType); - - if (ItemType <= -1) - { - a_Item.Empty(); - return PARSE_OK; - } - a_Item.m_ItemType = ItemType; - - HANDLE_PACKET_READ(ReadChar, char, ItemCount); - HANDLE_PACKET_READ(ReadBEShort, short, ItemDamage); - a_Item.m_ItemCount = ItemCount; - a_Item.m_ItemDamage = ItemDamage; - if (ItemCount <= 0) - { - a_Item.Empty(); - } - - HANDLE_PACKET_READ(ReadBEShort, short, MetadataLength); - if (MetadataLength <= 0) - { - return PARSE_OK; - } - - // Read the metadata - AString Metadata; - Metadata.resize((size_t)MetadataLength); - if (!m_ReceivedData.ReadBuf((void *)Metadata.data(), (size_t)MetadataLength)) - { - return PARSE_INCOMPLETE; - } - - return ParseItemMetadata(a_Item, Metadata); -} - - - - - -int cProtocol132::ParseItemMetadata(cItem & a_Item, const AString & a_Metadata) -{ - // Uncompress the GZIPped data: - AString Uncompressed; - if (UncompressStringGZIP(a_Metadata.data(), a_Metadata.size(), Uncompressed) != Z_OK) - { - AString HexDump; - CreateHexDump(HexDump, a_Metadata.data(), a_Metadata.size(), 16); - LOG("Cannot unGZIP item metadata:\n%s", HexDump.c_str()); - return PARSE_ERROR; - } - - // Parse into NBT: - cParsedNBT NBT(Uncompressed.data(), Uncompressed.size()); - if (!NBT.IsValid()) - { - AString HexDump; - CreateHexDump(HexDump, Uncompressed.data(), Uncompressed.size(), 16); - LOG("Cannot parse NBT item metadata:\n%s", HexDump.c_str()); - return PARSE_ERROR; - } - - // Load enchantments from the NBT: - for (int tag = NBT.GetFirstChild(NBT.GetRoot()); tag >= 0; tag = NBT.GetNextSibling(tag)) - { - if ( - (NBT.GetType(tag) == TAG_List) && - ( - (NBT.GetName(tag) == "ench") || - (NBT.GetName(tag) == "StoredEnchantments") - ) - ) - { - EnchantmentSerializer::ParseFromNBT(a_Item.m_Enchantments, NBT, tag); - } - } - - return PARSE_OK; -} - - - - - -void cProtocol132::SendCompass(const cWorld & a_World) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_COMPASS); - WriteInt((int)(a_World.GetSpawnX())); - WriteInt((int)(a_World.GetSpawnY())); - WriteInt((int)(a_World.GetSpawnZ())); - Flush(); -} - - - - - -void cProtocol132::SendEncryptionKeyRequest(void) -{ - cCSLock Lock(m_CSPacket); - cServer * Server = cRoot::Get()->GetServer(); - WriteByte(0xfd); - WriteString(Server->GetServerID()); - const AString & PublicKeyDER = Server->GetPublicKeyDER(); - WriteShort((short)(PublicKeyDER.size())); - SendData(PublicKeyDER.data(), PublicKeyDER.size()); - WriteShort(4); - WriteInt((int)(intptr_t)this); // Using 'this' as the cryptographic nonce, so that we don't have to generate one each time :) - Flush(); -} - - - - - -void cProtocol132::HandleEncryptionKeyResponse(const AString & a_EncKey, const AString & a_EncNonce) -{ - // Decrypt EncNonce using privkey - 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)); - if (res != 4) - { - LOGD("Bad nonce length"); - m_Client->Kick("Hacked client"); - return; - } - if (ntohl(DecryptedNonce[0]) != (unsigned)(uintptr_t)this) - { - LOGD("Bad nonce value"); - m_Client->Kick("Hacked client"); - return; - } - - // Decrypt the symmetric encryption key using privkey: - Byte DecryptedKey[MAX_ENC_LEN]; - res = rsaDecryptor.Decrypt((const Byte *)a_EncKey.data(), a_EncKey.size(), DecryptedKey, sizeof(DecryptedKey)); - if (res != 16) - { - LOGD("Bad key length"); - m_Client->Kick("Hacked client"); - return; - } - - { - // Send encryption key response: - cCSLock Lock(m_CSPacket); - WriteByte(0xfc); - WriteShort(0); - WriteShort(0); - Flush(); - } - - #ifdef _DEBUG - AString DecryptedKeyHex; - CreateHexDump(DecryptedKeyHex, DecryptedKey, res, 16); - LOGD("Received encryption key, %d bytes:\n%s", res, DecryptedKeyHex.c_str()); - #endif - - StartEncryption(DecryptedKey); - return; -} - - - - - -void cProtocol132::StartEncryption(const Byte * a_Key) -{ - m_Encryptor.Init(a_Key, a_Key); - m_Decryptor.Init(a_Key, a_Key); - m_IsEncrypted = true; - - // Prepare the m_AuthServerID: - cSha1Checksum Checksum; - cServer * Server = cRoot::Get()->GetServer(); - AString ServerID = Server->GetServerID(); - Checksum.Update((const Byte *)ServerID.c_str(), ServerID.length()); - Checksum.Update(a_Key, 16); - Checksum.Update((const Byte *)Server->GetPublicKeyDER().data(), Server->GetPublicKeyDER().size()); - Byte Digest[20]; - Checksum.Finalize(Digest); - cSha1Checksum::DigestToJava(Digest, m_AuthServerID); -} - - - - diff --git a/src/Protocol/Protocol132.h b/src/Protocol/Protocol132.h deleted file mode 100644 index 1124a7253..000000000 --- a/src/Protocol/Protocol132.h +++ /dev/null @@ -1,115 +0,0 @@ - -// Protocol132.h - -// Interfaces to the cProtocol132 class representing the release 1.3.2 protocol (#39) - - - - - -#pragma once - -#include "Protocol125.h" - -#ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable:4127) - #pragma warning(disable:4189) - #pragma warning(disable:4231) - #pragma warning(disable:4244) - #pragma warning(disable:4702) -#endif - -#ifdef _MSC_VER - #pragma warning(pop) -#endif - -#include "PolarSSL++/AesCfb128Decryptor.h" -#include "PolarSSL++/AesCfb128Encryptor.h" - - - - - -class cProtocol132 : - public cProtocol125 -{ - typedef cProtocol125 super; -public: - - cProtocol132(cClientHandle * a_Client); - virtual ~cProtocol132(); - - /// Called when client sends some data: - virtual void DataReceived(const char * a_Data, size_t a_Size) override; - - // Sending commands (alphabetically sorted): - virtual void SendBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType) override; - virtual void SendBlockBreakAnim (int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage) override; - virtual void SendBlockChange (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) override; - virtual void SendChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) override; - virtual void SendCollectEntity (const cEntity & a_Entity, const cPlayer & a_Player) override; - virtual void SendDestroyEntity (const cEntity & a_Entity) override; - virtual void SendEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item) override; - virtual void SendLogin (const cPlayer & a_Player, const cWorld & a_World) override; - virtual void SendPlayerSpawn (const cPlayer & a_Player) override; - virtual void SendSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch) override; - virtual void SendSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) override; - virtual void SendSpawnMob (const cMonster & a_Mob) override; - virtual void SendTabCompletionResults(const AStringVector & a_Results) override; - virtual void SendUnloadChunk (int a_ChunkX, int a_ChunkZ) override; - virtual void SendWholeInventory (const cWindow & a_Window) override; - - virtual AString GetAuthServerID(void) override; - - /// Handling of the additional packets: - virtual int ParsePacket(unsigned char a_PacketType) override; - - // Modified packets: - virtual int ParseBlockPlace (void) override; - virtual int ParseHandshake (void) override; - virtual int ParseLogin (void) override; - virtual int ParsePlayerAbilities(void) override; - - // New packets: - virtual int ParseClientStatuses (void); - virtual int ParseEncryptionKeyResponse(void); - virtual int ParseLocaleViewDistance (void); - virtual int ParseTabCompletion (void); - -protected: - bool m_IsEncrypted; - - cAesCfb128Decryptor m_Decryptor; - cAesCfb128Encryptor m_Encryptor; - - AString m_DataToSend; - - /// The ServerID used for session authentication; set in StartEncryption(), used in GetAuthServerID() - AString m_AuthServerID; - - virtual void SendData(const char * a_Data, size_t a_Size) override; - - // DEBUG: - virtual void Flush(void) override; - - // Items in slots are sent differently - virtual void WriteItem(const cItem & a_Item) override; - virtual int ParseItem(cItem & a_Item) override; - - /// Parses the metadata that may come with the item. - int ParseItemMetadata(cItem & a_Item, const AString & a_Metadata); - - virtual void SendCompass(const cWorld & a_World); - virtual void SendEncryptionKeyRequest(void); - - /// Decrypts the key and nonce, checks nonce, starts the symmetric encryption - void HandleEncryptionKeyResponse(const AString & a_EncKey, const AString & a_EncNonce); - - /// Starts the symmetric encryption with the specified key; also sets m_AuthServerID - void StartEncryption(const Byte * a_Key); -} ; - - - - diff --git a/src/Protocol/Protocol14x.cpp b/src/Protocol/Protocol14x.cpp deleted file mode 100644 index d33314a2f..000000000 --- a/src/Protocol/Protocol14x.cpp +++ /dev/null @@ -1,265 +0,0 @@ - -// Protocol14x.cpp - -/* -Implements the 1.4.x protocol classes representing these protocols: -- cProtocol142: - - release 1.4.2 protocol (#47) - - release 1.4.4 protocol (#49) - the same protocol class is used, because the only difference is in a packet that MCServer doesn't implement yet (ITEM_DATA) - - release 1.4.5 protocol (same as 1.4.4) -- cProtocol146: - - release 1.4.6 protocol (#51) -*/ - -#include "Globals.h" -#include "Protocol14x.h" -#include "../Root.h" -#include "../Server.h" -#include "../ClientHandle.h" -#include "../Item.h" -#include "ChunkDataSerializer.h" -#include "../Entities/Player.h" -#include "../Mobs/Monster.h" -#include "../UI/Window.h" -#include "../Entities/Pickup.h" -#include "../Entities/FallingBlock.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 - - -#define HANDLE_PACKET_READ(Proc, Type, Var) \ - Type Var; \ - { \ - if (!m_ReceivedData.Proc(Var)) \ - { \ - m_ReceivedData.CheckValid(); \ - return PARSE_INCOMPLETE; \ - } \ - m_ReceivedData.CheckValid(); \ - } - - - - - -enum -{ - PACKET_UPDATE_TIME = 0x04, - PACKET_PICKUP_SPAWN = 0x15, - PACKET_SPAWN_OBJECT = 0x17, - PACKET_ENTITY_METADATA = 0x28, - PACKET_SOUND_PARTICLE_EFFECT = 0x3d -} ; - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cProtocol142: - -cProtocol142::cProtocol142(cClientHandle * a_Client) : - super(a_Client) -{ -} - - - - - -int cProtocol142::ParseLocaleViewDistance(void) -{ - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Locale); - HANDLE_PACKET_READ(ReadChar, char, ViewDistance); - HANDLE_PACKET_READ(ReadChar, char, ChatFlags); - HANDLE_PACKET_READ(ReadChar, char, ClientDifficulty); - HANDLE_PACKET_READ(ReadChar, char, ShouldShowCape); // <-- new in 1.4.2 - m_Client->SetLocale(Locale); - // TODO: m_Client->HandleViewDistance(ViewDistance); - // TODO: m_Client->HandleChatFlags(ChatFlags); - // Ignoring client difficulty - return PARSE_OK; -} - - - - - -void cProtocol142::SendPickupSpawn(const cPickup & a_Pickup) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_PICKUP_SPAWN); - WriteInt (a_Pickup.GetUniqueID()); - WriteItem (a_Pickup.GetItem()); - WriteVectorI((Vector3i)(a_Pickup.GetPosition() * 32)); - WriteChar((char)(a_Pickup.GetSpeedX() * 8)); - WriteChar((char)(a_Pickup.GetSpeedY() * 8)); - WriteChar((char)(a_Pickup.GetSpeedZ() * 8)); - Flush(); -} - - - - - -void cProtocol142::SendSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_SOUND_PARTICLE_EFFECT); - WriteInt (a_EffectID); - WriteInt (a_SrcX); - WriteByte((Byte)a_SrcY); - WriteInt (a_SrcZ); - WriteInt (a_Data); - WriteBool(0); - Flush(); -} - - - - - -void cProtocol142::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_UPDATE_TIME); - WriteInt64(a_WorldAge); - WriteInt64(a_TimeOfDay); - Flush(); -} - - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cProtocol146: - -cProtocol146::cProtocol146(cClientHandle * a_Client) : - super(a_Client) -{ -} - - - - - -void cProtocol146::SendPickupSpawn(const cPickup & a_Pickup) -{ - ASSERT(!a_Pickup.GetItem().IsEmpty()); - - cCSLock Lock(m_CSPacket); - - // Send a SPAWN_OBJECT packet for the base entity: - WriteByte(PACKET_SPAWN_OBJECT); - WriteInt (a_Pickup.GetUniqueID()); - WriteByte(0x02); - WriteInt ((int)(a_Pickup.GetPosX() * 32)); - WriteInt ((int)(a_Pickup.GetPosY() * 32)); - WriteInt ((int)(a_Pickup.GetPosZ() * 32)); - WriteInt (1); - WriteShort((short)(a_Pickup.GetSpeedX() * 32)); - WriteShort((short)(a_Pickup.GetSpeedY() * 32)); - WriteShort((short)(a_Pickup.GetSpeedZ() * 32)); - WriteByte(0); - WriteByte(0); - - // Send a ENTITY_METADATA packet with the slot info: - WriteByte(PACKET_ENTITY_METADATA); - WriteInt(a_Pickup.GetUniqueID()); - WriteByte(0xaa); // a slot value at index 10 - WriteItem(a_Pickup.GetItem()); - WriteByte(0x7f); // End of metadata - Flush(); -} - - - - - -void cProtocol146::SendSpawnFallingBlock(const cFallingBlock & a_FallingBlock) -{ - // Send a spawn object / vehicle packet - cCSLock Lock(m_CSPacket); - - WriteByte(PACKET_SPAWN_OBJECT); - WriteInt (a_FallingBlock.GetUniqueID()); - WriteByte(70); - WriteInt ((int)(a_FallingBlock.GetPosX() * 32)); - WriteInt ((int)(a_FallingBlock.GetPosY() * 32)); - WriteInt ((int)(a_FallingBlock.GetPosZ() * 32)); - WriteByte (0); // Pitch - WriteByte (0); // Yaw - WriteInt (a_FallingBlock.GetBlockType()); // data indicator = blocktype - WriteShort((short)(a_FallingBlock.GetSpeedX() * 400)); - WriteShort((short)(a_FallingBlock.GetSpeedY() * 400)); - WriteShort((short)(a_FallingBlock.GetSpeedZ() * 400)); - Flush(); -} - - - - - -void cProtocol146::SendSpawnObject(const cEntity & a_Entity, char a_ObjectType, int a_ObjectData, Byte a_Yaw, Byte a_Pitch) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_SPAWN_OBJECT); - WriteInt (a_Entity.GetUniqueID()); - WriteChar(a_ObjectType); - WriteInt ((int)(a_Entity.GetPosX() * 32)); - WriteInt ((int)(a_Entity.GetPosY() * 32)); - WriteInt ((int)(a_Entity.GetPosZ() * 32)); - WriteByte(a_Pitch); - WriteByte(a_Yaw); - WriteInt (a_ObjectData); - if (a_ObjectData != 0) - { - WriteShort((short)(a_Entity.GetSpeedX() * 400)); - WriteShort((short)(a_Entity.GetSpeedY() * 400)); - WriteShort((short)(a_Entity.GetSpeedZ() * 400)); - } - Flush(); -} - - - - - -void cProtocol146::SendSpawnVehicle(const cEntity & a_Vehicle, char a_VehicleType, char a_VehicleSubType) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_SPAWN_OBJECT); - WriteInt (a_Vehicle.GetUniqueID()); - WriteChar (a_VehicleType); - WriteInt ((int)(a_Vehicle.GetPosX() * 32)); - WriteInt ((int)(a_Vehicle.GetPosY() * 32)); - WriteInt ((int)(a_Vehicle.GetPosZ() * 32)); - WriteByte ((Byte)((a_Vehicle.GetPitch() / 360.f) * 256)); - WriteByte ((Byte)((a_Vehicle.GetYaw() / 360.f) * 256)); - WriteInt (a_VehicleSubType); - if (a_VehicleSubType != 0) - { - WriteShort((short)(a_Vehicle.GetSpeedX() * 400)); - WriteShort((short)(a_Vehicle.GetSpeedY() * 400)); - WriteShort((short)(a_Vehicle.GetSpeedZ() * 400)); - } - Flush(); -} - - - - - diff --git a/src/Protocol/Protocol14x.h b/src/Protocol/Protocol14x.h deleted file mode 100644 index 227cc8cc7..000000000 --- a/src/Protocol/Protocol14x.h +++ /dev/null @@ -1,63 +0,0 @@ - -// Protocol14x.h - -/* -Interfaces to the 1.4.x protocol classes representing these protocols: -- cProtocol142: - - release 1.4.2 protocol (#47) - - release 1.4.4 protocol (#49) - the same protocol class is used, because the only difference is in a packet that MCServer doesn't implement yet (ITEM_DATA) - - release 1.4.5 protocol (same as 1.4.4) -- cProtocol146: - - release 1.4.6 protocol (#51) -*/ - - - - - -#pragma once - -#include "Protocol132.h" - - - - - -class cProtocol142 : - public cProtocol132 -{ - typedef cProtocol132 super; - -public: - cProtocol142(cClientHandle * a_Client); - - // Sending commands (alphabetically sorted): - virtual void SendPickupSpawn (const cPickup & a_Pickup) override; - virtual void SendSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) override; - virtual void SendTimeUpdate (Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle) override; - - // Specific packet parsers: - virtual int ParseLocaleViewDistance(void) override; -} ; - - - - - -class cProtocol146 : - public cProtocol142 -{ - typedef cProtocol142 super; - -public: - cProtocol146(cClientHandle * a_Client); - - virtual void SendPickupSpawn (const cPickup & a_Pickup) override; - virtual void SendSpawnFallingBlock(const cFallingBlock & a_FallingBlock) override; - virtual void SendSpawnObject (const cEntity & a_Entity, char a_ObjectType, int a_ObjectData, Byte a_Yaw, Byte a_Pitch) override; - virtual void SendSpawnVehicle (const cEntity & a_Vehicle, char a_VehicleType, char a_VehicleSubType) override; -} ; - - - - diff --git a/src/Protocol/Protocol15x.cpp b/src/Protocol/Protocol15x.cpp deleted file mode 100644 index 089296fdf..000000000 --- a/src/Protocol/Protocol15x.cpp +++ /dev/null @@ -1,209 +0,0 @@ - -// Protocol15x.cpp - -/* -Implements the 1.5.x protocol classes: - - cProtocol150 - - release 1.5 protocol (#60) - - release 1.5.2 protocol (#61, no relevant changes found) -*/ - -#include "Globals.h" -#include "Protocol15x.h" -#include "../ClientHandle.h" -#include "../Item.h" -#include "../UI/Window.h" - - - - - -#define HANDLE_PACKET_READ(Proc, Type, Var) \ - Type Var; \ - { \ - if (!m_ReceivedData.Proc(Var)) \ - { \ - m_ReceivedData.CheckValid(); \ - return PARSE_INCOMPLETE; \ - } \ - m_ReceivedData.CheckValid(); \ - } - - - - - -enum -{ - PACKET_WINDOW_OPEN = 0x64, - PACKET_PARTICLE_EFFECT = 0x3F, - PACKET_SCOREBOARD_OBJECTIVE = 0xCE, - PACKET_SCORE_UPDATE = 0xCF, - PACKET_DISPLAY_OBJECTIVE = 0xD0 -} ; - - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cProtocol150: - -cProtocol150::cProtocol150(cClientHandle * a_Client) : - super(a_Client) -{ -} - - - - - -void cProtocol150::SendWindowOpen(const cWindow & a_Window) -{ - if (a_Window.GetWindowType() < 0) - { - // Do not send for inventory windows - return; - } - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_WINDOW_OPEN); - WriteByte (a_Window.GetWindowID()); - WriteByte (a_Window.GetWindowType()); - WriteString(a_Window.GetWindowTitle()); - WriteByte (a_Window.GetNumNonInventorySlots()); - WriteByte (1); // Use title - Flush(); -} - - - - - -void cProtocol150::SendParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_PARTICLE_EFFECT); - WriteString(a_ParticleName); - WriteFloat(a_SrcX); - WriteFloat(a_SrcY); - WriteFloat(a_SrcZ); - WriteFloat(a_OffsetX); - WriteFloat(a_OffsetY); - WriteFloat(a_OffsetZ); - WriteFloat(a_ParticleData); - WriteInt(a_ParticleAmount); - Flush(); -} - - - - - -void cProtocol150::SendScoreboardObjective(const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_SCOREBOARD_OBJECTIVE); - WriteString(a_Name); - WriteString(a_DisplayName); - WriteByte(a_Mode); - Flush(); -} - - - - - -void cProtocol150::SendScoreUpdate(const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_SCORE_UPDATE); - WriteString(a_Player); - WriteByte(a_Mode); - - if (a_Mode != 1) - { - WriteString(a_Objective); - WriteInt((int) a_Score); - } - - Flush(); -} - - - - - -void cProtocol150::SendDisplayObjective(const AString & a_Objective, cScoreboard::eDisplaySlot a_Display) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_DISPLAY_OBJECTIVE); - WriteByte((int) a_Display); - WriteString(a_Objective); - Flush(); -} - - - - - -int cProtocol150::ParseWindowClick(void) -{ - HANDLE_PACKET_READ(ReadChar, char, WindowID); - HANDLE_PACKET_READ(ReadBEShort, short, SlotNum); - HANDLE_PACKET_READ(ReadByte, Byte, Button); - HANDLE_PACKET_READ(ReadBEShort, short, TransactionID); - HANDLE_PACKET_READ(ReadByte, Byte, Mode); - cItem HeldItem; - int res = ParseItem(HeldItem); - if (res < 0) - { - return res; - } - - // Convert Button, Mode, SlotNum and HeldItem into eClickAction: - eClickAction Action = caUnknown; - switch ((Mode << 8) | Button) - { - case 0x0000: Action = (SlotNum != -999) ? caLeftClick : caLeftClickOutside; break; - case 0x0001: Action = (SlotNum != -999) ? caRightClick : caRightClickOutside; break; - case 0x0100: Action = caShiftLeftClick; break; - case 0x0101: Action = caShiftRightClick; break; - case 0x0200: Action = caNumber1; break; - case 0x0201: Action = caNumber2; break; - case 0x0202: Action = caNumber3; break; - case 0x0203: Action = caNumber4; break; - case 0x0204: Action = caNumber5; break; - case 0x0205: Action = caNumber6; break; - case 0x0206: Action = caNumber7; break; - case 0x0207: Action = caNumber8; break; - case 0x0208: Action = caNumber9; break; - case 0x0300: Action = caMiddleClick; break; - case 0x0400: Action = (SlotNum == -999) ? caLeftClickOutsideHoldNothing : caDropKey; break; - case 0x0401: Action = (SlotNum == -999) ? caRightClickOutsideHoldNothing : caCtrlDropKey; break; - case 0x0500: Action = (SlotNum == -999) ? caLeftPaintBegin : caUnknown; break; - case 0x0501: Action = (SlotNum != -999) ? caLeftPaintProgress : caUnknown; break; - case 0x0502: Action = (SlotNum == -999) ? caLeftPaintEnd : caUnknown; break; - case 0x0504: Action = (SlotNum == -999) ? caRightPaintBegin : caUnknown; break; - case 0x0505: Action = (SlotNum != -999) ? caRightPaintProgress : caUnknown; break; - case 0x0506: Action = (SlotNum == -999) ? caRightPaintEnd : caUnknown; break; - case 0x0600: Action = caDblClick; break; - } - - if (Action == caUnknown) - { - LOGWARNING("Received an unknown click action combination: Mode = %d, Button = %d, Slot = %d, HeldItem = %s. Ignoring packet.", - Mode, Button, SlotNum, ItemToFullString(HeldItem).c_str() - ); - ASSERT(!"Unknown click action"); - return PARSE_OK; - } - - m_Client->HandleWindowClick(WindowID, SlotNum, Action, HeldItem); - return PARSE_OK; -} - - - - - diff --git a/src/Protocol/Protocol15x.h b/src/Protocol/Protocol15x.h deleted file mode 100644 index 968d5ebcf..000000000 --- a/src/Protocol/Protocol15x.h +++ /dev/null @@ -1,42 +0,0 @@ - -// Protocol15x.h - -/* -Declares the 1.5.x protocol classes: - - cProtocol150 - - release 1.5 and 1.5.1 protocol (#60) - - release 1.5.2 protocol (#61; no relevant changes found) -*/ - - - - - -#pragma once - -#include "Protocol14x.h" - - - - - -class cProtocol150 : - public cProtocol146 -{ - typedef cProtocol146 super; - -public: - cProtocol150(cClientHandle * a_Client); - - virtual void SendWindowOpen (const cWindow & a_Window) override; - virtual void SendParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount) override; - virtual void SendScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) override; - virtual void SendScoreUpdate (const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode) override; - virtual void SendDisplayObjective (const AString & a_Objective, cScoreboard::eDisplaySlot a_Display) override; - - virtual int ParseWindowClick(void); -} ; - - - - diff --git a/src/Protocol/Protocol16x.cpp b/src/Protocol/Protocol16x.cpp deleted file mode 100644 index 0d354a030..000000000 --- a/src/Protocol/Protocol16x.cpp +++ /dev/null @@ -1,312 +0,0 @@ - -// Protocol16x.cpp - -/* -Implements the 1.6.x protocol classes: - - cProtocol161 - - release 1.6.1 protocol (#73) - - cProtocol162 - - release 1.6.2 protocol (#74) - - release 1.6.3 protocol (#77) - no relevant changes - - release 1.6.4 protocol (#78) - no relevant changes -(others may be added later in the future for the 1.6 release series) -*/ - -#include "Globals.h" -#include "Protocol16x.h" -#include "../ClientHandle.h" -#include "../Entities/Entity.h" -#include "../Entities/Player.h" -#include "../UI/Window.h" -#include "../CompositeChat.h" - - - - - -#define HANDLE_PACKET_READ(Proc, Type, Var) \ - Type Var; \ - { \ - if (!m_ReceivedData.Proc(Var)) \ - { \ - m_ReceivedData.CheckValid(); \ - return PARSE_INCOMPLETE; \ - } \ - m_ReceivedData.CheckValid(); \ - } - - - - - -enum -{ - PACKET_CHAT = 0x03, - PACKET_UPDATE_HEALTH = 0x08, - PACKET_STEER_VEHICLE = 0x1b, - PACKET_ATTACH_ENTITY = 0x27, - PACKET_ENTITY_PROPERTIES = 0x2c, - PACKET_WINDOW_OPEN = 0x64, - PACKET_TILE_EDITOR_OPEN = 0x85, - PACKET_PLAYER_ABILITIES = 0xca, -} ; - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cProtocol161: - -cProtocol161::cProtocol161(cClientHandle * a_Client) : - super(a_Client) -{ -} - - - - - -void cProtocol161::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_Vehicle) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_ATTACH_ENTITY); - WriteInt(a_Entity.GetUniqueID()); - WriteInt((a_Vehicle == NULL) ? -1 : a_Vehicle->GetUniqueID()); - WriteBool(false); // TODO: "Should use leash?" -> no - Flush(); -} - - - - - -void cProtocol161::SendChat(const AString & a_Message) -{ - super::SendChat(Printf("{\"text\":\"%s\"}", EscapeString(a_Message).c_str())); -} - - - - - -void cProtocol161::SendChat(const cCompositeChat & a_Message) -{ - // This protocol version doesn't support composite messages to the full - // Just extract each part's text and use it: - - super::SendChat(Printf("{\"text\":\"%s\"}", EscapeString(a_Message.ExtractText()).c_str())); -} - - - - - -void cProtocol161::SendEditSign(int a_BlockX, int a_BlockY, int a_BlockZ) -{ - cCSLock Lock(m_CSPacket); - WriteByte(PACKET_TILE_EDITOR_OPEN); - WriteByte(0); - WriteInt(a_BlockX); - WriteInt(a_BlockY); - WriteInt(a_BlockZ); - Flush(); -} - - - - - -void cProtocol161::SendGameMode(eGameMode a_GameMode) -{ - super::SendGameMode(a_GameMode); - SendPlayerMaxSpeed(); -} - - - - - -void cProtocol161::SendHealth(void) -{ - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_UPDATE_HEALTH); - cPlayer * Player = m_Client->GetPlayer(); - WriteFloat((float)Player->GetHealth()); - WriteShort((short)Player->GetFoodLevel()); - WriteFloat((float)Player->GetFoodSaturationLevel()); - Flush(); -} - - - - - -void cProtocol161::SendPlayerMaxSpeed(void) -{ - cCSLock Lock(m_CSPacket); - cPlayer * Player = m_Client->GetPlayer(); - WriteByte(PACKET_ENTITY_PROPERTIES); - WriteInt(Player->GetUniqueID()); - WriteInt(1); - WriteString("generic.movementSpeed"); - WriteDouble(0.1 * Player->GetMaxSpeed()); - Flush(); -} - - - - - -void cProtocol161::SendRespawn(eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks) -{ - // Besides sending the respawn, we need to also send the player max speed, otherwise the client reverts to super-fast - super::SendRespawn(a_Dimension, a_ShouldIgnoreDimensionChecks); - SendPlayerMaxSpeed(); -} - - - - - -void cProtocol161::SendWindowOpen(const cWindow & a_Window) -{ - if (a_Window.GetWindowType() < 0) - { - // Do not send for inventory windows - return; - } - cCSLock Lock(m_CSPacket); - WriteByte (PACKET_WINDOW_OPEN); - WriteChar (a_Window.GetWindowID()); - WriteByte ((Byte)a_Window.GetWindowType()); - WriteString(a_Window.GetWindowTitle()); - WriteByte ((Byte)a_Window.GetNumNonInventorySlots()); - WriteByte (1); // Use title - if (a_Window.GetWindowType() == cWindow::wtAnimalChest) - { - WriteInt(0); // TODO: The animal's EntityID - } - Flush(); -} - - - - - -int cProtocol161::ParseEntityAction(void) -{ - HANDLE_PACKET_READ(ReadBEInt, int, EntityID); - HANDLE_PACKET_READ(ReadChar, char, ActionID); - HANDLE_PACKET_READ(ReadBEInt, int, UnknownHorseVal); - - switch (ActionID) - { - case 1: m_Client->HandleEntityCrouch(EntityID, true); break; // Crouch - case 2: m_Client->HandleEntityCrouch(EntityID, false); break; // Uncrouch - case 3: m_Client->HandleEntityLeaveBed(EntityID); break; // Leave Bed - case 4: m_Client->HandleEntitySprinting(EntityID, true); break; // Start sprinting - case 5: m_Client->HandleEntitySprinting(EntityID, false); break; // Stop sprinting - } - - return PARSE_OK; -} - - - - - -int cProtocol161::ParseLogin(void) -{ - // The login packet is sent by Forge clients only - // Only parse the packet, do no extra processing - // Note that the types and the names have been only guessed and are not verified at all! - HANDLE_PACKET_READ(ReadBEInt, int, Int1); - HANDLE_PACKET_READ(ReadBEUTF16String16, AString, String1); - HANDLE_PACKET_READ(ReadChar, char, Char1); - HANDLE_PACKET_READ(ReadChar, char, Char2); - HANDLE_PACKET_READ(ReadChar, char, Char3); - HANDLE_PACKET_READ(ReadByte, Byte, Byte1); - HANDLE_PACKET_READ(ReadByte, Byte, Byte2); - return PARSE_OK; -} - - - - - -int cProtocol161::ParsePlayerAbilities(void) -{ - HANDLE_PACKET_READ(ReadByte, Byte, Flags); - HANDLE_PACKET_READ(ReadBEFloat, float, FlyingSpeed); - HANDLE_PACKET_READ(ReadBEFloat, float, WalkingSpeed); - // TODO: m_Client->HandlePlayerAbilities(...); - return PARSE_OK; -} - - - - - -int cProtocol161::ParseSteerVehicle(void) -{ - HANDLE_PACKET_READ(ReadBEFloat, float, Sideways); - HANDLE_PACKET_READ(ReadBEFloat, float, Forward); - HANDLE_PACKET_READ(ReadBool, bool, Jump); - HANDLE_PACKET_READ(ReadBool, bool, Unmount); - if (Unmount) - { - m_Client->HandleUnmount(); - } - else - { - m_Client->HandleSteerVehicle(Forward, Sideways); - } - return PARSE_OK; -} - - - - - -int cProtocol161::ParsePacket(unsigned char a_PacketType) -{ - switch (a_PacketType) - { - case PACKET_STEER_VEHICLE: return ParseSteerVehicle(); - default: return super::ParsePacket(a_PacketType); - } -} - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cProtocol162: - -cProtocol162::cProtocol162(cClientHandle * a_Client) : - super(a_Client) -{ -} - - - - - -void cProtocol162::SendPlayerMaxSpeed(void) -{ - cCSLock Lock(m_CSPacket); - cPlayer * Player = m_Client->GetPlayer(); - WriteByte(PACKET_ENTITY_PROPERTIES); - WriteInt(Player->GetUniqueID()); - WriteInt(1); - WriteString("generic.movementSpeed"); - WriteDouble(0.1 * Player->GetMaxSpeed()); - WriteShort(0); - Flush(); -} - - - - diff --git a/src/Protocol/Protocol16x.h b/src/Protocol/Protocol16x.h deleted file mode 100644 index add761d1e..000000000 --- a/src/Protocol/Protocol16x.h +++ /dev/null @@ -1,78 +0,0 @@ - -// Protocol16x.h - -/* -Declares the 1.6.x protocol classes: - - cProtocol161 - - release 1.6.1 protocol (#73) - - cProtocol162 - - release 1.6.2 protocol (#74) - - release 1.6.3 protocol (#77) - no relevant changes - - release 1.6.4 protocol (#78) - no relevant changes -(others may be added later in the future for the 1.6 release series) -*/ - - - - - -#pragma once - -#include "Protocol15x.h" - - - - - -class cProtocol161 : - public cProtocol150 -{ - typedef cProtocol150 super; - -public: - cProtocol161(cClientHandle * a_Client); - -protected: - - // cProtocol150 overrides: - virtual void SendAttachEntity (const cEntity & a_Entity, const cEntity * a_Vehicle) override; - virtual void SendChat (const AString & a_Message) override; - virtual void SendChat (const cCompositeChat & a_Message) override; - virtual void SendEditSign (int a_BlockX, int a_BlockY, int a_BlockZ) override; ///< Request the client to open up the sign editor for the sign (1.6+) - virtual void SendGameMode (eGameMode a_GameMode) override; - virtual void SendHealth (void) override; - virtual void SendPlayerMaxSpeed(void) override; - virtual void SendRespawn (eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks) override; - virtual void SendWindowOpen (const cWindow & a_Window) override; - - virtual int ParseEntityAction (void) override; - virtual int ParseLogin (void) override; - virtual int ParsePlayerAbilities(void) override; - - // New packets: - virtual int ParseSteerVehicle(void); - - // Enable new packets' handling - virtual int ParsePacket(unsigned char a_PacketType) override; -} ; - - - - - -class cProtocol162 : - public cProtocol161 -{ - typedef cProtocol161 super; - -public: - cProtocol162(cClientHandle * a_Client); - -protected: - // cProtocol161 overrides: - virtual void SendPlayerMaxSpeed(void) override; -} ; - - - - diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index ac58ef28b..e4c33908a 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -2217,20 +2217,6 @@ void cProtocol172::HandlePacketWindowClose(cByteBuffer & a_ByteBuffer) -void cProtocol172::WritePacket(cByteBuffer & a_Packet) -{ - cCSLock Lock(m_CSPacket); - AString Pkt; - a_Packet.ReadAll(Pkt); - WriteVarInt((UInt32)Pkt.size()); - SendData(Pkt.data(), Pkt.size()); - Flush(); -} - - - - - void cProtocol172::SendData(const char * a_Data, size_t a_Size) { if (m_IsEncrypted) diff --git a/src/Protocol/Protocol17x.h b/src/Protocol/Protocol17x.h index 8f537f5d7..0bc86a72a 100644 --- a/src/Protocol/Protocol17x.h +++ b/src/Protocol/Protocol17x.h @@ -296,9 +296,6 @@ protected: void HandlePacketWindowClose (cByteBuffer & a_ByteBuffer); - /** Writes an entire packet into the output stream. a_Packet is expected to start with the packet type; data length is prepended here. */ - void WritePacket(cByteBuffer & a_Packet); - /** Sends the data to the client, encrypting them if needed. */ virtual void SendData(const char * a_Data, size_t a_Size) override; diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index a2dbb7a1f..c983f6671 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -2507,20 +2507,6 @@ void cProtocol180::HandlePacketWindowClose(cByteBuffer & a_ByteBuffer) -void cProtocol180::WritePacket(cByteBuffer & a_Packet) -{ - cCSLock Lock(m_CSPacket); - AString Pkt; - a_Packet.ReadAll(Pkt); - WriteVarInt((UInt32)Pkt.size()); - SendData(Pkt.data(), Pkt.size()); - Flush(); -} - - - - - void cProtocol180::SendData(const char * a_Data, size_t a_Size) { if (m_IsEncrypted) diff --git a/src/Protocol/Protocol18x.h b/src/Protocol/Protocol18x.h index 554edecc8..acc167a6d 100644 --- a/src/Protocol/Protocol18x.h +++ b/src/Protocol/Protocol18x.h @@ -313,9 +313,6 @@ protected: void HandlePacketWindowClose (cByteBuffer & a_ByteBuffer); - /** Writes an entire packet into the output stream. a_Packet is expected to start with the packet type; data length is prepended here. */ - void WritePacket(cByteBuffer & a_Packet); - /** Sends the data to the client, encrypting them if needed. */ virtual void SendData(const char * a_Data, size_t a_Size) override; diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index fe53aede1..bfa5334d5 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -7,11 +7,6 @@ #include "Globals.h" #include "ProtocolRecognizer.h" -#include "Protocol125.h" -#include "Protocol132.h" -#include "Protocol14x.h" -#include "Protocol15x.h" -#include "Protocol16x.h" #include "Protocol17x.h" #include "Protocol18x.h" #include "../ClientHandle.h" @@ -50,17 +45,6 @@ AString cProtocolRecognizer::GetVersionTextFromInt(int a_ProtocolVersion) { switch (a_ProtocolVersion) { - case PROTO_VERSION_1_2_5: return "1.2.5"; - case PROTO_VERSION_1_3_2: return "1.3.2"; - // case PROTO_VERSION_1_4_2: return "1.4.2"; - case PROTO_VERSION_1_4_4: return "1.4.4"; - case PROTO_VERSION_1_4_6: return "1.4.6"; - case PROTO_VERSION_1_5_0: return "1.5"; - case PROTO_VERSION_1_5_2: return "1.5.2"; - case PROTO_VERSION_1_6_1: return "1.6.1"; - case PROTO_VERSION_1_6_2: return "1.6.2"; - case PROTO_VERSION_1_6_3: return "1.6.3"; - case PROTO_VERSION_1_6_4: return "1.6.4"; case PROTO_VERSION_1_7_2: return "1.7.2"; case PROTO_VERSION_1_7_6: return "1.7.6"; case PROTO_VERSION_1_8_0: return "1.8"; @@ -206,16 +190,8 @@ void cProtocolRecognizer::SendDestroyEntity(const cEntity & a_Entity) void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) { - if (m_Protocol != NULL) - { - m_Protocol->SendDisconnect(a_Reason); - } - else - { - // This is used when the client sends a server-ping, respond with the default packet: - WriteByte (0xff); // PACKET_DISCONNECT - WriteString(a_Reason); - } + ASSERT(m_Protocol != NULL); + m_Protocol->SendDisconnect(a_Reason); } @@ -873,51 +849,8 @@ bool cProtocolRecognizer::TryRecognizeProtocol(void) { // NOTE: If a new protocol is added or an old one is removed, adjust MCS_CLIENT_VERSIONS and // MCS_PROTOCOL_VERSIONS macros in the header file, as well as PROTO_VERSION_LATEST macro - - // The first packet should be a Handshake, 0x02: - unsigned char PacketType; - if (!m_Buffer.ReadByte(PacketType)) - { - return false; - } - switch (PacketType) - { - case 0x02: return TryRecognizeLengthlessProtocol(); // Handshake, continue recognizing - case 0xfe: - { - // This may be either a packet length or the length-less Ping packet - Byte NextByte; - if (!m_Buffer.ReadByte(NextByte)) - { - // Not enough data for either protocol - // This could actually happen with the 1.2 / 1.3 client, but their support is fading out anyway - return false; - } - if (NextByte != 0x01) - { - // This is definitely NOT a length-less Ping packet, handle as lengthed protocol: - break; - } - if (!m_Buffer.ReadByte(NextByte)) - { - // There is no more data. Although this *could* mean TCP fragmentation, it is highly unlikely - // and rather this is a 1.4 client sending a regular Ping packet (without the following Plugin message) - SendLengthlessServerPing(); - return false; - } - if (NextByte == 0xfa) - { - // Definitely a length-less Ping followed by a Plugin message - SendLengthlessServerPing(); - return false; - } - // Definitely a lengthed Initial handshake, handle below: - break; - } - } // switch (PacketType) - // This must be a lengthed protocol, try if it has the entire initial handshake packet: - m_Buffer.ResetRead(); + // Lengthed protocol, try if it has the entire initial handshake packet: UInt32 PacketLen; UInt32 ReadSoFar = (UInt32)m_Buffer.GetReadableSpace(); if (!m_Buffer.ReadVarInt(PacketLen)) @@ -938,61 +871,6 @@ bool cProtocolRecognizer::TryRecognizeProtocol(void) -bool cProtocolRecognizer::TryRecognizeLengthlessProtocol(void) -{ - // The comm started with 0x02, which is a Handshake packet in the length-less protocol family - // 1.3.2 starts with 0x02 0x39 - // 1.2.5 starts with 0x02 and name is expected to less than 0x3900 long :) - char ch; - if (!m_Buffer.ReadChar(ch)) - { - return false; - } - switch (ch) - { - case PROTO_VERSION_1_3_2: - { - m_Protocol = new cProtocol132(m_Client); - return true; - } - case PROTO_VERSION_1_4_2: - case PROTO_VERSION_1_4_4: - { - m_Protocol = new cProtocol142(m_Client); - return true; - } - case PROTO_VERSION_1_4_6: - { - m_Protocol = new cProtocol146(m_Client); - return true; - } - case PROTO_VERSION_1_5_0: - case PROTO_VERSION_1_5_2: - { - m_Protocol = new cProtocol150(m_Client); - return true; - } - case PROTO_VERSION_1_6_1: - { - m_Protocol = new cProtocol161(m_Client); - return true; - } - case PROTO_VERSION_1_6_2: - case PROTO_VERSION_1_6_3: - case PROTO_VERSION_1_6_4: - { - m_Protocol = new cProtocol162(m_Client); - return true; - } - } - m_Protocol = new cProtocol125(m_Client); - return true; -} - - - - - bool cProtocolRecognizer::TryRecognizeLengthedProtocol(UInt32 a_PacketLengthRemaining) { UInt32 PacketType; @@ -1090,80 +968,3 @@ bool cProtocolRecognizer::TryRecognizeLengthedProtocol(UInt32 a_PacketLengthRema - -void cProtocolRecognizer::SendLengthlessServerPing(void) -{ - AString Reply; - cServer * Server = cRoot::Get()->GetServer(); - - AString ServerDescription = Server->GetDescription(); - int NumPlayers = Server->GetNumPlayers(); - int MaxPlayers = Server->GetMaxPlayers(); - AString Favicon = Server->GetFaviconData(); - cRoot::Get()->GetPluginManager()->CallHookServerPing(*m_Client, ServerDescription, NumPlayers, MaxPlayers, Favicon); - - switch (cRoot::Get()->GetPrimaryServerVersion()) - { - case PROTO_VERSION_1_2_5: - case PROTO_VERSION_1_3_2: - { - // http://wiki.vg/wiki/index.php?title=Protocol&oldid=3099#Server_List_Ping_.280xFE.29 - Printf(Reply, "%s%s%i%s%i", - ServerDescription.c_str(), - cChatColor::Delimiter, - NumPlayers, - cChatColor::Delimiter, - MaxPlayers - ); - break; - } - - case PROTO_VERSION_1_4_2: - case PROTO_VERSION_1_4_4: - case PROTO_VERSION_1_4_6: - case PROTO_VERSION_1_5_0: - case PROTO_VERSION_1_5_2: - case PROTO_VERSION_1_6_1: - case PROTO_VERSION_1_6_2: - case PROTO_VERSION_1_6_3: - case PROTO_VERSION_1_6_4: - { - // The server list ping now has 1 more byte of "magic". Mojang just loves to complicate stuff. - // http://wiki.vg/wiki/index.php?title=Protocol&oldid=3101#Server_List_Ping_.280xFE.29 - // _X 2012_10_31: I know that this needn't eat the byte, since it still may be in transit. - // Who cares? We're disconnecting anyway. - m_Buffer.ResetRead(); - if (m_Buffer.CanReadBytes(2)) - { - Byte val; - m_Buffer.ReadByte(val); // Packet type - Serverlist ping - m_Buffer.ReadByte(val); // 0x01 magic value - ASSERT(val == 0x01); - } - - AString ProtocolVersionNum; - Printf(ProtocolVersionNum, "%d", cRoot::Get()->GetPrimaryServerVersion()); - AString ProtocolVersionTxt(GetVersionTextFromInt(cRoot::Get()->GetPrimaryServerVersion())); - - // Cannot use Printf() because of in-string NUL bytes. - Reply = cChatColor::Delimiter; - Reply.append("1"); - Reply.push_back(0); - Reply.append(ProtocolVersionNum); - Reply.push_back(0); - Reply.append(ProtocolVersionTxt); - Reply.push_back(0); - Reply.append(ServerDescription); - Reply.push_back(0); - Reply.append(Printf("%d", NumPlayers)); - Reply.push_back(0); - Reply.append(Printf("%d", MaxPlayers)); - break; - } - } // switch (m_PrimaryServerVersion) - m_Client->Kick(Reply); -} - - - - diff --git a/src/Protocol/ProtocolRecognizer.h b/src/Protocol/ProtocolRecognizer.h index e4419f6ae..96a7e17d2 100644 --- a/src/Protocol/ProtocolRecognizer.h +++ b/src/Protocol/ProtocolRecognizer.h @@ -18,8 +18,8 @@ // Adjust these if a new protocol is added or an old one is removed: -#define MCS_CLIENT_VERSIONS "1.2.4, 1.2.5, 1.3.1, 1.3.2, 1.4.2, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.5, 1.5.1, 1.5.2, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.7.2, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.8" -#define MCS_PROTOCOL_VERSIONS "29, 39, 47, 49, 51, 60, 61, 73, 74, 77, 78, 4, 5" +#define MCS_CLIENT_VERSIONS "1.7.x, 1.8" +#define MCS_PROTOCOL_VERSIONS "4, 5, 47" @@ -33,22 +33,6 @@ class cProtocolRecognizer : public: enum { - PROTO_VERSION_1_2_5 = 29, - PROTO_VERSION_1_3_2 = 39, - PROTO_VERSION_1_4_2 = 47, - PROTO_VERSION_1_4_4 = 49, - PROTO_VERSION_1_4_6 = 51, - PROTO_VERSION_1_5_0 = 60, - PROTO_VERSION_1_5_2 = 61, - PROTO_VERSION_1_6_1 = 73, - PROTO_VERSION_1_6_2 = 74, - PROTO_VERSION_1_6_3 = 77, - PROTO_VERSION_1_6_4 = 78, - - PROTO_VERSION_NEXT, - PROTO_VERSION_LATEST = PROTO_VERSION_NEXT - 1, ///< Automatically assigned to the last protocol version, this serves as the default for PrimaryServerVersion - - // These will be kept "under" the next / latest, because the next and latest are only needed for previous protocols PROTO_VERSION_1_7_2 = 4, PROTO_VERSION_1_7_6 = 5, PROTO_VERSION_1_8_0 = 47, @@ -150,23 +134,11 @@ protected: /// Tries to recognize protocol based on m_Buffer contents; returns true if recognized bool TryRecognizeProtocol(void); - /** Tries to recognize a protocol in the length-less family, based on m_Buffer; returns true if recognized. - Handles protocols before release 1.7, that didn't include packet lengths, and started with a 0x02 handshake packet - Note that length-less server ping is handled directly in TryRecognizeProtocol(), this function is called only - when the 0x02 Handshake packet has been received - */ - bool TryRecognizeLengthlessProtocol(void); - /** Tries to recognize a protocol in the leghted family (1.7+), based on m_Buffer; returns true if recognized. The packet length and type have already been read, type is 0 The number of bytes remaining in the packet is passed as a_PacketLengthRemaining **/ bool TryRecognizeLengthedProtocol(UInt32 a_PacketLengthRemaining); - - /** Called when the recognizer gets a length-less protocol's server ping packet - Responds with server stats and destroys the client. - */ - void SendLengthlessServerPing(void); } ; diff --git a/src/Root.cpp b/src/Root.cpp index 966a9b4ba..aa3d43cba 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -42,7 +42,6 @@ cRoot* cRoot::s_Root = NULL; cRoot::cRoot(void) : - m_PrimaryServerVersion(cProtocolRecognizer::PROTO_VERSION_LATEST), m_pDefaultWorld(NULL), m_InputThread(NULL), m_Server(NULL), @@ -142,17 +141,6 @@ void cRoot::Start(void) IniFile.AddHeaderComment(" See: http://wiki.mc-server.org/doku.php?id=configure:settings.ini for further configuration help"); } - m_PrimaryServerVersion = IniFile.GetValueI("Server", "PrimaryServerVersion", 0); - if (m_PrimaryServerVersion == 0) - { - m_PrimaryServerVersion = cProtocolRecognizer::PROTO_VERSION_LATEST; - } - else - { - // Make a note in the log that the primary server version is explicitly set in the ini file - LOGINFO("Primary server version set explicitly to %d.", m_PrimaryServerVersion); - } - LOG("Starting server..."); m_MojangAPI.Start(IniFile); // Mojang API needs to be started before plugins, so that plugins may use it for DB upgrades on server init if (!m_Server->InitServer(IniFile)) diff --git a/src/Root.h b/src/Root.h index 9bc975889..9a482556c 100644 --- a/src/Root.h +++ b/src/Root.h @@ -73,9 +73,6 @@ public: /// Writes chunkstats, for each world and totals, to the output callback void LogChunkStats(cCommandOutputCallback & a_Output); - int GetPrimaryServerVersion(void) const { return m_PrimaryServerVersion; } // tolua_export - void SetPrimaryServerVersion(int a_Version) { m_PrimaryServerVersion = a_Version; } // tolua_export - cMonsterConfig * GetMonsterConfig(void) { return m_MonsterConfig; } cCraftingRecipes * GetCraftingRecipes(void) { return m_CraftingRecipes; } // tolua_export @@ -169,9 +166,6 @@ private: typedef std::map WorldMap; typedef std::vector cCommandQueue; - - /// The version of the protocol that is primary for the server (reported in the server list). All versions are still supported. - int m_PrimaryServerVersion; cWorld * m_pDefaultWorld; WorldMap m_WorldsByName; -- cgit v1.2.3 From 4f8818748e8b32bc58e251bbd359216554c3e6c6 Mon Sep 17 00:00:00 2001 From: worktycho Date: Sat, 27 Sep 2014 14:46:50 +0100 Subject: Add data accessor. --- src/Chunk.h | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/Chunk.h b/src/Chunk.h index b525fbb82..bc66b6528 100644 --- a/src/Chunk.h +++ b/src/Chunk.h @@ -421,6 +421,7 @@ public: cSandSimulatorChunkData & GetSandSimulatorData (void) { return m_SandSimulatorData; } cRedstoneSimulatorChunkData * GetRedstoneSimulatorData(void) { return m_RedstoneSimulatorData; } + void SetRedstoneSimulatorData(cRedstoneSimulatorChunkData * a_Data) { m_RedstoneSimulatorData = a_Data; } bool IsRedstoneDirty(void) const { return m_IsRedstoneDirty; } void SetIsRedstoneDirty(bool a_Flag) { m_IsRedstoneDirty = a_Flag; } -- cgit v1.2.3 From 94a0d04d58110d3a54669c0b7bbb7f0a618a60bd Mon Sep 17 00:00:00 2001 From: worktycho Date: Sat, 27 Sep 2014 14:49:03 +0100 Subject: Set chunk data --- src/Simulator/IncrementalRedstoneSimulator.inc | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index 6fda9824c..ba67d4014 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -554,6 +554,11 @@ template class Get void cIncrementalRedstoneSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, ChunkType * a_Chunk) { m_RedstoneSimulatorChunkData = (cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData *)a_Chunk->GetRedstoneSimulatorData(); + if (m_RedstoneSimulatorChunkData == NULL) + { + m_RedstoneSimulatorChunkData = new cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData(); + a_Chunk->SetRedstoneChunkData(m_RedstoneSimulatorChunkData); + } if (m_RedstoneSimulatorChunkData->m_ChunkData.empty() && ((cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData *)a_Chunk->GetRedstoneSimulatorData())->m_QueuedChunkData.empty()) { return; -- cgit v1.2.3 From 20101fab996a8c84225508502cfbe8491a7bb0ac Mon Sep 17 00:00:00 2001 From: worktycho Date: Sat, 27 Sep 2014 15:04:08 +0100 Subject: Correct method name. --- src/Simulator/IncrementalRedstoneSimulator.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index ba67d4014..c5cfbe3ed 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -557,7 +557,7 @@ void cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData(); - a_Chunk->SetRedstoneChunkData(m_RedstoneSimulatorChunkData); + a_Chunk->SetRedstoneData(m_RedstoneSimulatorChunkData); } if (m_RedstoneSimulatorChunkData->m_ChunkData.empty() && ((cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData *)a_Chunk->GetRedstoneSimulatorData())->m_QueuedChunkData.empty()) { -- cgit v1.2.3 From 88a07bd18461e04ca57b049ac6dff7deada5d298 Mon Sep 17 00:00:00 2001 From: worktycho Date: Sat, 27 Sep 2014 15:19:32 +0100 Subject: Update IncrementalRedstoneSimulator.inc --- src/Simulator/IncrementalRedstoneSimulator.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index c5cfbe3ed..299656b85 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -557,7 +557,7 @@ void cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData(); - a_Chunk->SetRedstoneData(m_RedstoneSimulatorChunkData); + a_Chunk->SetRedstoneSimulatorData(m_RedstoneSimulatorChunkData); } if (m_RedstoneSimulatorChunkData->m_ChunkData.empty() && ((cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData *)a_Chunk->GetRedstoneSimulatorData())->m_QueuedChunkData.empty()) { -- cgit v1.2.3 From cc73b70211ecab462edd373ebfd9f917250321c7 Mon Sep 17 00:00:00 2001 From: worktycho Date: Sat, 27 Sep 2014 15:24:01 +0100 Subject: Update IncrementalRedstoneSimulator.inc --- src/Simulator/IncrementalRedstoneSimulator.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index 299656b85..adaa47967 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -77,7 +77,7 @@ private: }; class cIncrementalRedstoneSimulatorChunkData : - cRedstoneSimulatorChunkData + public cRedstoneSimulatorChunkData { public: /// Per-chunk data for the simulator, specified individual chunks to simulate -- cgit v1.2.3 From 7ce09a9113d693b85fdda13b3c04a8b8eb900153 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sat, 27 Sep 2014 19:19:28 +0100 Subject: Suggestions --- src/BlockEntities/BlockEntityWithItems.h | 12 +++--- src/BlockEntities/EnderChestEntity.cpp | 3 +- src/BlockEntities/EnderChestEntity.h | 2 +- src/Entities/Minecart.cpp | 4 +- src/Entities/Minecart.h | 3 +- src/UI/WindowOwner.h | 68 ++++++++++++++++++++++++++------ 6 files changed, 69 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/BlockEntityWithItems.h b/src/BlockEntities/BlockEntityWithItems.h index ca6758e7a..f26ef07dd 100644 --- a/src/BlockEntities/BlockEntityWithItems.h +++ b/src/BlockEntities/BlockEntityWithItems.h @@ -20,12 +20,9 @@ // tolua_begin class cBlockEntityWithItems : - public cBlockEntity - // tolua_end - // tolua doesn't seem to support multiple inheritance? - , public cItemGrid::cListener - , public cWindowOwner - // tolua_begin + public cBlockEntity, + public cItemGrid::cListener, + public cBlockEntityWindowOwner { typedef cBlockEntity super; @@ -39,7 +36,8 @@ public: cWorld * a_World // Optional world to assign to the entity ) : super(a_BlockType, a_BlockX, a_BlockY, a_BlockZ, a_World), - m_Contents(a_ItemGridWidth, a_ItemGridHeight) + m_Contents(a_ItemGridWidth, a_ItemGridHeight), + cBlockEntityWindowOwner(this) { m_Contents.AddListener(*this); } diff --git a/src/BlockEntities/EnderChestEntity.cpp b/src/BlockEntities/EnderChestEntity.cpp index b870f9e50..0654d97dd 100644 --- a/src/BlockEntities/EnderChestEntity.cpp +++ b/src/BlockEntities/EnderChestEntity.cpp @@ -11,7 +11,8 @@ cEnderChestEntity::cEnderChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : - super(E_BLOCK_ENDER_CHEST, a_BlockX, a_BlockY, a_BlockZ, a_World) + super(E_BLOCK_ENDER_CHEST, a_BlockX, a_BlockY, a_BlockZ, a_World), + cBlockEntityWindowOwner(this) { } diff --git a/src/BlockEntities/EnderChestEntity.h b/src/BlockEntities/EnderChestEntity.h index ccfb2690b..311af8d76 100644 --- a/src/BlockEntities/EnderChestEntity.h +++ b/src/BlockEntities/EnderChestEntity.h @@ -11,7 +11,7 @@ // tolua_begin class cEnderChestEntity : public cBlockEntity, - public cWindowOwner + public cBlockEntityWindowOwner { typedef cBlockEntity super; diff --git a/src/Entities/Minecart.cpp b/src/Entities/Minecart.cpp index 42ac57a07..c5e1c07d5 100644 --- a/src/Entities/Minecart.cpp +++ b/src/Entities/Minecart.cpp @@ -7,7 +7,6 @@ #include "Globals.h" #include "Minecart.h" -#include "../World.h" #include "../ClientHandle.h" #include "../Chunk.h" #include "Player.h" @@ -1107,7 +1106,8 @@ void cRideableMinecart::OnRightClicked(cPlayer & a_Player) cMinecartWithChest::cMinecartWithChest(double a_X, double a_Y, double a_Z) : super(mpChest, a_X, a_Y, a_Z), - m_Contents(ContentsWidth, ContentsHeight) + m_Contents(ContentsWidth, ContentsHeight), + cEntityWindowOwner(this) { m_Contents.AddListener(*this); } diff --git a/src/Entities/Minecart.h b/src/Entities/Minecart.h index f77a171ba..6b6ad36b5 100644 --- a/src/Entities/Minecart.h +++ b/src/Entities/Minecart.h @@ -10,6 +10,7 @@ #pragma once #include "Entity.h" +#include "World.h" #include "../UI/WindowOwner.h" @@ -111,7 +112,7 @@ protected: class cMinecartWithChest : public cMinecart, public cItemGrid::cListener, - public cWindowOwner + public cEntityWindowOwner { typedef cMinecart super; diff --git a/src/UI/WindowOwner.h b/src/UI/WindowOwner.h index a8be3e6cb..6845a161b 100644 --- a/src/UI/WindowOwner.h +++ b/src/UI/WindowOwner.h @@ -1,4 +1,3 @@ - #pragma once #include "../BlockEntities/BlockEntity.h" @@ -16,12 +15,6 @@ for entities / players in motion to close their windows when they get too far aw -// class cWindow; - - - - - /** Base class for the window owning */ @@ -32,16 +25,16 @@ public: m_Window(NULL) { } - + virtual ~cWindowOwner() { } - + void CloseWindow(void) { m_Window = NULL; } - + void OpenWindow(cWindow * a_Window) { m_Window = a_Window; @@ -52,7 +45,10 @@ public: { return m_Window; } - + + /// Returns the block position at which the element owning the window is + virtual Vector3i GetBlockPos(void) = 0; + private: cWindow * m_Window; }; @@ -60,3 +56,53 @@ private: + +/** +Window owner that is associated with a block entity (chest, furnace, ...) +*/ +class cBlockEntityWindowOwner : + public cWindowOwner +{ +public: + cBlockEntityWindowOwner(cBlockEntity * a_BlockEntity) : + m_BlockEntity(a_BlockEntity) + { + } + + virtual Vector3i GetBlockPos(void) override + { + return Vector3i(m_BlockEntity->GetPosX(), m_BlockEntity->GetPosY(), m_BlockEntity->GetPosZ()); + } + +private: + cBlockEntity * m_BlockEntity; +}; + + + + + +/** +Window owner that is associated with an entity (chest minecart) +*/ +class cEntityWindowOwner : + public cWindowOwner +{ +public: + cEntityWindowOwner(cEntity * a_Entity) : + m_Entity(a_Entity) + { + } + + virtual Vector3i GetBlockPos(void) override + { + return m_Entity->GetPosition().Floor(); + } + +private: + cEntity * m_Entity; +}; + + + + -- cgit v1.2.3 From fc22ba0ce89b12b13bca00f5005f96528d1c91ae Mon Sep 17 00:00:00 2001 From: Masy98 Date: Sat, 27 Sep 2014 21:07:52 +0200 Subject: Added barriers correctly --- src/ChunkMap.cpp | 1 + src/ClientHandle.cpp | 5 +++++ 2 files changed, 6 insertions(+) (limited to 'src') diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index 38a7d9bd4..299fe0eca 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -1888,6 +1888,7 @@ void cChunkMap::DoExplosionAt(double a_ExplosionSize, double a_BlockX, double a_ case E_BLOCK_OBSIDIAN: case E_BLOCK_BEACON: case E_BLOCK_BEDROCK: + case E_BLOCK_BARRIER: case E_BLOCK_WATER: case E_BLOCK_LAVA: { diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 878d309c9..52ea59884 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -1153,6 +1153,11 @@ void cClientHandle::HandleBlockDigFinished(int a_BlockX, int a_BlockY, int a_Blo Kick("You can't break a bedrock!"); return; } + if (!m_Player->IsGameModeCreative() && (a_OldBlock == E_BLOCK_BARRIER)) + { + Kick("You can't break a barrier!"); + return; + } cWorld * World = m_Player->GetWorld(); cItemHandler * ItemHandler = cItemHandler::GetItemHandler(m_Player->GetEquippedItem()); -- cgit v1.2.3 From d1a72eb6de22d6b8fd4ba126e796baca68c0ae2b Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sat, 27 Sep 2014 21:33:50 +0200 Subject: Wrapped clang-specific pragma into an #ifdef block. MSVC was complaining about an unknown pragma. --- src/Simulator/Simulator.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Simulator/Simulator.cpp b/src/Simulator/Simulator.cpp index d26702166..29a1132ad 100644 --- a/src/Simulator/Simulator.cpp +++ b/src/Simulator/Simulator.cpp @@ -8,6 +8,11 @@ #include "Simulator.inc" -#pragma clang diagnostic ignored "-Wweak-template-vtables" +#ifdef __clang__ + #pragma clang diagnostic ignored "-Wweak-template-vtables" +#endif // __clang__ + template class cSimulator; + + -- cgit v1.2.3 From e7de548c89e8ece5b0d66f597a9690d8ada5b2ad Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sat, 27 Sep 2014 21:37:36 +0200 Subject: Fixed minor style issues. --- src/BlockInfo.cpp | 2 +- src/Blocks/ChunkInterface.cpp | 2 +- src/Mobs/Monster.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp index fb9b746b3..14e814084 100644 --- a/src/BlockInfo.cpp +++ b/src/BlockInfo.cpp @@ -734,7 +734,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_NEW_LOG ].m_PlaceSound = "dig.wood"; a_Info[E_BLOCK_ACACIA_WOOD_STAIRS ].m_PlaceSound = "dig.wood"; a_Info[E_BLOCK_DARK_OAK_WOOD_STAIRS ].m_PlaceSound = "dig.wood"; - a_Info[E_BLOCK_SLIME_BLOCK ].m_PlaceSound = "dig.slime"; // I hope it is named slime, it's definetly a new sound type though... + a_Info[E_BLOCK_SLIME_BLOCK ].m_PlaceSound = "dig.slime"; // TODO: Check that this is the correct name a_Info[E_BLOCK_BARRIER ].m_PlaceSound = "dig.stone"; a_Info[E_BLOCK_IRON_TRAPDOOR ].m_PlaceSound = "dig.metal"; a_Info[E_BLOCK_PRISMARINE_BLOCK ].m_PlaceSound = "dig.stone"; diff --git a/src/Blocks/ChunkInterface.cpp b/src/Blocks/ChunkInterface.cpp index e22a1410e..817640e98 100644 --- a/src/Blocks/ChunkInterface.cpp +++ b/src/Blocks/ChunkInterface.cpp @@ -4,7 +4,7 @@ #include "ChunkInterface.h" #include "ChunkMap.h" #include "BlockHandler.h" -#include "WorldInterface.h" +#include "WorldInterface.h" diff --git a/src/Mobs/Monster.h b/src/Mobs/Monster.h index ba746ebc8..a1f9c4a5b 100644 --- a/src/Mobs/Monster.h +++ b/src/Mobs/Monster.h @@ -25,7 +25,7 @@ class cMonster : typedef cPawn super; public: - //Depreciated + // Deprecated typedef eMonsterType eType; enum eFamily -- cgit v1.2.3 From 79110b29dbdfafae13ae4448b1672b129ebf7128 Mon Sep 17 00:00:00 2001 From: Masy98 Date: Sat, 27 Sep 2014 21:49:03 +0200 Subject: Combined conditions --- src/ClientHandle.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 52ea59884..3bd48eb3d 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -1148,15 +1148,18 @@ void cClientHandle::HandleBlockDigFinished(int a_BlockX, int a_BlockY, int a_Blo FinishDigAnimation(); - if (!m_Player->IsGameModeCreative() && (a_OldBlock == E_BLOCK_BEDROCK)) - { - Kick("You can't break a bedrock!"); - return; - } - if (!m_Player->IsGameModeCreative() && (a_OldBlock == E_BLOCK_BARRIER)) + if (!m_Player->IsGameModeCreative()) { - Kick("You can't break a barrier!"); - return; + if (a_OldBlock == E_BLOCK_BEDROCK) + { + Kick("You can't break a bedrock!"); + return; + } + if (a_OldBlock == E_BLOCK_BARRIER) + { + Kick("You can't break a barrier!"); + return; + } } cWorld * World = m_Player->GetWorld(); -- cgit v1.2.3 From 113b54aefda025f3cb47d5285e12104e8681506e Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sat, 27 Sep 2014 22:01:47 +0200 Subject: BioGen: TwoLevel is now fully settable in INI. --- src/Generating/BioGen.cpp | 60 +++++++++++++++++------------------------------ src/Generating/BioGen.h | 15 +++++++----- 2 files changed, 31 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 3ee0bd4c5..8924a7999 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -737,8 +737,6 @@ void cBioGenMultiStepMap::FreezeWaterBiomes(cChunkDef::BiomeMap & a_BiomeMap, co cBioGenTwoLevel::cBioGenTwoLevel(int a_Seed) : m_VoronoiLarge(a_Seed + 1000), m_VoronoiSmall(a_Seed + 2000), - m_DistortX(a_Seed + 3000), - m_DistortZ(a_Seed + 4000), m_Noise1(a_Seed + 5001), m_Noise2(a_Seed + 5002), m_Noise3(a_Seed + 5003), @@ -762,19 +760,17 @@ void cBioGenTwoLevel::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap int DistortZ[cChunkDef::Width + 1][cChunkDef::Width + 1]; for (int x = 0; x <= 4; x++) for (int z = 0; z <= 4; z++) { - int BlockX = BaseX + x * 4; - int BlockZ = BaseZ + z * 4; - float BlockXF = (float)(16 * BlockX) / 128; - float BlockZF = (float)(16 * BlockZ) / 128; - double NoiseX = m_Noise1.CubicNoise2D(BlockXF / 16, BlockZF / 16); - NoiseX += 0.5 * m_Noise2.CubicNoise2D(BlockXF / 8, BlockZF / 8); - NoiseX += 0.08 * m_Noise3.CubicNoise2D(BlockXF, BlockZF); - double NoiseZ = m_Noise4.CubicNoise2D(BlockXF / 16, BlockZF / 16); - NoiseZ += 0.5 * m_Noise5.CubicNoise2D(BlockXF / 8, BlockZF / 8); - NoiseZ += 0.08 * m_Noise6.CubicNoise2D(BlockXF, BlockZF); + float BlockX = BaseX + x * 4; + float BlockZ = BaseZ + z * 4; + double NoiseX = m_AmpX1 * m_Noise1.CubicNoise2D(BlockX * m_FreqX1, BlockZ * m_FreqX1); + NoiseX += m_AmpX2 * m_Noise2.CubicNoise2D(BlockX * m_FreqX2, BlockZ * m_FreqX2); + NoiseX += m_AmpX3 * m_Noise3.CubicNoise2D(BlockX * m_FreqX3, BlockZ * m_FreqX3); + double NoiseZ = m_AmpZ1 * m_Noise4.CubicNoise2D(BlockX * m_FreqZ1, BlockZ * m_FreqZ1); + NoiseZ += m_AmpZ2 * m_Noise5.CubicNoise2D(BlockX * m_FreqZ2, BlockZ * m_FreqZ2); + NoiseZ += m_AmpZ3 * m_Noise6.CubicNoise2D(BlockX * m_FreqZ3, BlockZ * m_FreqZ3); - DistortX[4 * x][4 * z] = BlockX + (int)(64 * NoiseX); - DistortZ[4 * x][4 * z] = BlockZ + (int)(64 * NoiseZ); + DistortX[4 * x][4 * z] = (int)(BlockX + NoiseX); + DistortZ[4 * x][4 * z] = (int)(BlockZ + NoiseZ); } LinearUpscale2DArrayInPlace(&DistortX[0][0]); @@ -915,30 +911,18 @@ void cBioGenTwoLevel::InitializeBiomeGen(cIniFile & a_IniFile) { m_VoronoiLarge.SetCellSize(a_IniFile.GetValueSetI("Generator", "TwoLevelLargeCellSize", 1024)); m_VoronoiSmall.SetCellSize(a_IniFile.GetValueSetI("Generator", "TwoLevelSmallCellSize", 128)); - m_DistortX.AddOctave( - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave1Freq", 0.01), - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave1Amp", 16) - ); - m_DistortX.AddOctave( - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave2Freq", 0.005), - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave2Amp", 8) - ); - m_DistortX.AddOctave( - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave3Freq", 0.0025), - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave3Amp", 4) - ); - m_DistortZ.AddOctave( - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave1Freq", 0.01), - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave1Amp", 16) - ); - m_DistortZ.AddOctave( - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave2Freq", 0.005), - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave2Amp", 8) - ); - m_DistortZ.AddOctave( - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave3Freq", 0.0025), - (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave3Amp", 4) - ); + m_FreqX1 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave1Freq", 0.01); + m_AmpX1 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave1Amp", 80); + m_FreqX2 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave2Freq", 0.05); + m_AmpX2 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave2Amp", 20); + m_FreqX3 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave3Freq", 0.1), + m_AmpX3 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortXOctave3Amp", 8); + m_FreqZ1 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave1Freq", 0.01); + m_AmpZ1 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave1Amp", 80); + m_FreqZ2 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave2Freq", 0.05); + m_AmpZ2 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave2Amp", 20); + m_FreqZ3 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave3Freq", 0.1); + m_AmpZ3 = (float)a_IniFile.GetValueSetF("Generator", "TwoLevelDistortZOctave3Amp", 8); } diff --git a/src/Generating/BioGen.h b/src/Generating/BioGen.h index 20d199611..22ddfae5c 100644 --- a/src/Generating/BioGen.h +++ b/src/Generating/BioGen.h @@ -285,12 +285,7 @@ protected: /// The Voronoi map that decides biomes inside individual biome groups cVoronoiMap m_VoronoiSmall; - /// The noise used to distort the input X coord - cPerlinNoise m_DistortX; - - /// The noise used to distort the inupt Z coord - cPerlinNoise m_DistortZ; - + // The noises used for the distortion: cNoise m_Noise1; cNoise m_Noise2; cNoise m_Noise3; @@ -298,6 +293,14 @@ protected: cNoise m_Noise5; cNoise m_Noise6; + // Frequencies and amplitudes for the distortion noises: + float m_FreqX1, m_AmpX1; + float m_FreqX2, m_AmpX2; + float m_FreqX3, m_AmpX3; + float m_FreqZ1, m_AmpZ1; + float m_FreqZ2, m_AmpZ2; + float m_FreqZ3, m_AmpZ3; + // cBiomeGen overrides: virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) override; -- cgit v1.2.3 From 03791b1e632e8494ba5e261f430d8a8d91a599b8 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sat, 27 Sep 2014 22:24:49 +0200 Subject: Fixed another redstone crash. --- src/Simulator/IncrementalRedstoneSimulator.inc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index adaa47967..937e6b790 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -408,7 +408,12 @@ void cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData *)a_Chunk->GetRedstoneSimulatorData())->m_PoweredBlocks; + cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData * SimulatorChunkData = ((cIncrementalRedstoneSimulator::cIncrementalRedstoneSimulatorChunkData *)a_Chunk->GetRedstoneSimulatorData()); + if (SimulatorChunkData == NULL) + { + return; + } + PoweredBlocksList & PoweredBlocks = SimulatorChunkData->m_PoweredBlocks; for (typename PoweredBlocksList::iterator itr = PoweredBlocks.begin(); itr != PoweredBlocks.end();) { if (!itr->a_SourcePos.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) -- cgit v1.2.3 From 1f8ee70d55d0d076583e14329ca09377c41b12e0 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sat, 27 Sep 2014 22:13:37 +0100 Subject: Bug fix --- src/ByteBuffer.cpp | 17 ----------------- src/ByteBuffer.h | 1 - src/Protocol/ProtocolRecognizer.cpp | 17 +++++++++++++++-- src/StringUtils.cpp | 20 ++++++++++---------- src/StringUtils.h | 4 ++-- 5 files changed, 27 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/ByteBuffer.cpp b/src/ByteBuffer.cpp index 70fdc008c..dc6b32a44 100644 --- a/src/ByteBuffer.cpp +++ b/src/ByteBuffer.cpp @@ -627,23 +627,6 @@ bool cByteBuffer::WriteBool(bool a_Value) -bool cByteBuffer::WriteBEUTF16String16(const AString & a_Value) -{ - CHECK_THREAD; - CheckValid(); - PUTBYTES(2); - AString UTF16BE; - UTF8ToRawBEUTF16(a_Value.data(), a_Value.size(), UTF16BE); - WriteBEShort((short)(UTF16BE.size() / 2)); - PUTBYTES(UTF16BE.size()); - WriteBuf(UTF16BE.data(), UTF16BE.size()); - return true; -} - - - - - bool cByteBuffer::WriteVarInt(UInt32 a_Value) { CHECK_THREAD; diff --git a/src/ByteBuffer.h b/src/ByteBuffer.h index 74dc378d4..70de419f0 100644 --- a/src/ByteBuffer.h +++ b/src/ByteBuffer.h @@ -88,7 +88,6 @@ public: bool WriteBEFloat (float a_Value); bool WriteBEDouble (double a_Value); bool WriteBool (bool a_Value); - bool WriteBEUTF16String16(const AString & a_Value); // string length as BE short, then string as UTF-16BE bool WriteVarInt (UInt32 a_Value); bool WriteVarUTF8String (const AString & a_Value); // string length as VarInt, then string as UTF-8 bool WriteLEInt (int a_Value); diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index bfa5334d5..93d7cf0aa 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -190,8 +190,21 @@ void cProtocolRecognizer::SendDestroyEntity(const cEntity & a_Entity) void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) { - ASSERT(m_Protocol != NULL); - m_Protocol->SendDisconnect(a_Reason); + if (m_Protocol != NULL) + { + m_Protocol->SendDisconnect(a_Reason); + } + else + { + // This is used when the client sends a server-ping, respond with the default packet: + static const int Packet = 0xff; // PACKET_DISCONNECT + SendData((const char *)&Packet, 1); // WriteByte() + + AString & UTF16 = UTF8ToRawBEUTF16(a_Reason.c_str(), a_Reason.length()); + static const short Size = htons((short)(UTF16.size() / 2)); + SendData((const char *)&Size, 2); // WriteShort() + SendData(UTF16.data(), UTF16.size()); // WriteString() + } } diff --git a/src/StringUtils.cpp b/src/StringUtils.cpp index 73147eebc..21962f832 100644 --- a/src/StringUtils.cpp +++ b/src/StringUtils.cpp @@ -441,10 +441,10 @@ static bool isLegalUTF8(const unsigned char * source, int length) -AString & UTF8ToRawBEUTF16(const char * a_UTF8, size_t a_UTF8Length, AString & a_UTF16) +AString UTF8ToRawBEUTF16(const char * a_UTF8, size_t a_UTF8Length) { - a_UTF16.clear(); - a_UTF16.reserve(a_UTF8Length * 3); + AString UTF16; + UTF16.reserve(a_UTF8Length * 3); const unsigned char * source = (const unsigned char*)a_UTF8; const unsigned char * sourceEnd = source + a_UTF8Length; @@ -458,12 +458,12 @@ AString & UTF8ToRawBEUTF16(const char * a_UTF8, size_t a_UTF8Length, AString & a unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; if (source + extraBytesToRead >= sourceEnd) { - return a_UTF16; + return UTF16; } // Do this check whether lenient or strict if (!isLegalUTF8(source, extraBytesToRead + 1)) { - return a_UTF16; + return UTF16; } // The cases all fall through. See "Note A" below. @@ -487,13 +487,13 @@ AString & UTF8ToRawBEUTF16(const char * a_UTF8, size_t a_UTF8Length, AString & a ch = ' '; } unsigned short v = htons((unsigned short)ch); - a_UTF16.append((const char *)&v, 2); + UTF16.append((const char *)&v, 2); } else if (ch > UNI_MAX_UTF16) { // Invalid value, replace with a space unsigned short v = htons(' '); - a_UTF16.append((const char *)&v, 2); + UTF16.append((const char *)&v, 2); } else { @@ -501,11 +501,11 @@ AString & UTF8ToRawBEUTF16(const char * a_UTF8, size_t a_UTF8Length, AString & a ch -= halfBase; unsigned short v1 = htons((ch >> halfShift) + UNI_SUR_HIGH_START); unsigned short v2 = htons((ch & halfMask) + UNI_SUR_LOW_START); - a_UTF16.append((const char *)&v1, 2); - a_UTF16.append((const char *)&v2, 2); + UTF16.append((const char *)&v1, 2); + UTF16.append((const char *)&v2, 2); } } - return a_UTF16; + return UTF16; } /* diff --git a/src/StringUtils.h b/src/StringUtils.h index a76894d05..159e8ecac 100644 --- a/src/StringUtils.h +++ b/src/StringUtils.h @@ -66,8 +66,8 @@ extern void ReplaceString(AString & iHayStack, const AString & iNeedle, const AS /// Converts a stream of BE shorts into UTF-8 string; returns a ref to a_UTF8 extern AString & RawBEToUTF8(const char * a_RawData, size_t a_NumShorts, AString & a_UTF8); -/// Converts a UTF-8 string into a UTF-16 BE string, packing that back into AString; return a ref to a_UTF16 -extern AString & UTF8ToRawBEUTF16(const char * a_UTF8, size_t a_UTF8Length, AString & a_UTF16); +/// Converts a UTF-8 string into a UTF-16 BE string; returns a ref to a_UTF16 +extern AString UTF8ToRawBEUTF16(const char * a_UTF8, size_t a_UTF8Length); /// Creates a nicely formatted HEX dump of the given memory block. Max a_BytesPerLine is 120 extern AString & CreateHexDump(AString & a_Out, const void * a_Data, size_t a_Size, size_t a_BytesPerLine); -- cgit v1.2.3 From 04ee8c43dd17eb98d1e3d66ff691898e9f269b95 Mon Sep 17 00:00:00 2001 From: Howaner Date: Sat, 27 Sep 2014 23:22:26 +0200 Subject: 1.8: Fixed plugin messages. --- src/Protocol/Protocol18x.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index a2dbb7a1f..4ec447401 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -989,7 +989,6 @@ void cProtocol180::SendPluginMessage(const AString & a_Channel, const AString & cPacketizer Pkt(*this, 0x3f); Pkt.WriteString(a_Channel); - Pkt.WriteVarInt((UInt32)a_Message.size()); Pkt.WriteBuf(a_Message.data(), a_Message.size()); } @@ -2316,9 +2315,11 @@ void cProtocol180::HandlePacketPlayerPosLook(cByteBuffer & a_ByteBuffer) void cProtocol180::HandlePacketPluginMessage(cByteBuffer & a_ByteBuffer) { HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Channel); - HANDLE_READ(a_ByteBuffer, ReadVarInt, UInt32, DataLen); AString Data; - a_ByteBuffer.ReadString(Data, DataLen); + if (!a_ByteBuffer.ReadString(Data, a_ByteBuffer.GetReadableSpace() - 1)) + { + return; + } m_Client->HandlePluginMessage(Channel, Data); } -- cgit v1.2.3 From 2fb3eb3532c2c40e21def269cb9d5ca6eb11ef6d Mon Sep 17 00:00:00 2001 From: Howaner Date: Sun, 28 Sep 2014 02:17:32 +0200 Subject: cRankManager: Added GetAllPlayers() and GetPlayerName() --- src/Bindings/ManualBindings_RankManager.cpp | 61 ++++++++++++++++++++++ src/Entities/Player.cpp | 5 ++ src/RankManager.cpp | 81 +++++++++++++++++++++++++++++ src/RankManager.h | 10 ++++ 4 files changed, 157 insertions(+) (limited to 'src') diff --git a/src/Bindings/ManualBindings_RankManager.cpp b/src/Bindings/ManualBindings_RankManager.cpp index 2e93ad264..b43cd9ef2 100644 --- a/src/Bindings/ManualBindings_RankManager.cpp +++ b/src/Bindings/ManualBindings_RankManager.cpp @@ -183,6 +183,33 @@ static int tolua_cRankManager_GetAllPermissions(lua_State * L) +/** Binds cRankManager::GetAllPlayers */ +static int tolua_cRankManager_GetAllPlayers(lua_State * L) +{ + // Function signature: + // cRankManager:GetAllPlayers() -> arraytable of Player UUID's + + cLuaState S(L); + if ( + !S.CheckParamUserTable(1, "cRankManager") || + !S.CheckParamEnd(2) + ) + { + return 0; + } + + // Get the player uuid's: + AStringVector Players = cRoot::Get()->GetRankManager().GetAllPlayers(); + + // Push the results: + S.Push(Players); + return 1; +} + + + + + /** Binds cRankManager::GetAllRanks */ static int tolua_cRankManager_GetAllRanks(lua_State * L) { @@ -400,6 +427,38 @@ static int tolua_cRankManager_GetPlayerRankName(lua_State * L) +/** Binds cRankManager::GetPlayerName */ +static int tolua_cRankManager_GetPlayerName(lua_State * L) +{ + // Function signature: + // cRankManager:GetPlayerName(PlayerUUID) -> string + + cLuaState S(L); + if ( + !S.CheckParamUserTable(1, "cRankManager") || + !S.CheckParamString(2) || + !S.CheckParamEnd(3) + ) + { + return 0; + } + + // Get the params: + AString PlayerUUID; + S.GetStackValue(2, PlayerUUID); + + // Get the player name: + AString PlayerName = cRoot::Get()->GetRankManager().GetPlayerName(PlayerUUID); + + // Push the result: + S.Push(PlayerName); + return 1; +} + + + + + /** Binds cRankManager::GetRankGroups */ static int tolua_cRankManager_GetRankGroups(lua_State * L) { @@ -974,6 +1033,7 @@ void ManualBindings::BindRankManager(lua_State * tolua_S) tolua_function(tolua_S, "AddRank", tolua_cRankManager_AddRank); tolua_function(tolua_S, "GetAllGroups", tolua_cRankManager_GetAllGroups); tolua_function(tolua_S, "GetAllPermissions", tolua_cRankManager_GetAllPermissions); + tolua_function(tolua_S, "GetAllPlayers", tolua_cRankManager_GetAllPlayers); tolua_function(tolua_S, "GetAllRanks", tolua_cRankManager_GetAllRanks); tolua_function(tolua_S, "GetDefaultRank", tolua_cRankManager_GetDefaultRank); tolua_function(tolua_S, "GetGroupPermissions", tolua_cRankManager_GetGroupPermissions); @@ -981,6 +1041,7 @@ void ManualBindings::BindRankManager(lua_State * tolua_S) tolua_function(tolua_S, "GetPlayerMsgVisuals", tolua_cRankManager_GetPlayerMsgVisuals); tolua_function(tolua_S, "GetPlayerPermissions", tolua_cRankManager_GetPlayerPermissions); tolua_function(tolua_S, "GetPlayerRankName", tolua_cRankManager_GetPlayerRankName); + tolua_function(tolua_S, "GetPlayerName", tolua_cRankManager_GetPlayerName); tolua_function(tolua_S, "GetRankGroups", tolua_cRankManager_GetRankGroups); tolua_function(tolua_S, "GetRankPermissions", tolua_cRankManager_GetRankPermissions); tolua_function(tolua_S, "GetRankVisuals", tolua_cRankManager_GetRankVisuals); diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index 66da14c0c..f58a0a016 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -2140,6 +2140,11 @@ void cPlayer::LoadRank(void) { m_Rank = RankMgr.GetDefaultRank(); } + else + { + // Update the name: + RankMgr.UpdatePlayerName(m_UUID, m_PlayerName); + } m_Permissions = RankMgr.GetPlayerPermissions(m_UUID); RankMgr.GetRankVisuals(m_Rank, m_MsgPrefix, m_MsgSuffix, m_MsgNameColorCode); diff --git a/src/RankManager.cpp b/src/RankManager.cpp index e5896f8f3..0f267473a 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -496,6 +496,33 @@ AString cRankManager::GetPlayerRankName(const AString & a_PlayerUUID) +AString cRankManager::GetPlayerName(const AString & a_PlayerUUID) +{ + ASSERT(m_IsInitialized); + cCSLock Lock(m_CS); + + try + { + // Prepare the DB statement: + SQLite::Statement stmt(m_DB, "SELECT PlayerName FROM PlayerRank WHERE PlayerUUID = ?"); + stmt.bind(1, a_PlayerUUID); + + if (stmt.executeStep()) + { + return stmt.getColumn(0).getText(); + } + } + catch (SQLite::Exception & ex) + { + LOGWARNING("%s: Cannot get player name: %s", __FUNCTION__, ex.what()); + } + return AString(); +} + + + + + AStringVector cRankManager::GetPlayerGroups(const AString & a_PlayerUUID) { ASSERT(m_IsInitialized); @@ -636,6 +663,32 @@ AStringVector cRankManager::GetRankPermissions(const AString & a_RankName) +AStringVector cRankManager::GetAllPlayers(void) +{ + ASSERT(m_IsInitialized); + cCSLock Lock(m_CS); + + AStringVector res; + try + { + SQLite::Statement stmt(m_DB, "SELECT PlayerUUID FROM PlayerRank"); + while (stmt.executeStep()) + { + res.push_back(stmt.getColumn(0).getText()); + } + } + catch (const SQLite::Exception & ex) + { + LOGWARNING("%s: Failed to get players from DB: %s", __FUNCTION__, ex.what()); + } + return res; +} + + + + + + AStringVector cRankManager::GetAllRanks(void) { ASSERT(m_IsInitialized); @@ -1764,6 +1817,34 @@ bool cRankManager::SetDefaultRank(const AString & a_RankName) +bool cRankManager::UpdatePlayerName(const AString & a_PlayerUUID, const AString & a_NewPlayerName) +{ + ASSERT(m_IsInitialized); + cCSLock Lock(m_CS); + + try + { + SQLite::Statement stmt(m_DB, "UPDATE PlayerRank SET PlayerName = ? WHERE PlayerUUID = ?"); + stmt.bind(1, a_NewPlayerName); + stmt.bind(2, a_PlayerUUID); + if (stmt.exec() > 0) + { + // The player name was changed, returns true + return true; + } + } + catch (const SQLite::Exception & ex) + { + LOGWARNING("%s: Failed to update player name from UUID %s: %s", __FUNCTION__, a_PlayerUUID.c_str(), ex.what()); + } + return false; +} + + + + + + bool cRankManager::AreDBTablesEmpty(void) { return ( diff --git a/src/RankManager.h b/src/RankManager.h index f364bba6a..ebdba17a0 100644 --- a/src/RankManager.h +++ b/src/RankManager.h @@ -60,6 +60,10 @@ public: If the player has no rank assigned, returns an empty string (NOT the default rank). */ AString GetPlayerRankName(const AString & a_PlayerUUID); + /** Returns the last name that the specified player has. + If the player isn't in the database, this returns an empty string. */ + AString GetPlayerName(const AString & a_PlayerUUID); + /** Returns the names of Groups that the specified player has assigned to them. */ AStringVector GetPlayerGroups(const AString & a_PlayerUUID); @@ -79,6 +83,9 @@ public: Returns an empty vector if the rank doesn't exist. Any non-existent groups are ignored. */ AStringVector GetRankPermissions(const AString & a_RankName); + /** Returns the short uuids of all defined players. */ + AStringVector GetAllPlayers(void); + /** Returns the names of all defined ranks. */ AStringVector GetAllRanks(void); @@ -210,6 +217,9 @@ public: /** Returns the name of the default rank. */ const AString & GetDefaultRank(void) const { return m_DefaultRank; } + + /** Updates the playername that is saved with this uuid. Returns false if a error occurred */ + bool UpdatePlayerName(const AString & a_PlayerUUID, const AString & a_NewPlayerName); protected: -- cgit v1.2.3 From 27331da017625c748a104c72d72c8958003e1e90 Mon Sep 17 00:00:00 2001 From: Howaner Date: Sun, 28 Sep 2014 11:17:36 +0200 Subject: Updated api documentation. --- src/RankManager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/RankManager.h b/src/RankManager.h index ebdba17a0..b577fad05 100644 --- a/src/RankManager.h +++ b/src/RankManager.h @@ -61,7 +61,7 @@ public: AString GetPlayerRankName(const AString & a_PlayerUUID); /** Returns the last name that the specified player has. - If the player isn't in the database, this returns an empty string. */ + An empty string is returned if the player isn't in the database. */ AString GetPlayerName(const AString & a_PlayerUUID); /** Returns the names of Groups that the specified player has assigned to them. */ -- cgit v1.2.3 From ae36ba5d33b1ce61fab33ffc310da6bba38ca316 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sun, 28 Sep 2014 13:08:00 +0100 Subject: Compilation fix --- src/Protocol/ProtocolRecognizer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index 93d7cf0aa..ef6802d2b 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -200,7 +200,7 @@ void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) static const int Packet = 0xff; // PACKET_DISCONNECT SendData((const char *)&Packet, 1); // WriteByte() - AString & UTF16 = UTF8ToRawBEUTF16(a_Reason.c_str(), a_Reason.length()); + AString UTF16 = UTF8ToRawBEUTF16(a_Reason.c_str(), a_Reason.length()); static const short Size = htons((short)(UTF16.size() / 2)); SendData((const char *)&Size, 2); // WriteShort() SendData(UTF16.data(), UTF16.size()); // WriteString() -- cgit v1.2.3 From a9243257e583ae22d7a27f6439f6eb973f7e11ce Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sun, 28 Sep 2014 13:11:41 +0100 Subject: Compilation fix --- src/BlockEntities/BlockEntityWithItems.h | 4 ++-- src/Entities/Minecart.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/BlockEntityWithItems.h b/src/BlockEntities/BlockEntityWithItems.h index f26ef07dd..00173cbcb 100644 --- a/src/BlockEntities/BlockEntityWithItems.h +++ b/src/BlockEntities/BlockEntityWithItems.h @@ -36,8 +36,8 @@ public: cWorld * a_World // Optional world to assign to the entity ) : super(a_BlockType, a_BlockX, a_BlockY, a_BlockZ, a_World), - m_Contents(a_ItemGridWidth, a_ItemGridHeight), - cBlockEntityWindowOwner(this) + cBlockEntityWindowOwner(this), + m_Contents(a_ItemGridWidth, a_ItemGridHeight) { m_Contents.AddListener(*this); } diff --git a/src/Entities/Minecart.cpp b/src/Entities/Minecart.cpp index c5e1c07d5..f45e7bb69 100644 --- a/src/Entities/Minecart.cpp +++ b/src/Entities/Minecart.cpp @@ -1106,8 +1106,8 @@ void cRideableMinecart::OnRightClicked(cPlayer & a_Player) cMinecartWithChest::cMinecartWithChest(double a_X, double a_Y, double a_Z) : super(mpChest, a_X, a_Y, a_Z), - m_Contents(ContentsWidth, ContentsHeight), - cEntityWindowOwner(this) + cEntityWindowOwner(this), + m_Contents(ContentsWidth, ContentsHeight) { m_Contents.AddListener(*this); } -- cgit v1.2.3 From 63c53a8e23776cc3011fd0260857bd22274e2c62 Mon Sep 17 00:00:00 2001 From: Howaner Date: Sun, 28 Sep 2014 15:16:11 +0200 Subject: cRankManager: Added ClearPlayerRanks() --- src/Bindings/ManualBindings_RankManager.cpp | 22 ++++++++++++++++++++++ src/RankManager.cpp | 19 +++++++++++++++++++ src/RankManager.h | 4 ++++ 3 files changed, 45 insertions(+) (limited to 'src') diff --git a/src/Bindings/ManualBindings_RankManager.cpp b/src/Bindings/ManualBindings_RankManager.cpp index b43cd9ef2..cddf1ec2e 100644 --- a/src/Bindings/ManualBindings_RankManager.cpp +++ b/src/Bindings/ManualBindings_RankManager.cpp @@ -129,6 +129,27 @@ static int tolua_cRankManager_AddRank(lua_State * L) +/** Binds cRankManager::ClearPlayerRanks */ +static int tolua_cRankManager_ClearPlayerRanks(lua_State * L) +{ + cLuaState S(L); + if ( + !S.CheckParamUserTable(1, "cRankManager") || + !S.CheckParamEnd(2) + ) + { + return 0; + } + + // Remove all players: + cRoot::Get()->GetRankManager().ClearPlayerRanks(); + return 1; +} + + + + + /** Binds cRankManager::GetAllGroups */ static int tolua_cRankManager_GetAllGroups(lua_State * L) { @@ -1031,6 +1052,7 @@ void ManualBindings::BindRankManager(lua_State * tolua_S) tolua_function(tolua_S, "AddGroupToRank", tolua_cRankManager_AddGroupToRank); tolua_function(tolua_S, "AddPermissionToGroup", tolua_cRankManager_AddPermissionToGroup); tolua_function(tolua_S, "AddRank", tolua_cRankManager_AddRank); + tolua_function(tolua_S, "ClearPlayerRanks", tolua_cRankManager_ClearPlayerRanks); tolua_function(tolua_S, "GetAllGroups", tolua_cRankManager_GetAllGroups); tolua_function(tolua_S, "GetAllPermissions", tolua_cRankManager_GetAllPermissions); tolua_function(tolua_S, "GetAllPlayers", tolua_cRankManager_GetAllPlayers); diff --git a/src/RankManager.cpp b/src/RankManager.cpp index 0f267473a..fd5e58025 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -1817,6 +1817,25 @@ bool cRankManager::SetDefaultRank(const AString & a_RankName) +void cRankManager::ClearPlayerRanks(void) +{ + ASSERT(m_IsInitialized); + cCSLock Lock(m_CS); + + try { + SQLite::Statement stmt(m_DB, "DELETE FROM PlayerRank"); + stmt.exec(); + } + catch (SQLite::Exception & ex) + { + LOGWARNING("%s: Failed to remove/clear all players: %s", __FUNCTION__, ex.what()); + } +} + + + + + bool cRankManager::UpdatePlayerName(const AString & a_PlayerUUID, const AString & a_NewPlayerName) { ASSERT(m_IsInitialized); diff --git a/src/RankManager.h b/src/RankManager.h index b577fad05..acfcdb01d 100644 --- a/src/RankManager.h +++ b/src/RankManager.h @@ -217,6 +217,10 @@ public: /** Returns the name of the default rank. */ const AString & GetDefaultRank(void) const { return m_DefaultRank; } + + /** Removes all player ranks from the database. Note that this doesn't change the cPlayer instances + for the already connected players, you need to update all the instances manually. */ + void ClearPlayerRanks(void); /** Updates the playername that is saved with this uuid. Returns false if a error occurred */ bool UpdatePlayerName(const AString & a_PlayerUUID, const AString & a_NewPlayerName); -- cgit v1.2.3 From f6979642e68dbbcb144ea376cc42a17dab8f3b37 Mon Sep 17 00:00:00 2001 From: Tycho Date: Sun, 28 Sep 2014 15:36:00 +0100 Subject: Use factory method to construct redstone simulator data --- src/Chunk.cpp | 2 +- src/Simulator/IncrementalRedstoneSimulator.inc | 5 +++++ src/Simulator/NoopRedstoneSimulator.h | 5 +++++ src/Simulator/RedstoneSimulator.h | 2 ++ 4 files changed, 13 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 3012f30b6..00cea4416 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -92,7 +92,7 @@ cChunk::cChunk( m_NeighborZP(a_NeighborZP), m_WaterSimulatorData(a_World->GetWaterSimulator()->CreateChunkData()), m_LavaSimulatorData (a_World->GetLavaSimulator ()->CreateChunkData()), - m_RedstoneSimulatorData(NULL), + m_RedstoneSimulatorData(a_World->GetRedstoneSimulator ()->CreateChunkData()), m_AlwaysTicked(0) { if (a_NeighborXM != NULL) diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index 937e6b790..200fc0971 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -27,6 +27,11 @@ public: { } ~cIncrementalRedstoneSimulator(); + + virtual cRedstoneSimulatorChunkData * CreateChunkData() override + { + return new cIncrementalRedstoneSimulatorChunkData; + } virtual void Simulate(float a_Dt) override { UNUSED(a_Dt);} // not used virtual void SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, ChunkType * a_Chunk) override; diff --git a/src/Simulator/NoopRedstoneSimulator.h b/src/Simulator/NoopRedstoneSimulator.h index 88e141e85..7c961f32b 100644 --- a/src/Simulator/NoopRedstoneSimulator.h +++ b/src/Simulator/NoopRedstoneSimulator.h @@ -36,5 +36,10 @@ public: UNUSED(a_BlockZ); UNUSED(a_Chunk); } + + virtual cRedstoneSimulatorChunkData * CreateChunkData() override + { + return NULL; + } } ; diff --git a/src/Simulator/RedstoneSimulator.h b/src/Simulator/RedstoneSimulator.h index f6d36f869..6104d39b4 100644 --- a/src/Simulator/RedstoneSimulator.h +++ b/src/Simulator/RedstoneSimulator.h @@ -24,5 +24,7 @@ public: super(a_World) { } + + virtual cRedstoneSimulatorChunkData * CreateChunkData() = 0; } ; -- cgit v1.2.3 From 80fe8d778973286397e91564a203521b8bfd3760 Mon Sep 17 00:00:00 2001 From: worktycho Date: Sun, 28 Sep 2014 17:57:01 +0100 Subject: Update Chunk.cpp --- src/Chunk.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 00cea4416..96b8eda4e 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -92,7 +92,7 @@ cChunk::cChunk( m_NeighborZP(a_NeighborZP), m_WaterSimulatorData(a_World->GetWaterSimulator()->CreateChunkData()), m_LavaSimulatorData (a_World->GetLavaSimulator ()->CreateChunkData()), - m_RedstoneSimulatorData(a_World->GetRedstoneSimulator ()->CreateChunkData()), + m_RedstoneSimulatorData(a_World->GetRedstoneSimulator()->CreateChunkData()), m_AlwaysTicked(0) { if (a_NeighborXM != NULL) -- cgit v1.2.3 From 4391b3fc0910e3e51f2b6a8bf6d319933a2cc8ad Mon Sep 17 00:00:00 2001 From: Howaner Date: Sun, 28 Sep 2014 19:08:33 +0200 Subject: Fixed SetDefaultRank() return value. --- src/Bindings/ManualBindings_RankManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Bindings/ManualBindings_RankManager.cpp b/src/Bindings/ManualBindings_RankManager.cpp index cddf1ec2e..6e623af0d 100644 --- a/src/Bindings/ManualBindings_RankManager.cpp +++ b/src/Bindings/ManualBindings_RankManager.cpp @@ -975,7 +975,7 @@ static int tolua_cRankManager_SetDefaultRank(lua_State * L) // Set the rank, return the result: S.Push(cRoot::Get()->GetRankManager().SetDefaultRank(RankName)); - return 0; + return 1; } -- cgit v1.2.3 From 76e0c592ef2f9660f10ab099cb8e8cbffc35153b Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Sun, 28 Sep 2014 19:27:08 +0200 Subject: Added Granite, Diorite and Andesite to the NaturalPatches generator. --- src/Generating/ComposableGenerator.cpp | 27 +++++++++++++++++++++++++++ src/Generating/StructGen.cpp | 6 ++++-- src/Generating/StructGen.h | 11 ++++++----- 3 files changed, 37 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 69068d231..4efcd1284 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -428,6 +428,33 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) GravelVein.NestSize = 32; Ores.push_back(GravelVein); + // Granite vein + cStructGenOreNests::OreInfo GraniteVein; + GraniteVein.BlockType = E_BLOCK_STONE; + GraniteVein.BlockMeta = 1; + GraniteVein.MaxHeight = 127; + GraniteVein.NumNests = 20; + GraniteVein.NestSize = 32; + Ores.push_back(GraniteVein); + + // Diorite vein + cStructGenOreNests::OreInfo DioriteVein; + DioriteVein.BlockType = E_BLOCK_STONE; + DioriteVein.BlockMeta = 3; + DioriteVein.MaxHeight = 127; + DioriteVein.NumNests = 20; + DioriteVein.NestSize = 32; + Ores.push_back(DioriteVein); + + // Andesite vein + cStructGenOreNests::OreInfo AndesiteVein; + AndesiteVein.BlockType = E_BLOCK_STONE; + AndesiteVein.BlockMeta = 5; + AndesiteVein.MaxHeight = 127; + AndesiteVein.NumNests = 20; + AndesiteVein.NestSize = 32; + Ores.push_back(AndesiteVein); + m_FinishGens.push_back(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE)); } else if (NoCaseCompare(*itr, "NetherClumpFoliage") == 0) diff --git a/src/Generating/StructGen.cpp b/src/Generating/StructGen.cpp index 731324b0d..c23a72621 100644 --- a/src/Generating/StructGen.cpp +++ b/src/Generating/StructGen.cpp @@ -272,13 +272,14 @@ void cStructGenOreNests::GenFinish(cChunkDesc & a_ChunkDesc) int ChunkX = a_ChunkDesc.GetChunkX(); int ChunkZ = a_ChunkDesc.GetChunkZ(); cChunkDef::BlockTypes & BlockTypes = a_ChunkDesc.GetBlockTypes(); + cChunkDesc::BlockNibbleBytes & BlockMetas = a_ChunkDesc.GetBlockMetasUncompressed(); int seq = 1; // Generate the ores from the ore list. for (OreList::const_iterator itr = m_OreList.begin(); itr != m_OreList.end(); ++itr) { - GenerateOre(ChunkX, ChunkZ, itr->BlockType, itr->MaxHeight, itr->NumNests, itr->NestSize, BlockTypes, seq); + GenerateOre(ChunkX, ChunkZ, itr->BlockType, itr->BlockMeta, itr->MaxHeight, itr->NumNests, itr->NestSize, BlockTypes, BlockMetas, seq); seq++; } } @@ -287,7 +288,7 @@ void cStructGenOreNests::GenFinish(cChunkDesc & a_ChunkDesc) -void cStructGenOreNests::GenerateOre(int a_ChunkX, int a_ChunkZ, BLOCKTYPE a_OreType, int a_MaxHeight, int a_NumNests, int a_NestSize, cChunkDef::BlockTypes & a_BlockTypes, int a_Seq) +void cStructGenOreNests::GenerateOre(int a_ChunkX, int a_ChunkZ, BLOCKTYPE a_OreType, NIBBLETYPE a_BlockMeta, int a_MaxHeight, int a_NumNests, int a_NestSize, cChunkDef::BlockTypes & a_BlockTypes, cChunkDesc::BlockNibbleBytes & a_BlockMetas, int a_Seq) { // This function generates several "nests" of ore, each nest consisting of number of ore blocks relatively adjacent to each other. // It does so by making a random XYZ walk and adding ore along the way in cuboids of different (random) sizes @@ -341,6 +342,7 @@ void cStructGenOreNests::GenerateOre(int a_ChunkX, int a_ChunkZ, BLOCKTYPE a_Ore if (a_BlockTypes[Index] == m_ToReplace) { a_BlockTypes[Index] = a_OreType; + a_BlockMetas[Index] = a_BlockMeta; } Num++; } // for z diff --git a/src/Generating/StructGen.h b/src/Generating/StructGen.h index 55d5bc1c7..76bdf44d4 100644 --- a/src/Generating/StructGen.h +++ b/src/Generating/StructGen.h @@ -78,10 +78,11 @@ class cStructGenOreNests : public: struct OreInfo { - BLOCKTYPE BlockType; // The type of the nest. - int MaxHeight; // The highest possible a nest can occur - int NumNests; // How many nests per chunk - int NestSize; // The amount of blocks a nest can have. + BLOCKTYPE BlockType; // The type of the nest. + NIBBLETYPE BlockMeta = 0; // The block meta + int MaxHeight; // The highest possible a nest can occur + int NumNests; // How many nests per chunk + int NestSize; // The amount of blocks a nest can have. }; typedef std::vector OreList; @@ -103,7 +104,7 @@ protected: // cFinishGen override: virtual void GenFinish(cChunkDesc & a_ChunkDesc) override; - void GenerateOre(int a_ChunkX, int a_ChunkZ, BLOCKTYPE a_OreType, int a_MaxHeight, int a_NumNests, int a_NestSize, cChunkDef::BlockTypes & a_BlockTypes, int a_Seq); + void GenerateOre(int a_ChunkX, int a_ChunkZ, BLOCKTYPE a_OreType, NIBBLETYPE a_BlockMeta, int a_MaxHeight, int a_NumNests, int a_NestSize, cChunkDef::BlockTypes & a_BlockTypes, cChunkDesc::BlockNibbleBytes & a_BlockMetas, int a_Seq); } ; -- cgit v1.2.3 From 7c18681e092c905eafbcdcb7ecbd98ec13946502 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Sun, 28 Sep 2014 22:10:03 +0200 Subject: Fixed compilation --- src/Generating/StructGen.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Generating/StructGen.h b/src/Generating/StructGen.h index 76bdf44d4..96aa3e437 100644 --- a/src/Generating/StructGen.h +++ b/src/Generating/StructGen.h @@ -79,10 +79,19 @@ public: struct OreInfo { BLOCKTYPE BlockType; // The type of the nest. - NIBBLETYPE BlockMeta = 0; // The block meta + NIBBLETYPE BlockMeta; // The block meta int MaxHeight; // The highest possible a nest can occur int NumNests; // How many nests per chunk int NestSize; // The amount of blocks a nest can have. + + OreInfo() : + BlockType(0), + BlockMeta(0), + MaxHeight(0), + NumNests(0), + NestSize(0) + { + } }; typedef std::vector OreList; -- cgit v1.2.3 From 5a44be13b7facbc3718b8cbc4eb76bbd50de085e Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sun, 28 Sep 2014 22:17:29 +0200 Subject: Fixed trailing whitespace. --- src/ClientHandle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index bd00c0b9e..20e219309 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -1153,7 +1153,7 @@ void cClientHandle::HandleBlockDigFinished(int a_BlockX, int a_BlockY, int a_Blo if (a_OldBlock == E_BLOCK_BEDROCK) { Kick("You can't break a bedrock!"); - return; + return; } if (a_OldBlock == E_BLOCK_BARRIER) { -- cgit v1.2.3 From f8c627141ae930abfeb2a76599133a455bceaa9b Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sun, 28 Sep 2014 22:25:48 +0200 Subject: Protocol 1.8: Fixed possible crash on malformed packet. --- src/Protocol/Protocol18x.cpp | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index 7a6eb5f28..625a29b7a 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -1713,6 +1713,11 @@ void cProtocol180::AddReceivedData(const char * a_Data, size_t a_Size) { UInt32 NumBytesRead = m_ReceivedData.GetReadableSpace(); m_ReceivedData.ReadVarInt(CompressedSize); + if (CompressedSize > PacketLen) + { + m_Client->Kick("Bad compression"); + return; + } if (CompressedSize > 0) { // Decompress the data: -- cgit v1.2.3 From 488c6159df656e81cc90415d9f9026b34f1f1158 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sun, 28 Sep 2014 22:27:23 +0200 Subject: Revert "1.8: Fixed plugin messages." This reverts commit 04ee8c43dd17eb98d1e3d66ff691898e9f269b95. --- src/Protocol/Protocol18x.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index 625a29b7a..3985f5224 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -989,6 +989,7 @@ void cProtocol180::SendPluginMessage(const AString & a_Channel, const AString & cPacketizer Pkt(*this, 0x3f); Pkt.WriteString(a_Channel); + Pkt.WriteVarInt((UInt32)a_Message.size()); Pkt.WriteBuf(a_Message.data(), a_Message.size()); } @@ -2320,8 +2321,9 @@ void cProtocol180::HandlePacketPlayerPosLook(cByteBuffer & a_ByteBuffer) void cProtocol180::HandlePacketPluginMessage(cByteBuffer & a_ByteBuffer) { HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Channel); + HANDLE_READ(a_ByteBuffer, ReadVarInt, UInt32, DataLen); AString Data; - if (!a_ByteBuffer.ReadString(Data, a_ByteBuffer.GetReadableSpace() - 1)) + if (!a_ByteBuffer.ReadString(Data, DataLen)) { return; } -- cgit v1.2.3 From 126b14aa09fcde7a54bc8a176b44f5f6c8f936c1 Mon Sep 17 00:00:00 2001 From: Jonathan Frederick Date: Sun, 28 Sep 2014 13:56:41 -0700 Subject: Make endermen take damage in water --- src/Mobs/Enderman.cpp | 20 ++++++++++++++++++++ src/Mobs/Enderman.h | 1 + 2 files changed, 21 insertions(+) (limited to 'src') diff --git a/src/Mobs/Enderman.cpp b/src/Mobs/Enderman.cpp index 51255beb3..fb372709a 100644 --- a/src/Mobs/Enderman.cpp +++ b/src/Mobs/Enderman.cpp @@ -181,3 +181,23 @@ bool cEnderman::CheckLight() return true; } + + + + + +void cEnderman::Tick(float a_Dt, cChunk & a_Chunk) +{ + super::Tick(a_Dt, a_Chunk); + + //TODO take damage in rain + + //Take damage when touching water, drowning damage seems to be most appropriate + if (IsSwimming()) + { + EventLosePlayer(); + TakeDamage(dtDrowning, NULL, 1, 0); + //TODO teleport to a safe location + } + +} diff --git a/src/Mobs/Enderman.h b/src/Mobs/Enderman.h index 4583746e7..947c32b96 100644 --- a/src/Mobs/Enderman.h +++ b/src/Mobs/Enderman.h @@ -21,6 +21,7 @@ public: virtual void CheckEventSeePlayer(void) override; virtual void CheckEventLostPlayer(void) override; virtual void EventLosePlayer(void) override; + virtual void Tick(float a_Dt, cChunk & a_Chunk) override; bool IsScreaming(void) const {return m_bIsScreaming; } BLOCKTYPE GetCarriedBlock(void) const {return CarriedBlock; } -- cgit v1.2.3 From 280831df264fe34a771fa16593e860037c5b4444 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sun, 28 Sep 2014 23:03:44 +0200 Subject: Plugin messages: Vanilla prefixes its payloads with VarInt lengths. --- src/Protocol/Protocol18x.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index 3985f5224..1070a8434 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -989,7 +989,10 @@ void cProtocol180::SendPluginMessage(const AString & a_Channel, const AString & cPacketizer Pkt(*this, 0x3f); Pkt.WriteString(a_Channel); - Pkt.WriteVarInt((UInt32)a_Message.size()); + if (a_Channel.substr(0, 3) == "MC|") + { + Pkt.WriteVarInt((UInt32)a_Message.size()); + } Pkt.WriteBuf(a_Message.data(), a_Message.size()); } @@ -2321,12 +2324,18 @@ void cProtocol180::HandlePacketPlayerPosLook(cByteBuffer & a_ByteBuffer) void cProtocol180::HandlePacketPluginMessage(cByteBuffer & a_ByteBuffer) { HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Channel); - HANDLE_READ(a_ByteBuffer, ReadVarInt, UInt32, DataLen); AString Data; - if (!a_ByteBuffer.ReadString(Data, DataLen)) + if (Channel.substr(0, 3) == "MC|") { - return; + // Vanilla sends the payload length within the payload itself, so skip it: + HANDLE_READ(a_ByteBuffer, ReadVarInt, UInt32, DataLen); + if (DataLen != a_ByteBuffer.GetReadableSpace() - 1) + { + ASSERT(!"Bad plugin message payload length"); + return; + } } + a_ByteBuffer.ReadString(Data, a_ByteBuffer.GetReadableSpace() - 1); // Always succeeds m_Client->HandlePluginMessage(Channel, Data); } -- cgit v1.2.3 From 7a61e1e6040e7df5e5e928a619b5828b8eff556e Mon Sep 17 00:00:00 2001 From: Jonathan Frederick Date: Sun, 28 Sep 2014 19:24:47 -0700 Subject: Fix comments --- src/Mobs/Enderman.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Mobs/Enderman.cpp b/src/Mobs/Enderman.cpp index fb372709a..ffc24e56b 100644 --- a/src/Mobs/Enderman.cpp +++ b/src/Mobs/Enderman.cpp @@ -190,9 +190,9 @@ void cEnderman::Tick(float a_Dt, cChunk & a_Chunk) { super::Tick(a_Dt, a_Chunk); - //TODO take damage in rain + // TODO take damage in rain - //Take damage when touching water, drowning damage seems to be most appropriate + // Take damage when touching water, drowning damage seems to be most appropriate if (IsSwimming()) { EventLosePlayer(); -- cgit v1.2.3 From c02711633dd3491242ba5d73148bb9289db04ebf Mon Sep 17 00:00:00 2001 From: Jonathan Frederick Date: Sun, 28 Sep 2014 19:27:53 -0700 Subject: Derp --- src/Mobs/Enderman.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Mobs/Enderman.cpp b/src/Mobs/Enderman.cpp index ffc24e56b..567714382 100644 --- a/src/Mobs/Enderman.cpp +++ b/src/Mobs/Enderman.cpp @@ -197,7 +197,7 @@ void cEnderman::Tick(float a_Dt, cChunk & a_Chunk) { EventLosePlayer(); TakeDamage(dtDrowning, NULL, 1, 0); - //TODO teleport to a safe location + // TODO teleport to a safe location } } -- cgit v1.2.3 From 0b438b5fe8552f72ca04c25592a1ecb8cf3adcbe Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Mon, 29 Sep 2014 13:12:50 +0200 Subject: Added torches placeable on upside-down-halfslaps --- src/Blocks/BlockTorch.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index fa46b37a8..bdb3e9914 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -124,7 +124,9 @@ public: ((BlockInQuestion == E_BLOCK_GLASS) || (BlockInQuestion == E_BLOCK_FENCE) || (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL)) && + (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || + (BlockInQuestion == E_BLOCK_STONE_SLAB) || + (BlockInQuestion == E_BLOCK_WOODEN_SLAB)) && (Face == BLOCK_FACE_TOP) ) { -- cgit v1.2.3 From f014d8764b0591c6216af6ff9ea2a0d89c0dc4b3 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Mon, 29 Sep 2014 13:17:24 +0200 Subject: Update BlockTorch.h --- src/Blocks/BlockTorch.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index bdb3e9914..0aabcdf67 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -124,9 +124,9 @@ public: ((BlockInQuestion == E_BLOCK_GLASS) || (BlockInQuestion == E_BLOCK_FENCE) || (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB)) && + (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || + (BlockInQuestion == E_BLOCK_STONE_SLAB) || + (BlockInQuestion == E_BLOCK_WOODEN_SLAB)) && (Face == BLOCK_FACE_TOP) ) { -- cgit v1.2.3 From ff3a3b801d5fa6edb855b13b73af497b29e8a42e Mon Sep 17 00:00:00 2001 From: Howaner Date: Mon, 29 Sep 2014 14:43:16 +0200 Subject: Renamed GetAllPlayers() to GetAllPlayerUUIDs() --- src/Bindings/ManualBindings_RankManager.cpp | 10 +++++----- src/RankManager.cpp | 2 +- src/RankManager.h | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/Bindings/ManualBindings_RankManager.cpp b/src/Bindings/ManualBindings_RankManager.cpp index 6e623af0d..3c58a0a92 100644 --- a/src/Bindings/ManualBindings_RankManager.cpp +++ b/src/Bindings/ManualBindings_RankManager.cpp @@ -204,11 +204,11 @@ static int tolua_cRankManager_GetAllPermissions(lua_State * L) -/** Binds cRankManager::GetAllPlayers */ -static int tolua_cRankManager_GetAllPlayers(lua_State * L) +/** Binds cRankManager::GetAllPlayerUUIDs */ +static int tolua_cRankManager_GetAllPlayerUUIDs(lua_State * L) { // Function signature: - // cRankManager:GetAllPlayers() -> arraytable of Player UUID's + // cRankManager:GetAllPlayerUUIDs() -> arraytable of Player UUID's cLuaState S(L); if ( @@ -220,7 +220,7 @@ static int tolua_cRankManager_GetAllPlayers(lua_State * L) } // Get the player uuid's: - AStringVector Players = cRoot::Get()->GetRankManager().GetAllPlayers(); + AStringVector Players = cRoot::Get()->GetRankManager().GetAllPlayerUUIDs(); // Push the results: S.Push(Players); @@ -1055,7 +1055,7 @@ void ManualBindings::BindRankManager(lua_State * tolua_S) tolua_function(tolua_S, "ClearPlayerRanks", tolua_cRankManager_ClearPlayerRanks); tolua_function(tolua_S, "GetAllGroups", tolua_cRankManager_GetAllGroups); tolua_function(tolua_S, "GetAllPermissions", tolua_cRankManager_GetAllPermissions); - tolua_function(tolua_S, "GetAllPlayers", tolua_cRankManager_GetAllPlayers); + tolua_function(tolua_S, "GetAllPlayerUUIDs", tolua_cRankManager_GetAllPlayerUUIDs); tolua_function(tolua_S, "GetAllRanks", tolua_cRankManager_GetAllRanks); tolua_function(tolua_S, "GetDefaultRank", tolua_cRankManager_GetDefaultRank); tolua_function(tolua_S, "GetGroupPermissions", tolua_cRankManager_GetGroupPermissions); diff --git a/src/RankManager.cpp b/src/RankManager.cpp index fd5e58025..c9b428e3b 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -663,7 +663,7 @@ AStringVector cRankManager::GetRankPermissions(const AString & a_RankName) -AStringVector cRankManager::GetAllPlayers(void) +AStringVector cRankManager::GetAllPlayerUUIDs(void) { ASSERT(m_IsInitialized); cCSLock Lock(m_CS); diff --git a/src/RankManager.h b/src/RankManager.h index acfcdb01d..3f5884f2e 100644 --- a/src/RankManager.h +++ b/src/RankManager.h @@ -84,7 +84,7 @@ public: AStringVector GetRankPermissions(const AString & a_RankName); /** Returns the short uuids of all defined players. */ - AStringVector GetAllPlayers(void); + AStringVector GetAllPlayerUUIDs(void); /** Returns the names of all defined ranks. */ AStringVector GetAllRanks(void); -- cgit v1.2.3 From 6127c21af97e450037daecd981cc88f40c3af423 Mon Sep 17 00:00:00 2001 From: netchip Date: Mon, 29 Sep 2014 17:18:20 +0200 Subject: BlockStone: drop the right cobblestone on onBreak(). Signed-off-by: netchip --- src/BlockID.h | 6 ++++++ src/Blocks/BlockStone.h | 12 +++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 45e71d85d..80b5700a8 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -652,6 +652,12 @@ enum E_META_STAINED_GLASS_PANE_RED = 14, E_META_STAINED_GLASS_PANE_BLACK = 15, + // E_BLOCK_STONE metas: + E_META_STONE = 0, + E_META_STONE_GRANITE = 1, + E_META_STONE_DIORITE = 3, + E_META_STONE_ANDESITE = 5, + // E_BLOCK_STONE_SLAB metas: E_META_STONE_SLAB_STONE = 0, E_META_STONE_SLAB_SANDSTONE = 1, diff --git a/src/Blocks/BlockStone.h b/src/Blocks/BlockStone.h index cd5230f49..2b71cebf1 100644 --- a/src/Blocks/BlockStone.h +++ b/src/Blocks/BlockStone.h @@ -2,7 +2,7 @@ #pragma once #include "BlockHandler.h" - +#include "BlockID.h" @@ -18,9 +18,15 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - a_Pickups.push_back(cItem(E_BLOCK_COBBLESTONE, 1, 0)); + switch(a_BlockMeta) { + case E_META_STONE: + a_Pickups.push_back(cItem(E_BLOCK_COBBLESTONE, 1, 0)); + break; + default: + a_Pickups.push_back(cItem(E_BLOCK_STONE, 1, a_BlockMeta)); + } } -} ; +}; -- cgit v1.2.3 From d5ae659da389c1a7a67c92a9202182d4f243b2eb Mon Sep 17 00:00:00 2001 From: w00tc0d3 Date: Mon, 29 Sep 2014 17:35:30 +0200 Subject: Tabs -> spaces --- src/BlockID.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 80b5700a8..9a8830710 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -653,10 +653,10 @@ enum E_META_STAINED_GLASS_PANE_BLACK = 15, // E_BLOCK_STONE metas: - E_META_STONE = 0, - E_META_STONE_GRANITE = 1, - E_META_STONE_DIORITE = 3, - E_META_STONE_ANDESITE = 5, + E_META_STONE = 0, + E_META_STONE_GRANITE = 1, + E_META_STONE_DIORITE = 3, + E_META_STONE_ANDESITE = 5, // E_BLOCK_STONE_SLAB metas: E_META_STONE_SLAB_STONE = 0, -- cgit v1.2.3 From 9628733df2ab39668bf1e92571442b1486d9d9de Mon Sep 17 00:00:00 2001 From: w00tc0d3 Date: Mon, 29 Sep 2014 19:19:17 +0200 Subject: BlockStone.h: fix the codestyle --- src/Blocks/BlockStone.h | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockStone.h b/src/Blocks/BlockStone.h index 2b71cebf1..2e7801f8e 100644 --- a/src/Blocks/BlockStone.h +++ b/src/Blocks/BlockStone.h @@ -18,13 +18,12 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - switch(a_BlockMeta) { - case E_META_STONE: - a_Pickups.push_back(cItem(E_BLOCK_COBBLESTONE, 1, 0)); - break; - default: - a_Pickups.push_back(cItem(E_BLOCK_STONE, 1, a_BlockMeta)); + if(a_BlockMeta == E_META_STONE) + { + a_Pickups.push_back(cItem(E_BLOCK_COBBLESTONE, 1, 0)); + return; } + a_Pickups.push_back(cItem(E_BLOCK_STONE, 1, a_BlockMeta)); } }; -- cgit v1.2.3 From bdb8d916c0ed886e739be397f1aefc1ad2ae1940 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 29 Sep 2014 19:45:12 +0100 Subject: Fixed codestyle again. --- src/Blocks/BlockStone.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockStone.h b/src/Blocks/BlockStone.h index 2e7801f8e..e52599c0f 100644 --- a/src/Blocks/BlockStone.h +++ b/src/Blocks/BlockStone.h @@ -18,7 +18,7 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - if(a_BlockMeta == E_META_STONE) + if (a_BlockMeta == E_META_STONE) { a_Pickups.push_back(cItem(E_BLOCK_COBBLESTONE, 1, 0)); return; -- cgit v1.2.3 From 30b083ed63b598dd26802682492d060d4d93921c Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Mon, 29 Sep 2014 21:34:15 +0200 Subject: World: Fixed chunk generation by plugins. ChunkWorx was broken, it was trying to generate chunks that were not properly marked as InQueue. --- src/World.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/World.cpp b/src/World.cpp index 61c061867..6059b841f 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -3003,7 +3003,7 @@ void cWorld::RegenerateChunk(int a_ChunkX, int a_ChunkZ) void cWorld::GenerateChunk(int a_ChunkX, int a_ChunkZ) { - m_Generator.QueueGenerateChunk(a_ChunkX, a_ChunkZ, false); + m_ChunkMap->TouchChunk(a_ChunkX, a_ChunkZ); } -- cgit v1.2.3 From aae90c2cf0d670ab4be05c0e7f09b00523b3b823 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Mon, 29 Sep 2014 21:38:11 +0200 Subject: Style fixes. --- src/Blocks/BlockTorch.h | 14 ++++++++------ src/Protocol/ProtocolRecognizer.cpp | 6 +++--- src/RankManager.cpp | 3 ++- 3 files changed, 13 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index 0aabcdf67..eb201dd05 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -121,12 +121,14 @@ public: // If on a block that can only hold a torch if torch is standing on it, return that face if ( - ((BlockInQuestion == E_BLOCK_GLASS) || - (BlockInQuestion == E_BLOCK_FENCE) || - (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB)) && + ( + (BlockInQuestion == E_BLOCK_GLASS) || + (BlockInQuestion == E_BLOCK_FENCE) || + (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || + (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || + (BlockInQuestion == E_BLOCK_STONE_SLAB) || + (BlockInQuestion == E_BLOCK_WOODEN_SLAB) + ) && (Face == BLOCK_FACE_TOP) ) { diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index ef6802d2b..4f8eb59db 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -201,9 +201,9 @@ void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) SendData((const char *)&Packet, 1); // WriteByte() AString UTF16 = UTF8ToRawBEUTF16(a_Reason.c_str(), a_Reason.length()); - static const short Size = htons((short)(UTF16.size() / 2)); - SendData((const char *)&Size, 2); // WriteShort() - SendData(UTF16.data(), UTF16.size()); // WriteString() + static const u_short Size = htons((u_short)(UTF16.size() / 2)); + SendData((const char *)&Size, 2); // WriteShort() + SendData(UTF16.data(), UTF16.size()); // WriteString() } } diff --git a/src/RankManager.cpp b/src/RankManager.cpp index c9b428e3b..4abe8d1e1 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -1822,7 +1822,8 @@ void cRankManager::ClearPlayerRanks(void) ASSERT(m_IsInitialized); cCSLock Lock(m_CS); - try { + try + { SQLite::Statement stmt(m_DB, "DELETE FROM PlayerRank"); stmt.exec(); } -- cgit v1.2.3 From 33dc66a4d23246b5794cf9ca5bd4287a72db4cec Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Mon, 29 Sep 2014 22:00:14 +0200 Subject: RankMgr: GetAllPlayers() returns players sorted by name. --- src/RankManager.cpp | 2 +- src/RankManager.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/RankManager.cpp b/src/RankManager.cpp index 4abe8d1e1..f5342ed3d 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -671,7 +671,7 @@ AStringVector cRankManager::GetAllPlayerUUIDs(void) AStringVector res; try { - SQLite::Statement stmt(m_DB, "SELECT PlayerUUID FROM PlayerRank"); + SQLite::Statement stmt(m_DB, "SELECT PlayerUUID FROM PlayerRank ORDER BY PlayerName COLLATE NOCASE"); while (stmt.executeStep()) { res.push_back(stmt.getColumn(0).getText()); diff --git a/src/RankManager.h b/src/RankManager.h index 3f5884f2e..61c52fda6 100644 --- a/src/RankManager.h +++ b/src/RankManager.h @@ -83,7 +83,7 @@ public: Returns an empty vector if the rank doesn't exist. Any non-existent groups are ignored. */ AStringVector GetRankPermissions(const AString & a_RankName); - /** Returns the short uuids of all defined players. */ + /** Returns the short uuids of all defined players. The returned players are ordered by their name (NOT their UUIDs). */ AStringVector GetAllPlayerUUIDs(void); /** Returns the names of all defined ranks. */ -- cgit v1.2.3 From d731ad37b15c735a66de9c92f9125c99ca3aaf50 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Tue, 30 Sep 2014 12:43:48 +0200 Subject: actual solving of the halfslap+torch problem --- src/Blocks/BlockTorch.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index eb201dd05..3280aef36 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -165,7 +165,9 @@ public: (BlockInQuestion == E_BLOCK_MOB_SPAWNER) || (BlockInQuestion == E_BLOCK_END_PORTAL_FRAME) || // Actual vanilla behaviour (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) + (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || + (BlockInQuestion == E_BLOCK_STONE_SLAB) || + (BlockInQuestion == E_BLOCK_WOODEN_SLAB) ) { // Torches can be placed on tops of glass and fences, despite them being 'untorcheable' -- cgit v1.2.3 From b2cf4004f8e198d4528981468e59ba276bffe986 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Tue, 30 Sep 2014 12:45:44 +0200 Subject: Set right indentation --- src/Blocks/BlockTorch.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index 3280aef36..f7973a607 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -165,9 +165,9 @@ public: (BlockInQuestion == E_BLOCK_MOB_SPAWNER) || (BlockInQuestion == E_BLOCK_END_PORTAL_FRAME) || // Actual vanilla behaviour (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB) + (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || + (BlockInQuestion == E_BLOCK_STONE_SLAB) || + (BlockInQuestion == E_BLOCK_WOODEN_SLAB) ) { // Torches can be placed on tops of glass and fences, despite them being 'untorcheable' -- cgit v1.2.3 From d7066f43d3fd592457e69a46f0fed098c80b3190 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Tue, 30 Sep 2014 13:33:57 +0200 Subject: Rewritten plugin messages, vanilla are being parsed directly. This should finally fix the compatibility problems between 1.7 and 1.8 protocols with the changes in the vanilla plugin messages. --- src/ClientHandle.cpp | 120 +++++++++++-------------------------------- src/ClientHandle.h | 55 ++++++++++++++------ src/Protocol/Protocol17x.cpp | 92 +++++++++++++++++++++++++++++++++ src/Protocol/Protocol17x.h | 3 ++ src/Protocol/Protocol18x.cpp | 86 ++++++++++++++++++++++++++----- src/Protocol/Protocol18x.h | 4 ++ 6 files changed, 242 insertions(+), 118 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 20e219309..a29bef0c0 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -551,6 +551,16 @@ void cClientHandle::RemoveFromAllChunks() +void cClientHandle::HandleNPCTrade(int a_SlotNum) +{ + // TODO + LOGWARNING("%s: Not implemented yet", __FUNCTION__); +} + + + + + void cClientHandle::HandlePing(void) { // Somebody tries to retrieve information about the server @@ -573,7 +583,6 @@ void cClientHandle::HandlePing(void) bool cClientHandle::HandleLogin(int a_ProtocolVersion, const AString & a_Username) { - LOGD("LOGIN %s", a_Username.c_str()); m_Username = a_Username; if (cRoot::Get()->GetPluginManager()->CallHookLogin(this, a_ProtocolVersion, a_Username)) @@ -676,25 +685,7 @@ void cClientHandle::HandlePlayerPos(double a_PosX, double a_PosY, double a_PosZ, void cClientHandle::HandlePluginMessage(const AString & a_Channel, const AString & a_Message) { - if (a_Channel == "MC|AdvCdm") - { - // Command block, set text, Client -> Server - HandleCommandBlockMessage(a_Message.c_str(), a_Message.size()); - } - else if (a_Channel == "MC|Brand") - { - // Client <-> Server branding exchange - SendPluginMessage("MC|Brand", "MCServer"); - } - else if (a_Channel == "MC|Beacon") - { - HandleBeaconSelection(a_Message.c_str(), a_Message.size()); - } - else if (a_Channel == "MC|ItemName") - { - HandleAnvilItemName(a_Message.c_str(), a_Message.size()); - } - else if (a_Channel == "REGISTER") + if (a_Channel == "REGISTER") { if (HasPluginChannel(a_Channel)) { @@ -777,15 +768,8 @@ void cClientHandle::UnregisterPluginChannels(const AStringVector & a_ChannelList -void cClientHandle::HandleBeaconSelection(const char * a_Data, size_t a_Length) +void cClientHandle::HandleBeaconSelection(int a_PrimaryEffect, int a_SecondaryEffect) { - if (a_Length < 14) - { - SendChat("Failure setting beacon selection; bad request", mtFailure); - LOGD("Malformed MC|Beacon packet."); - return; - } - cWindow * Window = m_Player->GetWindow(); if ((Window == NULL) || (Window->GetWindowType() != cWindow::wtBeacon)) { @@ -798,23 +782,15 @@ void cClientHandle::HandleBeaconSelection(const char * a_Data, size_t a_Length) return; } - cByteBuffer Buffer(a_Length); - Buffer.Write(a_Data, a_Length); - - int PrimaryEffectID, SecondaryEffectID; - Buffer.ReadBEInt(PrimaryEffectID); - Buffer.ReadBEInt(SecondaryEffectID); - cEntityEffect::eType PrimaryEffect = cEntityEffect::effNoEffect; - if ((PrimaryEffectID >= 0) && (PrimaryEffectID <= (int)cEntityEffect::effSaturation)) + if ((a_PrimaryEffect >= 0) && (a_PrimaryEffect <= (int)cEntityEffect::effSaturation)) { - PrimaryEffect = (cEntityEffect::eType)PrimaryEffectID; + PrimaryEffect = (cEntityEffect::eType)a_PrimaryEffect; } - cEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect; - if ((SecondaryEffectID >= 0) && (SecondaryEffectID <= (int)cEntityEffect::effSaturation)) + if ((a_SecondaryEffect >= 0) && (a_SecondaryEffect <= (int)cEntityEffect::effSaturation)) { - SecondaryEffect = (cEntityEffect::eType)SecondaryEffectID; + SecondaryEffect = (cEntityEffect::eType)a_SecondaryEffect; } Window->SetSlot(*m_Player, 0, cItem()); @@ -841,52 +817,12 @@ void cClientHandle::HandleBeaconSelection(const char * a_Data, size_t a_Length) -void cClientHandle::HandleCommandBlockMessage(const char * a_Data, size_t a_Length) +void cClientHandle::HandleCommandBlockBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_NewCommand) { - if (a_Length < 14) - { - SendChat("Failure setting command block command; bad request", mtFailure); - LOGD("Malformed MC|AdvCdm packet."); - return; - } - - cByteBuffer Buffer(a_Length); - Buffer.Write(a_Data, a_Length); - - int BlockX, BlockY, BlockZ; - - AString Command; - - char Mode; - - Buffer.ReadChar(Mode); - - switch (Mode) - { - case 0x00: - { - Buffer.ReadBEInt(BlockX); - Buffer.ReadBEInt(BlockY); - Buffer.ReadBEInt(BlockZ); - - Buffer.ReadVarUTF8String(Command); - break; - } - - default: - { - SendChat("Failure setting command block command; unhandled mode", mtFailure); - LOGD("Unhandled MC|AdvCdm packet mode."); - return; - } - } - cWorld * World = m_Player->GetWorld(); - if (World->AreCommandBlocksEnabled()) { - World->SetCommandBlockCommand(BlockX, BlockY, BlockZ, Command); - + World->SetCommandBlockCommand(a_BlockX, a_BlockY, a_BlockZ, a_NewCommand); SendChat("Successfully set command block command", mtSuccess); } else @@ -899,22 +835,26 @@ void cClientHandle::HandleCommandBlockMessage(const char * a_Data, size_t a_Leng -void cClientHandle::HandleAnvilItemName(const char * a_Data, size_t a_Length) +void cClientHandle::HandleCommandBlockEntityChange(int a_EntityID, const AString & a_NewCommand) { - if (a_Length < 1) - { - return; - } + // TODO + LOGWARNING("%s: Not implemented yet", __FUNCTION__); +} + + + + +void cClientHandle::HandleAnvilItemName(const AString & a_ItemName) +{ if ((m_Player->GetWindow() == NULL) || (m_Player->GetWindow()->GetWindowType() != cWindow::wtAnvil)) { return; } - AString Name(a_Data, a_Length); - if (Name.length() <= 30) + if (a_ItemName.length() <= 30) { - ((cAnvilWindow *)m_Player->GetWindow())->SetRepairedItemName(Name, m_Player); + ((cAnvilWindow *)m_Player->GetWindow())->SetRepairedItemName(a_ItemName, m_Player); } } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 10cf6ae28..1f22762c0 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -222,6 +222,13 @@ public: bool HasPluginChannel(const AString & a_PluginChannel); + /** Called by the protocol when it receives the MC|Brand plugin message. Also callable by plugins. + Simply stores the string value. */ + void SetClientBrand(const AString & a_ClientBrand) { m_ClientBrand = a_ClientBrand; } + + /** Returns the client brand received in the MC|Brand plugin message or set by a plugin. */ + const AString & GetClientBrand(void) const { return m_ClientBrand; } + // tolua_end /** Returns true if the client wants the chunk specified to be sent (in m_ChunksToSend) */ @@ -236,12 +243,31 @@ public: void PacketError(unsigned char a_PacketType); // Calls that cProtocol descendants use for handling packets: - void HandleAnimation (char a_Animation); - void HandleChat (const AString & a_Message); - void HandleCreativeInventory(short a_SlotNum, const cItem & a_HeldItem); - void HandleEntityCrouch (int a_EntityID, bool a_IsCrouching); - void HandleEntityLeaveBed (int a_EntityID); - void HandleEntitySprinting (int a_EntityID, bool a_IsSprinting); + void HandleAnimation(char a_Animation); + + /** Called when the protocol receives a MC|ItemName plugin message, indicating that the player named + an item in the anvil UI. */ + void HandleAnvilItemName(const AString & a_ItemName); + + /** Called when the protocol receives a MC|Beacon plugin message, indicating that the player set an effect + in the beacon UI. */ + void HandleBeaconSelection(int a_PrimaryEffect, int a_SecondaryEffect); + + /** Called when the protocol detects a chat packet. */ + void HandleChat(const AString & a_Message); + + /** Called when the protocol receives a MC|AdvCdm plugin message, indicating that the player set a new + command in the command block UI, for a block-based commandblock. */ + void HandleCommandBlockBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_NewCommand); + + /** Called when the protocol receives a MC|AdvCdm plugin message, indicating that the player set a new + command in the command block UI, for an entity-based commandblock (minecart?). */ + void HandleCommandBlockEntityChange(int a_EntityID, const AString & a_NewCommand); + + void HandleCreativeInventory (short a_SlotNum, const cItem & a_HeldItem); + void HandleEntityCrouch (int a_EntityID, bool a_IsCrouching); + void HandleEntityLeaveBed (int a_EntityID); + void HandleEntitySprinting (int a_EntityID, bool a_IsSprinting); /** Called when the protocol handshake has been received (for protocol versions that support it; otherwise the first instant when a username is received). @@ -251,6 +277,11 @@ public: void HandleKeepAlive (int a_KeepAliveID); void HandleLeftClick (int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, char a_Status); + + /** Called when the protocol receives a MC|TrSel packet, indicating that the player used a trade in + the NPC UI. */ + void HandleNPCTrade(int a_SlotNum); + void HandlePing (void); void HandlePlayerAbilities (bool a_CanFly, bool a_IsFlying, float FlyingSpeed, float WalkingSpeed); void HandlePlayerLook (float a_Rotation, float a_Pitch, bool a_IsOnGround); @@ -392,6 +423,9 @@ private: /** The plugin channels that the client has registered. */ cChannels m_PluginChannels; + + /** The brand identification of the client, as received in the MC|Brand plugin message or set from a plugin. */ + AString m_ClientBrand; /** Handles the block placing packet when it is a real block placement (not block-using, item-using or eating) */ @@ -421,15 +455,6 @@ private: /** Removes all of the channels from the list of current plugin channels. Ignores channels that are not found. */ void UnregisterPluginChannels(const AStringVector & a_ChannelList); - /** Handles the "MC|Beacon" plugin message */ - void HandleBeaconSelection(const char * a_Data, size_t a_Length); - - /** Handles the "MC|AdvCdm" plugin message */ - void HandleCommandBlockMessage(const char * a_Data, size_t a_Length); - - /** Handles the "MC|ItemName" plugin message */ - void HandleAnvilItemName(const char * a_Data, size_t a_Length); - // cSocketThreads::cCallback overrides: 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/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index e4c33908a..07338f395 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -2064,6 +2064,22 @@ void cProtocol172::HandlePacketPluginMessage(cByteBuffer & a_ByteBuffer) { HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Channel); HANDLE_READ(a_ByteBuffer, ReadBEShort, short, Length); + if (Length + 1 != (int)a_ByteBuffer.GetReadableSpace()) + { + LOGD("Invalid plugin message packet, payload length doesn't match packet length (exp %d, got %d)", + (int)a_ByteBuffer.GetReadableSpace() - 1, Length + ); + return; + } + + // If the plugin channel is recognized vanilla, handle it directly: + if (Channel.substr(0, 3) == "MC|") + { + HandleVanillaPluginMessage(a_ByteBuffer, Channel, Length); + return; + } + + // Read the plugin message and relay to clienthandle: AString Data; if (!a_ByteBuffer.ReadString(Data, Length)) { @@ -2217,6 +2233,82 @@ void cProtocol172::HandlePacketWindowClose(cByteBuffer & a_ByteBuffer) +void cProtocol172::HandleVanillaPluginMessage(cByteBuffer & a_ByteBuffer, const AString & a_Channel, short a_PayloadLength) +{ + if (a_Channel == "MC|AdvCdm") + { + HANDLE_READ(a_ByteBuffer, ReadByte, Byte, Mode) + switch (Mode) + { + case 0x00: + { + // Block-based commandblock update: + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, BlockX); + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, BlockY); + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, BlockZ); + HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Command); + m_Client->HandleCommandBlockBlockChange(BlockX, BlockY, BlockZ, Command); + break; + } + + // TODO: Entity-based commandblock update + + default: + { + m_Client->SendChat(Printf("Failure setting command block command; unhandled mode %d", Mode), mtFailure); + LOG("Unhandled MC|AdvCdm packet mode."); + return; + } + } // switch (Mode) + return; + } + else if (a_Channel == "MC|Brand") + { + // Read the client's brand: + AString Brand; + if (a_ByteBuffer.ReadString(Brand, a_PayloadLength)) + { + m_Client->SetClientBrand(Brand); + } + + // Send back our brand: + SendPluginMessage("MC|Brand", "MCServer"); + return; + } + else if (a_Channel == "MC|Beacon") + { + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, Effect1); + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, Effect2); + m_Client->HandleBeaconSelection(Effect1, Effect2); + return; + } + else if (a_Channel == "MC|ItemName") + { + AString ItemName; + if (a_ByteBuffer.ReadString(ItemName, a_PayloadLength)) + { + m_Client->HandleAnvilItemName(ItemName); + } + return; + } + else if (a_Channel == "MC|TrSel") + { + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, SlotNum); + m_Client->HandleNPCTrade(SlotNum); + return; + } + LOG("Unhandled vanilla plugin channel: \"%s\".", a_Channel.c_str()); + + // Read the payload and send it through to the clienthandle: + AString Message; + VERIFY(a_ByteBuffer.ReadString(Message, a_PayloadLength)); + m_Client->HandlePluginMessage(a_Channel, Message); +} + + + + + void cProtocol172::SendData(const char * a_Data, size_t a_Size) { if (m_IsEncrypted) diff --git a/src/Protocol/Protocol17x.h b/src/Protocol/Protocol17x.h index 0bc86a72a..7709df59d 100644 --- a/src/Protocol/Protocol17x.h +++ b/src/Protocol/Protocol17x.h @@ -295,6 +295,9 @@ protected: void HandlePacketWindowClick (cByteBuffer & a_ByteBuffer); void HandlePacketWindowClose (cByteBuffer & a_ByteBuffer); + /** Parses Vanilla plugin messages into specific ClientHandle calls. + The message payload is still in the bytebuffer, to be read by this function. */ + void HandleVanillaPluginMessage(cByteBuffer & a_ByteBuffer, const AString & a_Channel, short a_PayloadLength); /** Sends the data to the client, encrypting them if needed. */ virtual void SendData(const char * a_Data, size_t a_Size) override; diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index 1070a8434..acdb48cf7 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -989,10 +989,6 @@ void cProtocol180::SendPluginMessage(const AString & a_Channel, const AString & cPacketizer Pkt(*this, 0x3f); Pkt.WriteString(a_Channel); - if (a_Channel.substr(0, 3) == "MC|") - { - Pkt.WriteVarInt((UInt32)a_Message.size()); - } Pkt.WriteBuf(a_Message.data(), a_Message.size()); } @@ -2324,18 +2320,17 @@ void cProtocol180::HandlePacketPlayerPosLook(cByteBuffer & a_ByteBuffer) void cProtocol180::HandlePacketPluginMessage(cByteBuffer & a_ByteBuffer) { HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Channel); - AString Data; + + // If the plugin channel is recognized vanilla, handle it directly: if (Channel.substr(0, 3) == "MC|") { - // Vanilla sends the payload length within the payload itself, so skip it: - HANDLE_READ(a_ByteBuffer, ReadVarInt, UInt32, DataLen); - if (DataLen != a_ByteBuffer.GetReadableSpace() - 1) - { - ASSERT(!"Bad plugin message payload length"); - return; - } + HandleVanillaPluginMessage(a_ByteBuffer, Channel); + return; } - a_ByteBuffer.ReadString(Data, a_ByteBuffer.GetReadableSpace() - 1); // Always succeeds + + // Read the plugin message and relay to clienthandle: + AString Data; + VERIFY(a_ByteBuffer.ReadString(Data, a_ByteBuffer.GetReadableSpace() - 1)); // Always succeeds m_Client->HandlePluginMessage(Channel, Data); } @@ -2524,6 +2519,71 @@ void cProtocol180::HandlePacketWindowClose(cByteBuffer & a_ByteBuffer) +void cProtocol180::HandleVanillaPluginMessage(cByteBuffer & a_ByteBuffer, const AString & a_Channel) +{ + if (a_Channel == "MC|AdvCdm") + { + HANDLE_READ(a_ByteBuffer, ReadByte, Byte, Mode) + switch (Mode) + { + case 0x00: + { + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, BlockX); + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, BlockY); + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, BlockZ); + HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Command); + m_Client->HandleCommandBlockBlockChange(BlockX, BlockY, BlockZ, Command); + break; + } + + default: + { + m_Client->SendChat(Printf("Failure setting command block command; unhandled mode %d", Mode), mtFailure); + LOG("Unhandled MC|AdvCdm packet mode."); + return; + } + } // switch (Mode) + return; + } + else if (a_Channel == "MC|Brand") + { + HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, Brand); + m_Client->SetClientBrand(Brand); + // Send back our brand, including the length: + SendPluginMessage("MC|Brand", "\x08MCServer"); + return; + } + else if (a_Channel == "MC|Beacon") + { + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, Effect1); + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, Effect2); + m_Client->HandleBeaconSelection(Effect1, Effect2); + return; + } + else if (a_Channel == "MC|ItemName") + { + HANDLE_READ(a_ByteBuffer, ReadVarUTF8String, AString, ItemName); + m_Client->HandleAnvilItemName(ItemName); + return; + } + else if (a_Channel == "MC|TrSel") + { + HANDLE_READ(a_ByteBuffer, ReadBEInt, int, SlotNum); + m_Client->HandleNPCTrade(SlotNum); + return; + } + LOG("Unhandled vanilla plugin channel: \"%s\".", a_Channel.c_str()); + + // Read the payload and send it through to the clienthandle: + AString Message; + VERIFY(a_ByteBuffer.ReadString(Message, a_ByteBuffer.GetReadableSpace() - 1)); + m_Client->HandlePluginMessage(a_Channel, Message); +} + + + + + void cProtocol180::SendData(const char * a_Data, size_t a_Size) { if (m_IsEncrypted) diff --git a/src/Protocol/Protocol18x.h b/src/Protocol/Protocol18x.h index acc167a6d..8c0b77a21 100644 --- a/src/Protocol/Protocol18x.h +++ b/src/Protocol/Protocol18x.h @@ -312,6 +312,10 @@ protected: void HandlePacketWindowClick (cByteBuffer & a_ByteBuffer); void HandlePacketWindowClose (cByteBuffer & a_ByteBuffer); + /** Parses Vanilla plugin messages into specific ClientHandle calls. + The message payload is still in the bytebuffer, the handler reads it specifically for each handled channel */ + void HandleVanillaPluginMessage(cByteBuffer & a_ByteBuffer, const AString & a_Channel); + /** Sends the data to the client, encrypting them if needed. */ virtual void SendData(const char * a_Data, size_t a_Size) override; -- cgit v1.2.3 From b77480b4ef83e131d1c0c59409ec284a1040dab1 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Tue, 30 Sep 2014 14:05:23 +0200 Subject: Indentation --- src/Blocks/BlockTorch.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index f7973a607..dd252f2a4 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -165,9 +165,9 @@ public: (BlockInQuestion == E_BLOCK_MOB_SPAWNER) || (BlockInQuestion == E_BLOCK_END_PORTAL_FRAME) || // Actual vanilla behaviour (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB) + (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || + (BlockInQuestion == E_BLOCK_STONE_SLAB) || + (BlockInQuestion == E_BLOCK_WOODEN_SLAB) ) { // Torches can be placed on tops of glass and fences, despite them being 'untorcheable' -- cgit v1.2.3 From 5111628ba5b60aa5c9191ff6a09573920ac50e9c Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 30 Sep 2014 19:49:42 +0200 Subject: Fixed 1.8 doors. --- src/Blocks/BlockDoor.h | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockDoor.h b/src/Blocks/BlockDoor.h index 0ff8bcfc8..7e46feec4 100644 --- a/src/Blocks/BlockDoor.h +++ b/src/Blocks/BlockDoor.h @@ -173,7 +173,20 @@ public: /** Returns true if the specified blocktype is any kind of door */ inline static bool IsDoor(BLOCKTYPE a_Block) { - return (a_Block == E_BLOCK_WOODEN_DOOR) || (a_Block == E_BLOCK_IRON_DOOR); + switch (a_Block) + { + case E_BLOCK_ACACIA_DOOR: + case E_BLOCK_BIRCH_DOOR: + case E_BLOCK_DARK_OAK_DOOR: + case E_BLOCK_IRON_DOOR: + case E_BLOCK_JUNGLE_DOOR: + case E_BLOCK_SPRUCE_DOOR: + case E_BLOCK_WOODEN_DOOR: + { + return true; + } + } + return false; } -- cgit v1.2.3 From 83973520c8492225e5ea02ebfd0a5d47b7e35f85 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 30 Sep 2014 20:04:49 +0200 Subject: Fixed iron trapdoors --- src/BlockInfo.cpp | 1 + src/Blocks/BlockTrapdoor.h | 5 +++++ src/Simulator/SandSimulator.cpp | 1 + src/World.cpp | 4 ++-- 4 files changed, 9 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp index 14e814084..719ba0550 100644 --- a/src/BlockInfo.cpp +++ b/src/BlockInfo.cpp @@ -329,6 +329,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE].m_PistonBreakable = true; a_Info[E_BLOCK_INACTIVE_COMPARATOR ].m_PistonBreakable = true; a_Info[E_BLOCK_IRON_DOOR ].m_PistonBreakable = true; + a_Info[E_BLOCK_IRON_TRAPDOOR ].m_PistonBreakable = true; a_Info[E_BLOCK_JACK_O_LANTERN ].m_PistonBreakable = true; a_Info[E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE].m_PistonBreakable = true; a_Info[E_BLOCK_LILY_PAD ].m_PistonBreakable = true; diff --git a/src/Blocks/BlockTrapdoor.h b/src/Blocks/BlockTrapdoor.h index 41256ae55..d3f3c9a38 100644 --- a/src/Blocks/BlockTrapdoor.h +++ b/src/Blocks/BlockTrapdoor.h @@ -29,6 +29,11 @@ public: virtual void OnUse(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) override { + if (m_BlockType == E_BLOCK_IRON_TRAPDOOR) + { + return; + } + // Flip the ON bit on/off using the XOR bitwise operation NIBBLETYPE Meta = (a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) ^ 0x04); a_ChunkInterface.SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, Meta); diff --git a/src/Simulator/SandSimulator.cpp b/src/Simulator/SandSimulator.cpp index e8887ce59..aad41e463 100644 --- a/src/Simulator/SandSimulator.cpp +++ b/src/Simulator/SandSimulator.cpp @@ -160,6 +160,7 @@ bool cSandSimulator::CanContinueFallThrough(BLOCKTYPE a_BlockType) case E_BLOCK_FIRE: case E_BLOCK_FLOWER_POT: case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE: + case E_BLOCK_IRON_TRAPDOOR: case E_BLOCK_LAVA: case E_BLOCK_LEVER: case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE: diff --git a/src/World.cpp b/src/World.cpp index 6059b841f..a3c804b44 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -2954,7 +2954,7 @@ bool cWorld::IsTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ) BLOCKTYPE Block; NIBBLETYPE Meta; GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, Meta); - if (Block != E_BLOCK_TRAPDOOR) + if ((Block != E_BLOCK_TRAPDOOR) && (Block != E_BLOCK_IRON_TRAPDOOR)) { return false; } @@ -2971,7 +2971,7 @@ bool cWorld::SetTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ, bool a_Op BLOCKTYPE Block; NIBBLETYPE Meta; GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, Meta); - if (Block != E_BLOCK_TRAPDOOR) + if ((Block != E_BLOCK_TRAPDOOR) && (Block != E_BLOCK_IRON_TRAPDOOR)) { return false; } -- cgit v1.2.3 From e74510bddf41ab4f92e9255ea0be2786ef1e621b Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Tue, 30 Sep 2014 20:27:20 +0200 Subject: Fixed a missing semicolon. --- src/Protocol/Protocol17x.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index 07338f395..a7abd240f 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -2237,7 +2237,7 @@ void cProtocol172::HandleVanillaPluginMessage(cByteBuffer & a_ByteBuffer, const { if (a_Channel == "MC|AdvCdm") { - HANDLE_READ(a_ByteBuffer, ReadByte, Byte, Mode) + HANDLE_READ(a_ByteBuffer, ReadByte, Byte, Mode); switch (Mode) { case 0x00: -- cgit v1.2.3 From 425df6b69490e29b367c62476a125aa84bbcbcc5 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 30 Sep 2014 20:31:27 +0200 Subject: Fixed 1.8 dirt types --- src/BlockID.h | 1 + src/Blocks/BlockDirt.h | 10 +++++++++- src/Items/ItemHoe.h | 27 +++++++++++++++++++++++++-- 3 files changed, 35 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 9a8830710..03a7f63e6 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -477,6 +477,7 @@ enum // E_BLOCK_DIRT metas: E_META_DIRT_NORMAL = 0, E_META_DIRT_GRASSLESS = 1, + E_META_DIRT_COARSE = 1, E_META_DIRT_PODZOL = 2, // E_BLOCK_DISPENSER / E_BLOCK_DROPPER metas: diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h index 60d81db72..b6d762dcf 100644 --- a/src/Blocks/BlockDirt.h +++ b/src/Blocks/BlockDirt.h @@ -21,7 +21,15 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - a_Pickups.push_back(cItem(E_BLOCK_DIRT, 1, 0)); + if (a_BlockMeta == E_META_DIRT_COARSE) + { + // Drop the coarse block (dirt, meta 1) + a_Pickups.Add(E_BLOCK_DIRT, 1, 1); + } + else + { + a_Pickups.Add(E_BLOCK_DIRT, 1, 0); + } } diff --git a/src/Items/ItemHoe.h b/src/Items/ItemHoe.h index de8b9a061..ae3723323 100644 --- a/src/Items/ItemHoe.h +++ b/src/Items/ItemHoe.h @@ -24,12 +24,35 @@ public: { return false; } - BLOCKTYPE Block = a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ); BLOCKTYPE UpperBlock = a_World->GetBlock(a_BlockX, a_BlockY + 1, a_BlockZ); + BLOCKTYPE Block; + NIBBLETYPE BlockMeta; + a_World->GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, BlockMeta); + if (((Block == E_BLOCK_DIRT) || (Block == E_BLOCK_GRASS)) && (UpperBlock == E_BLOCK_AIR)) { - a_World->FastSetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_FARMLAND, 0); + BLOCKTYPE NewBlock = E_BLOCK_FARMLAND; + if (Block == E_BLOCK_DIRT) + { + switch (BlockMeta) + { + case E_META_DIRT_COARSE: + { + // Transform to normal dirt + NewBlock = E_BLOCK_DIRT; + break; + } + case E_META_DIRT_PODZOL: + { + // You can't transform this block with a hoe in vanilla + return false; + } + default: break; + } + } + + a_World->FastSetBlock(a_BlockX, a_BlockY, a_BlockZ, NewBlock, 0); a_World->BroadcastSoundEffect("dig.gravel", a_BlockX + 0.5, a_BlockY + 0.5, a_BlockZ + 0.5, 1.0f, 0.8f); a_Player->UseEquippedItem(); return true; -- cgit v1.2.3 From 7d3016c7adc1a2d88447acfaf6c642ab25028a35 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 30 Sep 2014 20:59:59 +0200 Subject: Code improvements --- src/Blocks/BlockDirt.h | 4 ++-- src/Blocks/BlockDoor.h | 5 ++++- src/Blocks/BlockTrapdoor.h | 1 + 3 files changed, 7 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h index b6d762dcf..19f889372 100644 --- a/src/Blocks/BlockDirt.h +++ b/src/Blocks/BlockDirt.h @@ -24,11 +24,11 @@ public: if (a_BlockMeta == E_META_DIRT_COARSE) { // Drop the coarse block (dirt, meta 1) - a_Pickups.Add(E_BLOCK_DIRT, 1, 1); + a_Pickups.Add(E_BLOCK_DIRT, 1, E_META_DIRT_COARSE); } else { - a_Pickups.Add(E_BLOCK_DIRT, 1, 0); + a_Pickups.Add(E_BLOCK_DIRT, 1, E_META_DIRT_NORMAL); } } diff --git a/src/Blocks/BlockDoor.h b/src/Blocks/BlockDoor.h index 7e46feec4..92ad8da12 100644 --- a/src/Blocks/BlockDoor.h +++ b/src/Blocks/BlockDoor.h @@ -185,8 +185,11 @@ public: { return true; } + default: + { + return false; + } } - return false; } diff --git a/src/Blocks/BlockTrapdoor.h b/src/Blocks/BlockTrapdoor.h index d3f3c9a38..8c96de0f1 100644 --- a/src/Blocks/BlockTrapdoor.h +++ b/src/Blocks/BlockTrapdoor.h @@ -31,6 +31,7 @@ public: { if (m_BlockType == E_BLOCK_IRON_TRAPDOOR) { + // Iron doors can only be toggled by redstone, not by right-clicking return; } -- cgit v1.2.3 From 48c99dcd2ec972ebf627aa0b4d64a0e484d47aa5 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Tue, 30 Sep 2014 22:00:33 +0100 Subject: Improved torch handler --- src/BlockInfo.cpp | 1 + src/Blocks/BlockTorch.h | 121 ++++++++++++++++++++---------------------------- 2 files changed, 52 insertions(+), 70 deletions(-) (limited to 'src') diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp index 14e814084..05a1e13f8 100644 --- a/src/BlockInfo.cpp +++ b/src/BlockInfo.cpp @@ -527,6 +527,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_LAPIS_ORE ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_LOG ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_MELON ].m_FullyOccupiesVoxel = true; + a_Info[E_BLOCK_MOB_SPAWNER ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_MOSSY_COBBLESTONE ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_MYCELIUM ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_NETHERRACK ].m_FullyOccupiesVoxel = true; diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index dd252f2a4..3070adfd9 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -24,32 +24,22 @@ public: BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta ) override { - // Find proper placement of torch + BLOCKTYPE Block; + NIBBLETYPE Meta; + AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, true); // Set to clicked block + a_ChunkInterface.GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, Meta); - if ((a_BlockFace == BLOCK_FACE_TOP) || (a_BlockFace == BLOCK_FACE_BOTTOM)) + if (!CanBePlacedOn(Block, Meta, a_BlockFace)) // Try to preserve original direction { - a_BlockFace = FindSuitableFace(a_ChunkInterface, a_BlockX, a_BlockY, a_BlockZ); // Top or bottom faces clicked, find a suitable face + // Torch couldn't be placed on whatever face was clicked, last ditch resort - find another face + + AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, false); // Reset to torch block + a_BlockFace = FindSuitableFace(a_ChunkInterface, a_BlockX, a_BlockY, a_BlockZ); // Set a_BlockFace to a valid direction which will be converted later to a metadata if (a_BlockFace == BLOCK_FACE_NONE) { - // Client wouldn't have sent anything anyway, but whatever return false; } } - else - { - // Not top or bottom faces, try to preserve whatever face was clicked - AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, true); // Set to clicked block - if (!CanBePlacedOn(a_ChunkInterface.GetBlock(a_BlockX, a_BlockY, a_BlockZ), a_BlockFace)) - { - AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, false); // Reset to torch block - // Torch couldn't be placed on whatever face was clicked, last ditch resort - find another face - a_BlockFace = FindSuitableFace(a_ChunkInterface, a_BlockX, a_BlockY, a_BlockZ); - if (a_BlockFace == BLOCK_FACE_NONE) - { - return false; - } - } - } a_BlockType = m_BlockType; a_BlockMeta = DirectionToMetaData(a_BlockFace); @@ -97,15 +87,40 @@ public: } - static bool CanBePlacedOn(BLOCKTYPE a_BlockType, eBlockFace a_BlockFace) + static bool CanBePlacedOn(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, eBlockFace a_BlockFace) { - if (!cBlockInfo::FullyOccupiesVoxel(a_BlockType)) - { - return (a_BlockFace == BLOCK_FACE_TOP); // Allow placement only when torch upright (for glass, etc.); exceptions won't even be sent by client, no need to handle - } - else + switch (a_BlockType) { - return true; + case E_BLOCK_END_PORTAL_FRAME: + case E_BLOCK_SOULSAND: + { + // Exceptional vanilla behaviour + return true; + } + case E_BLOCK_GLASS: + case E_BLOCK_STAINED_GLASS: + case E_BLOCK_FENCE: + case E_BLOCK_NETHER_BRICK_FENCE: + case E_BLOCK_COBBLESTONE_WALL: + { + // Torches can only be placed on top of these blocks + return (a_BlockFace == BLOCK_FACE_YP); + } + case E_BLOCK_STONE_SLAB: + case E_BLOCK_WOODEN_SLAB: + { + // Toches can be placed on the top of these slabs only if the occupy the top half of the voxel + return ((a_BlockFace == BLOCK_FACE_YP) && ((a_BlockMeta & 0x08) == 0x08)); + } + default: + { + if (cBlockInfo::FullyOccupiesVoxel(a_BlockType)) + { + // Torches can be placed on full blocks unless their bottom side is clicked + return (a_BlockFace != BLOCK_FACE_YM); + } + return false; + } } } @@ -117,26 +132,12 @@ public: { eBlockFace Face = static_cast(i); AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, Face, true); - BLOCKTYPE BlockInQuestion = a_ChunkInterface.GetBlock(a_BlockX, a_BlockY, a_BlockZ); - - // If on a block that can only hold a torch if torch is standing on it, return that face - if ( - ( - (BlockInQuestion == E_BLOCK_GLASS) || - (BlockInQuestion == E_BLOCK_FENCE) || - (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB) - ) && - (Face == BLOCK_FACE_TOP) - ) - { - return Face; - } - else if (cBlockInfo::FullyOccupiesVoxel(BlockInQuestion) && (i != BLOCK_FACE_BOTTOM)) + BLOCKTYPE BlockInQuestion; + NIBBLETYPE BlockInQuestionMeta; + a_ChunkInterface.GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, BlockInQuestion, BlockInQuestionMeta); + + if (CanBePlacedOn(BlockInQuestion, BlockInQuestionMeta, Face)) { - // Otherwise, if block in that direction is torch placeable and we haven't gotten to it via the bottom face, return that face return Face; } else @@ -152,36 +153,16 @@ public: virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { eBlockFace Face = MetaDataToDirection(a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ)); - AddFaceDirection(a_RelX, a_RelY, a_RelZ, Face, true); + BLOCKTYPE BlockInQuestion; - a_Chunk.UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, BlockInQuestion); - - if ( - (BlockInQuestion == E_BLOCK_GLASS) || - (BlockInQuestion == E_BLOCK_STAINED_GLASS) || - (BlockInQuestion == E_BLOCK_FENCE) || - (BlockInQuestion == E_BLOCK_SOULSAND) || - (BlockInQuestion == E_BLOCK_MOB_SPAWNER) || - (BlockInQuestion == E_BLOCK_END_PORTAL_FRAME) || // Actual vanilla behaviour - (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB) - ) - { - // Torches can be placed on tops of glass and fences, despite them being 'untorcheable' - // No need to check for upright orientation, it was done when the torch was placed - return true; - } - else if (!cBlockInfo::FullyOccupiesVoxel(BlockInQuestion)) + NIBBLETYPE BlockInQuestionMeta; + if (!a_Chunk.UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockInQuestion, BlockInQuestionMeta)) { return false; } - else - { - return true; - } + + return CanBePlacedOn(BlockInQuestion, BlockInQuestionMeta, Face); } -- cgit v1.2.3 From 9e4a5f824ae88e3a19de6a14db91b43c1759e29e Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Tue, 30 Sep 2014 22:20:21 +0100 Subject: Removed WSSCompact --- src/BlockEntities/BeaconEntity.cpp | 62 -- src/BlockEntities/BeaconEntity.h | 2 - src/BlockEntities/BlockEntity.h | 2 - src/BlockEntities/ChestEntity.cpp | 42 -- src/BlockEntities/ChestEntity.h | 3 - src/BlockEntities/CommandBlockEntity.cpp | 32 - src/BlockEntities/CommandBlockEntity.h | 3 - src/BlockEntities/DropSpenserEntity.cpp | 48 -- src/BlockEntities/DropSpenserEntity.h | 3 - src/BlockEntities/EnderChestEntity.h | 1 - src/BlockEntities/FlowerPotEntity.cpp | 31 - src/BlockEntities/FlowerPotEntity.h | 3 - src/BlockEntities/FurnaceEntity.cpp | 54 -- src/BlockEntities/FurnaceEntity.h | 3 - src/BlockEntities/HopperEntity.cpp | 11 - src/BlockEntities/HopperEntity.h | 1 - src/BlockEntities/JukeboxEntity.cpp | 28 - src/BlockEntities/JukeboxEntity.h | 3 - src/BlockEntities/MobHeadEntity.cpp | 32 - src/BlockEntities/MobHeadEntity.h | 3 - src/BlockEntities/NoteEntity.cpp | 29 - src/BlockEntities/NoteEntity.h | 3 - src/BlockEntities/SignEntity.cpp | 35 - src/BlockEntities/SignEntity.h | 3 - src/WorldStorage/CMakeLists.txt | 2 - src/WorldStorage/WSSCompact.cpp | 1066 ------------------------------ src/WorldStorage/WSSCompact.h | 157 ----- src/WorldStorage/WorldStorage.cpp | 2 - 28 files changed, 1664 deletions(-) delete mode 100644 src/WorldStorage/WSSCompact.cpp delete mode 100644 src/WorldStorage/WSSCompact.h (limited to 'src') diff --git a/src/BlockEntities/BeaconEntity.cpp b/src/BlockEntities/BeaconEntity.cpp index dcf659f47..02f45a097 100644 --- a/src/BlockEntities/BeaconEntity.cpp +++ b/src/BlockEntities/BeaconEntity.cpp @@ -303,68 +303,6 @@ void cBeaconEntity::UsedBy(cPlayer * a_Player) -bool cBeaconEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - Json::Value AllSlots = a_Value.get("Slots", 0); - int SlotIdx = 0; - for (Json::Value::iterator itr = AllSlots.begin(); itr != AllSlots.end(); ++itr) - { - cItem Item; - Item.FromJson(*itr); - SetSlot(SlotIdx, Item); - SlotIdx++; - } - - m_BeaconLevel = (char)a_Value.get("Level", 0).asInt(); - int PrimaryEffect = a_Value.get("PrimaryEffect", 0).asInt(); - int SecondaryEffect = a_Value.get("SecondaryEffect", 0).asInt(); - - if ((PrimaryEffect >= 0) && (PrimaryEffect <= (int)cEntityEffect::effSaturation)) - { - m_PrimaryEffect = (cEntityEffect::eType)PrimaryEffect; - } - - if ((SecondaryEffect >= 0) && (SecondaryEffect <= (int)cEntityEffect::effSaturation)) - { - m_SecondaryEffect = (cEntityEffect::eType)SecondaryEffect; - } - - return true; -} - - - - - -void cBeaconEntity::SaveToJson(Json::Value& a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - Json::Value AllSlots; - int NumSlots = m_Contents.GetNumSlots(); - for (int i = 0; i < NumSlots; i++) - { - Json::Value Slot; - m_Contents.GetSlot(i).GetJson(Slot); - AllSlots.append(Slot); - } - a_Value["Slots"] = AllSlots; - - a_Value["Level"] = m_BeaconLevel; - a_Value["PrimaryEffect"] = (int)m_PrimaryEffect; - a_Value["SecondaryEffect"] = (int)m_SecondaryEffect; -} - - - - - void cBeaconEntity::SendTo(cClientHandle & a_Client) { a_Client.SendUpdateBlockEntity(*this); diff --git a/src/BlockEntities/BeaconEntity.h b/src/BlockEntities/BeaconEntity.h index 0d7150aef..8c2dad254 100644 --- a/src/BlockEntities/BeaconEntity.h +++ b/src/BlockEntities/BeaconEntity.h @@ -34,9 +34,7 @@ public: cBeaconEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); - bool LoadFromJson(const Json::Value & a_Value); // cBlockEntity overrides: - virtual void SaveToJson(Json::Value& a_Value) override; virtual void SendTo(cClientHandle & a_Client) override; virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/BlockEntity.h b/src/BlockEntities/BlockEntity.h index 066bbc696..54ab40f3e 100644 --- a/src/BlockEntities/BlockEntity.h +++ b/src/BlockEntities/BlockEntity.h @@ -74,8 +74,6 @@ public: int GetRelZ(void) const { return m_RelZ; } // tolua_end - - virtual void SaveToJson (Json::Value & a_Value) = 0; /// Called when a player uses this entity; should open the UI window virtual void UsedBy( cPlayer * a_Player) = 0; diff --git a/src/BlockEntities/ChestEntity.cpp b/src/BlockEntities/ChestEntity.cpp index a89e5747e..19d88b646 100644 --- a/src/BlockEntities/ChestEntity.cpp +++ b/src/BlockEntities/ChestEntity.cpp @@ -33,48 +33,6 @@ cChestEntity::~cChestEntity() -bool cChestEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - Json::Value AllSlots = a_Value.get("Slots", 0); - int SlotIdx = 0; - for (Json::Value::iterator itr = AllSlots.begin(); itr != AllSlots.end(); ++itr) - { - cItem Item; - Item.FromJson(*itr); - SetSlot(SlotIdx, Item); - SlotIdx++; - } - return true; -} - - - - - -void cChestEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - Json::Value AllSlots; - for (int i = m_Contents.GetNumSlots() - 1; i >= 0; i--) - { - Json::Value Slot; - m_Contents.GetSlot(i).GetJson(Slot); - AllSlots.append(Slot); - } - a_Value["Slots"] = AllSlots; -} - - - - - void cChestEntity::SendTo(cClientHandle & a_Client) { // The chest entity doesn't need anything sent to the client when it's created / gets in the viewdistance diff --git a/src/BlockEntities/ChestEntity.h b/src/BlockEntities/ChestEntity.h index fa36e08be..af5d851a8 100644 --- a/src/BlockEntities/ChestEntity.h +++ b/src/BlockEntities/ChestEntity.h @@ -39,11 +39,8 @@ public: virtual ~cChestEntity(); static const char * GetClassStatic(void) { return "cChestEntity"; } - - bool LoadFromJson(const Json::Value & a_Value); // cBlockEntity overrides: - virtual void SaveToJson(Json::Value & a_Value) override; virtual void SendTo(cClientHandle & a_Client) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/CommandBlockEntity.cpp b/src/BlockEntities/CommandBlockEntity.cpp index 318874a9b..1a5a3f01e 100644 --- a/src/BlockEntities/CommandBlockEntity.cpp +++ b/src/BlockEntities/CommandBlockEntity.cpp @@ -152,38 +152,6 @@ void cCommandBlockEntity::SendTo(cClientHandle & a_Client) -bool cCommandBlockEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - m_Command = a_Value.get("Command", "").asString(); - m_LastOutput = a_Value.get("LastOutput", "").asString(); - m_Result = (NIBBLETYPE)a_Value.get("SuccessCount", 0).asInt(); - - return true; -} - - - - - -void cCommandBlockEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - a_Value["Command"] = m_Command; - a_Value["LastOutput"] = m_LastOutput; - a_Value["SuccessCount"] = m_Result; -} - - - - - void cCommandBlockEntity::Execute() { ASSERT(m_World != NULL); // Execute should not be called before the command block is attached to a world diff --git a/src/BlockEntities/CommandBlockEntity.h b/src/BlockEntities/CommandBlockEntity.h index 22cd44322..939f38610 100644 --- a/src/BlockEntities/CommandBlockEntity.h +++ b/src/BlockEntities/CommandBlockEntity.h @@ -39,9 +39,6 @@ public: /// Creates a new empty command block entity cCommandBlockEntity(int a_X, int a_Y, int a_Z, cWorld * a_World); - bool LoadFromJson( const Json::Value& a_Value); - virtual void SaveToJson(Json::Value& a_Value) override; - virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void SendTo(cClientHandle & a_Client) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/DropSpenserEntity.cpp b/src/BlockEntities/DropSpenserEntity.cpp index 05c7403e7..dac951b27 100644 --- a/src/BlockEntities/DropSpenserEntity.cpp +++ b/src/BlockEntities/DropSpenserEntity.cpp @@ -142,54 +142,6 @@ bool cDropSpenserEntity::Tick(float a_Dt, cChunk & a_Chunk) -bool cDropSpenserEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - Json::Value AllSlots = a_Value.get("Slots", 0); - int SlotIdx = 0; - for (Json::Value::iterator itr = AllSlots.begin(); itr != AllSlots.end(); ++itr) - { - cItem Contents; - Contents.FromJson(*itr); - m_Contents.SetSlot(SlotIdx, Contents); - SlotIdx++; - if (SlotIdx >= m_Contents.GetNumSlots()) - { - return true; - } - } - - return true; -} - - - - - -void cDropSpenserEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - Json::Value AllSlots; - int NumSlots = m_Contents.GetNumSlots(); - for (int i = 0; i < NumSlots; i++) - { - Json::Value Slot; - m_Contents.GetSlot(i).GetJson(Slot); - AllSlots.append(Slot); - } - a_Value["Slots"] = AllSlots; -} - - - - - void cDropSpenserEntity::SendTo(cClientHandle & a_Client) { // Nothing needs to be sent diff --git a/src/BlockEntities/DropSpenserEntity.h b/src/BlockEntities/DropSpenserEntity.h index c70cd0531..23f0ae89a 100644 --- a/src/BlockEntities/DropSpenserEntity.h +++ b/src/BlockEntities/DropSpenserEntity.h @@ -49,11 +49,8 @@ public: virtual ~cDropSpenserEntity(); static const char * GetClassStatic(void) { return "cDropSpenserEntity"; } - - bool LoadFromJson(const Json::Value & a_Value); // cBlockEntity overrides: - virtual void SaveToJson(Json::Value & a_Value) override; virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void SendTo(cClientHandle & a_Client) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/EnderChestEntity.h b/src/BlockEntities/EnderChestEntity.h index 311af8d76..2719eb5e4 100644 --- a/src/BlockEntities/EnderChestEntity.h +++ b/src/BlockEntities/EnderChestEntity.h @@ -25,7 +25,6 @@ public: // cBlockEntity overrides: virtual void UsedBy(cPlayer * a_Player) override; - virtual void SaveToJson(Json::Value & a_Value) override { UNUSED(a_Value); } virtual void SendTo(cClientHandle & a_Client) override { UNUSED(a_Client); } static void LoadFromJson(const Json::Value & a_Value, cItemGrid & a_Grid); diff --git a/src/BlockEntities/FlowerPotEntity.cpp b/src/BlockEntities/FlowerPotEntity.cpp index d2bc59d34..01560f814 100644 --- a/src/BlockEntities/FlowerPotEntity.cpp +++ b/src/BlockEntities/FlowerPotEntity.cpp @@ -72,37 +72,6 @@ void cFlowerPotEntity::Destroy(void) -bool cFlowerPotEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - m_Item = cItem(); - m_Item.FromJson(a_Value.get("Item", 0)); - - return true; -} - - - - - -void cFlowerPotEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - Json::Value Item; - m_Item.GetJson(Item); - a_Value["Item"] = Item; -} - - - - - bool cFlowerPotEntity::IsFlower(short m_ItemType, short m_ItemData) { switch (m_ItemType) diff --git a/src/BlockEntities/FlowerPotEntity.h b/src/BlockEntities/FlowerPotEntity.h index b86f9c840..b68d3b118 100644 --- a/src/BlockEntities/FlowerPotEntity.h +++ b/src/BlockEntities/FlowerPotEntity.h @@ -38,9 +38,6 @@ public: /** Creates a new flowerpot entity at the specified block coords. a_World may be NULL */ cFlowerPotEntity(int a_BlocX, int a_BlockY, int a_BlockZ, cWorld * a_World); - - bool LoadFromJson( const Json::Value& a_Value); - virtual void SaveToJson(Json::Value& a_Value) override; virtual void Destroy(void) override; diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index fb88e9b35..4452fc00a 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -129,60 +129,6 @@ bool cFurnaceEntity::Tick(float a_Dt, cChunk & a_Chunk) -bool cFurnaceEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - Json::Value AllSlots = a_Value.get("Slots", 0); - int SlotIdx = 0; - for (Json::Value::iterator itr = AllSlots.begin(); itr != AllSlots.end(); ++itr) - { - cItem Item; - Item.FromJson(*itr); - SetSlot(SlotIdx, Item); - SlotIdx++; - } - - m_NeedCookTime = (int)(a_Value.get("CookTime", 0).asDouble() / 50); - m_TimeCooked = (int)(a_Value.get("TimeCooked", 0).asDouble() / 50); - m_FuelBurnTime = (int)(a_Value.get("BurnTime", 0).asDouble() / 50); - m_TimeBurned = (int)(a_Value.get("TimeBurned", 0).asDouble() / 50); - - return true; -} - - - - - -void cFurnaceEntity::SaveToJson( Json::Value& a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - Json::Value AllSlots; - int NumSlots = m_Contents.GetNumSlots(); - for (int i = 0; i < NumSlots; i++) - { - Json::Value Slot; - m_Contents.GetSlot(i).GetJson(Slot); - AllSlots.append(Slot); - } - a_Value["Slots"] = AllSlots; - - a_Value["CookTime"] = m_NeedCookTime * 50; - a_Value["TimeCooked"] = m_TimeCooked * 50; - a_Value["BurnTime"] = m_FuelBurnTime * 50; - a_Value["TimeBurned"] = m_TimeBurned * 50; -} - - - - - void cFurnaceEntity::SendTo(cClientHandle & a_Client) { // Nothing needs to be sent diff --git a/src/BlockEntities/FurnaceEntity.h b/src/BlockEntities/FurnaceEntity.h index 7ac25cf52..ed3317af6 100644 --- a/src/BlockEntities/FurnaceEntity.h +++ b/src/BlockEntities/FurnaceEntity.h @@ -44,11 +44,8 @@ public: virtual ~cFurnaceEntity(); static const char * GetClassStatic() { return "cFurnaceEntity"; } - - bool LoadFromJson(const Json::Value & a_Value); // cBlockEntity overrides: - virtual void SaveToJson(Json::Value & a_Value) override; virtual void SendTo(cClientHandle & a_Client) override; virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/HopperEntity.cpp b/src/BlockEntities/HopperEntity.cpp index 444378c92..103f516fc 100644 --- a/src/BlockEntities/HopperEntity.cpp +++ b/src/BlockEntities/HopperEntity.cpp @@ -70,17 +70,6 @@ bool cHopperEntity::Tick(float a_Dt, cChunk & a_Chunk) -void cHopperEntity::SaveToJson(Json::Value & a_Value) -{ - UNUSED(a_Value); - // TODO - LOGWARNING("%s: Not implemented yet", __FUNCTION__); -} - - - - - void cHopperEntity::SendTo(cClientHandle & a_Client) { // The hopper entity doesn't need anything sent to the client when it's created / gets in the viewdistance diff --git a/src/BlockEntities/HopperEntity.h b/src/BlockEntities/HopperEntity.h index 8e856fcda..5d06581c2 100644 --- a/src/BlockEntities/HopperEntity.h +++ b/src/BlockEntities/HopperEntity.h @@ -49,7 +49,6 @@ protected: // cBlockEntity overrides: virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; - virtual void SaveToJson(Json::Value & a_Value) override; virtual void SendTo(cClientHandle & a_Client) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/JukeboxEntity.cpp b/src/BlockEntities/JukeboxEntity.cpp index 1131b99b0..bb9b335e0 100644 --- a/src/BlockEntities/JukeboxEntity.cpp +++ b/src/BlockEntities/JukeboxEntity.cpp @@ -117,31 +117,3 @@ void cJukeboxEntity::SetRecord(int a_Record) - -bool cJukeboxEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - m_Record = a_Value.get("Record", 0).asInt(); - - return true; -} - - - - - -void cJukeboxEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - a_Value["Record"] = m_Record; -} - - - - diff --git a/src/BlockEntities/JukeboxEntity.h b/src/BlockEntities/JukeboxEntity.h index a6fdf3c7e..49d2faa89 100644 --- a/src/BlockEntities/JukeboxEntity.h +++ b/src/BlockEntities/JukeboxEntity.h @@ -29,9 +29,6 @@ public: cJukeboxEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual ~cJukeboxEntity(); - bool LoadFromJson(const Json::Value & a_Value); - virtual void SaveToJson(Json::Value & a_Value) override; - // tolua_begin int GetRecord(void); diff --git a/src/BlockEntities/MobHeadEntity.cpp b/src/BlockEntities/MobHeadEntity.cpp index 9a1a40abe..67e13ffb2 100644 --- a/src/BlockEntities/MobHeadEntity.cpp +++ b/src/BlockEntities/MobHeadEntity.cpp @@ -77,35 +77,3 @@ void cMobHeadEntity::SendTo(cClientHandle & a_Client) - -bool cMobHeadEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - m_Type = static_cast(a_Value.get("Type", 0).asInt()); - m_Rotation = static_cast(a_Value.get("Rotation", 0).asInt()); - m_Owner = a_Value.get("Owner", "").asString(); - - return true; -} - - - - - -void cMobHeadEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - a_Value["Type"] = m_Type; - a_Value["Rotation"] = m_Rotation; - a_Value["Owner"] = m_Owner; -} - - - - diff --git a/src/BlockEntities/MobHeadEntity.h b/src/BlockEntities/MobHeadEntity.h index 45fa0d951..fcdeaa8a6 100644 --- a/src/BlockEntities/MobHeadEntity.h +++ b/src/BlockEntities/MobHeadEntity.h @@ -37,9 +37,6 @@ public: /** Creates a new mob head entity at the specified block coords. a_World may be NULL */ cMobHeadEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); - bool LoadFromJson( const Json::Value& a_Value); - virtual void SaveToJson(Json::Value& a_Value) override; - // tolua_begin /** Set the Type */ diff --git a/src/BlockEntities/NoteEntity.cpp b/src/BlockEntities/NoteEntity.cpp index ecbedbcb1..a9af13c55 100644 --- a/src/BlockEntities/NoteEntity.cpp +++ b/src/BlockEntities/NoteEntity.cpp @@ -124,32 +124,3 @@ void cNoteEntity::IncrementPitch(void) - -bool cNoteEntity::LoadFromJson(const Json::Value & a_Value) -{ - - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - m_Pitch = (char)a_Value.get("p", 0).asInt(); - - return true; -} - - - - - -void cNoteEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - a_Value["p"] = m_Pitch; -} - - - - diff --git a/src/BlockEntities/NoteEntity.h b/src/BlockEntities/NoteEntity.h index f538de060..d1ffa126a 100644 --- a/src/BlockEntities/NoteEntity.h +++ b/src/BlockEntities/NoteEntity.h @@ -44,9 +44,6 @@ public: cNoteEntity(int a_X, int a_Y, int a_Z, cWorld * a_World); virtual ~cNoteEntity() {} - bool LoadFromJson(const Json::Value & a_Value); - virtual void SaveToJson(Json::Value & a_Value) override; - // tolua_begin char GetPitch(void); diff --git a/src/BlockEntities/SignEntity.cpp b/src/BlockEntities/SignEntity.cpp index 423d254d2..d048d0218 100644 --- a/src/BlockEntities/SignEntity.cpp +++ b/src/BlockEntities/SignEntity.cpp @@ -22,7 +22,6 @@ cSignEntity::cSignEntity(BLOCKTYPE a_BlockType, int a_X, int a_Y, int a_Z, cWorl -// It don't do anything when 'used' void cSignEntity::UsedBy(cPlayer * a_Player) { UNUSED(a_Player); @@ -80,37 +79,3 @@ void cSignEntity::SendTo(cClientHandle & a_Client) - -bool cSignEntity::LoadFromJson(const Json::Value & a_Value) -{ - m_PosX = a_Value.get("x", 0).asInt(); - m_PosY = a_Value.get("y", 0).asInt(); - m_PosZ = a_Value.get("z", 0).asInt(); - - m_Line[0] = a_Value.get("Line1", "").asString(); - m_Line[1] = a_Value.get("Line2", "").asString(); - m_Line[2] = a_Value.get("Line3", "").asString(); - m_Line[3] = a_Value.get("Line4", "").asString(); - - return true; -} - - - - - -void cSignEntity::SaveToJson(Json::Value & a_Value) -{ - a_Value["x"] = m_PosX; - a_Value["y"] = m_PosY; - a_Value["z"] = m_PosZ; - - a_Value["Line1"] = m_Line[0]; - a_Value["Line2"] = m_Line[1]; - a_Value["Line3"] = m_Line[2]; - a_Value["Line4"] = m_Line[3]; -} - - - - diff --git a/src/BlockEntities/SignEntity.h b/src/BlockEntities/SignEntity.h index 33af100a4..53c43b758 100644 --- a/src/BlockEntities/SignEntity.h +++ b/src/BlockEntities/SignEntity.h @@ -37,9 +37,6 @@ public: /// Creates a new empty sign entity at the specified block coords and block type (wall or standing). a_World may be NULL cSignEntity(BLOCKTYPE a_BlockType, int a_X, int a_Y, int a_Z, cWorld * a_World); - bool LoadFromJson( const Json::Value& a_Value); - virtual void SaveToJson(Json::Value& a_Value) override; - // tolua_begin /// Sets all the sign's lines diff --git a/src/WorldStorage/CMakeLists.txt b/src/WorldStorage/CMakeLists.txt index a00ff3b2f..59193db2a 100644 --- a/src/WorldStorage/CMakeLists.txt +++ b/src/WorldStorage/CMakeLists.txt @@ -14,7 +14,6 @@ SET (SRCS ScoreboardSerializer.cpp StatSerializer.cpp WSSAnvil.cpp - WSSCompact.cpp WorldStorage.cpp) SET (HDRS @@ -27,7 +26,6 @@ SET (HDRS ScoreboardSerializer.h StatSerializer.h WSSAnvil.h - WSSCompact.h WorldStorage.h) if(NOT MSVC) diff --git a/src/WorldStorage/WSSCompact.cpp b/src/WorldStorage/WSSCompact.cpp deleted file mode 100644 index 6760186b2..000000000 --- a/src/WorldStorage/WSSCompact.cpp +++ /dev/null @@ -1,1066 +0,0 @@ - -// WSSCompact.cpp - -// Interfaces to the cWSSCompact class representing the "compact" storage schema (PAK-files) - -#include "Globals.h" -#include "WSSCompact.h" -#include "../World.h" -#include "zlib/zlib.h" -#include "json/json.h" -#include "../StringCompression.h" -#include "../BlockEntities/BeaconEntity.h" -#include "../BlockEntities/ChestEntity.h" -#include "../BlockEntities/CommandBlockEntity.h" -#include "../BlockEntities/DispenserEntity.h" -#include "../BlockEntities/FlowerPotEntity.h" -#include "../BlockEntities/FurnaceEntity.h" -#include "../BlockEntities/JukeboxEntity.h" -#include "../BlockEntities/MobHeadEntity.h" -#include "../BlockEntities/NoteEntity.h" -#include "../BlockEntities/SignEntity.h" -#include "../SetChunkData.h" - - - - - -#pragma pack(push, 1) -/// The chunk header, as stored in the file: -struct cWSSCompact::sChunkHeader -{ - int m_ChunkX; - int m_ChunkZ; - int m_CompressedSize; - int m_UncompressedSize; -} ; -#pragma pack(pop) - - - - - -/// The maximum number of PAK files that are cached -const size_t MAX_PAK_FILES = 16; - -/// The maximum number of unsaved chunks before the cPAKFile saves them to disk -const int MAX_DIRTY_CHUNKS = 16; - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cJsonChunkSerializer: - -cJsonChunkSerializer::cJsonChunkSerializer(void) : - m_HasJsonData(false) -{ -} - - - - - -void cJsonChunkSerializer::Entity(cEntity * a_Entity) -{ - // TODO: a_Entity->SaveToJson(m_Root); -} - - - - - -void cJsonChunkSerializer::BlockEntity(cBlockEntity * a_BlockEntity) -{ - const char * SaveInto = NULL; - switch (a_BlockEntity->GetBlockType()) - { - case E_BLOCK_BEACON: SaveInto = "Beacons"; break; - case E_BLOCK_CHEST: SaveInto = "Chests"; break; - case E_BLOCK_DISPENSER: SaveInto = "Dispensers"; break; - case E_BLOCK_DROPPER: SaveInto = "Droppers"; break; - case E_BLOCK_FLOWER_POT: SaveInto = "FlowerPots"; break; - case E_BLOCK_FURNACE: SaveInto = "Furnaces"; break; - case E_BLOCK_SIGN_POST: SaveInto = "Signs"; break; - case E_BLOCK_WALLSIGN: SaveInto = "Signs"; break; - case E_BLOCK_NOTE_BLOCK: SaveInto = "Notes"; break; - case E_BLOCK_JUKEBOX: SaveInto = "Jukeboxes"; break; - case E_BLOCK_COMMAND_BLOCK: SaveInto = "CommandBlocks"; break; - case E_BLOCK_HEAD: SaveInto = "MobHeads"; break; - - default: - { - ASSERT(!"Unhandled blocktype in BlockEntities list while saving to JSON"); - break; - } - } // switch (BlockEntity->GetBlockType()) - if (SaveInto == NULL) - { - return; - } - - Json::Value val; - a_BlockEntity->SaveToJson(val); - m_Root[SaveInto].append(val); - m_HasJsonData = true; -} - - - - - -void cJsonChunkSerializer::LightIsValid(bool a_IsLightValid) -{ - if (a_IsLightValid) - { - m_Root["IsLightValid"] = true; - m_HasJsonData = true; - } -} - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cWSSCompact: - -cWSSCompact::~cWSSCompact() -{ - for (cPAKFiles::iterator itr = m_PAKFiles.begin(); itr != m_PAKFiles.end(); ++itr) - { - delete *itr; - } -} - - - - - -bool cWSSCompact::LoadChunk(const cChunkCoords & a_Chunk) -{ - AString ChunkData; - int UncompressedSize = 0; - if (!GetChunkData(a_Chunk, UncompressedSize, ChunkData)) - { - // The reason for failure is already printed in GetChunkData() - return false; - } - - return LoadChunkFromData(a_Chunk, UncompressedSize, ChunkData, m_World); -} - - - - - -bool cWSSCompact::SaveChunk(const cChunkCoords & a_Chunk) -{ - cCSLock Lock(m_CS); - - cPAKFile * f = LoadPAKFile(a_Chunk); - if (f == NULL) - { - // For some reason we couldn't locate the file - LOG("Cannot locate a proper PAK file for chunk [%d, %d]", a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ); - return false; - } - return f->SaveChunk(a_Chunk, m_World); -} - - - - - -cWSSCompact::cPAKFile * cWSSCompact::LoadPAKFile(const cChunkCoords & a_Chunk) -{ - // ASSUMES that m_CS has been locked - - // We need to retain this weird conversion code, because some edge chunks are in the wrong PAK file - const int LayerX = FAST_FLOOR_DIV(a_Chunk.m_ChunkX, 32); - const int LayerZ = FAST_FLOOR_DIV(a_Chunk.m_ChunkZ, 32); - - // Is it already cached? - for (cPAKFiles::iterator itr = m_PAKFiles.begin(); itr != m_PAKFiles.end(); ++itr) - { - if (((*itr) != NULL) && ((*itr)->GetLayerX() == LayerX) && ((*itr)->GetLayerZ() == LayerZ)) - { - // Move the file to front and return it: - cPAKFile * f = *itr; - if (itr != m_PAKFiles.begin()) - { - m_PAKFiles.erase(itr); - m_PAKFiles.push_front(f); - } - return f; - } - } - - // Load it anew: - AString FileName; - Printf(FileName, "%s/X%i_Z%i.pak", m_World->GetName().c_str(), LayerX, LayerZ); - cPAKFile * f = new cPAKFile(FileName, LayerX, LayerZ, m_CompressionFactor); - if (f == NULL) - { - return NULL; - } - m_PAKFiles.push_front(f); - - // If there are too many PAK files cached, delete the last one used: - if (m_PAKFiles.size() > MAX_PAK_FILES) - { - delete m_PAKFiles.back(); - m_PAKFiles.pop_back(); - } - return f; -} - - - - - -bool cWSSCompact::GetChunkData(const cChunkCoords & a_Chunk, int & a_UncompressedSize, AString & a_Data) -{ - cCSLock Lock(m_CS); - cPAKFile * f = LoadPAKFile(a_Chunk); - if (f == NULL) - { - return false; - } - return f->GetChunkData(a_Chunk, a_UncompressedSize, a_Data); -} - - - - - -/* -// TODO: Rewrite saving to use the same principles as loading -bool cWSSCompact::SetChunkData(const cChunkCoords & a_Chunk, int a_UncompressedSize, const AString & a_Data) -{ - cCSLock Lock(m_CS); - cPAKFile * f = LoadPAKFile(a_Chunk); - if (f == NULL) - { - return false; - } - return f->SetChunkData(a_Chunk, a_UncompressedSize, a_Data); -} -*/ - - - - - -bool cWSSCompact::EraseChunkData(const cChunkCoords & a_Chunk) -{ - cCSLock Lock(m_CS); - cPAKFile * f = LoadPAKFile(a_Chunk); - if (f == NULL) - { - return false; - } - return f->EraseChunkData(a_Chunk); -} - - - - - -void cWSSCompact::LoadEntitiesFromJson(Json::Value & a_Value, cEntityList & a_Entities, cBlockEntityList & a_BlockEntities, cWorld * a_World) -{ - // Load beacon: - Json::Value AllBeacons = a_Value.get("Beacons", Json::nullValue); - if (!AllBeacons.empty()) - { - for (Json::Value::iterator itr = AllBeacons.begin(); itr != AllBeacons.end(); ++itr) - { - std::auto_ptr BeaconEntity(new cBeaconEntity(0, 0, 0, a_World)); - if (!BeaconEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING BEACON FROM JSON!"); - } - else - { - a_BlockEntities.push_back(BeaconEntity.release()); - } - } // for itr - AllBeacons[] - } - - // Load chests: - Json::Value AllChests = a_Value.get("Chests", Json::nullValue); - if (!AllChests.empty()) - { - for (Json::Value::iterator itr = AllChests.begin(); itr != AllChests.end(); ++itr) - { - std::auto_ptr ChestEntity(new cChestEntity(0, 0, 0, a_World, E_BLOCK_CHEST)); - if (!ChestEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING CHEST FROM JSON!"); - } - else - { - a_BlockEntities.push_back(ChestEntity.release()); - } - } // for itr - AllChests[] - } - - // Load dispensers: - Json::Value AllDispensers = a_Value.get("Dispensers", Json::nullValue); - for (Json::Value::iterator itr = AllDispensers.begin(); itr != AllDispensers.end(); ++itr) - { - std::auto_ptr DispenserEntity(new cDispenserEntity(0, 0, 0, a_World)); - if (!DispenserEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING DISPENSER FROM JSON!"); - } - else - { - a_BlockEntities.push_back(DispenserEntity.release()); - } - } // for itr - AllDispensers[] - - // Load Flowerpots: - Json::Value AllFlowerPots = a_Value.get("FlowerPots", Json::nullValue); - for (Json::Value::iterator itr = AllFlowerPots.begin(); itr != AllFlowerPots.end(); ++itr) - { - std::auto_ptr FlowerPotEntity(new cFlowerPotEntity(0, 0, 0, a_World)); - if (!FlowerPotEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING FLOWERPOT FROM JSON!"); - } - else - { - a_BlockEntities.push_back(FlowerPotEntity.release()); - } - } // for itr - AllFlowerPots[] - - // Load furnaces: - Json::Value AllFurnaces = a_Value.get("Furnaces", Json::nullValue); - for (Json::Value::iterator itr = AllFurnaces.begin(); itr != AllFurnaces.end(); ++itr) - { - // TODO: The block type and meta aren't correct, there's no way to get them here - std::auto_ptr FurnaceEntity(new cFurnaceEntity(0, 0, 0, E_BLOCK_FURNACE, 0, a_World)); - if (!FurnaceEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING FURNACE FROM JSON!"); - } - else - { - a_BlockEntities.push_back(FurnaceEntity.release()); - } - } // for itr - AllFurnaces[] - - // Load signs: - Json::Value AllSigns = a_Value.get("Signs", Json::nullValue); - for (Json::Value::iterator itr = AllSigns.begin(); itr != AllSigns.end(); ++itr) - { - std::auto_ptr SignEntity(new cSignEntity(E_BLOCK_SIGN_POST, 0, 0, 0, a_World)); - if (!SignEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING SIGN FROM JSON!"); - } - else - { - a_BlockEntities.push_back(SignEntity.release()); - } - } // for itr - AllSigns[] - - // Load note blocks: - Json::Value AllNotes = a_Value.get("Notes", Json::nullValue); - for (Json::Value::iterator itr = AllNotes.begin(); itr != AllNotes.end(); ++itr) - { - std::auto_ptr NoteEntity(new cNoteEntity(0, 0, 0, a_World)); - if (!NoteEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING NOTE BLOCK FROM JSON!"); - } - else - { - a_BlockEntities.push_back(NoteEntity.release()); - } - } // for itr - AllNotes[] - - // Load jukeboxes: - Json::Value AllJukeboxes = a_Value.get("Jukeboxes", Json::nullValue); - for (Json::Value::iterator itr = AllJukeboxes.begin(); itr != AllJukeboxes.end(); ++itr) - { - std::auto_ptr JukeboxEntity(new cJukeboxEntity(0, 0, 0, a_World)); - if (!JukeboxEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING JUKEBOX FROM JSON!"); - } - else - { - a_BlockEntities.push_back(JukeboxEntity.release()); - } - } // for itr - AllJukeboxes[] - - // Load command blocks: - Json::Value AllCommandBlocks = a_Value.get("CommandBlocks", Json::nullValue); - for (Json::Value::iterator itr = AllCommandBlocks.begin(); itr != AllCommandBlocks.end(); ++itr) - { - std::auto_ptr CommandBlockEntity(new cCommandBlockEntity(0, 0, 0, a_World)); - if (!CommandBlockEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING COMMAND BLOCK FROM JSON!"); - } - else - { - a_BlockEntities.push_back(CommandBlockEntity.release()); - } - } // for itr - AllCommandBlocks[] - - // Load mob heads: - Json::Value AllMobHeads = a_Value.get("MobHeads", Json::nullValue); - for (Json::Value::iterator itr = AllMobHeads.begin(); itr != AllMobHeads.end(); ++itr) - { - std::auto_ptr MobHeadEntity(new cMobHeadEntity(0, 0, 0, a_World)); - if (!MobHeadEntity->LoadFromJson(*itr)) - { - LOGWARNING("ERROR READING MOB HEAD FROM JSON!"); - } - else - { - a_BlockEntities.push_back(MobHeadEntity.release()); - } - } // for itr - AllMobHeads[] -} - - - - - -//////////////////////////////////////////////////////////////////////////////// -// cWSSCompact::cPAKFile - -#define READ(Var) \ - if (f.Read(&Var, sizeof(Var)) != sizeof(Var)) \ - { \ - LOGERROR("ERROR READING %s FROM FILE %s (line %d); file offset %d", #Var, m_FileName.c_str(), __LINE__, f.Tell()); \ - return; \ - } - -cWSSCompact::cPAKFile::cPAKFile(const AString & a_FileName, int a_LayerX, int a_LayerZ, int a_CompressionFactor) : - m_FileName(a_FileName), - m_CompressionFactor(a_CompressionFactor), - m_LayerX(a_LayerX), - m_LayerZ(a_LayerZ), - m_NumDirty(0), - m_ChunkVersion( CHUNK_VERSION), // Init with latest version - m_PakVersion( PAK_VERSION) -{ - cFile f; - if (!f.Open(m_FileName, cFile::fmRead)) - { - return; - } - - // Read headers: - READ(m_PakVersion); - if (m_PakVersion != 1) - { - LOGERROR("File \"%s\" is in an unknown pak format (%d)", m_FileName.c_str(), m_PakVersion); - return; - } - - READ(m_ChunkVersion); - switch (m_ChunkVersion) - { - case 1: - { - m_ChunkSize.Set(16, 128, 16); - break; - } - case 2: - case 3: - { - m_ChunkSize.Set(16, 256, 16); - break; - } - default: - { - LOGERROR("File \"%s\" is in an unknown chunk format (%d)", m_FileName.c_str(), m_ChunkVersion); - return; - } - }; - - short NumChunks = 0; - READ(NumChunks); - - // Read chunk headers: - for (int i = 0; i < NumChunks; i++) - { - sChunkHeader * Header = new sChunkHeader; - - // Here we do not use the READ macro, as it does not free the resources - // allocated with new in case of error. - if (f.Read(Header, sizeof(*Header)) != sizeof(*Header)) - { - LOGERROR("ERROR READING %s FROM FILE %s (line %d); file offset %d", "Header", m_FileName.c_str(), __LINE__, f.Tell()); - delete Header; - Header = NULL; - return; - } - m_ChunkHeaders.push_back(Header); - } // for i - chunk headers - - // Read chunk data: - if (f.ReadRestOfFile(m_DataContents) == -1) - { - LOGERROR("Cannot read file \"%s\" contents", m_FileName.c_str()); - return; - } - - if (m_ChunkVersion == 1) // Convert chunks to version 2 - { - UpdateChunk1To2(); - } -#if AXIS_ORDER == AXIS_ORDER_XZY - if (m_ChunkVersion == 2) // Convert chunks to version 3 - { - UpdateChunk2To3(); - } -#endif -} - - - - - -cWSSCompact::cPAKFile::~cPAKFile() -{ - if (m_NumDirty > 0) - { - SynchronizeFile(); - } - for (sChunkHeaders::iterator itr = m_ChunkHeaders.begin(); itr != m_ChunkHeaders.end(); ++itr) - { - delete *itr; - } -} - - - - - -bool cWSSCompact::cPAKFile::GetChunkData(const cChunkCoords & a_Chunk, int & a_UncompressedSize, AString & a_Data) -{ - int ChunkX = a_Chunk.m_ChunkX; - int ChunkZ = a_Chunk.m_ChunkZ; - sChunkHeader * Header = NULL; - int Offset = 0; - for (sChunkHeaders::iterator itr = m_ChunkHeaders.begin(); itr != m_ChunkHeaders.end(); ++itr) - { - if (((*itr)->m_ChunkX == ChunkX) && ((*itr)->m_ChunkZ == ChunkZ)) - { - Header = *itr; - break; - } - Offset += (*itr)->m_CompressedSize; - } - if ((Header == NULL) || (Offset + Header->m_CompressedSize > (int)m_DataContents.size())) - { - // Chunk not found / data invalid - return false; - } - - a_UncompressedSize = Header->m_UncompressedSize; - a_Data.assign(m_DataContents, Offset, Header->m_CompressedSize); - return true; -} - - - - - -bool cWSSCompact::cPAKFile::SaveChunk(const cChunkCoords & a_Chunk, cWorld * a_World) -{ - if (!SaveChunkToData(a_Chunk, a_World)) - { - return false; - } - if (m_NumDirty > MAX_DIRTY_CHUNKS) - { - SynchronizeFile(); - } - return true; -} - - - - - -void cWSSCompact::cPAKFile::UpdateChunk1To2() -{ - int Offset = 0; - AString NewDataContents; - int ChunksConverted = 0; - for (sChunkHeaders::iterator itr = m_ChunkHeaders.begin(); itr != m_ChunkHeaders.end(); ++itr) - { - sChunkHeader * Header = *itr; - - if (ChunksConverted % 32 == 0) - { - LOGINFO("Updating \"%s\" version 1 to version 2: " SIZE_T_FMT " %%", m_FileName.c_str(), (ChunksConverted * 100) / m_ChunkHeaders.size()); - } - ChunksConverted++; - - AString Data; - int UncompressedSize = Header->m_UncompressedSize; - Data.assign(m_DataContents, Offset, Header->m_CompressedSize); - Offset += Header->m_CompressedSize; - - // Crude data integrity check: - int ExpectedSize = (16*128*16)*2 + (16*128*16)/2; // For version 1 - if (UncompressedSize < ExpectedSize) - { - LOGWARNING("Chunk [%d, %d] has too short decompressed data (%d bytes out of %d needed), erasing", - Header->m_ChunkX, Header->m_ChunkZ, - UncompressedSize, ExpectedSize - ); - Offset += Header->m_CompressedSize; - continue; - } - - // Decompress the data: - AString UncompressedData; - { - int errorcode = UncompressString(Data.data(), Data.size(), UncompressedData, (size_t)UncompressedSize); - if (errorcode != Z_OK) - { - LOGERROR("Error %d decompressing data for chunk [%d, %d]", - errorcode, - Header->m_ChunkX, Header->m_ChunkZ - ); - Offset += Header->m_CompressedSize; - continue; - } - } - - if (UncompressedSize != (int)UncompressedData.size()) - { - LOGWARNING("Uncompressed data size differs (exp %d bytes, got " SIZE_T_FMT ") for chunk [%d, %d]", - UncompressedSize, UncompressedData.size(), - Header->m_ChunkX, Header->m_ChunkZ - ); - Offset += Header->m_CompressedSize; - continue; - } - - - // Old version is 128 blocks high with YZX axis order - char ConvertedData[cChunkDef::BlockDataSize]; - int Index = 0; - unsigned int InChunkOffset = 0; - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) - { - for (int y = 0; y < 128; ++y) - { - ConvertedData[Index++] = UncompressedData[y + z * 128 + x * 128 * 16 + InChunkOffset]; - } - // Add 128 empty blocks after an old y column - memset(ConvertedData + Index, E_BLOCK_AIR, 128); - Index += 128; - } - InChunkOffset += (16 * 128 * 16); - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) // Metadata - { - for (int y = 0; y < 64; ++y) - { - ConvertedData[Index++] = UncompressedData[y + z * 64 + x * 64 * 16 + InChunkOffset]; - } - memset(ConvertedData + Index, 0, 64); - Index += 64; - } - InChunkOffset += (16 * 128 * 16) / 2; - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) // Block light - { - for (int y = 0; y < 64; ++y) - { - ConvertedData[Index++] = UncompressedData[y + z * 64 + x * 64 * 16 + InChunkOffset]; - } - memset(ConvertedData + Index, 0, 64); - Index += 64; - } - InChunkOffset += (16*128*16)/2; - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) // Sky light - { - for (int y = 0; y < 64; ++y) - { - ConvertedData[Index++] = UncompressedData[y + z * 64 + x * 64 * 16 + InChunkOffset]; - } - memset(ConvertedData + Index, 0, 64); - Index += 64; - } - InChunkOffset += (16 * 128 * 16) / 2; - - AString Converted(ConvertedData, ARRAYCOUNT(ConvertedData)); - - // Add JSON data afterwards - if (UncompressedData.size() > InChunkOffset) - { - Converted.append( UncompressedData.begin() + InChunkOffset, UncompressedData.end()); - } - - // Re-compress data - AString CompressedData; - { - int errorcode = CompressString(Converted.data(), Converted.size(), CompressedData, m_CompressionFactor); - if (errorcode != Z_OK) - { - LOGERROR("Error %d compressing data for chunk [%d, %d]", - errorcode, - Header->m_ChunkX, Header->m_ChunkZ - ); - continue; - } - } - - // Save into file's cache - Header->m_UncompressedSize = (int)Converted.size(); - Header->m_CompressedSize = (int)CompressedData.size(); - NewDataContents.append(CompressedData); - } - - // Done converting - m_DataContents = NewDataContents; - m_ChunkVersion = 2; - SynchronizeFile(); - - LOGINFO("Updated \"%s\" version 1 to version 2", m_FileName.c_str()); -} - - - - - -void cWSSCompact::cPAKFile::UpdateChunk2To3() -{ - int Offset = 0; - AString NewDataContents; - int ChunksConverted = 0; - for (sChunkHeaders::iterator itr = m_ChunkHeaders.begin(); itr != m_ChunkHeaders.end(); ++itr) - { - sChunkHeader * Header = *itr; - - if (ChunksConverted % 32 == 0) - { - LOGINFO("Updating \"%s\" version 2 to version 3: " SIZE_T_FMT " %%", m_FileName.c_str(), (ChunksConverted * 100) / m_ChunkHeaders.size()); - } - ChunksConverted++; - - AString Data; - int UncompressedSize = Header->m_UncompressedSize; - Data.assign(m_DataContents, Offset, Header->m_CompressedSize); - Offset += Header->m_CompressedSize; - - // Crude data integrity check: - const int ExpectedSize = (16 * 256 * 16) * 2 + (16 * 256 * 16) / 2; // For version 2 - if (UncompressedSize < ExpectedSize) - { - LOGWARNING("Chunk [%d, %d] has too short decompressed data (%d bytes out of %d needed), erasing", - Header->m_ChunkX, Header->m_ChunkZ, - UncompressedSize, ExpectedSize - ); - Offset += Header->m_CompressedSize; - continue; - } - - // Decompress the data: - AString UncompressedData; - { - int errorcode = UncompressString(Data.data(), Data.size(), UncompressedData, (size_t)UncompressedSize); - if (errorcode != Z_OK) - { - LOGERROR("Error %d decompressing data for chunk [%d, %d]", - errorcode, - Header->m_ChunkX, Header->m_ChunkZ - ); - Offset += Header->m_CompressedSize; - continue; - } - } - - if (UncompressedSize != (int)UncompressedData.size()) - { - LOGWARNING("Uncompressed data size differs (exp %d bytes, got " SIZE_T_FMT ") for chunk [%d, %d]", - UncompressedSize, UncompressedData.size(), - Header->m_ChunkX, Header->m_ChunkZ - ); - Offset += Header->m_CompressedSize; - continue; - } - - char ConvertedData[ExpectedSize]; - memset(ConvertedData, 0, ExpectedSize); - - // Cannot use cChunk::MakeIndex because it might change again????????? - // For compatibility, use what we know is current - #define MAKE_3_INDEX( x, y, z) ( x + (z * 16) + (y * 16 * 16)) - - unsigned int InChunkOffset = 0; - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) for (int y = 0; y < 256; ++y) // YZX Loop order is important, in 1.1 Y was first then Z then X - { - ConvertedData[ MAKE_3_INDEX(x, y, z) ] = UncompressedData[InChunkOffset]; - ++InChunkOffset; - } // for y, z, x - - - unsigned int index2 = 0; - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) for (int y = 0; y < 256; ++y) - { - ConvertedData[ InChunkOffset + MAKE_3_INDEX(x, y, z)/2 ] |= ( (UncompressedData[ InChunkOffset + index2/2 ] >> ((index2&1)*4)) & 0x0f) << ((x&1)*4); - ++index2; - } - InChunkOffset += index2 / 2; - index2 = 0; - - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) for (int y = 0; y < 256; ++y) - { - ConvertedData[ InChunkOffset + MAKE_3_INDEX(x, y, z)/2 ] |= ( (UncompressedData[ InChunkOffset + index2/2 ] >> ((index2&1)*4)) & 0x0f) << ((x&1)*4); - ++index2; - } - InChunkOffset += index2 / 2; - index2 = 0; - - for (int x = 0; x < 16; ++x) for (int z = 0; z < 16; ++z) for (int y = 0; y < 256; ++y) - { - ConvertedData[ InChunkOffset + MAKE_3_INDEX(x, y, z)/2 ] |= ( (UncompressedData[ InChunkOffset + index2/2 ] >> ((index2&1)*4)) & 0x0f) << ((x&1)*4); - ++index2; - } - InChunkOffset += index2 / 2; - - AString Converted(ConvertedData, ExpectedSize); - - // Add JSON data afterwards - if (UncompressedData.size() > InChunkOffset) - { - Converted.append( UncompressedData.begin() + InChunkOffset, UncompressedData.end()); - } - - // Re-compress data - AString CompressedData; - { - int errorcode = CompressString(Converted.data(), Converted.size(), CompressedData, m_CompressionFactor); - if (errorcode != Z_OK) - { - LOGERROR("Error %d compressing data for chunk [%d, %d]", - errorcode, - Header->m_ChunkX, Header->m_ChunkZ - ); - continue; - } - } - - // Save into file's cache - Header->m_UncompressedSize = (int)Converted.size(); - Header->m_CompressedSize = (int)CompressedData.size(); - NewDataContents.append(CompressedData); - } - - // Done converting - m_DataContents = NewDataContents; - m_ChunkVersion = 3; - SynchronizeFile(); - - LOGINFO("Updated \"%s\" version 2 to version 3", m_FileName.c_str()); -} - - - - - -bool cWSSCompact::LoadChunkFromData(const cChunkCoords & a_Chunk, int a_UncompressedSize, const AString & a_Data, cWorld * a_World) -{ - // Crude data integrity check: - if (a_UncompressedSize < cChunkDef::BlockDataSize) - { - LOGWARNING("Chunk [%d, %d] has too short decompressed data (%d bytes out of %d needed), erasing", - a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ, - a_UncompressedSize, cChunkDef::BlockDataSize - ); - EraseChunkData(a_Chunk); - return false; - } - - // Decompress the data: - AString UncompressedData; - int errorcode = UncompressString(a_Data.data(), a_Data.size(), UncompressedData, (size_t)a_UncompressedSize); - if (errorcode != Z_OK) - { - LOGERROR("Error %d decompressing data for chunk [%d, %d]", - errorcode, - a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ - ); - return false; - } - - if (a_UncompressedSize != (int)UncompressedData.size()) - { - LOGWARNING("Uncompressed data size differs (exp %d bytes, got " SIZE_T_FMT ") for chunk [%d, %d]", - a_UncompressedSize, UncompressedData.size(), - a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ - ); - return false; - } - - cEntityList Entities; - cBlockEntityList BlockEntities; - bool IsLightValid = false; - - if (a_UncompressedSize > cChunkDef::BlockDataSize) - { - Json::Value root; // will contain the root value after parsing. - Json::Reader reader; - if (!reader.parse( UncompressedData.data() + cChunkDef::BlockDataSize, root, false)) - { - LOGERROR("Failed to parse trailing JSON in chunk [%d, %d]!", - a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ - ); - } - else - { - LoadEntitiesFromJson(root, Entities, BlockEntities, a_World); - IsLightValid = root.get("IsLightValid", false).asBool(); - } - } - - BLOCKTYPE * BlockData = (BLOCKTYPE *)UncompressedData.data(); - NIBBLETYPE * MetaData = (NIBBLETYPE *)(BlockData + MetaOffset); - NIBBLETYPE * BlockLight = (NIBBLETYPE *)(BlockData + LightOffset); - NIBBLETYPE * SkyLight = (NIBBLETYPE *)(BlockData + SkyLightOffset); - - a_World->QueueSetChunkData(cSetChunkDataPtr(new cSetChunkData( - a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ, - BlockData, MetaData, - IsLightValid ? BlockLight : NULL, - IsLightValid ? SkyLight : NULL, - NULL, NULL, - Entities, BlockEntities, - false - ))); - - return true; -} - - - - - -bool cWSSCompact::cPAKFile::EraseChunkData(const cChunkCoords & a_Chunk) -{ - int ChunkX = a_Chunk.m_ChunkX; - int ChunkZ = a_Chunk.m_ChunkZ; - int Offset = 0; - for (sChunkHeaders::iterator itr = m_ChunkHeaders.begin(); itr != m_ChunkHeaders.end(); ++itr) - { - if (((*itr)->m_ChunkX == ChunkX) && ((*itr)->m_ChunkZ == ChunkZ)) - { - m_DataContents.erase(Offset, (*itr)->m_CompressedSize); - delete *itr; - itr = m_ChunkHeaders.erase(itr); - return true; - } - Offset += (*itr)->m_CompressedSize; - } - - return false; -} - - - - - -bool cWSSCompact::cPAKFile::SaveChunkToData(const cChunkCoords & a_Chunk, cWorld * a_World) -{ - // Serialize the chunk: - cJsonChunkSerializer Serializer; - if (!a_World->GetChunkData(a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ, Serializer)) - { - // Chunk not valid - LOG("cWSSCompact: Trying to save chunk [%d, %d] that has no data, ignoring request.", a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ); - return false; - } - - AString Data; - Data.assign((const char *)Serializer.GetBlockData(), cChunkDef::BlockDataSize); - if (Serializer.HasJsonData()) - { - AString JsonData; - Json::StyledWriter writer; - JsonData = writer.write(Serializer.GetRoot()); - Data.append(JsonData); - } - - // Compress the data: - AString CompressedData; - int errorcode = CompressString(Data.data(), Data.size(), CompressedData, m_CompressionFactor); - if (errorcode != Z_OK) - { - LOGERROR("Error %i compressing data for chunk [%d, %d]", errorcode, a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ); - return false; - } - - // Erase any existing data for the chunk: - EraseChunkData(a_Chunk); - - // Save the header: - sChunkHeader * Header = new sChunkHeader; - if (Header == NULL) - { - LOGWARNING("Cannot create a new chunk header to save chunk [%d, %d]", a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ); - return false; - } - Header->m_CompressedSize = (int)CompressedData.size(); - Header->m_ChunkX = a_Chunk.m_ChunkX; - Header->m_ChunkZ = a_Chunk.m_ChunkZ; - Header->m_UncompressedSize = (int)Data.size(); - m_ChunkHeaders.push_back(Header); - - m_DataContents.append(CompressedData.data(), CompressedData.size()); - - m_NumDirty++; - return true; -} - - - - - -#define WRITE(Var) \ - if (f.Write(&Var, sizeof(Var)) != sizeof(Var)) \ - { \ - LOGERROR("cWSSCompact: ERROR writing %s to file \"%s\" (line %d); file offset %d", #Var, m_FileName.c_str(), __LINE__, f.Tell()); \ - return; \ - } - -void cWSSCompact::cPAKFile::SynchronizeFile(void) -{ - cFile f; - if (!f.Open(m_FileName, cFile::fmWrite)) - { - LOGERROR("Cannot open PAK file \"%s\" for writing", m_FileName.c_str()); - return; - } - - WRITE(m_PakVersion); - WRITE(m_ChunkVersion); - short NumChunks = (short)m_ChunkHeaders.size(); - WRITE(NumChunks); - for (sChunkHeaders::iterator itr = m_ChunkHeaders.begin(); itr != m_ChunkHeaders.end(); ++itr) - { - WRITE(**itr); - } - if (f.Write(m_DataContents.data(), m_DataContents.size()) != (int)m_DataContents.size()) - { - LOGERROR("cWSSCompact: ERROR writing chunk contents to file \"%s\" (line %d); file offset %d", m_FileName.c_str(), __LINE__, f.Tell()); - return; - } - m_NumDirty = 0; -} - - - - diff --git a/src/WorldStorage/WSSCompact.h b/src/WorldStorage/WSSCompact.h deleted file mode 100644 index 83e9cb49f..000000000 --- a/src/WorldStorage/WSSCompact.h +++ /dev/null @@ -1,157 +0,0 @@ - -// WSSCompact.h - -// Interfaces to the cWSSCompact class representing the "Compact" storage schema (PAK-files) - - - - - -#pragma once -#ifndef WSSCOMPACT_H_INCLUDED -#define WSSCOMPACT_H_INCLUDED - -#include "WorldStorage.h" -#include "../Vector3.h" -#include "json/json.h" -#include "ChunkDataCallback.h" - - - - - -/// Helper class for serializing a chunk into Json -class cJsonChunkSerializer : - public cChunkDataArrayCollector -{ -public: - - cJsonChunkSerializer(void); - - Json::Value & GetRoot (void) {return m_Root; } - BLOCKTYPE * GetBlockData(void) {return (BLOCKTYPE *)m_BlockData; } - bool HasJsonData (void) const {return m_HasJsonData; } - -protected: - - // NOTE: block data is serialized into inherited cChunkDataCollector's m_BlockData[] array - - // Entities and BlockEntities are serialized to Json - Json::Value m_Root; - bool m_HasJsonData; - - // cChunkDataCollector overrides: - virtual void Entity (cEntity * a_Entity) override; - virtual void BlockEntity (cBlockEntity * a_Entity) override; - virtual void LightIsValid (bool a_IsLightValid) override; -} ; - - - - - -class cWSSCompact : - public cWSSchema -{ -public: - cWSSCompact(cWorld * a_World, int a_CompressionFactor) : cWSSchema(a_World), m_CompressionFactor(a_CompressionFactor) {} - virtual ~cWSSCompact(); - -protected: - - enum - { - // Offsets to individual components in the joined blockdata array - MetaOffset = cChunkDef::NumBlocks, - LightOffset = MetaOffset + cChunkDef::NumBlocks / 2, - SkyLightOffset = LightOffset + cChunkDef::NumBlocks / 2, - } ; - - struct sChunkHeader; - typedef std::vector sChunkHeaders; - - /// Implements a cache for a single PAK file; implements lazy-write in order to be able to write multiple chunks fast - class cPAKFile - { - public: - - cPAKFile(const AString & a_FileName, int a_LayerX, int a_LayerZ, int a_CompressionFactor); - ~cPAKFile(); - - bool GetChunkData(const cChunkCoords & a_Chunk, int & a_UncompressedSize, AString & a_Data); - bool SetChunkData(const cChunkCoords & a_Chunk, int a_UncompressedSize, const AString & a_Data); - bool EraseChunkData(const cChunkCoords & a_Chunk); - - bool SaveChunk(const cChunkCoords & a_Chunk, cWorld * a_World); - - int GetLayerX(void) const {return m_LayerX; } - int GetLayerZ(void) const {return m_LayerZ; } - - static const int PAK_VERSION = 1; -#if AXIS_ORDER == AXIS_ORDER_XZY - static const int CHUNK_VERSION = 3; -#elif AXIS_ORDER == AXIS_ORDER_YZX - static const int CHUNK_VERSION = 2; -#endif - protected: - - AString m_FileName; - int m_CompressionFactor; - int m_LayerX; - int m_LayerZ; - - sChunkHeaders m_ChunkHeaders; - AString m_DataContents; // Data contents of the file, cached - - int m_NumDirty; // Number of chunks that were written into m_DataContents but not into the file - - Vector3i m_ChunkSize; // Is related to m_ChunkVersion - char m_ChunkVersion; - char m_PakVersion; - - bool SaveChunkToData(const cChunkCoords & a_Chunk, cWorld * a_World); // Saves the chunk to m_DataContents, updates headers and m_NumDirty - void SynchronizeFile(void); // Writes m_DataContents along with the headers to file, resets m_NumDirty - - void UpdateChunk1To2(void); // Height from 128 to 256 - void UpdateChunk2To3(void); // Axis order from YZX to XZY - } ; - - typedef std::list cPAKFiles; - - cCriticalSection m_CS; - cPAKFiles m_PAKFiles; // A MRU cache of PAK files - - int m_CompressionFactor; - - /// Loads the correct PAK file either from cache or from disk, manages the m_PAKFiles cache - cPAKFile * LoadPAKFile(const cChunkCoords & a_Chunk); - - /// Gets chunk data from the correct file; locks CS as needed - bool GetChunkData(const cChunkCoords & a_Chunk, int & a_UncompressedSize, AString & a_Data); - - /// Sets chunk data to the correct file; locks CS as needed - bool SetChunkData(const cChunkCoords & a_Chunk, int a_UncompressedSize, const AString & a_Data); - - /// Erases chunk data from the correct file; locks CS as needed - bool EraseChunkData(const cChunkCoords & a_Chunk); - - /// Loads the chunk from the data (no locking needed) - bool LoadChunkFromData(const cChunkCoords & a_Chunk, int a_UncompressedSize, const AString & a_Data, cWorld * a_World); - - void LoadEntitiesFromJson(Json::Value & a_Value, cEntityList & a_Entities, cBlockEntityList & a_BlockEntities, cWorld * a_World); - - // cWSSchema overrides: - virtual bool LoadChunk(const cChunkCoords & a_Chunk) override; - virtual bool SaveChunk(const cChunkCoords & a_Chunk) override; - virtual const AString GetName(void) const override {return "compact"; } -} ; - - - - - -#endif // WSSCOMPACT_H_INCLUDED - - - - diff --git a/src/WorldStorage/WorldStorage.cpp b/src/WorldStorage/WorldStorage.cpp index 179cf9393..c611bfd90 100644 --- a/src/WorldStorage/WorldStorage.cpp +++ b/src/WorldStorage/WorldStorage.cpp @@ -7,7 +7,6 @@ #include "Globals.h" #include "WorldStorage.h" -#include "WSSCompact.h" #include "WSSAnvil.h" #include "../World.h" #include "../Generating/ChunkGenerator.h" @@ -187,7 +186,6 @@ void cWorldStorage::InitSchemas(int a_StorageCompressionFactor) { // The first schema added is considered the default m_Schemas.push_back(new cWSSAnvil (m_World, a_StorageCompressionFactor)); - m_Schemas.push_back(new cWSSCompact (m_World, a_StorageCompressionFactor)); m_Schemas.push_back(new cWSSForgetful(m_World)); // Add new schemas here -- cgit v1.2.3 From e65e0f1795e170dc339d5062eb2322e4c673560d Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Wed, 1 Oct 2014 12:14:38 +0200 Subject: cClientHandle: Alpha-sorted the sending functions. --- src/ClientHandle.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 1f22762c0..20592c190 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -145,7 +145,9 @@ public: void SendCollectEntity (const cEntity & a_Entity, const cPlayer & a_Player); void SendDestroyEntity (const cEntity & a_Entity); void SendDisconnect (const AString & a_Reason); + void SendDisplayObjective (const AString & a_Objective, cScoreboard::eDisplaySlot a_Display); void SendEditSign (int a_BlockX, int a_BlockY, int a_BlockZ); + void SendEntityAnimation (const cEntity & a_Entity, char a_Animation); // tolua_export void SendEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration); void SendEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item); void SendEntityHeadLook (const cEntity & a_Entity); @@ -156,6 +158,8 @@ public: void SendEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ); void SendEntityStatus (const cEntity & a_Entity, char a_Status); void SendEntityVelocity (const cEntity & a_Entity); + void SendExperience (void); + void SendExperienceOrb (const cExpOrb & a_ExpOrb); void SendExplosion (double a_BlockX, double a_BlockY, double a_BlockZ, float a_Radius, const cVector3iArray & a_BlocksAffected, const Vector3d & a_PlayerMotion); void SendGameMode (eGameMode a_GameMode); void SendHealth (void); @@ -164,15 +168,14 @@ public: void SendMapDecorators (int a_ID, const cMapDecoratorList & a_Decorators, unsigned int m_Scale); void SendMapInfo (int a_ID, unsigned int a_Scale); void SendPaintingSpawn (const cPainting & a_Painting); - void SendPickupSpawn (const cPickup & a_Pickup); - void SendEntityAnimation (const cEntity & a_Entity, char a_Animation); // tolua_export void SendParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount); + void SendPickupSpawn (const cPickup & a_Pickup); void SendPlayerAbilities (void); void SendPlayerListAddPlayer (const cPlayer & a_Player); void SendPlayerListRemovePlayer (const cPlayer & a_Player); + void SendPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName); void SendPlayerListUpdateGameMode (const cPlayer & a_Player); void SendPlayerListUpdatePing (const cPlayer & a_Player); - void SendPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName); void SendPlayerMaxSpeed (void); ///< Informs the client of the maximum player speed (1.6.1+) void SendPlayerMoveLook (void); void SendPlayerPosition (void); @@ -180,11 +183,8 @@ public: void SendPluginMessage (const AString & a_Channel, const AString & a_Message); // Exported in ManualBindings.cpp void SendRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID); void SendRespawn (eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks = false); - void SendExperience (void); - void SendExperienceOrb (const cExpOrb & a_ExpOrb); - void SendScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode); void SendScoreUpdate (const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode); - void SendDisplayObjective (const AString & a_Objective, cScoreboard::eDisplaySlot a_Display); + void SendScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode); void SendSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch); // tolua_export void SendSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data); void SendSpawnFallingBlock (const cFallingBlock & a_FallingBlock); -- cgit v1.2.3 From 901bed39895be35ceb66352f8120b8117f44fb4e Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Wed, 1 Oct 2014 12:44:28 +0200 Subject: Unified cRoot broadcast chat documentation. --- src/Root.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Root.h b/src/Root.h index 9a482556c..23ed81989 100644 --- a/src/Root.h +++ b/src/Root.h @@ -129,15 +129,15 @@ public: /// Sends a chat message to all connected clients (in all worlds) void BroadcastChat (const AString & a_Message, eMessageType a_ChatPrefix = mtCustom); - void BroadcastChatInfo (const AString & a_Message) { BroadcastChat(a_Message, mtInformation); } + void BroadcastChat (const cCompositeChat & a_Message); + void BroadcastChatDeath (const AString & a_Message) { BroadcastChat(a_Message, mtDeath); } void BroadcastChatFailure(const AString & a_Message) { BroadcastChat(a_Message, mtFailure); } - void BroadcastChatSuccess(const AString & a_Message) { BroadcastChat(a_Message, mtSuccess); } - void BroadcastChatWarning(const AString & a_Message) { BroadcastChat(a_Message, mtWarning); } void BroadcastChatFatal (const AString & a_Message) { BroadcastChat(a_Message, mtFailure); } + void BroadcastChatInfo (const AString & a_Message) { BroadcastChat(a_Message, mtInformation); } void BroadcastChatJoin (const AString & a_Message) { BroadcastChat(a_Message, mtJoin); } void BroadcastChatLeave (const AString & a_Message) { BroadcastChat(a_Message, mtLeave); } - void BroadcastChatDeath (const AString & a_Message) { BroadcastChat(a_Message, mtDeath); } - void BroadcastChat (const cCompositeChat & a_Message); + void BroadcastChatSuccess(const AString & a_Message) { BroadcastChat(a_Message, mtSuccess); } + void BroadcastChatWarning(const AString & a_Message) { BroadcastChat(a_Message, mtWarning); } /// Returns the textual description of the protocol version: 49 -> "1.4.4". Provided specifically for Lua API static AString GetProtocolVersionTextFromInt(int a_ProtocolVersionNum); -- cgit v1.2.3 From 886a7d7bbb48dbff2975892c441c68cfd5ad281b Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Wed, 1 Oct 2014 12:59:31 +0200 Subject: Bindings: Fixed binding for cPlayer::PermissionMatches(). --- src/Bindings/ManualBindings.cpp | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index d8134f159..f4764447c 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -1957,26 +1957,20 @@ static int tolua_cPlayer_PermissionMatches(lua_State * tolua_S) // Check the params: cLuaState L(tolua_S); if ( - !L.CheckParamUserType(1, "cPlayer") || - !L.CheckParamString (2, 3) || - !L.CheckParamEnd (4) + !L.CheckParamUserTable(1, "cPlayer") || + !L.CheckParamString (2, 3) || + !L.CheckParamEnd (4) ) { return 0; } // Get the params: - cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) - { - LOGWARNING("%s: invalid self (%p)", __FUNCTION__, self); - return 0; - } AString Permission, Template; L.GetStackValues(2, Permission, Template); // Push the result of the match: - L.Push(self->PermissionMatches(StringSplit(Permission, "."), StringSplit(Template, "."))); + L.Push(cPlayer::PermissionMatches(StringSplit(Permission, "."), StringSplit(Template, "."))); return 1; } -- cgit v1.2.3 From fd11b574bdc31721b007b31f1734f9ea69a2cd94 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Wed, 1 Oct 2014 17:24:02 +0200 Subject: cPlayer: Removed useless functions from the Lua API. --- src/Entities/Player.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Entities/Player.h b/src/Entities/Player.h index ffd0b7e03..22d6a2ae2 100644 --- a/src/Entities/Player.h +++ b/src/Entities/Player.h @@ -182,11 +182,11 @@ public: /** Sets the player team, NULL if none */ void SetTeam(cTeam * a_Team); + // tolua_end + /** Forces the player to query the scoreboard for his team */ cTeam * UpdateTeam(void); - // tolua_end - /** Return the associated statistic and achievement manager. */ cStatManager & GetStatManager() { return m_Stats; } @@ -421,9 +421,13 @@ public: /** Sets the player's bed (home) position */ void SetBedPos(const Vector3i & a_Pos) { m_LastBedPos = a_Pos; } + + // tolua_end /** Update movement-related statistics. */ void UpdateMovementStats(const Vector3d & a_DeltaPos); + + // tolua_begin /** Returns wheter the player can fly or not. */ virtual bool CanFly(void) const { return m_CanFly; } -- cgit v1.2.3 From 4789db5c28cca53078387711011f0d3901d6a364 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Wed, 1 Oct 2014 17:28:45 +0200 Subject: cRoot: Removed useless variable from Lua API. --- src/Root.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Root.h b/src/Root.h index 23ed81989..84c6a98ec 100644 --- a/src/Root.h +++ b/src/Root.h @@ -41,11 +41,12 @@ namespace Json class cRoot { public: - static bool m_TerminateEventRaised; - static cRoot * Get() { return s_Root; } // tolua_end + static bool m_TerminateEventRaised; + + cRoot(void); ~cRoot(); -- cgit v1.2.3 From cc9e5988039c760311f34fba721a1d3c20126097 Mon Sep 17 00:00:00 2001 From: Masy98 Date: Wed, 1 Oct 2014 17:57:53 +0200 Subject: Added missing 1.8 blocks, E_METAs and sounds --- src/BlockID.h | 53 ++++++++++++++++++++++++++++++++++++++++++------ src/BlockInfo.cpp | 11 +++++++++- src/Blocks/BlockPiston.h | 2 ++ 3 files changed, 59 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 03a7f63e6..014b02fa8 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -186,6 +186,9 @@ enum ENUM_BLOCK_ID E_BLOCK_BLOCK_OF_COAL = 173, E_BLOCK_PACKED_ICE = 174, E_BLOCK_BIG_FLOWER = 175, + E_BLOCK_STANDING_BANNER = 176, + E_BLOCK_WALL_BANNER = 177, + E_BLOCK_INVERTED_DAYLIGHT_SENSOR = 178, E_BLOCK_RED_SANDSTONE = 179, E_BLOCK_RED_SANDSTONE_STAIRS = 180, E_BLOCK_DOUBLE_NEW_STONE_SLAB= 181, @@ -541,15 +544,22 @@ enum E_META_NEW_LOG_DARK_OAK_WOOD = 1, // E_BLOCK_PLANKS metas: - E_META_PLANKS_APPLE = 0, - E_META_PLANKS_CONIFER = 1, - E_META_PLANKS_BIRCH = 2, - E_META_PLANKS_JUNGLE = 3, + E_META_PLANKS_APPLE = 0, + E_META_PLANKS_CONIFER = 1, + E_META_PLANKS_BIRCH = 2, + E_META_PLANKS_JUNGLE = 3, + E_META_PLANKS_ACACIA = 4, + E_META_PLANKS_DARK_OAK = 5, // E_BLOCK_(XXX_WEIGHTED)_PRESSURE_PLATE metas: E_META_PRESSURE_PLATE_RAISED = 0, E_META_PRESSURE_PLATE_DEPRESSED = 1, + // E_BLOCK_PRISMARINE + E_META_PRISMRAINE_ROUGH = 0, + E_META_PRISMARINE_BRICKS = 1, + E_META_PRISMARINE_DARK = 2, + // E_BLOCK_QUARTZ_BLOCK metas: E_META_QUARTZ_NORMAL = 0, E_META_QUARTZ_CHISELLED = 1, @@ -567,6 +577,11 @@ enum E_META_RAIL_CURVED_ZM_XM = 8, E_META_RAIL_CURVED_ZM_XP = 9, + // E_BLOCK_RED_SANDSTONE + E_META_RED_SANDSTONE_NORMAL = 0, + E_META_RED_SANDSTONE_ORNAMENT = 1, + E_META_RED_SANDSTONE_SMOOTH = 2, + // E_BLOCK_SAND metas: E_META_SAND_NORMAL = 0, E_META_SAND_RED = 1, @@ -656,8 +671,11 @@ enum // E_BLOCK_STONE metas: E_META_STONE = 0, E_META_STONE_GRANITE = 1, + E_META_STONE_POLISHED_GRANITE = 2, E_META_STONE_DIORITE = 3, + E_META_STONE_POLISHED_DIORITE = 4, E_META_STONE_ANDESITE = 5, + E_META_STONE_POLISHED_ANDESITE = 6, // E_BLOCK_STONE_SLAB metas: E_META_STONE_SLAB_STONE = 0, @@ -728,6 +746,24 @@ enum //////////////////////////////////////////////////////////////////////////////// // Item metas: + // E_ITEM_BANNER: + E_META_BANNER_BLACK = 0, + E_META_BANNER_RED = 1, + E_META_BANNER_GREEN = 2, + E_META_BANNER_BROWN = 3, + E_META_BANNER_BLUE = 4, + E_META_BANNER_PURPLE = 5, + E_META_BANNER_CYAN = 6, + E_META_BANNER_LIGHTGRAY = 7, + E_META_BANNER_GRAY = 8, + E_META_BANNER_PINK = 9, + E_META_BANNER_LIGHTGREEN = 10, + E_META_BANNER_YELLOW = 11, + E_META_BANNER_LIGHTBLUE = 12, + E_META_BANNER_MAGENTA = 13, + E_META_BANNER_ORANGE = 14, + E_META_BANNER_WHITE = 15, + // E_ITEM_COAL metas: E_META_COAL_NORMAL = 0, E_META_COAL_CHARCOAL = 1, @@ -754,6 +790,13 @@ enum E_META_GOLDEN_APPLE_NORMAL = 0, E_META_GOLDEN_APPLE_ENCHANTED = 1, + // E_ITEM_HEAD: + E_META_HEAD_SKELETON = 0, + E_META_HEAD_WITHER = 1, + E_META_HEAD_ZOMBIE = 2, + E_META_HEAD_PLAYER = 3, + E_META_HEAD_CREEPER = 4, + // E_ITEM_RAW_FISH metas: E_META_RAW_FISH_FISH = 0, E_META_RAW_FISH_SALMON = 1, @@ -763,8 +806,6 @@ enum // E_ITEM_COOKED_FISH metas: E_META_COOKED_FISH_FISH = 0, E_META_COOKED_FISH_SALMON = 1, - E_META_COOKED_FISH_CLOWNFISH = 2, - E_META_COOKED_FISH_PUFFERFISH = 3, // E_ITEM_MINECART_TRACKS metas: E_META_TRACKS_X = 1, diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp index 719ba0550..5e30514e2 100644 --- a/src/BlockInfo.cpp +++ b/src/BlockInfo.cpp @@ -99,6 +99,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_HOPPER ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_ICE ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_INACTIVE_COMPARATOR ].m_SpreadLightFalloff = 1; + a_Info[E_BLOCK_INVERTED_DAYLIGHT_SENSOR ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_IRON_BARS ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_IRON_DOOR ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_IRON_TRAPDOOR ].m_SpreadLightFalloff = 1; @@ -137,6 +138,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_SPRUCE_FENCE_GATE ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_STAINED_GLASS ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_STAINED_GLASS_PANE ].m_SpreadLightFalloff = 1; + a_Info[E_BLOCK_STANDING_BANNER ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_STICKY_PISTON ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_STONE_BUTTON ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_STONE_PRESSURE_PLATE].m_SpreadLightFalloff = 1; @@ -149,6 +151,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_TRIPWIRE ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_TRIPWIRE_HOOK ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_VINES ].m_SpreadLightFalloff = 1; + a_Info[E_BLOCK_WALL_BANNER ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_WALLSIGN ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_WOODEN_BUTTON ].m_SpreadLightFalloff = 1; a_Info[E_BLOCK_WOODEN_DOOR ].m_SpreadLightFalloff = 1; @@ -256,6 +259,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_STAINED_GLASS_PANE ].m_Transparent = true; a_Info[E_BLOCK_STATIONARY_LAVA ].m_Transparent = true; a_Info[E_BLOCK_STATIONARY_WATER ].m_Transparent = true; + a_Info[E_BLOCK_STANDING_BANNER ].m_Transparent = true; a_Info[E_BLOCK_STICKY_PISTON ].m_Transparent = true; a_Info[E_BLOCK_STONE_BUTTON ].m_Transparent = true; a_Info[E_BLOCK_STONE_PRESSURE_PLATE].m_Transparent = true; @@ -268,6 +272,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_TRIPWIRE ].m_Transparent = true; a_Info[E_BLOCK_TRIPWIRE_HOOK ].m_Transparent = true; a_Info[E_BLOCK_VINES ].m_Transparent = true; + a_Info[E_BLOCK_WALL_BANNER ].m_Transparent = true; a_Info[E_BLOCK_WALLSIGN ].m_Transparent = true; a_Info[E_BLOCK_WATER ].m_Transparent = true; a_Info[E_BLOCK_WOODEN_BUTTON ].m_Transparent = true; @@ -475,12 +480,14 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_SNOW ].m_IsSolid = false; a_Info[E_BLOCK_STATIONARY_LAVA ].m_IsSolid = false; a_Info[E_BLOCK_STATIONARY_WATER ].m_IsSolid = false; + a_Info[E_BLOCK_STANDING_BANNER ].m_IsSolid = false; a_Info[E_BLOCK_STONE_BUTTON ].m_IsSolid = false; a_Info[E_BLOCK_STONE_PRESSURE_PLATE].m_IsSolid = false; a_Info[E_BLOCK_TALL_GRASS ].m_IsSolid = false; a_Info[E_BLOCK_TORCH ].m_IsSolid = false; a_Info[E_BLOCK_TRIPWIRE ].m_IsSolid = false; a_Info[E_BLOCK_VINES ].m_IsSolid = false; + a_Info[E_BLOCK_WALL_BANNER ].m_IsSolid = false; a_Info[E_BLOCK_WALLSIGN ].m_IsSolid = false; a_Info[E_BLOCK_WATER ].m_IsSolid = false; a_Info[E_BLOCK_WOODEN_BUTTON ].m_IsSolid = false; @@ -735,7 +742,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_NEW_LOG ].m_PlaceSound = "dig.wood"; a_Info[E_BLOCK_ACACIA_WOOD_STAIRS ].m_PlaceSound = "dig.wood"; a_Info[E_BLOCK_DARK_OAK_WOOD_STAIRS ].m_PlaceSound = "dig.wood"; - a_Info[E_BLOCK_SLIME_BLOCK ].m_PlaceSound = "dig.slime"; // TODO: Check that this is the correct name + a_Info[E_BLOCK_SLIME_BLOCK ].m_PlaceSound = "mob.slime.big"; a_Info[E_BLOCK_BARRIER ].m_PlaceSound = "dig.stone"; a_Info[E_BLOCK_IRON_TRAPDOOR ].m_PlaceSound = "dig.metal"; a_Info[E_BLOCK_PRISMARINE_BLOCK ].m_PlaceSound = "dig.stone"; @@ -746,6 +753,8 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_BLOCK_OF_COAL ].m_PlaceSound = "dig.stone"; a_Info[E_BLOCK_PACKED_ICE ].m_PlaceSound = "dig.stone"; a_Info[E_BLOCK_BIG_FLOWER ].m_PlaceSound = "dig.grass"; + a_Info[E_BLOCK_STANDING_BANNER ].m_PlaceSound = "dig.wood"; + a_Info[E_BLOCK_WALL_BANNER ].m_PlaceSound = "dig.wood"; a_Info[E_BLOCK_RED_SANDSTONE ].m_PlaceSound = "dig.stone"; a_Info[E_BLOCK_RED_SANDSTONE_STAIRS ].m_PlaceSound = "dig.stone"; a_Info[E_BLOCK_NEW_STONE_SLAB ].m_PlaceSound = "dig.stone"; diff --git a/src/Blocks/BlockPiston.h b/src/Blocks/BlockPiston.h index 3a3fc7224..05bc3d3f9 100644 --- a/src/Blocks/BlockPiston.h +++ b/src/Blocks/BlockPiston.h @@ -115,7 +115,9 @@ private: case E_BLOCK_NOTE_BLOCK: case E_BLOCK_OBSIDIAN: case E_BLOCK_PISTON_EXTENSION: + case E_BLOCK_STANDING_BANNER: case E_BLOCK_TRAPPED_CHEST: + case E_BLOCK_WALL_BANNER: { return false; } -- cgit v1.2.3 From 0f0763303e804e6447c5523a10c80ca2d5c844a0 Mon Sep 17 00:00:00 2001 From: Masy98 Date: Wed, 1 Oct 2014 18:00:51 +0200 Subject: Fixed ":" --- src/BlockID.h | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 014b02fa8..9787b3bfa 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -445,7 +445,7 @@ enum //////////////////////////////////////////////////////////////////////////////// // Block metas: - // E_BLOCK_BIG_FLOWER metas + // E_BLOCK_BIG_FLOWER metas: E_META_BIG_FLOWER_SUNFLOWER = 0, E_META_BIG_FLOWER_LILAC = 1, E_META_BIG_FLOWER_DOUBLE_TALL_GRASS = 2, @@ -501,7 +501,7 @@ enum E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, E_META_DOUBLE_STONE_SLAB_STONE_SECRET = 7, - // E_BLOCK_FLOWER metas + // E_BLOCK_FLOWER metas: E_META_FLOWER_POPPY = 0, E_META_FLOWER_BLUE_ORCHID = 1, E_META_FLOWER_ALLIUM = 2, @@ -511,7 +511,7 @@ enum E_META_FLOWER_PINK_TULIP = 7, E_META_FLOWER_OXEYE_DAISY = 8, - // E_BLOCK_JUKEBOX metas + // E_BLOCK_JUKEBOX metas: E_META_JUKEBOX_OFF = 0, E_META_JUKEBOX_ON = 1, @@ -535,11 +535,11 @@ enum E_META_LOG_BIRCH = 2, E_META_LOG_JUNGLE = 3, - // E_BLOCK_NEW_LEAVES metas + // E_BLOCK_NEW_LEAVES metas: E_META_NEW_LEAVES_ACACIA_WOOD = 0, E_META_NEW_LEAVES_DARK_OAK_WOOD = 1, - // E_BLOCK_NEW_LOG metas + // E_BLOCK_NEW_LOG metas: E_META_NEW_LOG_ACACIA_WOOD = 0, E_META_NEW_LOG_DARK_OAK_WOOD = 1, @@ -555,7 +555,7 @@ enum E_META_PRESSURE_PLATE_RAISED = 0, E_META_PRESSURE_PLATE_DEPRESSED = 1, - // E_BLOCK_PRISMARINE + // E_BLOCK_PRISMARINE: E_META_PRISMRAINE_ROUGH = 0, E_META_PRISMARINE_BRICKS = 1, E_META_PRISMARINE_DARK = 2, @@ -565,7 +565,7 @@ enum E_META_QUARTZ_CHISELLED = 1, E_META_QUARTZ_PILLAR = 2, - // E_BLOCK_RAIL metas + // E_BLOCK_RAIL metas: E_META_RAIL_ZM_ZP = 0, E_META_RAIL_XM_XP = 1, E_META_RAIL_ASCEND_XP = 2, @@ -577,7 +577,7 @@ enum E_META_RAIL_CURVED_ZM_XM = 8, E_META_RAIL_CURVED_ZM_XP = 9, - // E_BLOCK_RED_SANDSTONE + // E_BLOCK_RED_SANDSTONE: E_META_RED_SANDSTONE_NORMAL = 0, E_META_RED_SANDSTONE_ORNAMENT = 1, E_META_RED_SANDSTONE_SMOOTH = 2, @@ -614,7 +614,7 @@ enum E_META_SNOW_LAYER_SEVEN = 6, E_META_SNOW_LAYER_EIGHT = 7, - // E_BLOCK_STAINED_CLAY metas + // E_BLOCK_STAINED_CLAY metas: E_META_STAINED_CLAY_WHITE = 0, E_META_STAINED_CLAY_ORANGE = 1, E_META_STAINED_CLAY_MAGENTA = 2, @@ -632,7 +632,7 @@ enum E_META_STAINED_CLAY_RED = 14, E_META_STAINED_CLAY_BLACK = 15, - // E_BLOCK_STAINED_GLASS metas + // E_BLOCK_STAINED_GLASS metas: E_META_STAINED_GLASS_WHITE = 0, E_META_STAINED_GLASS_ORANGE = 1, E_META_STAINED_GLASS_MAGENTA = 2, @@ -650,7 +650,7 @@ enum E_META_STAINED_GLASS_RED = 14, E_META_STAINED_GLASS_BLACK = 15, - // E_BLOCK_STAINED_GLASS_PANE metas + // E_BLOCK_STAINED_GLASS_PANE metas: E_META_STAINED_GLASS_PANE_WHITE = 0, E_META_STAINED_GLASS_PANE_ORANGE = 1, E_META_STAINED_GLASS_PANE_MAGENTA = 2, -- cgit v1.2.3 From 1d875d0bc8d1cf91baa20b592b19a1167cad978a Mon Sep 17 00:00:00 2001 From: Masy98 Date: Wed, 1 Oct 2014 18:08:31 +0200 Subject: Added Daylight Sensors to the "can't push" list --- src/Blocks/BlockPiston.h | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/Blocks/BlockPiston.h b/src/Blocks/BlockPiston.h index 05bc3d3f9..f868f4d8e 100644 --- a/src/Blocks/BlockPiston.h +++ b/src/Blocks/BlockPiston.h @@ -100,6 +100,7 @@ private: case E_BLOCK_BREWING_STAND: case E_BLOCK_CHEST: case E_BLOCK_COMMAND_BLOCK: + case E_BLOCK_DAYLIGHT_SENSOR: case E_BLOCK_DISPENSER: case E_BLOCK_DROPPER: case E_BLOCK_ENCHANTMENT_TABLE: @@ -108,6 +109,7 @@ private: // Notice the lack of an E_BLOCK_ENDER_CHEST here; its because ender chests can totally be pushed/pulled in MCS :) case E_BLOCK_FURNACE: case E_BLOCK_LIT_FURNACE: + case E_BLOCK_INVERTED_DAYLIGHT_SENSOR: case E_BLOCK_HOPPER: case E_BLOCK_JUKEBOX: case E_BLOCK_MOB_SPAWNER: -- cgit v1.2.3 From 0d2a041a69f741f10637ccc5a794075d05d1e03f Mon Sep 17 00:00:00 2001 From: Masy98 Date: Wed, 1 Oct 2014 19:13:59 +0200 Subject: Fixed Red Sandstone and Prismarine drops --- src/BlockID.h | 14 +++++++------- src/Items/ItemHandler.cpp | 1 + src/Items/ItemPickaxe.h | 39 ++++++++++++++++++++++----------------- 3 files changed, 30 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 9787b3bfa..984c782c4 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -555,10 +555,10 @@ enum E_META_PRESSURE_PLATE_RAISED = 0, E_META_PRESSURE_PLATE_DEPRESSED = 1, - // E_BLOCK_PRISMARINE: - E_META_PRISMRAINE_ROUGH = 0, - E_META_PRISMARINE_BRICKS = 1, - E_META_PRISMARINE_DARK = 2, + // E_BLOCK_PRISMARINE_BLOCK metas: + E_META_PRISMRAINE_BLOCK_ROUGH = 0, + E_META_PRISMARINE_BLOCK_BRICKS = 1, + E_META_PRISMARINE_BLOCK_DARK = 2, // E_BLOCK_QUARTZ_BLOCK metas: E_META_QUARTZ_NORMAL = 0, @@ -577,7 +577,7 @@ enum E_META_RAIL_CURVED_ZM_XM = 8, E_META_RAIL_CURVED_ZM_XP = 9, - // E_BLOCK_RED_SANDSTONE: + // E_BLOCK_RED_SANDSTONE metas: E_META_RED_SANDSTONE_NORMAL = 0, E_META_RED_SANDSTONE_ORNAMENT = 1, E_META_RED_SANDSTONE_SMOOTH = 2, @@ -746,7 +746,7 @@ enum //////////////////////////////////////////////////////////////////////////////// // Item metas: - // E_ITEM_BANNER: + // E_ITEM_BANNER metas: E_META_BANNER_BLACK = 0, E_META_BANNER_RED = 1, E_META_BANNER_GREEN = 2, @@ -790,7 +790,7 @@ enum E_META_GOLDEN_APPLE_NORMAL = 0, E_META_GOLDEN_APPLE_ENCHANTED = 1, - // E_ITEM_HEAD: + // E_ITEM_HEAD metas: E_META_HEAD_SKELETON = 0, E_META_HEAD_WITHER = 1, E_META_HEAD_ZOMBIE = 2, diff --git a/src/Items/ItemHandler.cpp b/src/Items/ItemHandler.cpp index caa623abc..dbfba14a7 100644 --- a/src/Items/ItemHandler.cpp +++ b/src/Items/ItemHandler.cpp @@ -574,6 +574,7 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_COBBLESTONE_WALL: case E_BLOCK_DIAMOND_BLOCK: case E_BLOCK_DIAMOND_ORE: + case E_BLOCK_DOUBLE_NEW_STONE_SLAB: case E_BLOCK_DOUBLE_STONE_SLAB: case E_BLOCK_EMERALD_ORE: case E_BLOCK_ENCHANTMENT_TABLE: diff --git a/src/Items/ItemPickaxe.h b/src/Items/ItemPickaxe.h index e0cf5d711..b5dc179f8 100644 --- a/src/Items/ItemPickaxe.h +++ b/src/Items/ItemPickaxe.h @@ -41,11 +41,11 @@ public: case E_BLOCK_DIAMOND_BLOCK: case E_BLOCK_DIAMOND_ORE: + case E_BLOCK_EMERALD_ORE: case E_BLOCK_GOLD_BLOCK: case E_BLOCK_GOLD_ORE: case E_BLOCK_REDSTONE_ORE: case E_BLOCK_REDSTONE_ORE_GLOWING: - case E_BLOCK_EMERALD_ORE: { return PickaxeLevel() >= 3; } @@ -59,29 +59,34 @@ public: } case E_BLOCK_ANVIL: - case E_BLOCK_ENCHANTMENT_TABLE: - case E_BLOCK_FURNACE: - case E_BLOCK_LIT_FURNACE: + case E_BLOCK_BRICK: + case E_BLOCK_CAULDRON: case E_BLOCK_COAL_ORE: - case E_BLOCK_STONE: case E_BLOCK_COBBLESTONE: + case E_BLOCK_COBBLESTONE_STAIRS: + case E_BLOCK_COBBLESTONE_WALL: + case E_BLOCK_DOUBLE_NEW_STONE_SLAB: + case E_BLOCK_DOUBLE_STONE_SLAB: + case E_BLOCK_ENCHANTMENT_TABLE: case E_BLOCK_END_STONE: + case E_BLOCK_FURNACE: + case E_BLOCK_LIT_FURNACE: + case E_BLOCK_MOB_SPAWNER: case E_BLOCK_MOSSY_COBBLESTONE: - case E_BLOCK_SANDSTONE_STAIRS: - case E_BLOCK_SANDSTONE: - case E_BLOCK_STONE_BRICKS: case E_BLOCK_NETHER_BRICK: + case E_BLOCK_NETHER_BRICK_STAIRS: case E_BLOCK_NETHERRACK: - case E_BLOCK_STONE_SLAB: - case E_BLOCK_DOUBLE_STONE_SLAB: - case E_BLOCK_STONE_PRESSURE_PLATE: - case E_BLOCK_BRICK: - case E_BLOCK_COBBLESTONE_STAIRS: - case E_BLOCK_COBBLESTONE_WALL: + case E_BLOCK_NEW_STONE_SLAB: + case E_BLOCK_PRISMARINE_BLOCK: + case E_BLOCK_RED_SANDSTONE: + case E_BLOCK_RED_SANDSTONE_STAIRS: + case E_BLOCK_SANDSTONE: + case E_BLOCK_SANDSTONE_STAIRS: + case E_BLOCK_STONE: + case E_BLOCK_STONE_BRICKS: case E_BLOCK_STONE_BRICK_STAIRS: - case E_BLOCK_NETHER_BRICK_STAIRS: - case E_BLOCK_CAULDRON: - case E_BLOCK_MOB_SPAWNER: + case E_BLOCK_STONE_PRESSURE_PLATE: + case E_BLOCK_STONE_SLAB: { return PickaxeLevel() >= 1; } -- cgit v1.2.3 From 3591edd47ee2290742b79e958439b475c1901c7c Mon Sep 17 00:00:00 2001 From: Masy98 Date: Wed, 1 Oct 2014 19:26:36 +0200 Subject: Fixed sorting --- src/Items/ItemHandler.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Items/ItemHandler.cpp b/src/Items/ItemHandler.cpp index dbfba14a7..912dde022 100644 --- a/src/Items/ItemHandler.cpp +++ b/src/Items/ItemHandler.cpp @@ -588,6 +588,7 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_LAPIS_BLOCK: case E_BLOCK_LAPIS_ORE: case E_BLOCK_LIT_FURNACE: + case E_BLOCK_MOB_SPAWNER: case E_BLOCK_MOSSY_COBBLESTONE: case E_BLOCK_NETHER_BRICK: case E_BLOCK_NETHER_BRICK_STAIRS: @@ -595,6 +596,7 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_NETHERRACK: case E_BLOCK_NEW_STONE_SLAB: case E_BLOCK_OBSIDIAN: + case E_BLOCK_PACKED_ICE: case E_BLOCK_PRISMARINE_BLOCK: case E_BLOCK_RED_SANDSTONE: case E_BLOCK_RED_SANDSTONE_STAIRS: @@ -609,8 +611,6 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_STONE_PRESSURE_PLATE: case E_BLOCK_STONE_SLAB: case E_BLOCK_VINES: - case E_BLOCK_PACKED_ICE: - case E_BLOCK_MOB_SPAWNER: { return false; } -- cgit v1.2.3 From 2f945475f2c031a1c60d5fe35cec17af82bde7f8 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Thu, 2 Oct 2014 07:22:12 +0100 Subject: Fix spelling of PRISMRAINE Fixes #1497 --- src/BlockID.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 984c782c4..69b5e2fe0 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -556,7 +556,7 @@ enum E_META_PRESSURE_PLATE_DEPRESSED = 1, // E_BLOCK_PRISMARINE_BLOCK metas: - E_META_PRISMRAINE_BLOCK_ROUGH = 0, + E_META_PRISMARINE_BLOCK_ROUGH = 0, E_META_PRISMARINE_BLOCK_BRICKS = 1, E_META_PRISMARINE_BLOCK_DARK = 2, -- cgit v1.2.3 From 382e014ebcd44a72788bea8cdcec7f64861b063f Mon Sep 17 00:00:00 2001 From: Howaner Date: Thu, 2 Oct 2014 23:50:41 +0200 Subject: Optimized chunk loader --- src/ChunkSender.cpp | 21 +++--- src/ClientHandle.cpp | 163 ++++++++++++++++++++----------------------- src/ClientHandle.h | 10 +-- src/Entities/Player.cpp | 1 - src/Protocol/Protocol17x.cpp | 1 + src/Protocol/Protocol18x.cpp | 1 + src/World.cpp | 1 - 7 files changed, 93 insertions(+), 105 deletions(-) (limited to 'src') diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index a3151eb3f..0bdc0cf75 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -192,40 +192,37 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien ASSERT(m_World != NULL); // Ask the client if it still wants the chunk: - if (a_Client != NULL) + if ((a_Client != NULL) && !a_Client->WantsSendChunk(a_ChunkX, a_ChunkZ)) { - if (!a_Client->WantsSendChunk(a_ChunkX, a_ChunkZ)) - { - return; - } + return; } - + // If the chunk has no clients, no need to packetize it: if (!m_World->HasChunkAnyClients(a_ChunkX, a_ChunkZ)) { return; } - + // If the chunk is not valid, do nothing - whoever needs it has queued it for loading / generating if (!m_World->IsChunkValid(a_ChunkX, a_ChunkZ)) { return; } - + // If the chunk is not lighted, queue it for relighting and get notified when it's ready: if (!m_World->IsChunkLighted(a_ChunkX, a_ChunkZ)) { m_World->QueueLightChunk(a_ChunkX, a_ChunkZ, &m_Notify); return; } - + // Query and prepare chunk data: if (!m_World->GetChunkData(a_ChunkX, a_ChunkZ, *this)) { return; } cChunkDataSerializer Data(m_BlockTypes, m_BlockMetas, m_BlockLight, m_BlockSkyLight, m_BiomeMap); - + // Send: if (a_Client == NULL) { @@ -235,7 +232,7 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien { a_Client->SendChunkData(a_ChunkX, a_ChunkZ, Data); } - + // Send block-entity packets: for (sBlockCoords::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr) { @@ -249,7 +246,7 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien } } // for itr - m_Packets[] m_BlockEntities.clear(); - + // TODO: Send entity spawn packets } diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index a29bef0c0..27d41da1b 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -70,8 +70,6 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_OutgoingData(64 KiB), m_Player(NULL), m_HasSentDC(false), - m_LastStreamedChunkX(0x7fffffff), // bogus chunk coords to force streaming upon login - m_LastStreamedChunkZ(0x7fffffff), m_TimeSinceLastPacket(0), m_Ping(1000), m_PingID(1), @@ -401,53 +399,84 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID, -void cClientHandle::StreamChunks(void) +void cClientHandle::StreamNextChunk(void) { if ((m_State < csAuthenticated) || (m_State >= csDestroying)) { return; } - ASSERT(m_Player != NULL); + Vector3d LookVector = m_Player->GetLookVector(); + LookVector.Normalize(); - int ChunkPosX = FAST_FLOOR_DIV((int)m_Player->GetPosX(), cChunkDef::Width); - int ChunkPosZ = FAST_FLOOR_DIV((int)m_Player->GetPosZ(), cChunkDef::Width); - if ((ChunkPosX == m_LastStreamedChunkX) && (ChunkPosZ == m_LastStreamedChunkZ)) + Vector3d Position = m_Player->GetEyePosition(); + for (size_t Range = 0; Range < (size_t)m_ViewDistance; Range++) { - // Already streamed for this position - return; + Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; + + int RangeX, RangeZ = 0; + cChunkDef::BlockToChunk((int)std::floor(Vector.x), (int)std::floor(Vector.z), RangeX, RangeZ); + + for (size_t X = 0; X < 6; X++) + { + for (size_t Z = 0; Z < 6; Z++) + { + int ChunkX = RangeX + ((X >= 3) ? (2 - X) : X); + int ChunkZ = RangeZ + ((Z >= 3) ? (2 - Z) : Z); + cChunkCoords Coords(ChunkX, ChunkZ); + + // If the chunk already loading/loaded -> skip + { + cCSLock Lock(m_CSChunkLists); + if ( + (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || + (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) + ) + { + continue; + } + } + + // Unloaded chunk found -> Send it to the client. + StreamChunk(ChunkX, ChunkZ); + return; + } + } } - m_LastStreamedChunkX = ChunkPosX; - m_LastStreamedChunkZ = ChunkPosZ; - - LOGD("Streaming chunks centered on [%d, %d], view distance %d", ChunkPosX, ChunkPosZ, m_ViewDistance); - - cWorld * World = m_Player->GetWorld(); - ASSERT(World != NULL); +} + + - // Remove all loaded chunks that are no longer in range; deferred to out-of-CS: - cChunkCoordsList RemoveChunks; + + +void cClientHandle::UnloadOutOfRangeChunks(void) +{ + int ChunkPosX = FAST_FLOOR_DIV((int)m_Player->GetPosX(), cChunkDef::Width); + int ChunkPosZ = FAST_FLOOR_DIV((int)m_Player->GetPosZ(), cChunkDef::Width); + + cChunkCoordsList ChunksToRemove; { cCSLock Lock(m_CSChunkLists); for (cChunkCoordsList::iterator itr = m_LoadedChunks.begin(); itr != m_LoadedChunks.end();) { - int RelX = (*itr).m_ChunkX - ChunkPosX; - int RelZ = (*itr).m_ChunkZ - ChunkPosZ; - if ((RelX > m_ViewDistance) || (RelX < -m_ViewDistance) || (RelZ > m_ViewDistance) || (RelZ < -m_ViewDistance)) + int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); + int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); + if ((DiffX > m_ViewDistance) || (DiffZ > m_ViewDistance)) { - RemoveChunks.push_back(*itr); + ChunksToRemove.push_back(*itr); itr = m_LoadedChunks.erase(itr); } else { ++itr; } - } // for itr - m_LoadedChunks[] + } + for (cChunkCoordsList::iterator itr = m_ChunksToSend.begin(); itr != m_ChunksToSend.end();) { - int RelX = (*itr).m_ChunkX - ChunkPosX; - int RelZ = (*itr).m_ChunkZ - ChunkPosZ; - if ((RelX > m_ViewDistance) || (RelX < -m_ViewDistance) || (RelZ > m_ViewDistance) || (RelZ < -m_ViewDistance)) + int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); + int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); + if ((DiffX > m_ViewDistance) || (DiffZ > m_ViewDistance)) { itr = m_ChunksToSend.erase(itr); } @@ -455,51 +484,20 @@ void cClientHandle::StreamChunks(void) { ++itr; } - } // for itr - m_ChunksToSend[] + } } - for (cChunkCoordsList::iterator itr = RemoveChunks.begin(); itr != RemoveChunks.end(); ++itr) + + for (cChunkCoordsList::iterator itr = ChunksToRemove.begin(); itr != ChunksToRemove.end(); ++itr) { - World->RemoveChunkClient(itr->m_ChunkX, itr->m_ChunkZ, this); + m_Player->GetWorld()->RemoveChunkClient(itr->m_ChunkX, itr->m_ChunkZ, this); m_Protocol->SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); - } // for itr - RemoveChunks[] - - // Add all chunks that are in range and not yet in m_LoadedChunks: - // Queue these smartly - from the center out to the edge - for (int d = 0; d <= m_ViewDistance; ++d) // cycle through (square) distance, from nearest to furthest - { - // For each distance add chunks in a hollow square centered around current position: - for (int i = -d; i <= d; ++i) - { - StreamChunk(ChunkPosX + d, ChunkPosZ + i); - StreamChunk(ChunkPosX - d, ChunkPosZ + i); - } // for i - for (int i = -d + 1; i < d; ++i) - { - StreamChunk(ChunkPosX + i, ChunkPosZ + d); - StreamChunk(ChunkPosX + i, ChunkPosZ - d); - } // for i - } // for d - - // Touch chunks GENERATEDISTANCE ahead to let them generate: - for (int d = m_ViewDistance + 1; d <= m_ViewDistance + GENERATEDISTANCE; ++d) // cycle through (square) distance, from nearest to furthest - { - // For each distance touch chunks in a hollow square centered around current position: - for (int i = -d; i <= d; ++i) - { - World->TouchChunk(ChunkPosX + d, ChunkPosZ + i); - World->TouchChunk(ChunkPosX - d, ChunkPosZ + i); - } // for i - for (int i = -d + 1; i < d; ++i) - { - World->TouchChunk(ChunkPosX + i, ChunkPosZ + d); - World->TouchChunk(ChunkPosX + i, ChunkPosZ - d); - } // for i - } // for d + } } + void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) { if (m_State >= csDestroying) @@ -539,11 +537,6 @@ void cClientHandle::RemoveFromAllChunks() cCSLock Lock(m_CSChunkLists); m_LoadedChunks.clear(); m_ChunksToSend.clear(); - - // Also reset the LastStreamedChunk coords to bogus coords, - // so that all chunks are streamed in subsequent StreamChunks() call (FS #407) - m_LastStreamedChunkX = 0x7fffffff; - m_LastStreamedChunkZ = 0x7fffffff; } } @@ -1858,10 +1851,7 @@ void cClientHandle::RemoveFromWorld(void) { m_Protocol->SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); } // for itr - Chunks[] - - // Here, we set last streamed values to bogus ones so everything is resent - m_LastStreamedChunkX = 0x7fffffff; - m_LastStreamedChunkZ = 0x7fffffff; + m_HasSentPlayerChunk = false; } @@ -1907,7 +1897,7 @@ void cClientHandle::Tick(float a_Dt) { return; } - + // If the chunk the player's in was just sent, spawn the player: if (m_HasSentPlayerChunk && (m_State == csDownloadingWorld)) { @@ -1928,6 +1918,17 @@ void cClientHandle::Tick(float a_Dt) } } + if ((m_State >= csAuthenticated) && (m_State < csDestroying)) + { + StreamNextChunk(); // Streams the next chunk + + // Unload all chunks that are out of the view distance (all 2 seconds) + if ((m_Player->GetWorld()->GetWorldAge() % 40) == 0) + { + UnloadOutOfRangeChunks(); + } + } + // Handle block break animation: if (m_BlockDigAnimStage > -1) { @@ -1964,7 +1965,7 @@ void cClientHandle::ServerTick(float a_Dt) if (m_State == csAuthenticated) { - StreamChunks(); + StreamNextChunk(); // Remove the client handle from the server, it will be ticked from its cPlayer object from now on cRoot::Get()->GetServer()->ClientMovedToWorld(this); @@ -2723,18 +2724,8 @@ void cClientHandle::SetUsername( const AString & a_Username) void cClientHandle::SetViewDistance(int a_ViewDistance) { - if (a_ViewDistance < MIN_VIEW_DISTANCE) - { - a_ViewDistance = MIN_VIEW_DISTANCE; - } - if (a_ViewDistance > MAX_VIEW_DISTANCE) - { - a_ViewDistance = MAX_VIEW_DISTANCE; - } - m_ViewDistance = a_ViewDistance; - - // Need to re-stream chunks for the change to become apparent: - StreamChunks(); + m_ViewDistance = Clamp(a_ViewDistance, MIN_VIEW_DISTANCE, MAX_VIEW_DISTANCE); + LOGD("Setted %s's view distance to %i", GetUsername().c_str(), m_ViewDistance); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 20592c190..897fb8705 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -113,7 +113,11 @@ public: /** Authenticates the specified user, called by cAuthenticator */ void Authenticate(const AString & a_Name, const AString & a_UUID, const Json::Value & a_Properties); - void StreamChunks(void); + /** This function sends a new unloaded chunk to the player. */ + void StreamNextChunk(void); + + /** Remove all loaded chunks that are no longer in range */ + void UnloadOutOfRangeChunks(void); // Removes the client from all chunks. Used when switching worlds or destroying the player void RemoveFromAllChunks(void); @@ -352,10 +356,6 @@ private: cPlayer * m_Player; bool m_HasSentDC; ///< True if a D/C packet has been sent in either direction - - // Chunk position when the last StreamChunks() was called; used to avoid re-streaming while in the same chunk - int m_LastStreamedChunkX; - int m_LastStreamedChunkZ; /** Seconds since the last packet data was received (updated in Tick(), reset in DataReceived()) */ float m_TimeSinceLastPacket; diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index f58a0a016..19273b0a9 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -235,7 +235,6 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk) CanMove = false; TeleportToCoords(m_LastPos.x, m_LastPos.y, m_LastPos.z); } - m_ClientHandle->StreamChunks(); } if (CanMove) diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index a7abd240f..494413f63 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -1901,6 +1901,7 @@ void cProtocol172::HandlePacketClientSettings(cByteBuffer & a_ByteBuffer) HANDLE_READ(a_ByteBuffer, ReadByte, Byte, ShowCape); m_Client->SetLocale(Locale); + m_Client->SetViewDistance(ViewDistance); // TODO: Do anything with the other values. } diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index acdb48cf7..f37409744 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -2160,6 +2160,7 @@ void cProtocol180::HandlePacketClientSettings(cByteBuffer & a_ByteBuffer) HANDLE_READ(a_ByteBuffer, ReadChar, char, SkinFlags); m_Client->SetLocale(Locale); + m_Client->SetViewDistance(ViewDistance); // TODO: Handle other values } diff --git a/src/World.cpp b/src/World.cpp index a3c804b44..30c1a73b1 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -3491,7 +3491,6 @@ void cWorld::AddQueuedPlayers(void) cClientHandle * Client = (*itr)->GetClientHandle(); if (Client != NULL) { - Client->StreamChunks(); Client->SendPlayerMoveLook(); Client->SendHealth(); Client->SendWholeInventory(*(*itr)->GetWindow()); -- cgit v1.2.3 From b5a2c6667ac0845d17a709cc436afb570079a9a7 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Fri, 3 Oct 2014 21:32:41 +0100 Subject: Improved furnaces * Fixed progress bar on 1.8 * Fixed bugs * Improved code * Fixes #1068 * Fixes #1070 --- src/BlockEntities/FurnaceEntity.cpp | 141 ++++++++++++------------------------ src/BlockEntities/FurnaceEntity.h | 110 ++++++++++++++++------------ src/Chunk.cpp | 2 +- src/Chunk.h | 2 +- src/ClientHandle.cpp | 2 +- src/ClientHandle.h | 2 +- src/Protocol/Protocol.h | 2 +- src/Protocol/Protocol17x.cpp | 2 +- src/Protocol/Protocol17x.h | 2 +- src/Protocol/Protocol18x.cpp | 2 +- src/Protocol/Protocol18x.h | 2 +- src/Protocol/ProtocolRecognizer.cpp | 2 +- src/Protocol/ProtocolRecognizer.h | 2 +- src/UI/Window.cpp | 23 ++---- src/UI/Window.h | 15 ++-- 15 files changed, 131 insertions(+), 180 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index 4452fc00a..222b27637 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -5,6 +5,7 @@ #include "../UI/Window.h" #include "../Entities/Player.h" #include "../Root.h" +#include "Chunk.h" @@ -13,8 +14,9 @@ enum { - PROGRESSBAR_SMELTING = 0, - PROGRESSBAR_FUEL = 1, + PROGRESSBAR_FUEL = 0, + PROGRESSBAR_SMELTING = 2, + PROGRESSBAR_SMELTING_CONFIRM = 3, } ; @@ -23,7 +25,6 @@ enum cFurnaceEntity::cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cWorld * a_World) : super(E_BLOCK_FURNACE, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), - m_BlockType(a_BlockType), m_BlockMeta(a_BlockMeta), m_CurrentRecipe(NULL), m_IsCooking((a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ) == E_BLOCK_LIT_FURNACE)), @@ -31,8 +32,7 @@ cFurnaceEntity::cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY m_TimeCooked(0), m_FuelBurnTime(0), m_TimeBurned(0), - m_LastProgressFuel(0), - m_LastProgressCook(0) + m_IsDestroyed(false) { m_Contents.AddListener(*this); } @@ -57,27 +57,28 @@ cFurnaceEntity::~cFurnaceEntity() void cFurnaceEntity::UsedBy(cPlayer * a_Player) { - if (GetWindow() == NULL) + cWindow * Window = GetWindow(); + if (Window == NULL) { OpenWindow(new cFurnaceWindow(m_PosX, m_PosY, m_PosZ, this)); + Window = GetWindow(); } - cWindow * Window = GetWindow(); + if (Window != NULL) { if (a_Player->GetWindow() != Window) { a_Player->OpenWindow(Window); - BroadcastProgress(PROGRESSBAR_FUEL, (short)m_LastProgressFuel); - BroadcastProgress(PROGRESSBAR_SMELTING, (short)m_LastProgressCook); } } + + UpdateProgressBars(true); } -/// Restarts cooking. Used after the furnace is loaded from storage to set up the internal variables so that cooking continues, if it was active. Returns true if cooking. bool cFurnaceEntity::ContinueCooking(void) { UpdateInput(); @@ -92,14 +93,16 @@ bool cFurnaceEntity::ContinueCooking(void) bool cFurnaceEntity::Tick(float a_Dt, cChunk & a_Chunk) { UNUSED(a_Dt); - UNUSED(a_Chunk); + if (m_FuelBurnTime <= 0) { - // No fuel is burning, reset progressbars and bail out - if ((m_LastProgressCook > 0) || (m_LastProgressFuel > 0)) - { - UpdateProgressBars(); - } + // Cooked time decreases twice as fast when ran out of fuel + m_TimeCooked -= 2; + m_TimeCooked = std::max(m_TimeCooked, 0); + + // Reset progressbars, block type, and bail out + a_Chunk.FastSetBlock(GetRelX(), m_PosY, GetRelZ(), E_BLOCK_FURNACE, m_BlockMeta); + UpdateProgressBars(); return false; } @@ -139,12 +142,12 @@ void cFurnaceEntity::SendTo(cClientHandle & a_Client) -void cFurnaceEntity::BroadcastProgress(int a_ProgressbarID, short a_Value) +void cFurnaceEntity::BroadcastProgress(short a_ProgressbarID, short a_Value) { cWindow * Window = GetWindow(); if (Window != NULL) { - Window->BroadcastProgress(a_ProgressbarID, a_Value); + Window->SetProperty(a_ProgressbarID, a_Value); } } @@ -152,7 +155,6 @@ void cFurnaceEntity::BroadcastProgress(int a_ProgressbarID, short a_Value) -/// One item finished cooking void cFurnaceEntity::FinishOne() { m_TimeCooked = 0; @@ -166,8 +168,6 @@ void cFurnaceEntity::FinishOne() m_Contents.ChangeSlotCount(fsOutput, m_CurrentRecipe->Out->m_ItemCount); } m_Contents.ChangeSlotCount(fsInput, -m_CurrentRecipe->In->m_ItemCount); - - UpdateIsCooking(); } @@ -181,8 +181,7 @@ void cFurnaceEntity::BurnNewFuel(void) if (NewTime == 0) { // The item in the fuel slot is not suitable - m_FuelBurnTime = 0; - m_TimeBurned = 0; + SetBurnTimes(0, 0); SetIsCooking(false); return; } @@ -194,8 +193,7 @@ void cFurnaceEntity::BurnNewFuel(void) } // Burn one new fuel: - m_FuelBurnTime = NewTime; - m_TimeBurned = 0; + SetBurnTimes(NewTime, 0); SetIsCooking(true); if (m_Contents.GetSlot(fsFuel).m_ItemType == E_ITEM_LAVA_BUCKET) { @@ -214,33 +212,19 @@ void cFurnaceEntity::BurnNewFuel(void) void cFurnaceEntity::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) { super::OnSlotChanged(a_ItemGrid, a_SlotNum); - - if (m_World == NULL) + + if (m_IsDestroyed) { - // The furnace isn't initialized yet, do no processing return; } ASSERT(a_ItemGrid == &m_Contents); switch (a_SlotNum) { - case fsInput: - { - UpdateInput(); - break; - } - - case fsFuel: - { - UpdateFuel(); - break; - } - - case fsOutput: - { - UpdateOutput(); - break; - } + case fsInput: UpdateInput(); break; + case fsFuel: UpdateFuel(); break; + case fsOutput: UpdateOutput(); break; + default: ASSERT(!"Invalid furnace slot update!"); break; } } @@ -249,7 +233,6 @@ void cFurnaceEntity::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) -/// Updates the current recipe, based on the current input void cFurnaceEntity::UpdateInput(void) { if (!m_Contents.GetSlot(fsInput).IsEqual(m_LastInput)) @@ -263,8 +246,8 @@ void cFurnaceEntity::UpdateInput(void) m_CurrentRecipe = FR->GetRecipeFrom(m_Contents.GetSlot(fsInput)); if (!CanCookInputToOutput()) { - // This input cannot be cooked - m_NeedCookTime = 0; + // This input cannot be cooked, reset cook counter immediately + SetCookTimes(0, 0); SetIsCooking(false); } else @@ -284,7 +267,6 @@ void cFurnaceEntity::UpdateInput(void) -/// Called when the fuel slot changes or when the fuel is spent, burns another piece of fuel if appropriate void cFurnaceEntity::UpdateFuel(void) { if (m_FuelBurnTime > m_TimeBurned) @@ -301,14 +283,12 @@ void cFurnaceEntity::UpdateFuel(void) -/// Called when the output slot changes; starts burning if space became available void cFurnaceEntity::UpdateOutput(void) { if (!CanCookInputToOutput()) { // Cannot cook anymore: - m_TimeCooked = 0; - m_NeedCookTime = 0; + SetCookTimes(0, 0); SetIsCooking(false); return; } @@ -324,30 +304,6 @@ void cFurnaceEntity::UpdateOutput(void) -/// Updates the m_IsCooking, based on the input slot, output slot and m_FuelBurnTime / m_TimeBurned -void cFurnaceEntity::UpdateIsCooking(void) -{ - if ( - !CanCookInputToOutput() || // Cannot cook this - (m_FuelBurnTime <= 0) || // No fuel - (m_TimeBurned >= m_FuelBurnTime) // Fuel burnt out - ) - { - // Reset everything - SetIsCooking(false); - m_TimeCooked = 0; - m_NeedCookTime = 0; - return; - } - - SetIsCooking(true); -} - - - - - -/// Returns true if the input can be cooked into output and the item counts allow for another cooking operation bool cFurnaceEntity::CanCookInputToOutput(void) const { if (m_CurrentRecipe == NULL) @@ -382,25 +338,20 @@ bool cFurnaceEntity::CanCookInputToOutput(void) const -/// Broadcasts progressbar updates, if needed -void cFurnaceEntity::UpdateProgressBars(void) +void cFurnaceEntity::UpdateProgressBars(bool a_ForceUpdate) { // In order to preserve bandwidth, an update is sent only every 10th tick - // That's why the comparisons use the division by eight - - int CurFuel = (m_FuelBurnTime > 0) ? (200 - 200 * m_TimeBurned / m_FuelBurnTime) : 0; - if ((CurFuel / 8) != (m_LastProgressFuel / 8)) + if (!a_ForceUpdate && (m_World->GetWorldAge() % 10 != 0)) { - BroadcastProgress(PROGRESSBAR_FUEL, (short)CurFuel); - m_LastProgressFuel = CurFuel; + return; } - int CurCook = (m_NeedCookTime > 0) ? (200 * m_TimeCooked / m_NeedCookTime) : 0; - if ((CurCook / 8) != (m_LastProgressCook / 8)) - { - BroadcastProgress(PROGRESSBAR_SMELTING, (short)CurCook); - m_LastProgressCook = CurCook; - } + int CurFuel = (m_FuelBurnTime > 0) ? 200 - (200 * m_TimeBurned / m_FuelBurnTime) : 0; + BroadcastProgress(PROGRESSBAR_FUEL, (short)CurFuel); + + int CurCook = (m_NeedCookTime > 0) ? (200 * m_TimeCooked / m_NeedCookTime) : 0; + BroadcastProgress(PROGRESSBAR_SMELTING_CONFIRM, 200); // Post 1.8, Mojang requires a random packet with an ID of three and value of 200. Wat. Wat. Wat. + BroadcastProgress(PROGRESSBAR_SMELTING, (short)CurCook); } @@ -413,11 +364,13 @@ void cFurnaceEntity::SetIsCooking(bool a_IsCooking) { return; } - m_IsCooking = a_IsCooking; - - // Light or extinguish the furnace: - m_World->FastSetBlock(m_PosX, m_PosY, m_PosZ, m_IsCooking ? E_BLOCK_LIT_FURNACE : E_BLOCK_FURNACE, m_BlockMeta); + + // Only light the furnace as it is extinguished only when the fuel runs out, not when cooking stops - handled in this::Tick() + if (m_IsCooking) + { + m_World->FastSetBlock(m_PosX, m_PosY, m_PosZ, E_BLOCK_LIT_FURNACE, m_BlockMeta); + } } diff --git a/src/BlockEntities/FurnaceEntity.h b/src/BlockEntities/FurnaceEntity.h index ed3317af6..14dadbec8 100644 --- a/src/BlockEntities/FurnaceEntity.h +++ b/src/BlockEntities/FurnaceEntity.h @@ -38,7 +38,7 @@ public: // tolua_end - /// Constructor used for normal operation + /** Constructor used for normal operation */ cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cWorld * a_World); virtual ~cFurnaceEntity(); @@ -49,103 +49,117 @@ public: virtual void SendTo(cClientHandle & a_Client) override; virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void UsedBy(cPlayer * a_Player) override; + virtual void Destroy() override + { + m_IsDestroyed = true; + super::Destroy(); + } - /// Restarts cooking. Used after the furnace is loaded from storage to set up the internal variables so that cooking continues, if it was active. Returns true if cooking. + /** Restarts cooking + Used after the furnace is loaded from storage to set up the internal variables so that cooking continues, if it was active + Returns true if cooking */ bool ContinueCooking(void); - - void ResetCookTimer(); // tolua_begin - /// Returns the item in the input slot + /** Returns the item in the input slot */ const cItem & GetInputSlot(void) const { return GetSlot(fsInput); } - /// Returns the item in the fuel slot + /** Returns the item in the fuel slot */ const cItem & GetFuelSlot(void) const { return GetSlot(fsFuel); } - /// Returns the item in the output slot + /** Returns the item in the output slot */ const cItem & GetOutputSlot(void) const { return GetSlot(fsOutput); } - /// Sets the item in the input slot + /** Sets the item in the input slot */ void SetInputSlot(const cItem & a_Item) { SetSlot(fsInput, a_Item); } - /// Sets the item in the fuel slot + /** Sets the item in the fuel slot */ void SetFuelSlot(const cItem & a_Item) { SetSlot(fsFuel, a_Item); } - /// Sets the item in the output slot + /** Sets the item in the output slot */ void SetOutputSlot(const cItem & a_Item) { SetSlot(fsOutput, a_Item); } - /// Returns the time that the current item has been cooking, in ticks - int GetTimeCooked(void) const {return m_TimeCooked; } + /** Returns the time that the current item has been cooking, in ticks */ + int GetTimeCooked(void) const { return m_TimeCooked; } - /// Returns the time until the current item finishes cooking, in ticks + /** Returns the time until the current item finishes cooking, in ticks */ int GetCookTimeLeft(void) const { return m_NeedCookTime - m_TimeCooked; } - /// Returns the time until the current fuel is depleted, in ticks - int GetFuelBurnTimeLeft(void) const {return m_FuelBurnTime - m_TimeBurned; } + /** Returns the time until the current fuel is depleted, in ticks */ + int GetFuelBurnTimeLeft(void) const { return m_FuelBurnTime - m_TimeBurned; } - /// Returns true if there's time left before the current fuel is depleted + /** Returns true if there's time left before the current fuel is depleted */ bool HasFuelTimeLeft(void) const { return (GetFuelBurnTimeLeft() > 0); } // tolua_end - void SetBurnTimes(int a_FuelBurnTime, int a_TimeBurned) {m_FuelBurnTime = a_FuelBurnTime; m_TimeBurned = a_TimeBurned; } - void SetCookTimes(int a_NeedCookTime, int a_TimeCooked) {m_NeedCookTime = a_NeedCookTime; m_TimeCooked = a_TimeCooked; } + void SetBurnTimes(int a_FuelBurnTime, int a_TimeBurned) + { + m_FuelBurnTime = a_FuelBurnTime; + m_TimeBurned = a_TimeBurned; + } + + void SetCookTimes(int a_NeedCookTime, int a_TimeCooked) + { + m_NeedCookTime = a_NeedCookTime; + m_TimeCooked = a_TimeCooked; + } protected: - - /// Block type of the block currently represented by this entity (changes when furnace lights up) - BLOCKTYPE m_BlockType; - /// Block meta of the block currently represented by this entity + /** Block meta of the block currently represented by this entity */ NIBBLETYPE m_BlockMeta; - /// The recipe for the current input slot + /** The recipe for the current input slot */ const cFurnaceRecipe::cRecipe * m_CurrentRecipe; - /// The item that is being smelted + /** The item that is being smelted */ cItem m_LastInput; + + /** Set to true when the furnace entity has been destroyed to prevent the block being set again */ + bool m_IsDestroyed; - bool m_IsCooking; ///< Set to true if the furnace is cooking an item - - // All timers are in ticks - int m_NeedCookTime; ///< Amount of time needed to fully cook current item - int m_TimeCooked; ///< Amount of time that the current item has been cooking - int m_FuelBurnTime; ///< Amount of time that the current fuel can burn (in total); zero if no fuel burning - int m_TimeBurned; ///< Amount of time that the current fuel has been burning - - int m_LastProgressFuel; ///< Last value sent as the progress for the fuel - int m_LastProgressCook; ///< Last value sent as the progress for the cooking + /** Set to true if the furnace is cooking an item */ + bool m_IsCooking; + /** Amount of ticks needed to fully cook current item */ + int m_NeedCookTime; + + /** Amount of ticks that the current item has been cooking */ + int m_TimeCooked; + + /** Amount of ticks that the current fuel can burn (in total); zero if no fuel burning */ + int m_FuelBurnTime; + + /** Amount of ticks that the current fuel has been burning */ + int m_TimeBurned; - /// Sends the specified progressbar value to all clients of the window - void BroadcastProgress(int a_ProgressbarID, short a_Value); + /** Sends the specified progressbar value to all clients of the window */ + void BroadcastProgress(short a_ProgressbarID, short a_Value); - /// One item finished cooking + /** One item finished cooking */ void FinishOne(); - /// Starts burning a new fuel, if possible + /** Starts burning a new fuel, if possible */ void BurnNewFuel(void); - /// Updates the recipe, based on the current input + /** Updates the recipe, based on the current input */ void UpdateInput(void); - /// Called when the fuel slot changes or when the fuel is spent, burns another piece of fuel if appropriate + /** Called when the fuel slot changes or when the fuel is spent, burns another piece of fuel if appropriate */ void UpdateFuel(void); - /// Called when the output slot changes + /** Called when the output slot changes */ void UpdateOutput(void); - /// Updates the m_IsCooking, based on the input slot, output slot and m_FuelBurnTime / m_TimeBurned - void UpdateIsCooking(void); - - /// Returns true if the input can be cooked into output and the item counts allow for another cooking operation + /** Returns true if the input can be cooked into output and the item counts allow for another cooking operation */ bool CanCookInputToOutput(void) const; - /// Broadcasts progressbar updates, if needed - void UpdateProgressBars(void); + /** Broadcasts progressbar updates, if needed */ + void UpdateProgressBars(bool a_ForceUpdate = false); - /// Sets the m_IsCooking variable, updates the furnace block type based on the value + /** Sets the m_IsCooking variable, updates the furnace block type based on the value */ void SetIsCooking(bool a_IsCooking); // cItemGrid::cListener overrides: diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 96b8eda4e..88ee9ba31 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -333,7 +333,7 @@ void cChunk::SetAllData(cSetChunkData & a_SetChunkData) { BLOCKTYPE EntityBlockType = (*itr)->GetBlockType(); BLOCKTYPE WorldBlockType = GetBlock((*itr)->GetRelX(), (*itr)->GetPosY(), (*itr)->GetRelZ()); - ASSERT(EntityBlockType == WorldBlockType); + ASSERT((EntityBlockType == E_BLOCK_FURNACE) ? ((EntityBlockType == E_BLOCK_FURNACE) || (EntityBlockType == E_BLOCK_LIT_FURNACE)) : (WorldBlockType == EntityBlockType)); } // for itr - m_BlockEntities #endif // _DEBUG diff --git a/src/Chunk.h b/src/Chunk.h index bc66b6528..8e13ff00e 100644 --- a/src/Chunk.h +++ b/src/Chunk.h @@ -33,7 +33,7 @@ class cChunkMap; class cBeaconEntity; class cBoundingBox; class cChestEntity; -class cCHunkDataCallback; +class cChunkDataCallback; class cCommandBlockEntity; class cDispenserEntity; class cFurnaceEntity; diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index a29bef0c0..359255a3e 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -2694,7 +2694,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/ClientHandle.h b/src/ClientHandle.h index 20592c190..674a8cafd 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -204,7 +204,7 @@ public: void SendWholeInventory (const cWindow & a_Window); void SendWindowClose (const cWindow & a_Window); void SendWindowOpen (const cWindow & a_Window); - void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value); + void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value); // tolua_begin const AString & GetUsername(void) const; diff --git a/src/Protocol/Protocol.h b/src/Protocol/Protocol.h index 7225f663d..02a8a52f6 100644 --- a/src/Protocol/Protocol.h +++ b/src/Protocol/Protocol.h @@ -130,7 +130,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, int a_Property, int a_Value) = 0; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) = 0; /// Returns the ServerID used for authentication through session.minecraft.net virtual AString GetAuthServerID(void) = 0; diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index a7abd240f..204691ede 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -1439,7 +1439,7 @@ void cProtocol172::SendWindowOpen(const cWindow & a_Window) -void cProtocol172::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) +void cProtocol172::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value) { ASSERT(m_State == 3); // In game mode? diff --git a/src/Protocol/Protocol17x.h b/src/Protocol/Protocol17x.h index 7709df59d..f939bfb5e 100644 --- a/src/Protocol/Protocol17x.h +++ b/src/Protocol/Protocol17x.h @@ -134,7 +134,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, int a_Property, int a_Value) override; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override; virtual AString GetAuthServerID(void) override { return m_AuthServerID; } diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index acdb48cf7..c9118c239 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -1500,7 +1500,7 @@ void cProtocol180::SendWindowOpen(const cWindow & a_Window) -void cProtocol180::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) +void cProtocol180::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value) { ASSERT(m_State == 3); // In game mode? diff --git a/src/Protocol/Protocol18x.h b/src/Protocol/Protocol18x.h index 8c0b77a21..92d9825ef 100644 --- a/src/Protocol/Protocol18x.h +++ b/src/Protocol/Protocol18x.h @@ -133,7 +133,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, int a_Property, int a_Value) override; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override; virtual AString GetAuthServerID(void) override { return m_AuthServerID; } diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index 4f8eb59db..0b829ac9e 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -350,7 +350,7 @@ void cProtocolRecognizer::SendHealth(void) -void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) +void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, short a_Property, short 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 96a7e17d2..f60df4158 100644 --- a/src/Protocol/ProtocolRecognizer.h +++ b/src/Protocol/ProtocolRecognizer.h @@ -121,7 +121,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, int a_Property, int a_Value) override; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override; virtual AString GetAuthServerID(void) override; diff --git a/src/UI/Window.cpp b/src/UI/Window.cpp index d83336f75..802d0d219 100644 --- a/src/UI/Window.cpp +++ b/src/UI/Window.cpp @@ -758,20 +758,7 @@ void cWindow::BroadcastWholeWindow(void) -void cWindow::BroadcastProgress(int a_Progressbar, int a_Value) -{ - cCSLock Lock(m_CS); - for (cPlayerList::iterator itr = m_OpenedBy.begin(); itr != m_OpenedBy.end(); ++itr) - { - (*itr)->GetClientHandle()->SendWindowProperty(*this, a_Progressbar, a_Value); - } // for itr - m_OpenedBy[] -} - - - - - -void cWindow::SetProperty(int a_Property, int a_Value) +void cWindow::SetProperty(short a_Property, short a_Value) { cCSLock Lock(m_CS); for (cPlayerList::iterator itr = m_OpenedBy.begin(), end = m_OpenedBy.end(); itr != end; ++itr) @@ -784,7 +771,7 @@ void cWindow::SetProperty(int a_Property, int a_Value) -void cWindow::SetProperty(int a_Property, int a_Value, cPlayer & a_Player) +void cWindow::SetProperty(short a_Property, short a_Value, cPlayer & a_Player) { a_Player.GetClientHandle()->SendWindowProperty(*this, a_Property, a_Value); } @@ -919,7 +906,7 @@ cEnchantingWindow::cEnchantingWindow(int a_BlockX, int a_BlockY, int a_BlockZ) : -void cEnchantingWindow::SetProperty(int a_Property, int a_Value) +void cEnchantingWindow::SetProperty(short a_Property, short a_Value) { if ((a_Property < 0) || ((size_t)a_Property >= ARRAYCOUNT(m_PropertyValue))) { @@ -935,7 +922,7 @@ void cEnchantingWindow::SetProperty(int a_Property, int a_Value) -void cEnchantingWindow::SetProperty(int a_Property, int a_Value, cPlayer & a_Player) +void cEnchantingWindow::SetProperty(short a_Property, short a_Value, cPlayer & a_Player) { if ((a_Property < 0) || ((size_t)a_Property >= ARRAYCOUNT(m_PropertyValue))) { @@ -951,7 +938,7 @@ void cEnchantingWindow::SetProperty(int a_Property, int a_Value, cPlayer & a_Pla -int cEnchantingWindow::GetPropertyValue(int a_Property) +short cEnchantingWindow::GetPropertyValue(short a_Property) { if ((a_Property < 0) || ((size_t)a_Property >= ARRAYCOUNT(m_PropertyValue))) { diff --git a/src/UI/Window.h b/src/UI/Window.h index 6b6dce346..26dd7f125 100644 --- a/src/UI/Window.h +++ b/src/UI/Window.h @@ -130,9 +130,6 @@ public: /// Sends the contents of the whole window to all clients of this window. void BroadcastWholeWindow(void); - - /// Sends the progressbar to all clients of this window (same as SetProperty) - void BroadcastProgress(int a_Progressbar, int a_Value); // tolua_begin @@ -140,10 +137,10 @@ public: void SetWindowTitle(const AString & a_WindowTitle) { m_WindowTitle = a_WindowTitle; } /// Sends the UpdateWindowProperty (0x69) packet to all clients of the window - virtual void SetProperty(int a_Property, int a_Value); + virtual void SetProperty(short a_Property, short a_Value); /// Sends the UpdateWindowPropert(0x69) packet to the specified player - virtual void SetProperty(int a_Property, int a_Value, cPlayer & a_Player); + virtual void SetProperty(short a_Property, short a_Value, cPlayer & a_Player); // tolua_end @@ -287,16 +284,16 @@ class cEnchantingWindow : typedef cWindow super; public: cEnchantingWindow(int a_BlockX, int a_BlockY, int a_BlockZ); - virtual void SetProperty(int a_Property, int a_Value, cPlayer & a_Player) override; - virtual void SetProperty(int a_Property, int a_Value) override; + virtual void SetProperty(short a_Property, short a_Value, cPlayer & a_Player) override; + virtual void SetProperty(short a_Property, short a_Value) override; /** Return the Value of a Property */ - int GetPropertyValue(int a_Property); + short GetPropertyValue(short a_Property); cSlotArea * m_SlotArea; protected: - int m_PropertyValue[3]; + short m_PropertyValue[3]; int m_BlockX, m_BlockY, m_BlockZ; }; -- cgit v1.2.3 From 79e9de8d67e5fdf61c1f80794b5a31e6ac80e7a6 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Fri, 3 Oct 2014 21:38:23 +0100 Subject: Comment suggestions --- src/Blocks/BlockTorch.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index 3070adfd9..e77bbd1b8 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -37,6 +37,7 @@ public: a_BlockFace = FindSuitableFace(a_ChunkInterface, a_BlockX, a_BlockY, a_BlockZ); // Set a_BlockFace to a valid direction which will be converted later to a metadata if (a_BlockFace == BLOCK_FACE_NONE) { + // No attachable face found - don't place the torch return false; } } @@ -116,7 +117,7 @@ public: { if (cBlockInfo::FullyOccupiesVoxel(a_BlockType)) { - // Torches can be placed on full blocks unless their bottom side is clicked + // Torches can be placed on all sides of full blocks except the bottom return (a_BlockFace != BLOCK_FACE_YM); } return false; @@ -125,7 +126,7 @@ public: } - /// Finds a suitable face to place the torch, returning BLOCK_FACE_NONE on failure + /** Finds a suitable face to place the torch, returning BLOCK_FACE_NONE on failure */ static eBlockFace FindSuitableFace(cChunkInterface & a_ChunkInterface, int a_BlockX, int a_BlockY, int a_BlockZ) { for (int i = BLOCK_FACE_YM; i <= BLOCK_FACE_XP; i++) // Loop through all directions -- cgit v1.2.3 From f8c1da4a7178e7bb3d1bab3aaff7e326a855a0a8 Mon Sep 17 00:00:00 2001 From: win32re Date: Sat, 4 Oct 2014 14:02:40 +0200 Subject: Fixes #1503 - No gravel is being generated --- src/Generating/ComposableGenerator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 4efcd1284..87461b944 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -422,7 +422,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) // Gravel vein cStructGenOreNests::OreInfo GravelVein; - GravelVein.BlockType = E_BLOCK_DIRT; + GravelVein.BlockType = E_BLOCK_GRAVEL; GravelVein.MaxHeight = 127; GravelVein.NumNests = 20; GravelVein.NestSize = 32; -- cgit v1.2.3 From ec71ffcc8015a9dccfa1d6f8dd474524412b605f Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 5 Oct 2014 19:04:30 +0200 Subject: Added a cEvent::Wait() with timeout. --- src/OSSupport/Event.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/OSSupport/Event.h | 4 ++++ 2 files changed, 51 insertions(+) (limited to 'src') diff --git a/src/OSSupport/Event.cpp b/src/OSSupport/Event.cpp index 74f823216..7cf8a826c 100644 --- a/src/OSSupport/Event.cpp +++ b/src/OSSupport/Event.cpp @@ -102,6 +102,53 @@ void cEvent::Wait(void) +bool cEvent::Wait(int a_TimeoutMSec) +{ + #ifdef _WIN32 + DWORD res = WaitForSingleObject(m_Event, (DWORD)a_TimeoutMSec); + switch (res) + { + case WAIT_OBJECT_0: return true; // Regular event signalled + case WAIT_TIMEOUT: return false; // Regular event timeout + default: + { + LOGWARN("cEvent: waiting for the event failed: %u, GLE = %u. Continuing, but server may be unstable.", (unsigned)res, (unsigned)GetLastError()); + return false; + } + } + #else + // Get the current time: + timespec timeout; + if (clock_gettime(CLOCK_REALTIME, &timeout) == -1) + { + LOGWARN("cEvent: Getting current time failed: %i, err = %s. Continuing, but the server may be unstable.", errno, GetOSErrorString(errno).c_str()); + return false; + } + + // Add the specified timeout: + timeout.tv_sec += a_TimeoutMSec / 1000; + timeout.tv_nsec += (a_TimeoutMSec % 1000) * 1000000; // 1 msec = 1000000 usec + + // Wait with timeout: + int res = sem_timedwait(m_Event, &timeout); + switch (res) + { + case 0: return true; // Regular event signalled + case ETIMEDOUT: return false; // Regular even timeout + default: + { + AString error = GetOSErrorString(errno); + LOGWARN("cEvent: waiting for the event failed: %i, err = %s. Continuing, but server may be unstable.", res, error.c_str()); + return false; + } + } + #endif +} + + + + + void cEvent::Set(void) { #ifdef _WIN32 diff --git a/src/OSSupport/Event.h b/src/OSSupport/Event.h index 71f418c0c..e2fa65a05 100644 --- a/src/OSSupport/Event.h +++ b/src/OSSupport/Event.h @@ -24,6 +24,10 @@ public: void Wait(void); void Set (void); + + /** Waits for the event until either it is signalled, or the (relative) timeout is passed. + Returns true if the event was signalled, false if the timeout was hit or there was an error. */ + bool Wait(int a_TimeoutMSec); private: -- cgit v1.2.3 From a8aeceab9d6e5e5e36ef7bd58783b65aca4d8be7 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 5 Oct 2014 20:19:21 +0200 Subject: cClientHandle: Added protocol version knowledge. --- src/ClientHandle.cpp | 12 ++++++++++-- src/ClientHandle.h | 9 +++++++++ src/Protocol/ProtocolRecognizer.cpp | 1 + src/Protocol/ProtocolRecognizer.h | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index a29bef0c0..3b677460b 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -92,7 +92,8 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_NumBlockChangeInteractionsThisTick(0), m_UniqueID(0), m_HasSentPlayerChunk(false), - m_Locale("en_GB") + m_Locale("en_GB"), + m_ProtocolVersion(0) { m_Protocol = new cProtocolRecognizer(this); @@ -583,15 +584,22 @@ void cClientHandle::HandlePing(void) bool cClientHandle::HandleLogin(int a_ProtocolVersion, const AString & a_Username) { + // If the protocol version hasn't been set yet, set it now: + if (m_ProtocolVersion == 0) + { + m_ProtocolVersion = a_ProtocolVersion; + } + m_Username = a_Username; + // Let the plugins know about this event, they may refuse the player: if (cRoot::Get()->GetPluginManager()->CallHookLogin(this, a_ProtocolVersion, a_Username)) { Destroy(); return false; } - // Schedule for authentication; until then, let them wait (but do not block) + // Schedule for authentication; until then, let the player wait (but do not block) m_State = csAuthenticating; cRoot::Get()->GetAuthenticator().Authenticate(GetUniqueID(), GetUsername(), m_Protocol->GetAuthServerID()); return true; diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 20592c190..a9cc29d50 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -316,6 +316,12 @@ public: /** Called when the player will enchant a Item */ void HandleEnchantItem(Byte & a_WindowID, Byte & a_Enchantment); + + /** Called by the protocol recognizer when the protocol version is known. */ + void SetProtocolVersion(UInt32 a_ProtocolVersion) { m_ProtocolVersion = a_ProtocolVersion; } + + /** Returns the protocol version number of the protocol that the client is talking. Returns zero if the protocol version is not (yet) known. */ + UInt32 GetProtocolVersion(void) const { return m_ProtocolVersion; } // tolua_export private: @@ -427,6 +433,9 @@ private: /** The brand identification of the client, as received in the MC|Brand plugin message or set from a plugin. */ AString m_ClientBrand; + /** The version of the protocol that the client is talking, or 0 if unknown. */ + UInt32 m_ProtocolVersion; + /** Handles the block placing packet when it is a real block placement (not block-using, item-using or eating) */ void HandlePlaceBlock(int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ, cItemHandler & a_ItemHandler); diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index 4f8eb59db..15bcd03b1 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -905,6 +905,7 @@ bool cProtocolRecognizer::TryRecognizeLengthedProtocol(UInt32 a_PacketLengthRema { return false; } + m_Client->SetProtocolVersion(ProtocolVersion); switch (ProtocolVersion) { case PROTO_VERSION_1_7_2: diff --git a/src/Protocol/ProtocolRecognizer.h b/src/Protocol/ProtocolRecognizer.h index 96a7e17d2..b42cfdec2 100644 --- a/src/Protocol/ProtocolRecognizer.h +++ b/src/Protocol/ProtocolRecognizer.h @@ -134,7 +134,7 @@ protected: /// Tries to recognize protocol based on m_Buffer contents; returns true if recognized bool TryRecognizeProtocol(void); - /** Tries to recognize a protocol in the leghted family (1.7+), based on m_Buffer; returns true if recognized. + /** Tries to recognize a protocol in the lengthed family (1.7+), based on m_Buffer; returns true if recognized. The packet length and type have already been read, type is 0 The number of bytes remaining in the packet is passed as a_PacketLengthRemaining **/ -- cgit v1.2.3 From 77c5b410e653433a17c7cf25b115dae4c25bdbd2 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sun, 5 Oct 2014 22:09:19 +0200 Subject: Fixed eMonsterType Lua API mismatch. --- src/Bindings/AllToLua.pkg | 1 + src/BlockID.cpp | 51 ----------------------------------------------- src/BlockID.h | 3 --- src/Mobs/CMakeLists.txt | 1 + src/Mobs/Monster.cpp | 10 ++++++++++ src/Mobs/MonsterTypes.h | 13 ++++++++++++ 6 files changed, 25 insertions(+), 54 deletions(-) (limited to 'src') diff --git a/src/Bindings/AllToLua.pkg b/src/Bindings/AllToLua.pkg index 37e6aecd2..73de98e22 100644 --- a/src/Bindings/AllToLua.pkg +++ b/src/Bindings/AllToLua.pkg @@ -27,6 +27,7 @@ $cfile "WebPlugin.h" $cfile "LuaWindow.h" $cfile "../BlockID.h" +$cfile "../Mobs/MonsterTypes.h" $cfile "../BlockInfo.h" $cfile "../StringUtils.h" $cfile "../Defines.h" diff --git a/src/BlockID.cpp b/src/BlockID.cpp index 9026d81f2..755c721db 100644 --- a/src/BlockID.cpp +++ b/src/BlockID.cpp @@ -253,57 +253,6 @@ AString ItemToFullString(const cItem & a_Item) -int StringToMobType(const AString & a_MobString) -{ - static struct - { - int m_MobType; - const char * m_String; - } MobMap [] = - { - {mtCreeper, "Creeper"}, - {mtSkeleton, "Skeleton"}, - {mtSpider, "Spider"}, - {mtGiant, "Giant"}, - {mtZombie, "Zombie"}, - {mtSlime, "Slime"}, - {mtGhast, "Ghast"}, - {mtZombiePigman, "ZombiePigman"}, - {mtEnderman, "Enderman"}, - {mtCaveSpider, "CaveSpider"}, - {mtSilverfish, "SilverFish"}, - {mtBlaze, "Blaze"}, - {mtMagmaCube, "MagmaCube"}, - {mtEnderDragon, "EnderDragon"}, - {mtWither, "Wither"}, - {mtBat, "Bat"}, - {mtWitch, "Witch"}, - {mtPig, "Pig"}, - {mtSheep, "Sheep"}, - {mtCow, "Cow"}, - {mtChicken, "Chicken"}, - {mtSquid, "Squid"}, - {mtWolf, "Wolf"}, - {mtMooshroom, "Mooshroom"}, - {mtSnowGolem, "SnowGolem"}, - {mtOcelot, "Ocelot"}, - {mtIronGolem, "IronGolem"}, - {mtVillager, "Villager"}, - }; - for (size_t i = 0; i < ARRAYCOUNT(MobMap); i++) - { - if (NoCaseCompare(MobMap[i].m_String, a_MobString) == 0) - { - return MobMap[i].m_MobType; - } - } // for i - MobMap[] - return -1; -} - - - - - eDimension StringToDimension(const AString & a_DimensionString) { // First try decoding as a number diff --git a/src/BlockID.h b/src/BlockID.h index 69b5e2fe0..e36843422 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -1005,9 +1005,6 @@ extern AString ItemTypeToString(short a_ItemType); /// Translates a full item into a fully-specified string (including meta and count). If the ItemType is not recognized, the ItemType number is output into the string. extern AString ItemToFullString(const cItem & a_Item); -/// Translates a mob string ("ocelot") to mobtype (E_ENTITY_TYPE_OCELOT) -extern int StringToMobType(const AString & a_MobString); - /// Translates a dimension string to dimension enum. Takes either a number or a dimension alias (built-in). Returns dimOverworld on failure extern eDimension StringToDimension(const AString & a_DimensionString); diff --git a/src/Mobs/CMakeLists.txt b/src/Mobs/CMakeLists.txt index 2c092c15f..bbbb9287a 100644 --- a/src/Mobs/CMakeLists.txt +++ b/src/Mobs/CMakeLists.txt @@ -54,6 +54,7 @@ SET (HDRS IronGolem.h MagmaCube.h Monster.h + MonsterTypes.h Mooshroom.h Ocelot.h PassiveAggressiveMonster.h diff --git a/src/Mobs/Monster.cpp b/src/Mobs/Monster.cpp index 12ca6bbbe..cc48dba5e 100644 --- a/src/Mobs/Monster.cpp +++ b/src/Mobs/Monster.cpp @@ -62,6 +62,16 @@ static const struct +eMonsterType StringToMobType(const AString & a_MobString) +{ + LOGWARNING("%s: Function is obsolete, use cMonster::StringToMobType() instead"); + return cMonster::StringToMobType(a_MobString); +} + + + + + //////////////////////////////////////////////////////////////////////////////// // cMonster: diff --git a/src/Mobs/MonsterTypes.h b/src/Mobs/MonsterTypes.h index 7a73e99f4..852eb3446 100644 --- a/src/Mobs/MonsterTypes.h +++ b/src/Mobs/MonsterTypes.h @@ -37,5 +37,18 @@ enum eMonsterType mtZombie = E_META_SPAWN_EGG_ZOMBIE, mtZombiePigman = E_META_SPAWN_EGG_ZOMBIE_PIGMAN, } ; + + + + + +/** Translates a mob string ("ocelot") to mobtype (mtOcelot). +OBSOLETE, use cMonster::StringToMobType() instead. +Implemented in Monster.cpp. */ +extern eMonsterType StringToMobType(const AString & a_MobString); + // tolua_end + + + -- cgit v1.2.3 From 112fac579829edf32e41da6da4bd8a98e5b6f0bd Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sun, 5 Oct 2014 22:12:25 +0200 Subject: Removed obsolete cMonster::eType. Has been replaced with global eMonsterType. --- src/Mobs/Monster.h | 3 --- 1 file changed, 3 deletions(-) (limited to 'src') diff --git a/src/Mobs/Monster.h b/src/Mobs/Monster.h index a1f9c4a5b..9fd67d67c 100644 --- a/src/Mobs/Monster.h +++ b/src/Mobs/Monster.h @@ -25,9 +25,6 @@ class cMonster : typedef cPawn super; public: - // Deprecated - typedef eMonsterType eType; - enum eFamily { mfHostile = 0, // Spider, Zombies ... -- cgit v1.2.3 From c94e82980e0c21f9a7ed18c5f3279e63849e8433 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Sun, 5 Oct 2014 22:56:56 +0200 Subject: Fixed a missed value. --- src/Mobs/Monster.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Mobs/Monster.cpp b/src/Mobs/Monster.cpp index cc48dba5e..73dbcb3c3 100644 --- a/src/Mobs/Monster.cpp +++ b/src/Mobs/Monster.cpp @@ -64,7 +64,7 @@ static const struct eMonsterType StringToMobType(const AString & a_MobString) { - LOGWARNING("%s: Function is obsolete, use cMonster::StringToMobType() instead"); + LOGWARNING("%s: Function is obsolete, use cMonster::StringToMobType() instead", __FUNCTION__); return cMonster::StringToMobType(a_MobString); } -- cgit v1.2.3 From a20bd0dbbd9c107a47049ce83f0b050384fd7b19 Mon Sep 17 00:00:00 2001 From: worktycho Date: Sun, 5 Oct 2014 23:44:55 +0100 Subject: Update CMakeLists.txt --- src/OSSupport/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index a42fcbed4..429949c59 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -39,6 +39,6 @@ if(NOT MSVC) add_library(OSSupport ${SRCS} ${HDRS}) if(UNIX) - target_link_libraries(OSSupport pthread) + target_link_libraries(OSSupport pthread rt) endif() endif() -- cgit v1.2.3 From 3d2d8a096b72a0af9d4e21198d112d97c9318410 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 5 Oct 2014 20:03:21 +0200 Subject: cMojangAPI: Added periodical refreshes. --- src/Protocol/MojangAPI.cpp | 130 ++++++++++++++++++++++++++++++++++++++------- src/Protocol/MojangAPI.h | 21 ++++++++ 2 files changed, 132 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp index 28da83c31..0a6716e6f 100644 --- a/src/Protocol/MojangAPI.cpp +++ b/src/Protocol/MojangAPI.cpp @@ -11,6 +11,8 @@ #include "json/json.h" #include "PolarSSL++/BlockingSslClientSocket.h" #include "../RankManager.h" +#include "../OSSupport/IsThread.h" +#include "../Root.h" @@ -151,6 +153,41 @@ cMojangAPI::sProfile::sProfile( +//////////////////////////////////////////////////////////////////////////////// +// cMojangAPI::cUpdateThread: + +class cMojangAPI::cUpdateThread : + public cIsThread +{ + typedef cIsThread super; +public: + cUpdateThread() : + super("cMojangAPI::cUpdateThread") + { + } + + ~cUpdateThread() + { + m_evtNotify.Set(); + Stop(); + } + +protected: + cEvent m_evtNotify; + + virtual void Execute(void) override + { + do + { + cRoot::Get()->GetMojangAPI().Update(); + } while (!m_evtNotify.Wait(60 * 60 * 1000)); // Repeat every 60 minutes + } +} ; + + + + + //////////////////////////////////////////////////////////////////////////////// // cMojangAPI: @@ -159,7 +196,8 @@ cMojangAPI::cMojangAPI(void) : m_NameToUUIDAddress(DEFAULT_NAME_TO_UUID_ADDRESS), m_UUIDToProfileServer(DEFAULT_UUID_TO_PROFILE_SERVER), m_UUIDToProfileAddress(DEFAULT_UUID_TO_PROFILE_ADDRESS), - m_RankMgr(NULL) + m_RankMgr(NULL), + m_UpdateThread(new cUpdateThread()) { } @@ -183,6 +221,7 @@ void cMojangAPI::Start(cIniFile & a_SettingsIni) m_UUIDToProfileServer = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileServer", DEFAULT_UUID_TO_PROFILE_SERVER); m_UUIDToProfileAddress = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileAddress", DEFAULT_UUID_TO_PROFILE_ADDRESS); LoadCachesFromDisk(); + m_UpdateThread->Start(); } @@ -465,21 +504,7 @@ void cMojangAPI::LoadCachesFromDisk(void) db.exec("CREATE TABLE IF NOT EXISTS PlayerNameToUUID (PlayerName, UUID, DateTime)"); db.exec("CREATE TABLE IF NOT EXISTS UUIDToProfile (UUID, PlayerName, Textures, TexturesSignature, DateTime)"); - // Clean up old entries: - { - SQLite::Statement stmt(db, "DELETE FROM PlayerNameToUUID WHERE DateTime < ?"); - Int64 LimitDateTime = time(NULL) - MAX_AGE; - stmt.bind(1, LimitDateTime); - stmt.exec(); - } - { - SQLite::Statement stmt(db, "DELETE FROM UUIDToProfile WHERE DateTime < ?"); - Int64 LimitDateTime = time(NULL) - MAX_AGE; - stmt.bind(1, LimitDateTime); - stmt.exec(); - } - - // Retrieve all remaining entries: + // Retrieve all entries: { SQLite::Statement stmt(db, "SELECT PlayerName, UUID, DateTime FROM PlayerNameToUUID"); while (stmt.executeStep()) @@ -596,18 +621,27 @@ void cMojangAPI::CacheNamesToUUIDs(const AStringVector & a_PlayerNames) } // for itr - a_PlayerNames[] } // Lock(m_CSNameToUUID) - while (!NamesToQuery.empty()) + QueryNamesToUUIDs(NamesToQuery); +} + + + + + +void cMojangAPI::QueryNamesToUUIDs(AStringVector & a_NamesToQuery) +{ + while (!a_NamesToQuery.empty()) { // Create the request body - a JSON containing up to MAX_PER_QUERY playernames: Json::Value root; int Count = 0; - AStringVector::iterator itr = NamesToQuery.begin(), end = NamesToQuery.end(); + AStringVector::iterator itr = a_NamesToQuery.begin(), end = a_NamesToQuery.end(); for (; (itr != end) && (Count < MAX_PER_QUERY); ++itr, ++Count) { Json::Value req(*itr); root.append(req); } // for itr - a_PlayerNames[] - NamesToQuery.erase(NamesToQuery.begin(), itr); + a_NamesToQuery.erase(a_NamesToQuery.begin(), itr); Json::FastWriter Writer; AString RequestBody = Writer.write(root); @@ -705,12 +739,22 @@ void cMojangAPI::CacheUUIDToProfile(const AString & a_UUID) // Check if already present: { + cCSLock Lock(m_CSUUIDToProfile); if (m_UUIDToProfile.find(a_UUID) != m_UUIDToProfile.end()) { return; } } + QueryUUIDToProfile(a_UUID); +} + + + + + +void cMojangAPI::QueryUUIDToProfile(const AString & a_UUID) +{ // Create the request address: AString Address = m_UUIDToProfileAddress; ReplaceString(Address, "%UUID%", a_UUID); @@ -817,3 +861,51 @@ void cMojangAPI::NotifyNameUUID(const AString & a_PlayerName, const AString & a_ + +void cMojangAPI::Update(void) +{ + Int64 LimitDateTime = time(NULL) - MAX_AGE; + + // Re-query all playernames that are stale: + AStringVector PlayerNames; + { + cCSLock Lock(m_CSNameToUUID); + for (cProfileMap::const_iterator itr = m_NameToUUID.begin(), end = m_NameToUUID.end(); itr != end; ++itr) + { + if (itr->second.m_DateTime < LimitDateTime) + { + PlayerNames.push_back(itr->first); + } + } // for itr - m_NameToUUID[] + } + if (!PlayerNames.empty()) + { + LOG("cMojangAPI: Updating name-to-uuid cache for %u names", (unsigned)PlayerNames.size()); + QueryNamesToUUIDs(PlayerNames); + } + + // Re-query all profiles that are stale: + AStringVector ProfileUUIDs; + { + cCSLock Lock(m_CSUUIDToProfile); + for (cProfileMap::const_iterator itr = m_UUIDToProfile.begin(), end = m_UUIDToProfile.end(); itr != end; ++itr) + { + if (itr->second.m_DateTime < LimitDateTime) + { + ProfileUUIDs.push_back(itr->first); + } + } // for itr - m_UUIDToProfile[] + } + if (!ProfileUUIDs.empty()) + { + LOG("cMojangAPI: Updating uuid-to-profile cache for %u uuids", (unsigned)ProfileUUIDs.size()); + for (AStringVector::const_iterator itr = ProfileUUIDs.begin(), end = ProfileUUIDs.end(); itr != end; ++itr) + { + QueryUUIDToProfile(*itr); + } + } +} + + + + diff --git a/src/Protocol/MojangAPI.h b/src/Protocol/MojangAPI.h index 252d32543..fa4c16e4e 100644 --- a/src/Protocol/MojangAPI.h +++ b/src/Protocol/MojangAPI.h @@ -93,6 +93,10 @@ public: void SetRankManager(cRankManager * a_RankManager) { m_RankMgr = a_RankManager; } protected: + /** The thread that periodically checks for stale data and re-queries it from the server. */ + class cUpdateThread; + + /** Holds data for a single player profile. */ struct sProfile { @@ -177,6 +181,9 @@ protected: /** Protects m_RankMgr agains simultaneous multi-threaded access. */ cCriticalSection m_CSRankMgr; + + /** The thread that periodically updates the stale data in the DB from the Mojang servers. */ + SharedPtr m_UpdateThread; /** Loads the caches from a disk storage. */ @@ -189,15 +196,29 @@ protected: Names that are not valid are not added into the cache. ASSUMEs that a_PlayerNames contains lowercased player names. */ void CacheNamesToUUIDs(const AStringVector & a_PlayerNames); + + /** Queries all the specified names and stores them into the m_PlayerNameToUUID cache. + Names that are not valid are not added into the cache. + ASSUMEs that a_PlayerNames contans lowercased player names. + For performance reasons takes a non-const reference and modifies the list given to it, until empty. */ + void QueryNamesToUUIDs(AStringVector & a_PlayerNames); /** Makes sure the specified UUID is in the m_UUIDToProfile cache. If missing, downloads it from Mojang API servers. UUIDs that are not valid will not be added into the cache. ASSUMEs that a_UUID is a lowercased short UUID. */ void CacheUUIDToProfile(const AString & a_UUID); + /** Queries the specified UUID's profile and stores it in the m_UUIDToProfile cache. If already present, updates the cache entry. + UUIDs that are not valid will not be added into the cache. + ASSUMEs that a_UUID is a lowercased short UUID. */ + void QueryUUIDToProfile(const AString & a_UUID); + /** Called for each name-uuid pairing that is discovered. If assigned, notifies the m_RankManager of the event. */ void NotifyNameUUID(const AString & a_PlayerName, const AString & a_PlayerUUID); + + /** Updates the stale values in the DB from the Mojang servers. Called from the cUpdateThread, blocks on the HTTPS API calls. */ + void Update(void); } ; // tolua_export -- cgit v1.2.3 From 4e82a580602226e37aae0b1c361e71e4ce47ef52 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Mon, 6 Oct 2014 13:48:44 +0200 Subject: Fixed crash in ForEachEntityInBox API. Fixes #1511. --- src/Bindings/LuaState.cpp | 14 +++++++++++--- src/Bindings/LuaState.h | 2 +- src/Bindings/ManualBindings.cpp | 8 ++++++-- 3 files changed, 18 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index ba2f3c5e0..85e3f9fc5 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -861,6 +861,11 @@ void cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal) void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal) { + if (lua_isnil(m_LuaState, a_StackPos)) + { + a_ReturnedVal = NULL; + return; + } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cBoundingBox", false, &err)) { @@ -874,6 +879,11 @@ void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal) void cLuaState::GetStackValue(int a_StackPos, pWorld & a_ReturnedVal) { + if (lua_isnil(m_LuaState, a_StackPos)) + { + a_ReturnedVal = NULL; + return; + } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cWorld", false, &err)) { @@ -1396,10 +1406,8 @@ void cLuaState::LogStack(const char * a_Header) void cLuaState::LogStack(lua_State * a_LuaState, const char * a_Header) { - UNUSED(a_Header); // The param seems unused when compiling for release, so the compiler warns - // Format string consisting only of %s is used to appease the compiler - LOGD("%s", (a_Header != NULL) ? a_Header : "Lua C API Stack contents:"); + LOG("%s", (a_Header != NULL) ? a_Header : "Lua C API Stack contents:"); for (int i = lua_gettop(a_LuaState); i > 0; i--) { AString Value; diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index 094a200e0..ef87c3efc 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -304,7 +304,7 @@ public: void ToString(int a_StackPos, AString & a_String); /** Logs all the elements' types on the API stack, with an optional header for the listing. */ - void LogStack(const char * a_Header); + void LogStack(const char * a_Header = NULL); /** Logs all the elements' types on the API stack, with an optional header for the listing. */ static void LogStack(lua_State * a_LuaState, const char * a_Header = NULL); diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index f4764447c..f643f06ec 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -697,8 +697,12 @@ static int tolua_ForEachInBox(lua_State * tolua_S) Ty1 * Self = NULL; cBoundingBox * Box = NULL; L.GetStackValues(1, Self, Box); - ASSERT(Self != NULL); // We have verified the type at the top, so we should get valid objects here - ASSERT(Box != NULL); + if ((Self == NULL) || (Box == NULL)) + { + LOGWARNING("Invalid world (%p) or boundingbox (%p)", Self, Box); + L.LogStackTrace(); + return 0; + } // Create a reference for the function: cLuaState::cRef FnRef(L, 3); -- cgit v1.2.3 From 5a6b86180e0144a5671c747b838d14992c21afae Mon Sep 17 00:00:00 2001 From: Howaner Date: Mon, 6 Oct 2014 17:38:17 +0200 Subject: Better StreamNextChunk() method --- src/ClientHandle.cpp | 131 +++++++++++++++++++++++++++++++++++++++++++++------ src/ClientHandle.h | 4 ++ 2 files changed, 120 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 27d41da1b..3c73296a4 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -70,6 +70,8 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_OutgoingData(64 KiB), m_Player(NULL), m_HasSentDC(false), + m_LastStreamedChunkX(0x7fffffff), // bogus chunk coords to force streaming upon login + m_LastStreamedChunkZ(0x7fffffff), m_TimeSinceLastPacket(0), m_Ping(1000), m_PingID(1), @@ -405,44 +407,133 @@ void cClientHandle::StreamNextChunk(void) { return; } + ASSERT(m_Player != NULL); + int ChunkPosX = m_Player->GetChunkX(); + int ChunkPosZ = m_Player->GetChunkZ(); + if ((m_LastStreamedChunkX == ChunkPosX) && (m_LastStreamedChunkZ == ChunkPosZ)) + { + // All chunks are already loaded. Abort loading. + return; + } + + // Get the look vector and normalize it. + Vector3d Position = m_Player->GetEyePosition(); Vector3d LookVector = m_Player->GetLookVector(); LookVector.Normalize(); - Vector3d Position = m_Player->GetEyePosition(); + // Lock the list + cCSLock Lock(m_CSChunkLists); + + // High priority: Load the chunks that are in the view-direction of the player (with a radius of 3) for (size_t Range = 0; Range < (size_t)m_ViewDistance; Range++) { Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; + // Get the chunk from the x/z coords. int RangeX, RangeZ = 0; cChunkDef::BlockToChunk((int)std::floor(Vector.x), (int)std::floor(Vector.z), RangeX, RangeZ); - for (size_t X = 0; X < 6; X++) + for (size_t X = 0; X < 7; X++) { - for (size_t Z = 0; Z < 6; Z++) + for (size_t Z = 0; Z < 7; Z++) { - int ChunkX = RangeX + ((X >= 3) ? (2 - X) : X); - int ChunkZ = RangeZ + ((Z >= 3) ? (2 - Z) : Z); + int ChunkX = RangeX + ((X >= 4) ? (3 - X) : X); + int ChunkZ = RangeZ + ((Z >= 4) ? (3 - Z) : Z); cChunkCoords Coords(ChunkX, ChunkZ); // If the chunk already loading/loaded -> skip + if ( + (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || + (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) + ) { - cCSLock Lock(m_CSChunkLists); - if ( - (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || - (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) - ) - { - continue; - } + continue; } // Unloaded chunk found -> Send it to the client. + Lock.Unlock(); StreamChunk(ChunkX, ChunkZ); return; } } } + + // Medium priority: Load the chunks that are behind the player + LookVector = m_Player->GetLookVector() * -1; + for (size_t Range = 0; Range < 3; Range++) + { + Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; + + // Get the chunk from the x/z coords. + int RangeX, RangeZ = 0; + cChunkDef::BlockToChunk((int)std::floor(Vector.x), (int)std::floor(Vector.z), RangeX, RangeZ); + + for (size_t X = 0; X < 7; X++) + { + for (size_t Z = 0; Z < 7; Z++) + { + int ChunkX = RangeX + ((X >= 4) ? (3 - X) : X); + int ChunkZ = RangeZ + ((Z >= 4) ? (3 - Z) : Z); + cChunkCoords Coords(ChunkX, ChunkZ); + + // If the chunk already loading/loaded -> skip + if ( + (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || + (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) + ) + { + continue; + } + + // Unloaded chunk found -> Send it to the client. + Lock.Unlock(); + StreamChunk(ChunkX, ChunkZ); + return; + } + } + } + + // Low priority: Add all chunks that are in range. (From the center out to the edge) + for (int d = 0; d <= m_ViewDistance; ++d) // cycle through (square) distance, from nearest to furthest + { + // For each distance add chunks in a hollow square centered around current position: + cChunkCoordsList CurcleChunks; + for (int i = -d; i <= d; ++i) + { + CurcleChunks.push_back(cChunkCoords(ChunkPosX + d, ChunkPosZ + i)); + CurcleChunks.push_back(cChunkCoords(ChunkPosX - d, ChunkPosZ + i)); + } + for (int i = -d + 1; i < d; ++i) + { + CurcleChunks.push_back(cChunkCoords(ChunkPosX + i, ChunkPosZ + d)); + CurcleChunks.push_back(cChunkCoords(ChunkPosX + i, ChunkPosZ - d)); + } + + // For each the CurcleChunks list and send the first unloaded chunk: + for (cChunkCoordsList::iterator itr = CurcleChunks.begin(), end = CurcleChunks.end(); itr != end; ++itr) + { + cChunkCoords Coords = *itr; + + // If the chunk already loading/loaded -> skip + if ( + (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || + (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) + ) + { + continue; + } + + // Unloaded chunk found -> Send it to the client. + Lock.Unlock(); + StreamChunk(Coords.m_ChunkX, Coords.m_ChunkZ); + return; + } + } + + // All chunks are loaded -> Sets the last loaded chunk coordinates to current coordinates + m_LastStreamedChunkX = ChunkPosX; + m_LastStreamedChunkZ = ChunkPosZ; } @@ -537,6 +628,11 @@ void cClientHandle::RemoveFromAllChunks() cCSLock Lock(m_CSChunkLists); m_LoadedChunks.clear(); m_ChunksToSend.clear(); + + // Also reset the LastStreamedChunk coords to bogus coords, + // so that all chunks are streamed in subsequent StreamChunks() call (FS #407) + m_LastStreamedChunkX = 0x7fffffff; + m_LastStreamedChunkZ = 0x7fffffff; } } @@ -1852,6 +1948,10 @@ void cClientHandle::RemoveFromWorld(void) m_Protocol->SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); } // for itr - Chunks[] + // Here, we set last streamed values to bogus ones so everything is resent + m_LastStreamedChunkX = 0x7fffffff; + m_LastStreamedChunkZ = 0x7fffffff; + m_HasSentPlayerChunk = false; } @@ -1920,10 +2020,11 @@ void cClientHandle::Tick(float a_Dt) if ((m_State >= csAuthenticated) && (m_State < csDestroying)) { + StreamNextChunk(); // Streams the next chunk - // Unload all chunks that are out of the view distance (all 2 seconds) - if ((m_Player->GetWorld()->GetWorldAge() % 40) == 0) + // Unload all chunks that are out of the view distance (all 5 seconds) + if ((m_Player->GetWorld()->GetWorldAge() % 100) == 0) { UnloadOutOfRangeChunks(); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 897fb8705..018c537c6 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -357,6 +357,10 @@ private: bool m_HasSentDC; ///< True if a D/C packet has been sent in either direction + // Chunk position when the last StreamChunks() was called; used to avoid re-streaming while in the same chunk + int m_LastStreamedChunkX; + int m_LastStreamedChunkZ; + /** Seconds since the last packet data was received (updated in Tick(), reset in DataReceived()) */ float m_TimeSinceLastPacket; -- cgit v1.2.3 From b493beb3bbac05d0402a6e388a61bf446c6c00ff Mon Sep 17 00:00:00 2001 From: Howaner Date: Mon, 6 Oct 2014 21:27:53 +0200 Subject: Stream 4 chunks per tick. Added priority. --- src/Chunk.cpp | 2 +- src/ChunkSender.cpp | 13 +++++++++---- src/ChunkSender.h | 18 ++++++++++++++++-- src/ClientHandle.cpp | 35 ++++++++++++++++++++++------------- src/ClientHandle.h | 7 ++++--- src/World.cpp | 8 ++++---- src/World.h | 4 ++-- 7 files changed, 58 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 96b8eda4e..e8a1de908 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -1742,7 +1742,7 @@ void cChunk::SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_Max // Re-send the chunk to all clients: for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr) { - m_World->ForceSendChunkTo(m_PosX, m_PosZ, (*itr)); + m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::E_CHUNK_PRIORITY_MEDIUM, (*itr)); } // for itr - m_LoadedByClient[] } diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index 0bdc0cf75..2a953db1f 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -91,17 +91,22 @@ void cChunkSender::ChunkReady(int a_ChunkX, int a_ChunkZ) -void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) +void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a_Priority, cClientHandle * a_Client) { ASSERT(a_Client != NULL); { + sSendChunk Chunk(a_ChunkX, a_ChunkZ, a_Priority, a_Client); + cCSLock Lock(m_CS); - if (std::find(m_SendChunks.begin(), m_SendChunks.end(), sSendChunk(a_ChunkX, a_ChunkZ, a_Client)) != m_SendChunks.end()) + if (std::find(m_SendChunks.begin(), m_SendChunks.end(), Chunk) != m_SendChunks.end()) { // Already queued, bail out return; } - m_SendChunks.push_back(sSendChunk(a_ChunkX, a_ChunkZ, a_Client)); + m_SendChunks.push_back(Chunk); + + // Sort the list: + m_SendChunks.sort(); } m_evtQueue.Set(); } @@ -169,7 +174,7 @@ void cChunkSender::Execute(void) sSendChunk Chunk(m_SendChunks.front()); m_SendChunks.pop_front(); Lock.Unlock(); - + SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, Chunk.m_Client); } Lock.Lock(); diff --git a/src/ChunkSender.h b/src/ChunkSender.h index a0e9087a9..3a1e1f5ea 100644 --- a/src/ChunkSender.h +++ b/src/ChunkSender.h @@ -75,6 +75,13 @@ class cChunkSender: public: cChunkSender(void); ~cChunkSender(); + + enum eChunkPriority + { + E_CHUNK_PRIORITY_HIGH = 0, + E_CHUNK_PRIORITY_MEDIUM = 1, + E_CHUNK_PRIORITY_LOW = 2, + }; bool Start(cWorld * a_World); @@ -84,7 +91,7 @@ public: void ChunkReady(int a_ChunkX, int a_ChunkZ); /// Queues a chunk to be sent to a specific client - void QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); + void QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a_Priority, cClientHandle * a_Client); /// Removes the a_Client from all waiting chunk send operations void RemoveClient(cClientHandle * a_Client); @@ -96,11 +103,13 @@ protected: { int m_ChunkX; int m_ChunkZ; + eChunkPriority m_Priority; cClientHandle * m_Client; - sSendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) : + sSendChunk(int a_ChunkX, int a_ChunkZ, eChunkPriority a_Priority, cClientHandle * a_Client) : m_ChunkX(a_ChunkX), m_ChunkZ(a_ChunkZ), + m_Priority(a_Priority), m_Client(a_Client) { } @@ -113,6 +122,11 @@ protected: (a_Other.m_Client == m_Client) ); } + + bool operator < (const sSendChunk & a_Other) + { + return (m_Priority < a_Other.m_Priority); + } } ; typedef std::list sSendChunkList; diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 535f9d386..588a1caba 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -402,11 +402,11 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID, -void cClientHandle::StreamNextChunk(void) +bool cClientHandle::StreamNextChunk(void) { if ((m_State < csAuthenticated) || (m_State >= csDestroying)) { - return; + return true; } ASSERT(m_Player != NULL); @@ -415,7 +415,7 @@ void cClientHandle::StreamNextChunk(void) if ((m_LastStreamedChunkX == ChunkPosX) && (m_LastStreamedChunkZ == ChunkPosZ)) { // All chunks are already loaded. Abort loading. - return; + return true; } // Get the look vector and normalize it. @@ -454,8 +454,8 @@ void cClientHandle::StreamNextChunk(void) // Unloaded chunk found -> Send it to the client. Lock.Unlock(); - StreamChunk(ChunkX, ChunkZ); - return; + StreamChunk(ChunkX, ChunkZ, cChunkSender::E_CHUNK_PRIORITY_HIGH); + return false; } } } @@ -489,8 +489,8 @@ void cClientHandle::StreamNextChunk(void) // Unloaded chunk found -> Send it to the client. Lock.Unlock(); - StreamChunk(ChunkX, ChunkZ); - return; + StreamChunk(ChunkX, ChunkZ, cChunkSender::E_CHUNK_PRIORITY_MEDIUM); + return false; } } } @@ -527,14 +527,15 @@ void cClientHandle::StreamNextChunk(void) // Unloaded chunk found -> Send it to the client. Lock.Unlock(); - StreamChunk(Coords.m_ChunkX, Coords.m_ChunkZ); - return; + StreamChunk(Coords.m_ChunkX, Coords.m_ChunkZ, cChunkSender::E_CHUNK_PRIORITY_LOW); + return false; } } // All chunks are loaded -> Sets the last loaded chunk coordinates to current coordinates m_LastStreamedChunkX = ChunkPosX; m_LastStreamedChunkZ = ChunkPosZ; + return true; } @@ -590,7 +591,7 @@ void cClientHandle::UnloadOutOfRangeChunks(void) -void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) +void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority) { if (m_State >= csDestroying) { @@ -608,7 +609,7 @@ void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) m_LoadedChunks.push_back(cChunkCoords(a_ChunkX, a_ChunkZ)); m_ChunksToSend.push_back(cChunkCoords(a_ChunkX, a_ChunkZ)); } - World->SendChunkTo(a_ChunkX, a_ChunkZ, this); + World->SendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, this); } } @@ -2028,8 +2029,16 @@ void cClientHandle::Tick(float a_Dt) if ((m_State >= csAuthenticated) && (m_State < csDestroying)) { - - StreamNextChunk(); // Streams the next chunk + // Stream 4 chunks per tick + for (int i = 0; i < 4; i++) + { + // Stream the next chunk + if (StreamNextChunk()) + { + // Streaming finished. All chunks are loaded. + break; + } + } // Unload all chunks that are out of the view distance (all 5 seconds) if ((m_Player->GetWorld()->GetWorldAge() % 100) == 0) diff --git a/src/ClientHandle.h b/src/ClientHandle.h index eb91b8487..c6444b1c2 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -21,6 +21,7 @@ #include "Enchantments.h" #include "UI/SlotArea.h" #include "json/json.h" +#include "ChunkSender.h" @@ -113,8 +114,8 @@ public: /** Authenticates the specified user, called by cAuthenticator */ void Authenticate(const AString & a_Name, const AString & a_UUID, const Json::Value & a_Properties); - /** This function sends a new unloaded chunk to the player. */ - void StreamNextChunk(void); + /** This function sends a new unloaded chunk to the player. Returns true if all chunks are loaded. */ + bool StreamNextChunk(); /** Remove all loaded chunks that are no longer in range */ void UnloadOutOfRangeChunks(void); @@ -448,7 +449,7 @@ private: bool CheckBlockInteractionsRate(void); /** Adds a single chunk to be streamed to the client; used by StreamChunks() */ - void StreamChunk(int a_ChunkX, int a_ChunkZ); + void StreamChunk(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority); /** Handles the DIG_STARTED dig packet: */ void HandleBlockDigStarted (int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, BLOCKTYPE a_OldBlock, NIBBLETYPE a_OldMeta); diff --git a/src/World.cpp b/src/World.cpp index 30c1a73b1..049dbc106 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -2850,19 +2850,19 @@ void cWorld::RemoveClientFromChunks(cClientHandle * a_Client) -void cWorld::SendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) +void cWorld::SendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client) { - m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Client); + m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, a_Client); } -void cWorld::ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) +void cWorld::ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client) { a_Client->AddWantedChunk(a_ChunkX, a_ChunkZ); - m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Client); + m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, a_Client); } diff --git a/src/World.h b/src/World.h index 90dada259..f940a98c4 100644 --- a/src/World.h +++ b/src/World.h @@ -359,11 +359,11 @@ public: /** Sends the chunk to the client specified, if the client doesn't have the chunk yet. If chunk not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ - void SendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); + void SendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client); /** Sends the chunk to the client specified, even if the client already has the chunk. If the chunk's not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ - void ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); + void ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client); /** Removes client from ChunkSender's queue of chunks to be sent */ void RemoveClientFromChunkSender(cClientHandle * a_Client); -- cgit v1.2.3 From e3a69a527d53fd7540dce4a424d280a9d0cbb1a9 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 7 Oct 2014 15:02:51 +0200 Subject: Removed unused cBlockHayBaleHandler. --- src/Blocks/BlockHandler.cpp | 3 +-- src/Blocks/BlockHayBale.h | 22 ---------------------- 2 files changed, 1 insertion(+), 24 deletions(-) delete mode 100644 src/Blocks/BlockHayBale.h (limited to 'src') diff --git a/src/Blocks/BlockHandler.cpp b/src/Blocks/BlockHandler.cpp index ff0b201e7..904e0a921 100644 --- a/src/Blocks/BlockHandler.cpp +++ b/src/Blocks/BlockHandler.cpp @@ -36,7 +36,6 @@ #include "BlockGlass.h" #include "BlockGlowstone.h" #include "BlockGravel.h" -#include "BlockHayBale.h" #include "BlockMobHead.h" #include "BlockHopper.h" #include "BlockIce.h" @@ -231,7 +230,7 @@ cBlockHandler * cBlockHandler::CreateBlockHandler(BLOCKTYPE a_BlockType) case E_BLOCK_GLASS_PANE: return new cBlockGlassHandler (a_BlockType); case E_BLOCK_GRASS: return new cBlockDirtHandler (a_BlockType); case E_BLOCK_GRAVEL: return new cBlockGravelHandler (a_BlockType); - case E_BLOCK_HAY_BALE: return new cBlockHayBaleHandler (a_BlockType); + case E_BLOCK_HAY_BALE: return new cBlockSidewaysHandler (a_BlockType); case E_BLOCK_HEAD: return new cBlockMobHeadHandler (a_BlockType); case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE: return new cBlockPressurePlateHandler(a_BlockType); case E_BLOCK_HOPPER: return new cBlockHopperHandler (a_BlockType); diff --git a/src/Blocks/BlockHayBale.h b/src/Blocks/BlockHayBale.h deleted file mode 100644 index 8150b10d3..000000000 --- a/src/Blocks/BlockHayBale.h +++ /dev/null @@ -1,22 +0,0 @@ - -#pragma once - -#include "BlockSideways.h" - - - - - -class cBlockHayBaleHandler : - public cBlockSidewaysHandler -{ -public: - cBlockHayBaleHandler(BLOCKTYPE a_BlockType) - : cBlockSidewaysHandler(a_BlockType) - { - } -} ; - - - - -- cgit v1.2.3 From fec509935dce9c51d597c58cba2acdd558d7ae53 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 7 Oct 2014 15:39:24 +0200 Subject: Removed BlockHaybale.h from CMakeLists.txt --- src/Blocks/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/CMakeLists.txt b/src/Blocks/CMakeLists.txt index 9f971a8bd..eed949aab 100644 --- a/src/Blocks/CMakeLists.txt +++ b/src/Blocks/CMakeLists.txt @@ -45,7 +45,6 @@ SET (HDRS BlockGlowstone.h BlockGravel.h BlockHandler.h - BlockHayBale.h BlockHopper.h BlockIce.h BlockLadder.h -- cgit v1.2.3 From e8e428a806173cc293f98beea1a8a88e95b4d101 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 7 Oct 2014 16:48:37 +0200 Subject: Corrected IsBlockAttachable() in BlockVine.h --- src/Blocks/BlockVine.h | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockVine.h b/src/Blocks/BlockVine.h index 06d84f2d4..7aa0378c7 100644 --- a/src/Blocks/BlockVine.h +++ b/src/Blocks/BlockVine.h @@ -23,10 +23,6 @@ public: BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta ) override { - UNUSED(a_Player); - UNUSED(a_CursorX); - UNUSED(a_CursorY); - UNUSED(a_CursorZ); // TODO: Disallow placement where the vine doesn't attach to something properly BLOCKTYPE BlockType = 0; NIBBLETYPE BlockMeta; @@ -80,7 +76,21 @@ public: /// Returns true if the specified block type is good for vines to attach to static bool IsBlockAttachable(BLOCKTYPE a_BlockType) { - return ((a_BlockType == E_BLOCK_LEAVES) || (a_BlockType == E_BLOCK_NEW_LEAVES) || cBlockInfo::IsSolid(a_BlockType)); + switch (a_BlockType) + { + case E_BLOCK_GLASS: + case E_BLOCK_STAINED_GLASS: + case E_BLOCK_CHEST: + case E_BLOCK_TRAPPED_CHEST: + { + // You can't attach a vine to this solid blocks. + return false; + } + default: + { + return cBlockInfo::IsSolid(a_BlockType); + } + } } -- cgit v1.2.3 From a5e09155c0188472592fe40a46c17b8bdd330ac3 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 7 Oct 2014 18:21:39 +0200 Subject: Corrected drops from dead bush, tall grass and cobweb. --- src/Blocks/BlockDeadBush.h | 24 +++++++++++++++++------- src/Blocks/BlockTallGrass.h | 23 +++++++---------------- src/ClientHandle.cpp | 10 +++++----- src/Items/ItemHandler.cpp | 4 ++++ src/Items/ItemShears.h | 42 +++++++++++++++++++++++++++++++----------- 5 files changed, 64 insertions(+), 39 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockDeadBush.h b/src/Blocks/BlockDeadBush.h index 5b687c710..09df16893 100644 --- a/src/Blocks/BlockDeadBush.h +++ b/src/Blocks/BlockDeadBush.h @@ -17,15 +17,25 @@ public: } - virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override - { - // Don't drop anything - } - - virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - return (a_RelY > 0) && (a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) == E_BLOCK_SAND); + if (a_RelY <= 0) + { + return false; + } + + BLOCKTYPE BelowBlock = a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ); + switch (BelowBlock) + { + case E_BLOCK_CLAY: + case E_BLOCK_HARDENED_CLAY: + case E_BLOCK_STAINED_CLAY: + case E_BLOCK_SAND: + { + return true; + } + default: return false; + } } } ; diff --git a/src/Blocks/BlockTallGrass.h b/src/Blocks/BlockTallGrass.h index f520414a7..3ef2d804d 100644 --- a/src/Blocks/BlockTallGrass.h +++ b/src/Blocks/BlockTallGrass.h @@ -26,32 +26,23 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { // Drop seeds, sometimes - MTRand r1; - if (r1.randInt(10) == 5) + cFastRandom Random; + if (Random.NextInt(8) == 0) { a_Pickups.push_back(cItem(E_ITEM_SEEDS, 1, 0)); } } - virtual void OnDestroyedByPlayer(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ) override + virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - NIBBLETYPE Meta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); - - if ((!a_Player->IsGameModeCreative()) && (a_Player->GetEquippedItem().m_ItemType == E_ITEM_SHEARS)) + if (a_RelY <= 0) { - cItems Pickups; - Pickups.Add(E_BLOCK_TALL_GRASS, 1, Meta); - a_WorldInterface.SpawnItemPickups(Pickups, a_BlockX, a_BlockY, a_BlockZ); - - a_Player->UseEquippedItem(); + return false; } - } - - virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override - { - return ((a_RelY > 0) && (a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) != E_BLOCK_AIR)); + BLOCKTYPE BelowBlock = a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ); + return IsBlockTypeOfDirt(BelowBlock); } } ; diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 3b677460b..b7e85cb32 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -1113,16 +1113,16 @@ void cClientHandle::HandleBlockDigFinished(int a_BlockX, int a_BlockY, int a_Blo cWorld * World = m_Player->GetWorld(); cItemHandler * ItemHandler = cItemHandler::GetItemHandler(m_Player->GetEquippedItem()); - if (cRoot::Get()->GetPluginManager()->CallHookPlayerBreakingBlock(*m_Player, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_OldBlock, a_OldMeta)) + if (a_OldBlock == E_BLOCK_AIR) { - // A plugin doesn't agree with the breaking. Bail out. Send the block back to the client, so that it knows: - m_Player->GetWorld()->SendBlockTo(a_BlockX, a_BlockY, a_BlockZ, m_Player); + LOGD("Dug air - what the function?"); return; } - if (a_OldBlock == E_BLOCK_AIR) + if (cRoot::Get()->GetPluginManager()->CallHookPlayerBreakingBlock(*m_Player, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_OldBlock, a_OldMeta)) { - LOGD("Dug air - what the function?"); + // A plugin doesn't agree with the breaking. Bail out. Send the block back to the client, so that it knows: + m_Player->GetWorld()->SendBlockTo(a_BlockX, a_BlockY, a_BlockZ, m_Player); return; } diff --git a/src/Items/ItemHandler.cpp b/src/Items/ItemHandler.cpp index 912dde022..9f6a751ef 100644 --- a/src/Items/ItemHandler.cpp +++ b/src/Items/ItemHandler.cpp @@ -572,6 +572,8 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_COBBLESTONE: case E_BLOCK_COBBLESTONE_STAIRS: case E_BLOCK_COBBLESTONE_WALL: + case E_BLOCK_COBWEB: + case E_BLOCK_DEAD_BUSH: case E_BLOCK_DIAMOND_BLOCK: case E_BLOCK_DIAMOND_ORE: case E_BLOCK_DOUBLE_NEW_STONE_SLAB: @@ -587,6 +589,7 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_IRON_TRAPDOOR: case E_BLOCK_LAPIS_BLOCK: case E_BLOCK_LAPIS_ORE: + case E_BLOCK_LEAVES: case E_BLOCK_LIT_FURNACE: case E_BLOCK_MOB_SPAWNER: case E_BLOCK_MOSSY_COBBLESTONE: @@ -594,6 +597,7 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_NETHER_BRICK_STAIRS: case E_BLOCK_NETHER_BRICK_FENCE: case E_BLOCK_NETHERRACK: + case E_BLOCK_NEW_LEAVES: case E_BLOCK_NEW_STONE_SLAB: case E_BLOCK_OBSIDIAN: case E_BLOCK_PACKED_ICE: diff --git a/src/Items/ItemShears.h b/src/Items/ItemShears.h index fa2794df2..e0c5c6623 100644 --- a/src/Items/ItemShears.h +++ b/src/Items/ItemShears.h @@ -28,21 +28,25 @@ public: virtual bool OnDiggingBlock(cWorld * a_World, cPlayer * a_Player, const cItem & a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Dir) override { - BLOCKTYPE Block = a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ); + BLOCKTYPE Block; + NIBBLETYPE BlockMeta; + a_World->GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, BlockMeta); + if ((Block == E_BLOCK_LEAVES) || (Block == E_BLOCK_NEW_LEAVES)) { - NIBBLETYPE Meta = a_World->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); + cItems Drops; cBlockHandler * Handler = cBlockInfo::GetHandler(Block); - cItems Drops; - Handler->ConvertToPickups(Drops, Meta); - Drops.push_back(cItem(Block, 1, Meta & 3)); + Handler->ConvertToPickups(Drops, BlockMeta); + Drops.Add(Block, 1, BlockMeta & 3); a_World->SpawnItemPickups(Drops, a_BlockX, a_BlockY, a_BlockZ); a_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_AIR, 0); + a_World->SpawnItemPickups(Drops, a_BlockX, a_BlockY, a_BlockZ); a_Player->UseEquippedItem(); return true; } + return false; } @@ -53,12 +57,10 @@ public: { case E_BLOCK_COBWEB: case E_BLOCK_VINES: - case E_BLOCK_LEAVES: - case E_BLOCK_NEW_LEAVES: { return true; } - } // switch (a_BlockType) + } return super::CanHarvestBlock(a_BlockType); } @@ -71,12 +73,30 @@ public: virtual void OnBlockDestroyed(cWorld * a_World, cPlayer * a_Player, const cItem & a_Item, int a_BlockX, int a_BlockY, int a_BlockZ) override { - super::OnBlockDestroyed(a_World, a_Player, a_Item, a_BlockX, a_BlockY, a_BlockZ); + BLOCKTYPE Block; + NIBBLETYPE BlockMeta; + a_World->GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, BlockMeta); - BLOCKTYPE Block = a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ); - if ((Block == E_BLOCK_TRIPWIRE) || (Block == E_BLOCK_VINES)) + if ((Block == E_BLOCK_TALL_GRASS) && !a_Player->IsGameModeCreative()) { + cItems Drops; + Drops.Add(Block, 1, BlockMeta); + a_World->SpawnItemPickups(Drops, a_BlockX, a_BlockY, a_BlockZ); a_Player->UseEquippedItem(); + return; + } + + super::OnBlockDestroyed(a_World, a_Player, a_Item, a_BlockX, a_BlockY, a_BlockZ); + switch (Block) + { + case E_BLOCK_COBWEB: + case E_BLOCK_DEAD_BUSH: + case E_BLOCK_TRIPWIRE: + case E_BLOCK_VINES: + case E_BLOCK_WOOL: + { + a_Player->UseEquippedItem(); + } } } } ; -- cgit v1.2.3 From 7631047bb77aa726c4dce6523f01bb2d2c709851 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 7 Oct 2014 18:24:22 +0200 Subject: Leaves are harvest-able. --- src/Items/ItemHandler.cpp | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/Items/ItemHandler.cpp b/src/Items/ItemHandler.cpp index 9f6a751ef..f1f1ddcc5 100644 --- a/src/Items/ItemHandler.cpp +++ b/src/Items/ItemHandler.cpp @@ -589,7 +589,6 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_IRON_TRAPDOOR: case E_BLOCK_LAPIS_BLOCK: case E_BLOCK_LAPIS_ORE: - case E_BLOCK_LEAVES: case E_BLOCK_LIT_FURNACE: case E_BLOCK_MOB_SPAWNER: case E_BLOCK_MOSSY_COBBLESTONE: @@ -597,7 +596,6 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_NETHER_BRICK_STAIRS: case E_BLOCK_NETHER_BRICK_FENCE: case E_BLOCK_NETHERRACK: - case E_BLOCK_NEW_LEAVES: case E_BLOCK_NEW_STONE_SLAB: case E_BLOCK_OBSIDIAN: case E_BLOCK_PACKED_ICE: -- cgit v1.2.3 From 97623fc634263eeff99e25b7527fde318108ea0d Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 7 Oct 2014 21:36:01 +0200 Subject: Added distance check. --- src/ClientHandle.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 588a1caba..897ee9e9e 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -443,6 +443,12 @@ bool cClientHandle::StreamNextChunk(void) int ChunkZ = RangeZ + ((Z >= 4) ? (3 - Z) : Z); cChunkCoords Coords(ChunkX, ChunkZ); + // Checks if the chunk is in distance + if ((Diff(ChunkX, ChunkPosX) > m_ViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_ViewDistance)) + { + continue; + } + // If the chunk already loading/loaded -> skip if ( (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || @@ -478,6 +484,12 @@ bool cClientHandle::StreamNextChunk(void) int ChunkZ = RangeZ + ((Z >= 4) ? (3 - Z) : Z); cChunkCoords Coords(ChunkX, ChunkZ); + // Checks if the chunk is in distance + if ((Diff(ChunkX, ChunkPosX) > m_ViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_ViewDistance)) + { + continue; + } + // If the chunk already loading/loaded -> skip if ( (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || -- cgit v1.2.3 From 68a54c90c9408f2b3351e778a632b024e1433984 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 8 Oct 2014 20:31:16 +0200 Subject: Added AcaciaTrees for the savanna biomes --- src/Generating/Trees.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Generating/Trees.cpp b/src/Generating/Trees.cpp index 1b0f2dc14..c78a30f9b 100644 --- a/src/Generating/Trees.cpp +++ b/src/Generating/Trees.cpp @@ -224,8 +224,6 @@ void GetTreeImageByBiome(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_No case biMegaTaiga: case biMegaTaigaHills: case biExtremeHillsPlus: - case biSavanna: - case biSavannaPlateau: case biMesa: case biMesaPlateauF: case biMesaPlateau: @@ -241,8 +239,6 @@ void GetTreeImageByBiome(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_No case biMegaSpruceTaiga: case biMegaSpruceTaigaHills: case biExtremeHillsPlusM: - case biSavannaM: - case biSavannaPlateauM: case biMesaBryce: case biMesaPlateauFM: case biMesaPlateauM: @@ -252,6 +248,15 @@ void GetTreeImageByBiome(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_No return; } + case biSavanna: + case biSavannaPlateau: + case biSavannaM: + case biSavannaPlateauM: + { + GetAcaciaTreeImage(a_BlockX, a_BlockY, a_BlockZ, a_Noise, a_Seq, a_LogBlocks, a_OtherBlocks); + return; + } + case biRoofedForest: case biRoofedForestM: { @@ -403,7 +408,53 @@ void GetBirchTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Nois void GetAcaciaTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noise, int a_Seq, sSetBlockVector & a_LogBlocks, sSetBlockVector & a_OtherBlocks) { - // TODO + int Height = 2 + (a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) / 11 % 3); + + // Create the trunk + for (int i = 0; i < Height; i++) + { + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); + } + + Vector3i BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); + Vector3i BranchDirection = Vector3i(a_Noise.IntNoise3DInt(a_BlockX * a_Seq, a_BlockY, a_BlockZ) % 3 - 1, 0, a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ * a_Seq) % 3 - 1); + int Attempts = 0; + while (BranchDirection.Length() == 0.0) + { + Attempts++; + BranchDirection = Vector3i(a_Noise.IntNoise3DInt(a_BlockX * a_Seq, a_BlockY * Attempts, a_BlockZ) % 3 - 1, 0, a_Noise.IntNoise3DInt(a_BlockX, a_BlockY * Attempts, a_BlockZ * a_Seq) % 3 - 1); + } + BranchDirection.y = 1; + + int BranchHeight = a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) % 3 + 1; + for (int i = 0; i < BranchHeight; i++) + { + BranchPos = BranchPos + BranchDirection; + a_LogBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y, BranchPos.z, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); + } + + PushCoordBlocks(BranchPos.x, BranchPos.y, BranchPos.z, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + PushCoordBlocks(BranchPos.x, BranchPos.y + 1, BranchPos.z, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + a_OtherBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y + 1, BranchPos.z, E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD)); + + bool TwoTop = (a_Noise.IntNoise3D(a_BlockX, a_BlockY, a_BlockZ) < 0 ? true : false); + if (!TwoTop) + { + return; + } + + BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); + BranchDirection = Vector3d(-BranchDirection.x, 1, -BranchDirection.z); + BranchHeight = a_Noise.IntNoise3DInt(a_BlockX * a_Seq, a_BlockY * a_Seq * 10, a_BlockZ * a_Seq) % 3 + 1; + for (int i = 0; i < BranchHeight; i++) + { + BranchPos = BranchPos + BranchDirection; + a_LogBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y, BranchPos.z, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); + } + + PushCoordBlocks(BranchPos.x, BranchPos.y, BranchPos.z, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + PushCoordBlocks(BranchPos.x, BranchPos.y + 1, BranchPos.z, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + a_OtherBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y + 1, BranchPos.z, E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD)); } -- cgit v1.2.3 From 36fa1c5c73ba273051904d539e82d1f8f33a50d7 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 8 Oct 2014 21:25:59 +0200 Subject: Using array with possible directions. --- src/Generating/Trees.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Generating/Trees.cpp b/src/Generating/Trees.cpp index c78a30f9b..8fce61b95 100644 --- a/src/Generating/Trees.cpp +++ b/src/Generating/Trees.cpp @@ -416,15 +416,16 @@ void GetAcaciaTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noi a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); } - Vector3i BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); - Vector3i BranchDirection = Vector3i(a_Noise.IntNoise3DInt(a_BlockX * a_Seq, a_BlockY, a_BlockZ) % 3 - 1, 0, a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ * a_Seq) % 3 - 1); - int Attempts = 0; - while (BranchDirection.Length() == 0.0) + const Vector3i AvailableDirections[] = { - Attempts++; - BranchDirection = Vector3i(a_Noise.IntNoise3DInt(a_BlockX * a_Seq, a_BlockY * Attempts, a_BlockZ) % 3 - 1, 0, a_Noise.IntNoise3DInt(a_BlockX, a_BlockY * Attempts, a_BlockZ * a_Seq) % 3 - 1); - } - BranchDirection.y = 1; + { -1, 1, 0 }, { 0, 1, -1 }, + { -1, 1, 1 }, { -1, 1, -1 }, + { 1, 1, 1 }, { 1, 1, -1 }, + { 1, 1, 0 }, { 0, 1, 1 }, + }; + + Vector3i BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); + Vector3i BranchDirection = AvailableDirections[a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) % 8]; int BranchHeight = a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) % 3 + 1; for (int i = 0; i < BranchHeight; i++) -- cgit v1.2.3 From e95ee55974b674d7f026bae3beac7836da74efba Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 8 Oct 2014 21:32:09 +0200 Subject: Added comments to the GetAcaciaTreeImage function --- src/Generating/Trees.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') diff --git a/src/Generating/Trees.cpp b/src/Generating/Trees.cpp index 8fce61b95..7fd6d6f07 100644 --- a/src/Generating/Trees.cpp +++ b/src/Generating/Trees.cpp @@ -408,6 +408,7 @@ void GetBirchTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Nois void GetAcaciaTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noise, int a_Seq, sSetBlockVector & a_LogBlocks, sSetBlockVector & a_OtherBlocks) { + // Calculate a base height int Height = 2 + (a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) / 11 % 3); // Create the trunk @@ -416,6 +417,7 @@ void GetAcaciaTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noi a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); } + // Array with possible directions for a branch to go to. const Vector3i AvailableDirections[] = { { -1, 1, 0 }, { 0, 1, -1 }, @@ -424,35 +426,51 @@ void GetAcaciaTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noi { 1, 1, 0 }, { 0, 1, 1 }, }; + // Set the starting point of the branch Vector3i BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); + + // Get a direction for the trunk to go to. Vector3i BranchDirection = AvailableDirections[a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) % 8]; + // Calculate a height for the branch between 1 and 3 int BranchHeight = a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) % 3 + 1; + + // Place the logs of the branch. for (int i = 0; i < BranchHeight; i++) { BranchPos = BranchPos + BranchDirection; a_LogBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y, BranchPos.z, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); } + // Add the leaves to the top of the branch PushCoordBlocks(BranchPos.x, BranchPos.y, BranchPos.z, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); PushCoordBlocks(BranchPos.x, BranchPos.y + 1, BranchPos.z, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); a_OtherBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y + 1, BranchPos.z, E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD)); + // Choose if we have to add another branch bool TwoTop = (a_Noise.IntNoise3D(a_BlockX, a_BlockY, a_BlockZ) < 0 ? true : false); if (!TwoTop) { return; } + // Reset the starting point of the branch BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); + + // Invert the direction of the previous branch. BranchDirection = Vector3d(-BranchDirection.x, 1, -BranchDirection.z); + + // Calculate a new height for the second branch BranchHeight = a_Noise.IntNoise3DInt(a_BlockX * a_Seq, a_BlockY * a_Seq * 10, a_BlockZ * a_Seq) % 3 + 1; + + // Place the logs in the same way as the first branch for (int i = 0; i < BranchHeight; i++) { BranchPos = BranchPos + BranchDirection; a_LogBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y, BranchPos.z, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); } + // And add the leaves ontop of the second branch PushCoordBlocks(BranchPos.x, BranchPos.y, BranchPos.z, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); PushCoordBlocks(BranchPos.x, BranchPos.y + 1, BranchPos.z, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); a_OtherBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y + 1, BranchPos.z, E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD)); -- cgit v1.2.3 From f91aa6f1d3c38f68ccf157731f1d1c3c6beda2ee Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 9 Oct 2014 12:33:16 +0200 Subject: DistortedHeightmap: Fixed crash on number rounding. Fixes #1521. --- src/Generating/DistortedHeightmap.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index c18c402da..bf8995dcb 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -540,10 +540,11 @@ void cDistortedHeightmap::InitializeCompoGen(cIniFile & a_IniFile) int cDistortedHeightmap::GetHeightmapAt(NOISE_DATATYPE a_X, NOISE_DATATYPE a_Z) { - int ChunkX = (int)floor(a_X / (NOISE_DATATYPE)16); - int ChunkZ = (int)floor(a_Z / (NOISE_DATATYPE)16); - int RelX = (int)(a_X - (NOISE_DATATYPE)ChunkX * cChunkDef::Width); - int RelZ = (int)(a_Z - (NOISE_DATATYPE)ChunkZ * cChunkDef::Width); + int RelX = (int)std::floor(a_X); + int RelY = 0; + int RelZ = (int)std::floor(a_Z); + int ChunkX, ChunkZ; + cChunkDef::AbsoluteToRelative(RelX, RelY, RelZ, ChunkX, ChunkZ); // If we're withing the same chunk, return the pre-cached heightmap: if ((ChunkX == m_CurChunkX) && (ChunkZ == m_CurChunkZ)) -- cgit v1.2.3 From f8d1e96ae7ac9a3483ff0a214796455946d7880f Mon Sep 17 00:00:00 2001 From: archshift Date: Wed, 3 Sep 2014 16:25:45 -0700 Subject: Use static casts instead of C casts, add floor-cast functions --- src/Entities/Entity.h | 6 +++--- src/Globals.h | 40 ++++++++++++++++++++++++++++++++++++---- src/Vector3.h | 33 ++++++++++++++++----------------- 3 files changed, 55 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h index 3fa7e80c1..0a03eb3f2 100644 --- a/src/Entities/Entity.h +++ b/src/Entities/Entity.h @@ -27,9 +27,9 @@ return super::GetClass(); \ } -#define POSX_TOINT (int)floor(GetPosX()) -#define POSY_TOINT (int)floor(GetPosY()) -#define POSZ_TOINT (int)floor(GetPosZ()) +#define POSX_TOINT FloorD(GetPosX()) +#define POSY_TOINT FloorD(GetPosY()) +#define POSZ_TOINT FloorD(GetPosZ()) #define POS_TOINT Vector3i(POSXTOINT, POSYTOINT, POSZTOINT) #define GET_AND_VERIFY_CURRENT_CHUNK(ChunkVarName, X, Z) cChunk * ChunkVarName = a_Chunk.GetNeighborChunk(X, Z); if ((ChunkVarName == NULL) || !ChunkVarName->IsValid()) { return; } diff --git a/src/Globals.h b/src/Globals.h index 0926457da..8bf7a0f0c 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -226,10 +226,10 @@ template class SizeChecker; // CRT stuff: #include -#include -#include -#include -#include +#include +#include +#include +#include @@ -400,6 +400,38 @@ T Clamp(T a_Value, T a_Min, T a_Max) +/** Floors a_Value, then casts it to C (an int by default) */ +template +C FloorD(double a_Value) +{ + return static_cast(std::floor(a_Value)); +} + +/** Floors a_Value, then casts it to C (an int by default) */ +template +C FloorF(double a_Value) +{ + return static_cast(std::floorf(a_Value)); +} + +/** Ciels a_Value, then casts it to C (an int by default) */ +template +C CeilD(double a_Value) +{ + return static_cast(std::ceil(a_Value)); +} + +/** Ciels a_Value, then casts it to C (an int by default) */ +template +C CeilF(double a_Value) +{ + return static_cast(std::ceilf(a_Value)); +} + + + + + #ifndef TOLUA_TEMPLATE_BIND #define TOLUA_TEMPLATE_BIND(x) #endif diff --git a/src/Vector3.h b/src/Vector3.h index 1dcb38f64..782b0d1c9 100644 --- a/src/Vector3.h +++ b/src/Vector3.h @@ -4,7 +4,6 @@ #define _USE_MATH_DEFINES // Enable non-standard math defines (MSVC) -#include #include #include @@ -29,9 +28,9 @@ public: // Hardcoded copy constructors (tolua++ does not support function templates .. yet) - Vector3(const Vector3 & a_Rhs) : x((T) a_Rhs.x), y((T) a_Rhs.y), z((T) a_Rhs.z) {} - Vector3(const Vector3 & a_Rhs) : x((T) a_Rhs.x), y((T) a_Rhs.y), z((T) a_Rhs.z) {} - Vector3(const Vector3 & a_Rhs) : x((T) a_Rhs.x), y((T) a_Rhs.y), z((T) a_Rhs.z) {} + Vector3(const Vector3 & a_Rhs) : x(static_cast(a_Rhs.x)), y(static_cast(a_Rhs.y)), z(static_cast(a_Rhs.z)) {} + Vector3(const Vector3 & a_Rhs) : x(static_cast(a_Rhs.x)), y(static_cast(a_Rhs.y)), z(static_cast(a_Rhs.z)) {} + Vector3(const Vector3 & a_Rhs) : x(static_cast(a_Rhs.x)), y(static_cast(a_Rhs.y)), z(static_cast(a_Rhs.z)) {} // tolua_end @@ -53,9 +52,9 @@ public: { double Len = 1.0 / Length(); - x = (T)(x * Len); - y = (T)(y * Len); - z = (T)(z * Len); + x = static_cast(x * Len); + y = static_cast(y * Len); + z = static_cast(z * Len); } inline Vector3 NormalizeCopy(void) const @@ -63,9 +62,9 @@ public: double Len = 1.0 / Length(); return Vector3( - (T)(x * Len), - (T)(y * Len), - (T)(z * Len) + static_cast(x * Len), + static_cast(y * Len), + static_cast(z * Len) ); } @@ -74,15 +73,15 @@ public: double Len = 1.0 / Length(); a_Rhs.Set( - (T)(x * Len), - (T)(y * Len), - (T)(z * Len) + static_cast(x * Len), + static_cast(y * Len), + static_cast(z * Len) ); } inline double Length(void) const { - return sqrt((double)(x * x + y * y + z * z)); + return sqrt(static_cast(x * x + y * y + z * z)); } inline double SqrLength(void) const @@ -138,9 +137,9 @@ public: inline Vector3 Floor(void) const { return Vector3( - (int)floor(x), - (int)floor(y), - (int)floor(z) + static_cast(floor(x)), + static_cast(floor(y)), + static_cast(floor(z)) ); } -- cgit v1.2.3 From 76b37acb421bf10e094182b2e9be111eb29c46f1 Mon Sep 17 00:00:00 2001 From: archshift Date: Wed, 3 Sep 2014 16:51:38 -0700 Subject: Float/Ciel: If it's going to use C++11, it might as well take advantage of it --- src/Entities/Entity.h | 6 +++--- src/Globals.h | 26 ++++++-------------------- src/Vector3.h | 6 +++--- 3 files changed, 12 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h index 0a03eb3f2..f0577aba2 100644 --- a/src/Entities/Entity.h +++ b/src/Entities/Entity.h @@ -27,9 +27,9 @@ return super::GetClass(); \ } -#define POSX_TOINT FloorD(GetPosX()) -#define POSY_TOINT FloorD(GetPosY()) -#define POSZ_TOINT FloorD(GetPosZ()) +#define POSX_TOINT FloorC(GetPosX()) +#define POSY_TOINT FloorC(GetPosY()) +#define POSZ_TOINT FloorC(GetPosZ()) #define POS_TOINT Vector3i(POSXTOINT, POSYTOINT, POSZTOINT) #define GET_AND_VERIFY_CURRENT_CHUNK(ChunkVarName, X, Z) cChunk * ChunkVarName = a_Chunk.GetNeighborChunk(X, Z); if ((ChunkVarName == NULL) || !ChunkVarName->IsValid()) { return; } diff --git a/src/Globals.h b/src/Globals.h index 8bf7a0f0c..9959d92a9 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -400,34 +400,20 @@ T Clamp(T a_Value, T a_Min, T a_Max) -/** Floors a_Value, then casts it to C (an int by default) */ -template -C FloorD(double a_Value) +/** Floors a value, then casts it to C (an int by default) */ +template +typename std::enable_if::value, C>::type FloorC(T a_Value) { return static_cast(std::floor(a_Value)); } -/** Floors a_Value, then casts it to C (an int by default) */ -template -C FloorF(double a_Value) -{ - return static_cast(std::floorf(a_Value)); -} - -/** Ciels a_Value, then casts it to C (an int by default) */ -template -C CeilD(double a_Value) +/** Ceils a value, then casts it to C (an int by default) */ +template +typename std::enable_if::value, C>::type CeilC(T a_Value) { return static_cast(std::ceil(a_Value)); } -/** Ciels a_Value, then casts it to C (an int by default) */ -template -C CeilF(double a_Value) -{ - return static_cast(std::ceilf(a_Value)); -} - diff --git a/src/Vector3.h b/src/Vector3.h index 782b0d1c9..937c8fdfa 100644 --- a/src/Vector3.h +++ b/src/Vector3.h @@ -137,9 +137,9 @@ public: inline Vector3 Floor(void) const { return Vector3( - static_cast(floor(x)), - static_cast(floor(y)), - static_cast(floor(z)) + FloorC(x), + FloorC(y), + FloorC(z) ); } -- cgit v1.2.3 From a47d9e53344144d7584c37bbac742cf2187492fe Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 10 Oct 2014 09:58:54 +0200 Subject: Fixed MSVC compilation. --- src/Globals.h | 3 +++ src/Vector3.h | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Globals.h b/src/Globals.h index 9959d92a9..4ee1352eb 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -51,6 +51,9 @@ #define NORETURN __declspec(noreturn) + // Use non-standard defines in + #define _USE_MATH_DEFINES + #elif defined(__GNUC__) // TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? diff --git a/src/Vector3.h b/src/Vector3.h index 937c8fdfa..1854e42e3 100644 --- a/src/Vector3.h +++ b/src/Vector3.h @@ -3,7 +3,6 @@ -#define _USE_MATH_DEFINES // Enable non-standard math defines (MSVC) #include #include -- cgit v1.2.3 From 473c0425d374132c097045a84e03510bc8a7876b Mon Sep 17 00:00:00 2001 From: tycho Date: Fri, 10 Oct 2014 15:33:19 +0100 Subject: Moved a few objects to unique_ptr --- src/Bindings/ManualBindings.cpp | 2 +- src/Globals.h | 7 ++++++ src/World.cpp | 53 +++++++++++++++++++---------------------- src/World.h | 18 +++++++------- 4 files changed, 41 insertions(+), 39 deletions(-) (limited to 'src') diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index f643f06ec..0558533ce 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -1160,7 +1160,7 @@ static int tolua_cWorld_QueueTask(lua_State * tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #1"); } - self->QueueTask(new cLuaWorldTask(*Plugin, FnRef)); + self->QueueTask(make_unique(*Plugin, FnRef)); return 0; } diff --git a/src/Globals.h b/src/Globals.h index 4ee1352eb..5c5a8b3d2 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -419,6 +419,12 @@ typename std::enable_if::value, C>::type CeilC(T a_Value) +//temporary replacement for std::make_unique until we get c++14 +template< class T, class... Args > +std::unique_ptr make_unique( Args&&... args ) +{ + return std::unique_ptr(new T(args...)); +} #ifndef TOLUA_TEMPLATE_BIND @@ -436,3 +442,4 @@ typename std::enable_if::value, C>::type CeilC(T a_Value) #include "BlockInfo.h" + diff --git a/src/World.cpp b/src/World.cpp index a3c804b44..a23db6242 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -256,14 +256,14 @@ cWorld::cWorld(const AString & a_WorldName, eDimension a_Dimension, const AStrin m_IsDeepSnowEnabled(false), m_ShouldLavaSpawnFire(true), m_VillagersShouldHarvestCrops(true), - m_SimulatorManager(NULL), - m_SandSimulator(NULL), + m_SimulatorManager(), + m_SandSimulator(), m_WaterSimulator(NULL), - m_LavaSimulator(NULL), - m_FireSimulator(NULL), + m_LavaSimulator(nullptr), + m_FireSimulator(), m_RedstoneSimulator(NULL), m_MaxPlayers(10), - m_ChunkMap(NULL), + m_ChunkMap(), m_bAnimals(true), m_Weather(eWeather_Sunny), m_WeatherInterval(24000), // Guaranteed 1 day of sunshine at server start :) @@ -303,11 +303,8 @@ cWorld::cWorld(const AString & a_WorldName, eDimension a_Dimension, const AStrin cWorld::~cWorld() { - delete m_SimulatorManager; m_SimulatorManager = NULL; - delete m_SandSimulator; m_SandSimulator = NULL; delete m_WaterSimulator; m_WaterSimulator = NULL; delete m_LavaSimulator; m_LavaSimulator = NULL; - delete m_FireSimulator; m_FireSimulator = NULL; delete m_RedstoneSimulator; m_RedstoneSimulator = NULL; UnloadUnusedChunks(); @@ -319,8 +316,6 @@ cWorld::~cWorld() Serializer.Save(); m_MapManager.SaveMapData(); - - delete m_ChunkMap; } @@ -631,7 +626,7 @@ void cWorld::Start(void) InitialiseAndLoadMobSpawningValues(IniFile); SetTimeOfDay(IniFile.GetValueSetI("General", "TimeInTicks", m_TimeOfDay)); - m_ChunkMap = new cChunkMap(this); + m_ChunkMap = make_unique(this); m_LastSave = 0; m_LastUnload = 0; @@ -641,16 +636,16 @@ void cWorld::Start(void) m_BlockTickQueueCopy.reserve(1000); // Simulators: - m_SimulatorManager = new cSimulatorManager(*this); + m_SimulatorManager = make_unique(*this); m_WaterSimulator = InitializeFluidSimulator(IniFile, "Water", E_BLOCK_WATER, E_BLOCK_STATIONARY_WATER); m_LavaSimulator = InitializeFluidSimulator(IniFile, "Lava", E_BLOCK_LAVA, E_BLOCK_STATIONARY_LAVA); - m_SandSimulator = new cSandSimulator(*this, IniFile); - m_FireSimulator = new cFireSimulator(*this, IniFile); + m_SandSimulator = make_unique(*this, IniFile); + m_FireSimulator = make_unique(*this, IniFile); m_RedstoneSimulator = InitializeRedstoneSimulator(IniFile); // Water, Lava and Redstone simulators get registered in their initialize function. - m_SimulatorManager->RegisterSimulator(m_SandSimulator, 1); - m_SimulatorManager->RegisterSimulator(m_FireSimulator, 1); + m_SimulatorManager->RegisterSimulator(m_SandSimulator.get(), 1); + m_SimulatorManager->RegisterSimulator(m_FireSimulator.get(), 1); m_Lighting.Start(this); m_Storage.Start(this, m_StorageSchema, m_StorageCompressionFactor); @@ -1059,7 +1054,6 @@ void cWorld::TickQueuedTasks(void) for (cTasks::iterator itr = Tasks.begin(), end = Tasks.end(); itr != end; ++itr) { (*itr)->Run(*this); - delete *itr; } // for itr - m_Tasks[] } @@ -1073,18 +1067,19 @@ void cWorld::TickScheduledTasks(void) cScheduledTasks Tasks; { cCSLock Lock(m_CSScheduledTasks); - while (!m_ScheduledTasks.empty() && (m_ScheduledTasks.front()->m_TargetTick < m_WorldAge)) - { - Tasks.push_back(m_ScheduledTasks.front()); - m_ScheduledTasks.pop_front(); - } + std::move( + m_ScheduledTasks.begin(), + std::find_if( + m_ScheduledTasks.begin(), + m_ScheduledTasks.end(), + [m_WorldAge] (std::unique_ptr& Task) { return Task->m_TargetTick < m_WorldAge;}), + std::back_inserter(Tasks)); } // Execute and delete each task: for (cScheduledTasks::iterator itr = Tasks.begin(), end = Tasks.end(); itr != end; ++itr) { (*itr)->m_Task->Run(*this); - delete *itr; } // for itr - m_Tasks[] } @@ -2593,7 +2588,7 @@ void cWorld::UnloadUnusedChunks(void) void cWorld::QueueUnloadUnusedChunks(void) { - QueueTask(new cWorld::cTaskUnloadUnusedChunks); + QueueTask(make_unique()); } @@ -3049,17 +3044,17 @@ void cWorld::SaveAllChunks(void) void cWorld::QueueSaveAllChunks(void) { - QueueTask(new cWorld::cTaskSaveAllChunks); + QueueTask(make_unique()); } -void cWorld::QueueTask(cTask * a_Task) +void cWorld::QueueTask(std::unique_ptr a_Task) { cCSLock Lock(m_CSTasks); - m_Tasks.push_back(a_Task); + m_Tasks.push_back(std::move(a_Task)); } @@ -3076,11 +3071,11 @@ void cWorld::ScheduleTask(int a_DelayTicks, cTask * a_Task) { if ((*itr)->m_TargetTick >= TargetTick) { - m_ScheduledTasks.insert(itr, new cScheduledTask(TargetTick, a_Task)); + m_ScheduledTasks.insert(itr, make_unique(TargetTick, a_Task)); return; } } - m_ScheduledTasks.push_back(new cScheduledTask(TargetTick, a_Task)); + m_ScheduledTasks.push_back(make_unique(TargetTick, a_Task)); } diff --git a/src/World.h b/src/World.h index 90dada259..66dd2494e 100644 --- a/src/World.h +++ b/src/World.h @@ -103,7 +103,7 @@ public: virtual void Run(cWorld & a_World) = 0; } ; - typedef std::vector cTasks; + typedef std::vector> cTasks; class cTaskSaveAllChunks : @@ -506,7 +506,7 @@ public: // tolua_end - inline cSimulatorManager * GetSimulatorManager(void) { return m_SimulatorManager; } + inline cSimulatorManager * GetSimulatorManager(void) { return m_SimulatorManager.get(); } inline cFluidSimulator * GetWaterSimulator(void) { return m_WaterSimulator; } inline cFluidSimulator * GetLavaSimulator (void) { return m_LavaSimulator; } @@ -671,7 +671,7 @@ public: void QueueSaveAllChunks(void); // tolua_export /** Queues a task onto the tick thread. The task object will be deleted once the task is finished */ - void QueueTask(cTask * a_Task); // Exported in ManualBindings.cpp + void QueueTask(std::unique_ptr a_Task); // Exported in ManualBindings.cpp /** Queues a task onto the tick thread, with the specified delay. The task object will be deleted once the task is finished */ @@ -764,7 +764,7 @@ public: cChunkGenerator & GetGenerator(void) { return m_Generator; } cWorldStorage & GetStorage (void) { return m_Storage; } - cChunkMap * GetChunkMap (void) { return m_ChunkMap; } + cChunkMap * GetChunkMap (void) { return m_ChunkMap.get(); } /** Sets the blockticking to start at the specified block. Only one blocktick per chunk may be set, second call overwrites the first call */ void SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_export @@ -861,7 +861,7 @@ private: } }; - typedef std::list cScheduledTasks; + typedef std::list> cScheduledTasks; AString m_WorldName; @@ -913,11 +913,11 @@ private: std::vector m_BlockTickQueue; std::vector m_BlockTickQueueCopy; // Second is for safely removing the objects from the queue - cSimulatorManager * m_SimulatorManager; - cSandSimulator * m_SandSimulator; + std::unique_ptr m_SimulatorManager; + std::unique_ptr m_SandSimulator; cFluidSimulator * m_WaterSimulator; cFluidSimulator * m_LavaSimulator; - cFireSimulator * m_FireSimulator; + std::unique_ptr m_FireSimulator; cRedstoneSimulator * m_RedstoneSimulator; cCriticalSection m_CSPlayers; @@ -927,7 +927,7 @@ private: unsigned int m_MaxPlayers; - cChunkMap * m_ChunkMap; + std::unique_ptr m_ChunkMap; bool m_bAnimals; std::set m_AllowedMobs; -- cgit v1.2.3 From 1a07dc897d13c775c6f540f3500db505e5e80abc Mon Sep 17 00:00:00 2001 From: worktycho Date: Sat, 11 Oct 2014 14:43:06 +0100 Subject: Fix lambda capture --- src/World.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/World.cpp b/src/World.cpp index a23db6242..f616063f5 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -1067,12 +1067,13 @@ void cWorld::TickScheduledTasks(void) cScheduledTasks Tasks; { cCSLock Lock(m_CSScheduledTasks); + auto WorldAge = m_WorldAge; std::move( m_ScheduledTasks.begin(), std::find_if( m_ScheduledTasks.begin(), m_ScheduledTasks.end(), - [m_WorldAge] (std::unique_ptr& Task) { return Task->m_TargetTick < m_WorldAge;}), + [WorldAge] (std::unique_ptr& Task) { return Task->m_TargetTick < m_WorldAge;}), std::back_inserter(Tasks)); } -- cgit v1.2.3 From 68762747e0455a5a3203f53bda8b576e170e3337 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Sat, 11 Oct 2014 16:59:13 +0100 Subject: Fixed typo and removed useless right side up slab meta. --- src/BlockID.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index b78c09f9c..f1aee3f4a 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -764,8 +764,7 @@ enum E_META_WOODEN_SLAB_JUNGLE = 3, E_META_WOODEN_SLAB_ACACIA = 4, E_META_WOODEN_SLAB_DARK_OAK = 5, - E_META_WOODEN_SLAB_RIGHT_SIDE_UP = 0, - E_META_WOODWN_SLAB_UPSIDE_DOWN = 8, + E_META_WOODEN_SLAB_UPSIDE_DOWN = 8, // E_BLOCK_WOOL metas: E_META_WOOL_WHITE = 0, -- cgit v1.2.3 From 6af9d5ba0142b5bff6147c5fbc844a39f8dd0d0d Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Sat, 11 Oct 2014 18:39:46 +0100 Subject: Fixed compilation. --- src/Blocks/BlockStone.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockStone.h b/src/Blocks/BlockStone.h index e52599c0f..69cc8301b 100644 --- a/src/Blocks/BlockStone.h +++ b/src/Blocks/BlockStone.h @@ -18,7 +18,7 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - if (a_BlockMeta == E_META_STONE) + if (a_BlockMeta == E_META_STONE_STONE) { a_Pickups.push_back(cItem(E_BLOCK_COBBLESTONE, 1, 0)); return; -- cgit v1.2.3 From 856764dee8f0c66397669e8c7c013c758f1d2c81 Mon Sep 17 00:00:00 2001 From: Steven Riehl Date: Sat, 11 Oct 2014 20:39:55 -0600 Subject: convert old style casts to fix warnings --- src/BlockArea.h | 136 ++++++++------- src/BlockEntities/BeaconEntity.cpp | 12 +- src/BlockEntities/DispenserEntity.cpp | 7 +- src/BlockEntities/DropSpenserEntity.cpp | 18 +- src/BlockEntities/FlowerPotEntity.cpp | 10 +- src/BlockEntities/FurnaceEntity.cpp | 52 +++--- src/BlockEntities/HopperEntity.cpp | 66 ++++---- src/BlockEntities/JukeboxEntity.cpp | 6 +- src/BlockEntities/SignEntity.cpp | 8 +- src/ChunkDef.h | 64 ++++--- src/Defines.h | 38 ++--- src/Entities/Entity.h | 184 ++++++++++----------- src/Entities/Pickup.h | 10 +- src/MersenneTwister.h | 44 ++--- src/Mobs/Monster.h | 60 ++++--- src/OSSupport/IsThread.h | 36 ++-- src/World.h | 284 ++++++++++++++++---------------- 17 files changed, 486 insertions(+), 549 deletions(-) (limited to 'src') diff --git a/src/BlockArea.h b/src/BlockArea.h index 86f7c4f2d..003872635 100644 --- a/src/BlockArea.h +++ b/src/BlockArea.h @@ -32,7 +32,7 @@ class cBlockArea // tolua_end DISALLOW_COPY_AND_ASSIGN(cBlockArea); // tolua_begin - + public: /** What data is to be queried (bit-mask) */ @@ -43,7 +43,7 @@ public: baLight = 4, baSkyLight = 8, } ; - + /** The per-block strategy to use when merging another block area into this object. See the Merge function for the description of these */ enum eMergeStrategy @@ -56,64 +56,64 @@ public: msDifference, msMask, } ; - + cBlockArea(void); ~cBlockArea(); - + /** Clears the data stored to reclaim memory */ void Clear(void); - + /** Creates a new area of the specified size and contents. Origin is set to all zeroes. BlockTypes are set to air, block metas to zero, blocklights to zero and skylights to full light. */ void Create(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes = baTypes | baMetas); - + /** Creates a new area of the specified size and contents. Origin is set to all zeroes. BlockTypes are set to air, block metas to zero, blocklights to zero and skylights to full light. */ void Create(const Vector3i & a_Size, int a_DataTypes = baTypes | baMetas); - + /** Resets the origin. No other changes are made, contents are untouched. */ void SetOrigin(int a_OriginX, int a_OriginY, int a_OriginZ); - + /** Resets the origin. No other changes are made, contents are untouched. */ void SetOrigin(const Vector3i & a_Origin); - + /** Reads an area of blocks specified. Returns true if successful. All coords are inclusive. */ bool Read(cForEachChunkProvider * a_ForEachChunkProvider, int a_MinBlockX, int a_MaxBlockX, int a_MinBlockY, int a_MaxBlockY, int a_MinBlockZ, int a_MaxBlockZ, int a_DataTypes = baTypes | baMetas); - + /** Reads an area of blocks specified. Returns true if successful. The bounds are included in the read area. */ bool Read(cForEachChunkProvider * a_ForEachChunkProvider, const cCuboid & a_Bounds, int a_DataTypes = baTypes | baMetas); - + /** Reads an area of blocks specified. Returns true if successful. The bounds are included in the read area. */ bool Read(cForEachChunkProvider * a_ForEachChunkProvider, const Vector3i & a_Point1, const Vector3i & a_Point2, int a_DataTypes = baTypes | baMetas); - + // TODO: Write() is not too good an interface: if it fails, there's no way to repeat only for the parts that didn't write // A better way may be to return a list of cBlockAreas for each part that didn't succeed writing, so that the caller may try again - + /** Writes the area back into cWorld at the coords specified. Returns true if successful in all chunks, false if only partially / not at all */ bool Write(cForEachChunkProvider * a_ForEachChunkProvider, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes = baTypes | baMetas); - + /** Writes the area back into cWorld at the coords specified. Returns true if successful in all chunks, false if only partially / not at all */ bool Write(cForEachChunkProvider * a_ForEachChunkProvider, const Vector3i & a_MinCoords, int a_DataTypes = baTypes | baMetas); - + /** Copies this object's contents into the specified BlockArea. */ void CopyTo(cBlockArea & a_Into) const; - + /** Copies the contents from the specified BlockArea into this object. */ void CopyFrom(const cBlockArea & a_From); - + /** For testing purposes only, dumps the area into a file. */ void DumpToRawFile(const AString & a_FileName); - + /** Crops the internal contents by the specified amount of blocks from each border. */ void Crop(int a_AddMinX, int a_SubMaxX, int a_AddMinY, int a_SubMaxY, int a_AddMinZ, int a_SubMaxZ); - + /** Expands the internal contents by the specified amount of blocks from each border */ void Expand(int a_SubMinX, int a_AddMaxX, int a_SubMinY, int a_AddMaxY, int a_SubMinZ, int a_AddMaxZ); - + /** Merges another block area into this one, using the specified block combinating strategy This function combines another BlockArea into the current object. The strategy parameter specifies how individual blocks are combined together, using the table below. @@ -125,7 +125,7 @@ public: | A | air | air | A | A | | air | B | B | B | B | | A | B | B | A | B | - + So to sum up: - msOverwrite completely overwrites all blocks with the Src's blocks - msFillAir overwrites only those blocks that were air @@ -147,7 +147,7 @@ public: | mycelium | stone | stone | ... and mycelium | A | stone | A | ... but nothing else | A | * | A | Everything else is left as it is - + msSpongePrint: Used for most generators, it allows carving out air pockets, too, and uses the Sponge as the NOP block | area block | | @@ -155,7 +155,7 @@ public: +----------+--------+--------+ | A | sponge | A | Sponge is the NOP block | * | B | B | Everything else overwrites anything - + msMask: Combines two areas, the blocks that are the same are kept, differing ones are reset to air | area block | | @@ -166,68 +166,68 @@ public: */ void Merge(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_RelZ, eMergeStrategy a_Strategy); - + /** Merges another block area into this one, using the specified block combinating strategy. See Merge() above for details. */ void Merge(const cBlockArea & a_Src, const Vector3i & a_RelMinCoords, eMergeStrategy a_Strategy); - + /** Fills the entire block area with the specified data */ void Fill(int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f); - + /** Fills a cuboid inside the block area with the specified data */ void FillRelCuboid(int a_MinRelX, int a_MaxRelX, int a_MinRelY, int a_MaxRelY, int a_MinRelZ, int a_MaxRelZ, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Fills a cuboid inside the block area with the specified data. a_Cuboid must be sorted. */ void FillRelCuboid(const cCuboid & a_RelCuboid, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Draws a line from between two points with the specified data */ void RelLine(int a_RelX1, int a_RelY1, int a_RelZ1, int a_RelX2, int a_RelY2, int a_RelZ2, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Draws a line from between two points with the specified data */ void RelLine(const Vector3i & a_Point1, const Vector3i & a_Point2, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Rotates the entire area counter-clockwise around the Y axis */ void RotateCCW(void); - + /** Rotates the entire area clockwise around the Y axis */ void RotateCW(void); - + /** Mirrors the entire area around the XY plane */ void MirrorXY(void); - + /** Mirrors the entire area around the XZ plane */ void MirrorXZ(void); - + /** Mirrors the entire area around the YZ plane */ void MirrorYZ(void); - + /** Rotates the entire area counter-clockwise around the Y axis, doesn't use blockhandlers for block meta */ void RotateCCWNoMeta(void); - + /** Rotates the entire area clockwise around the Y axis, doesn't use blockhandlers for block meta */ void RotateCWNoMeta(void); - + /** Mirrors the entire area around the XY plane, doesn't use blockhandlers for block meta */ void MirrorXYNoMeta(void); - + /** Mirrors the entire area around the XZ plane, doesn't use blockhandlers for block meta */ void MirrorXZNoMeta(void); - + /** Mirrors the entire area around the YZ plane, doesn't use blockhandlers for block meta */ void MirrorYZNoMeta(void); - + // Setters: void SetRelBlockType (int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType); void SetBlockType (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType); @@ -253,80 +253,80 @@ public: void SetBlockTypeMeta (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); void SetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); - + // tolua_end - + // These need manual exporting, tolua generates the binding as requiring 2 extra input params void GetBlockTypeMeta (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const; void GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const; - + // GetSize() is already exported manually to return 3 numbers, can't auto-export const Vector3i & GetSize(void) const { return m_Size; } - + // GetOrigin() is already exported manually to return 3 numbers, can't auto-export const Vector3i & GetOrigin(void) const { return m_Origin; } - + // tolua_begin - + int GetSizeX(void) const { return m_Size.x; } int GetSizeY(void) const { return m_Size.y; } int GetSizeZ(void) const { return m_Size.z; } - + /** Returns the volume of the area, as number of blocks */ int GetVolume(void) const { return m_Size.x * m_Size.y * m_Size.z; } - + int GetOriginX(void) const { return m_Origin.x; } int GetOriginY(void) const { return m_Origin.y; } int GetOriginZ(void) const { return m_Origin.z; } - + /** Returns the datatypes that are stored in the object (bitmask of baXXX values) */ int GetDataTypes(void) const; - + bool HasBlockTypes (void) const { return (m_BlockTypes != NULL); } bool HasBlockMetas (void) const { return (m_BlockMetas != NULL); } bool HasBlockLights (void) const { return (m_BlockLight != NULL); } bool HasBlockSkyLights(void) const { return (m_BlockSkyLight != NULL); } - + // tolua_end - + // Clients can use these for faster access to all blocktypes. Be careful though! /** Returns the internal pointer to the block types */ BLOCKTYPE * GetBlockTypes (void) const { return m_BlockTypes; } 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 (size_t)(m_Size.x * m_Size.y * m_Size.z); } + size_t GetBlockCount(void) const { return static_cast(m_Size.x * m_Size.y * m_Size.z); } int MakeIndex(int a_RelX, int a_RelY, int a_RelZ) const; protected: friend class cChunkDesc; friend class cSchematicFileSerializer; - + class cChunkReader : public cChunkDataCallback { public: cChunkReader(cBlockArea & a_Area); - + protected: cBlockArea & m_Area; Vector3i m_Origin; int m_CurrentChunkX; int m_CurrentChunkZ; - + void CopyNibbles(NIBBLETYPE * a_AreaDst, const NIBBLETYPE * a_ChunkSrc); - + // cChunkDataCallback overrides: virtual bool Coords(int a_ChunkX, int a_ChunkZ) override; virtual void ChunkData(const cChunkData & a_BlockTypes) override; } ; - + typedef NIBBLETYPE * NIBBLEARRAY; - - + + Vector3i m_Origin; Vector3i m_Size; - + /** An extra data value sometimes stored in the .schematic file. Used mainly by the WorldEdit plugin. cBlockArea doesn't use this value in any way. */ Vector3i m_WEOffset; @@ -335,10 +335,10 @@ protected: NIBBLETYPE * m_BlockMetas; // Each meta is stored as a separate byte for faster access NIBBLETYPE * m_BlockLight; // Each light value is stored as a separate byte for faster access NIBBLETYPE * m_BlockSkyLight; // Each light value is stored as a separate byte for faster access - + /** Clears the data stored and prepares a fresh new block area with the specified dimensions */ bool SetSize(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes); - + // Basic Setters: void SetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Value, NIBBLETYPE * a_Array); void SetNibble (int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Value, NIBBLETYPE * a_Array); @@ -346,11 +346,11 @@ protected: // Basic Getters: NIBBLETYPE GetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE * a_Array) const; NIBBLETYPE GetNibble (int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE * a_Array) const; - + // Crop helpers: void CropBlockTypes(int a_AddMinX, int a_SubMaxX, int a_AddMinY, int a_SubMaxY, int a_AddMinZ, int a_SubMaxZ); void CropNibbles (NIBBLEARRAY & a_Array, int a_AddMinX, int a_SubMaxX, int a_AddMinY, int a_SubMaxY, int a_AddMinZ, int a_SubMaxZ); - + // Expand helpers: void ExpandBlockTypes(int a_SubMinX, int a_AddMaxX, int a_SubMinY, int a_AddMaxY, int a_SubMinZ, int a_AddMaxZ); void ExpandNibbles (NIBBLEARRAY & a_Array, int a_SubMinX, int a_AddMaxX, int a_SubMinY, int a_AddMaxY, int a_SubMinZ, int a_AddMaxZ); @@ -361,13 +361,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/BlockEntities/BeaconEntity.cpp b/src/BlockEntities/BeaconEntity.cpp index 02f45a097..de23f7e79 100644 --- a/src/BlockEntities/BeaconEntity.cpp +++ b/src/BlockEntities/BeaconEntity.cpp @@ -227,9 +227,9 @@ void cBeaconEntity::GiveEffects(void) virtual bool Item(cPlayer * a_Player) { Vector3d PlayerPosition = Vector3d(a_Player->GetPosition()); - if (PlayerPosition.y > (double)m_PosY) + if (PlayerPosition.y > static_cast(m_PosY)) { - PlayerPosition.y = (double)m_PosY; + PlayerPosition.y = static_cast(m_PosY); } // TODO: Vanilla minecraft uses an AABB check instead of a radius one @@ -255,7 +255,7 @@ void cBeaconEntity::GiveEffects(void) , m_PrimaryEffect(a_PrimaryEffect) , m_SecondaryEffect(a_SecondaryEffect) , m_EffectLevel(a_EffectLevel) - {}; + {} } PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel); GetWorld()->ForEachPlayer(PlayerCallback); @@ -288,7 +288,7 @@ void cBeaconEntity::UsedBy(cPlayer * a_Player) OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this)); Window = GetWindow(); } - + if (Window != NULL) { // if (a_Player->GetWindow() != Window) @@ -307,7 +307,3 @@ void cBeaconEntity::SendTo(cClientHandle & a_Client) { a_Client.SendUpdateBlockEntity(*this); } - - - - diff --git a/src/BlockEntities/DispenserEntity.cpp b/src/BlockEntities/DispenserEntity.cpp index aea854dc2..157862bd1 100644 --- a/src/BlockEntities/DispenserEntity.cpp +++ b/src/BlockEntities/DispenserEntity.cpp @@ -105,7 +105,7 @@ void cDispenserEntity::DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) { double MobX = 0.5 + (DispX + DispChunk->GetPosX() * cChunkDef::Width); double MobZ = 0.5 + (DispZ + DispChunk->GetPosZ() * cChunkDef::Width); - if (m_World->SpawnMob(MobX, DispY, MobZ, (eMonsterType)m_Contents.GetSlot(a_SlotNum).m_ItemDamage) >= 0) + if (m_World->SpawnMob(MobX, DispY, MobZ, static_cast(m_Contents.GetSlot(a_SlotNum).m_ItemDamage)) >= 0) { m_Contents.ChangeSlotCount(a_SlotNum, -1); } @@ -190,7 +190,7 @@ void cDispenserEntity::DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) void cDispenserEntity::SpawnProjectileFromDispenser(int a_BlockX, int a_BlockY, int a_BlockZ, cProjectileEntity::eKind a_Kind, const Vector3d & a_ShootVector) { - m_World->CreateProjectile((double)a_BlockX + 0.5, (double)a_BlockY + 0.5, (double)a_BlockZ + 0.5, a_Kind, NULL, NULL, &a_ShootVector); + m_World->CreateProjectile(static_cast(a_BlockX + 0.5), static_cast(a_BlockY + 0.5), static_cast(a_BlockZ + 0.5), a_Kind, NULL, NULL, &a_ShootVector); } @@ -275,6 +275,3 @@ bool cDispenserEntity::EmptyLiquidBucket(BLOCKTYPE a_BlockInFront, int a_SlotNum m_Contents.AddItem(EmptyBucket); return true; } - - - diff --git a/src/BlockEntities/DropSpenserEntity.cpp b/src/BlockEntities/DropSpenserEntity.cpp index dac951b27..2cbc947dc 100644 --- a/src/BlockEntities/DropSpenserEntity.cpp +++ b/src/BlockEntities/DropSpenserEntity.cpp @@ -61,7 +61,7 @@ void cDropSpenserEntity::DropSpense(cChunk & a_Chunk) { // Pick one of the occupied slots: int OccupiedSlots[9]; - int SlotsCnt = 0; + uint SlotsCnt = 0; for (int i = m_Contents.GetNumSlots() - 1; i >= 0; i--) { if (!m_Contents.GetSlot(i).IsEmpty()) @@ -70,19 +70,19 @@ void cDropSpenserEntity::DropSpense(cChunk & a_Chunk) SlotsCnt++; } } // for i - m_Contents[] - + if (SlotsCnt == 0) { // Nothing in the dropspenser, play the click sound m_World->BroadcastSoundEffect("random.click", m_PosX * 8, m_PosY * 8, m_PosZ * 8, 1.0f, 1.2f); return; } - + int RandomSlot = m_World->GetTickRandomNumber(SlotsCnt - 1); - + // DropSpense the item, using the specialized behavior in the subclasses: DropSpenseFromSlot(a_Chunk, OccupiedSlots[RandomSlot]); - + // Broadcast a smoke and click effects: NIBBLETYPE Meta = a_Chunk.GetMeta(m_RelX, m_PosY, m_RelZ); int SmokeDir = 0; @@ -132,7 +132,7 @@ bool cDropSpenserEntity::Tick(float a_Dt, cChunk & a_Chunk) { return false; } - + m_ShouldDropSpense = false; DropSpense(a_Chunk); return true; @@ -160,7 +160,7 @@ void cDropSpenserEntity::UsedBy(cPlayer * a_Player) OpenWindow(new cDropSpenserWindow(m_PosX, m_PosY, m_PosZ, this)); Window = GetWindow(); } - + if (Window != NULL) { if (a_Player->GetWindow() != Window) @@ -205,7 +205,3 @@ void cDropSpenserEntity::DropFromSlot(cChunk & a_Chunk, int a_SlotNum) m_World->SpawnItemPickups(Pickups, MicroX, MicroY, MicroZ, PickupSpeedX, PickupSpeedY, PickupSpeedZ); } - - - - diff --git a/src/BlockEntities/FlowerPotEntity.cpp b/src/BlockEntities/FlowerPotEntity.cpp index 01560f814..ad7b496cc 100644 --- a/src/BlockEntities/FlowerPotEntity.cpp +++ b/src/BlockEntities/FlowerPotEntity.cpp @@ -28,7 +28,7 @@ void cFlowerPotEntity::UsedBy(cPlayer * a_Player) { return; } - + cItem SelectedItem = a_Player->GetInventory().GetEquippedItem(); if (IsFlower(SelectedItem.m_ItemType, SelectedItem.m_ItemDamage)) { @@ -63,7 +63,7 @@ void cFlowerPotEntity::Destroy(void) cItems Pickups; Pickups.Add(m_Item); m_World->SpawnItemPickups(Pickups, m_PosX + 0.5, m_PosY + 0.5, m_PosZ + 0.5); - + m_Item.Empty(); } } @@ -88,7 +88,7 @@ bool cFlowerPotEntity::IsFlower(short m_ItemType, short m_ItemData) } case E_BLOCK_TALL_GRASS: { - return (m_ItemData == (short) 2); + return (m_ItemData == static_cast(2)); } default: { @@ -96,7 +96,3 @@ bool cFlowerPotEntity::IsFlower(short m_ItemType, short m_ItemData) } } } - - - - diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index 4452fc00a..d165df079 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -67,8 +67,8 @@ void cFurnaceEntity::UsedBy(cPlayer * a_Player) if (a_Player->GetWindow() != Window) { a_Player->OpenWindow(Window); - BroadcastProgress(PROGRESSBAR_FUEL, (short)m_LastProgressFuel); - BroadcastProgress(PROGRESSBAR_SMELTING, (short)m_LastProgressCook); + BroadcastProgress(PROGRESSBAR_FUEL, static_cast(m_LastProgressFuel)); + BroadcastProgress(PROGRESSBAR_SMELTING, static_cast(m_LastProgressCook)); } } } @@ -112,16 +112,16 @@ bool cFurnaceEntity::Tick(float a_Dt, cChunk & a_Chunk) FinishOne(); } } - + m_TimeBurned++; if (m_TimeBurned >= m_FuelBurnTime) { // The current fuel has been exhausted, use another one, if possible BurnNewFuel(); } - + UpdateProgressBars(); - + return true; } @@ -166,7 +166,7 @@ void cFurnaceEntity::FinishOne() m_Contents.ChangeSlotCount(fsOutput, m_CurrentRecipe->Out->m_ItemCount); } m_Contents.ChangeSlotCount(fsInput, -m_CurrentRecipe->In->m_ItemCount); - + UpdateIsCooking(); } @@ -186,7 +186,7 @@ void cFurnaceEntity::BurnNewFuel(void) SetIsCooking(false); return; } - + // Is the input and output ready for cooking? if (!CanCookInputToOutput()) { @@ -214,13 +214,13 @@ void cFurnaceEntity::BurnNewFuel(void) void cFurnaceEntity::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) { super::OnSlotChanged(a_ItemGrid, a_SlotNum); - + if (m_World == NULL) { // The furnace isn't initialized yet, do no processing return; } - + ASSERT(a_ItemGrid == &m_Contents); switch (a_SlotNum) { @@ -229,13 +229,13 @@ void cFurnaceEntity::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) UpdateInput(); break; } - + case fsFuel: { UpdateFuel(); break; } - + case fsOutput: { UpdateOutput(); @@ -258,7 +258,7 @@ void cFurnaceEntity::UpdateInput(void) m_TimeCooked = 0; } m_LastInput = m_Contents.GetSlot(fsInput); - + cFurnaceRecipe * FR = cRoot::Get()->GetFurnaceRecipe(); m_CurrentRecipe = FR->GetRecipeFrom(m_Contents.GetSlot(fsInput)); if (!CanCookInputToOutput()) @@ -271,7 +271,7 @@ void cFurnaceEntity::UpdateInput(void) { m_NeedCookTime = m_CurrentRecipe->CookTime; SetIsCooking(true); - + // Start burning new fuel if there's no flame now: if (GetFuelBurnTimeLeft() <= 0) { @@ -292,7 +292,7 @@ void cFurnaceEntity::UpdateFuel(void) // The current fuel is still burning, don't modify anything: return; } - + // The current fuel is spent, try to burn some more: BurnNewFuel(); } @@ -312,7 +312,7 @@ void cFurnaceEntity::UpdateOutput(void) SetIsCooking(false); return; } - + // No need to burn new fuel, the Tick() function will take care of that // Can cook, start cooking if not already underway: @@ -339,7 +339,7 @@ void cFurnaceEntity::UpdateIsCooking(void) m_NeedCookTime = 0; return; } - + SetIsCooking(true); } @@ -355,7 +355,7 @@ bool cFurnaceEntity::CanCookInputToOutput(void) const // This input cannot be cooked return false; } - + const cItem & Slot = m_Contents.GetSlot(fsOutput); if (Slot.IsEmpty()) { @@ -368,13 +368,13 @@ bool cFurnaceEntity::CanCookInputToOutput(void) const // The output slot is blocked with something that cannot be stacked with the recipe's output return false; } - + if (Slot.IsFullStack()) { // Cannot add any more items to the output slot return false; } - + return true; } @@ -387,18 +387,18 @@ void cFurnaceEntity::UpdateProgressBars(void) { // In order to preserve bandwidth, an update is sent only every 10th tick // That's why the comparisons use the division by eight - + int CurFuel = (m_FuelBurnTime > 0) ? (200 - 200 * m_TimeBurned / m_FuelBurnTime) : 0; if ((CurFuel / 8) != (m_LastProgressFuel / 8)) { - BroadcastProgress(PROGRESSBAR_FUEL, (short)CurFuel); + BroadcastProgress(PROGRESSBAR_FUEL, static_cast(CurFuel)); m_LastProgressFuel = CurFuel; } - + int CurCook = (m_NeedCookTime > 0) ? (200 * m_TimeCooked / m_NeedCookTime) : 0; if ((CurCook / 8) != (m_LastProgressCook / 8)) { - BroadcastProgress(PROGRESSBAR_SMELTING, (short)CurCook); + BroadcastProgress(PROGRESSBAR_SMELTING, static_cast(CurCook)); m_LastProgressCook = CurCook; } } @@ -415,11 +415,7 @@ void cFurnaceEntity::SetIsCooking(bool a_IsCooking) } m_IsCooking = a_IsCooking; - + // Light or extinguish the furnace: m_World->FastSetBlock(m_PosX, m_PosY, m_PosZ, m_IsCooking ? E_BLOCK_LIT_FURNACE : E_BLOCK_FURNACE, m_BlockMeta); } - - - - diff --git a/src/BlockEntities/HopperEntity.cpp b/src/BlockEntities/HopperEntity.cpp index 103f516fc..9f64ea148 100644 --- a/src/BlockEntities/HopperEntity.cpp +++ b/src/BlockEntities/HopperEntity.cpp @@ -58,7 +58,7 @@ bool cHopperEntity::Tick(float a_Dt, cChunk & a_Chunk) { UNUSED(a_Dt); Int64 CurrentTick = a_Chunk.GetWorld()->GetWorldAge(); - + bool res = false; res = MoveItemsIn (a_Chunk, CurrentTick) || res; res = MovePickupsIn(a_Chunk, CurrentTick) || res; @@ -74,7 +74,7 @@ void cHopperEntity::SendTo(cClientHandle & a_Client) { // The hopper entity doesn't need anything sent to the client when it's created / gets in the viewdistance // All the actual handling is in the cWindow UI code that gets called when the hopper is rclked - + UNUSED(a_Client); } @@ -91,7 +91,7 @@ void cHopperEntity::UsedBy(cPlayer * a_Player) OpenNewWindow(); Window = GetWindow(); } - + // Open the window for the player: if (Window != NULL) { @@ -138,7 +138,7 @@ bool cHopperEntity::MoveItemsIn(cChunk & a_Chunk, Int64 a_CurrentTick) // Too early after the previous transfer return false; } - + // Try moving an item in: bool res = false; switch (a_Chunk.GetBlock(m_RelX, m_PosY + 1, m_RelZ)) @@ -161,17 +161,17 @@ bool cHopperEntity::MoveItemsIn(cChunk & a_Chunk, Int64 a_CurrentTick) case E_BLOCK_DROPPER: case E_BLOCK_HOPPER: { - res = MoveItemsFromGrid(*(cBlockEntityWithItems *)a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); + res = MoveItemsFromGrid(*static_cast(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ))); break; } } - + // If the item has been moved, reset the last tick: if (res) { m_LastMoveItemsInTick = a_CurrentTick; } - + return res; } @@ -205,12 +205,12 @@ bool cHopperEntity::MovePickupsIn(cChunk & a_Chunk, Int64 a_CurrentTick) } Vector3f EntityPos = a_Entity->GetPosition(); - Vector3f BlockPos(m_Pos.x + 0.5f, (float)m_Pos.y + 1, m_Pos.z + 0.5f); // One block above hopper, and search from center outwards + Vector3f BlockPos(m_Pos.x + 0.5f, static_cast(m_Pos.y) + 1, m_Pos.z + 0.5f); // One block above hopper, and search from center outwards double Distance = (EntityPos - BlockPos).Length(); if (Distance < 0.5) { - if (TrySuckPickupIn((cPickup *)a_Entity)) + if (TrySuckPickupIn(static_cast(a_Entity))) { return false; } @@ -238,9 +238,9 @@ bool cHopperEntity::MovePickupsIn(cChunk & a_Chunk, Int64 a_CurrentTick) m_bFoundPickupsAbove = true; int PreviousCount = m_Contents.GetSlot(i).m_ItemCount; - + Item.m_ItemCount -= m_Contents.ChangeSlotCount(i, Item.m_ItemCount) - PreviousCount; // Set count to however many items were added - + if (Item.IsEmpty()) { a_Pickup->Destroy(); // Kill pickup if all items were added @@ -280,7 +280,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) // Too early after the previous transfer return false; } - + // Get the coords of the block where to output items: int OutX, OutY, OutZ; NIBBLETYPE Meta = a_Chunk.GetMeta(m_RelX, m_PosY, m_RelZ); @@ -294,7 +294,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) // Cannot output below the zero-th block level return false; } - + // Convert coords to relative: int OutRelX = OutX - a_Chunk.GetPosX() * cChunkDef::Width; int OutRelZ = OutZ - a_Chunk.GetPosZ() * cChunkDef::Width; @@ -304,7 +304,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) // The destination chunk has been unloaded, don't tick return false; } - + // Call proper moving function, based on the blocktype present at the coords: bool res = false; switch (DestChunk->GetBlock(OutRelX, OutY, OutRelZ)) @@ -327,7 +327,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) case E_BLOCK_DROPPER: case E_BLOCK_HOPPER: { - cBlockEntityWithItems * BlockEntity = (cBlockEntityWithItems *)DestChunk->GetBlockEntity(OutX, OutY, OutZ); + cBlockEntityWithItems * BlockEntity = static_cast(DestChunk->GetBlockEntity(OutX, OutY, OutZ)); if (BlockEntity == NULL) { LOGWARNING("%s: A block entity was not found where expected at {%d, %d, %d}", __FUNCTION__, OutX, OutY, OutZ); @@ -337,13 +337,13 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) break; } } - + // If the item has been moved, reset the last tick: if (res) { m_LastMoveItemsOutTick = a_CurrentTick; } - + return res; } @@ -354,7 +354,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) /// Moves items from a chest (dblchest) above the hopper into this hopper. Returns true if contents have changed. bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) { - cChestEntity * MainChest = (cChestEntity *)a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ); + cChestEntity * MainChest = static_cast(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); if (MainChest == NULL) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX, m_PosY + 1, m_PosZ); @@ -365,7 +365,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) // Moved the item from the chest directly above the hopper return true; } - + // Check if the chest is a double-chest (chest directly above was empty), if so, try to move from there: static const struct { @@ -395,7 +395,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) continue; } - cChestEntity * SideChest = (cChestEntity *)Neighbor->GetBlockEntity(m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z); + cChestEntity * SideChest = static_cast(Neighbor->GetBlockEntity(m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z)); if (SideChest == NULL) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z); @@ -409,7 +409,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) } return false; } - + // The chest was single and nothing could be moved return false; } @@ -421,13 +421,13 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) /// Moves items from a furnace above the hopper into this hopper. Returns true if contents have changed. bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk) { - cFurnaceEntity * Furnace = (cFurnaceEntity *)a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ); + cFurnaceEntity * Furnace = static_cast(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); if (Furnace == NULL) { LOGWARNING("%s: A furnace entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX, m_PosY + 1, m_PosZ); return false; } - + // Try move from the output slot: if (MoveItemsFromSlot(*Furnace, cFurnaceEntity::fsOutput, true)) { @@ -435,7 +435,7 @@ bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk) Furnace->SetOutputSlot(NewOutput.AddCount(-1)); return true; } - + // No output moved, check if we can move an empty bucket out of the fuel slot: if (Furnace->GetFuelSlot().m_ItemType == E_ITEM_BUCKET) { @@ -445,7 +445,7 @@ bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk) return true; } } - + // Nothing can be moved return false; } @@ -458,7 +458,7 @@ bool cHopperEntity::MoveItemsFromGrid(cBlockEntityWithItems & a_Entity) { cItemGrid & Grid = a_Entity.GetContents(); int NumSlots = Grid.GetNumSlots(); - + // First try adding items of types already in the hopper: for (int i = 0; i < NumSlots; i++) { @@ -519,7 +519,7 @@ bool cHopperEntity::MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_Sl // Plugin disagrees with the move continue; } - + m_Contents.ChangeSlotCount(i, 1); return true; } @@ -535,7 +535,7 @@ bool cHopperEntity::MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_Sl bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_BlockY, int a_BlockZ) { // Try the chest directly connected to the hopper: - cChestEntity * ConnectedChest = (cChestEntity *)a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); + cChestEntity * ConnectedChest = static_cast(a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ)); if (ConnectedChest == NULL) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, a_BlockX, a_BlockY, a_BlockZ); @@ -578,7 +578,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block continue; } - cChestEntity * Chest = (cChestEntity *)Neighbor->GetBlockEntity(a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z); + cChestEntity * Chest = static_cast(Neighbor->GetBlockEntity(a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z)); if (Chest == NULL) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d} (%d, %d)", __FUNCTION__, a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z, x, z); @@ -590,7 +590,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block } return false; } - + // The chest was single and nothing could be moved return false; } @@ -602,7 +602,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block /// Moves items to the furnace at the specified coords. Returns true if contents have changed bool cHopperEntity::MoveItemsToFurnace(cChunk & a_Chunk, int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_HopperMeta) { - cFurnaceEntity * Furnace = (cFurnaceEntity *)a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); + cFurnaceEntity * Furnace = static_cast(a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ)); if (a_HopperMeta == E_META_HOPPER_FACING_YM) { // Feed the input slot of the furnace @@ -684,7 +684,3 @@ bool cHopperEntity::MoveItemsToSlot(cBlockEntityWithItems & a_Entity, int a_DstS return false; } } - - - - diff --git a/src/BlockEntities/JukeboxEntity.cpp b/src/BlockEntities/JukeboxEntity.cpp index bb9b335e0..473526855 100644 --- a/src/BlockEntities/JukeboxEntity.cpp +++ b/src/BlockEntities/JukeboxEntity.cpp @@ -79,7 +79,7 @@ bool cJukeboxEntity::EjectRecord(void) } cItems Drops; - Drops.push_back(cItem(m_Record, 1, 0)); + Drops.push_back(cItem(static_cast(m_Record), 1, 0)); m_Record = 0; m_World->SpawnItemPickups(Drops, m_PosX + 0.5, m_PosY + 1, m_PosZ + 0.5, 8); m_World->BroadcastSoundParticleEffect(1005, m_PosX, m_PosY, m_PosZ, 0); @@ -113,7 +113,3 @@ void cJukeboxEntity::SetRecord(int a_Record) { m_Record = a_Record; } - - - - diff --git a/src/BlockEntities/SignEntity.cpp b/src/BlockEntities/SignEntity.cpp index d048d0218..9a2695b3f 100644 --- a/src/BlockEntities/SignEntity.cpp +++ b/src/BlockEntities/SignEntity.cpp @@ -45,7 +45,7 @@ void cSignEntity::SetLines(const AString & a_Line1, const AString & a_Line2, con void cSignEntity::SetLine(int a_Index, const AString & a_Line) { - if ((a_Index < 0) || (a_Index >= (int)ARRAYCOUNT(m_Line))) + if ((a_Index < 0) || (a_Index >= static_cast(ARRAYCOUNT(m_Line)))) { LOGWARNING("%s: setting a non-existent line %d (value \"%s\"", __FUNCTION__, a_Index, a_Line.c_str()); return; @@ -59,7 +59,7 @@ void cSignEntity::SetLine(int a_Index, const AString & a_Line) AString cSignEntity::GetLine(int a_Index) const { - if ((a_Index < 0) || (a_Index >= (int)ARRAYCOUNT(m_Line))) + if ((a_Index < 0) || (a_Index >= static_cast(ARRAYCOUNT(m_Line)))) { LOGWARNING("%s: requesting a non-existent line %d", __FUNCTION__, a_Index); return ""; @@ -75,7 +75,3 @@ void cSignEntity::SendTo(cClientHandle & a_Client) { a_Client.SendUpdateSign(m_PosX, m_PosY, m_PosZ, m_Line[0], m_Line[1], m_Line[2], m_Line[3]); } - - - - diff --git a/src/ChunkDef.h b/src/ChunkDef.h index f4ed66c4b..6ffe47ffb 100644 --- a/src/ChunkDef.h +++ b/src/ChunkDef.h @@ -66,7 +66,7 @@ public: /// The type used for any heightmap operations and storage; idx = x + Width * z; Height points to the highest non-air block in the column typedef HEIGHTTYPE HeightMap[Width * Width]; - + /** The type used for any biomemap operations and storage inside MCServer, using MCServer biomes (need not correspond to client representation!) idx = x + Width * z // Need to verify this with the protocol spec, currently unknown! @@ -95,8 +95,8 @@ public: a_X = a_X - a_ChunkX * Width; a_Z = a_Z - a_ChunkZ * Width; } - - + + /// Converts absolute block coords to chunk coords: inline static void BlockToChunk(int a_X, int a_Z, int & a_ChunkX, int & a_ChunkZ) { @@ -165,15 +165,15 @@ public: ASSERT((a_Z >= 0) && (a_Z < Width)); a_BlockTypes[MakeIndexNoCheck(a_X, a_Y, a_Z)] = a_Type; } - - + + inline static void SetBlock(BLOCKTYPE * a_BlockTypes, int a_Index, BLOCKTYPE a_Type) { ASSERT((a_Index >= 0) && (a_Index <= NumBlocks)); a_BlockTypes[a_Index] = a_Type; } - - + + inline static BLOCKTYPE GetBlock(const BLOCKTYPE * a_BlockTypes, int a_X, int a_Y, int a_Z) { ASSERT((a_X >= 0) && (a_X < Width)); @@ -181,39 +181,39 @@ public: ASSERT((a_Z >= 0) && (a_Z < Width)); return a_BlockTypes[MakeIndexNoCheck(a_X, a_Y, a_Z)]; } - - + + inline static BLOCKTYPE GetBlock(const BLOCKTYPE * a_BlockTypes, int a_Idx) { ASSERT((a_Idx >= 0) && (a_Idx < NumBlocks)); return a_BlockTypes[a_Idx]; } - - + + inline static int GetHeight(const HeightMap & a_HeightMap, int a_X, int a_Z) { ASSERT((a_X >= 0) && (a_X < Width)); ASSERT((a_Z >= 0) && (a_Z < Width)); return a_HeightMap[a_X + Width * a_Z]; } - - + + inline static void SetHeight(HeightMap & a_HeightMap, int a_X, int a_Z, unsigned char a_Height) { ASSERT((a_X >= 0) && (a_X < Width)); ASSERT((a_Z >= 0) && (a_Z < Width)); a_HeightMap[a_X + Width * a_Z] = a_Height; } - - + + inline static EMCSBiome GetBiome(const BiomeMap & a_BiomeMap, int a_X, int a_Z) { ASSERT((a_X >= 0) && (a_X < Width)); ASSERT((a_Z >= 0) && (a_Z < Width)); return a_BiomeMap[a_X + Width * a_Z]; } - - + + inline static void SetBiome(BiomeMap & a_BiomeMap, int a_X, int a_Z, EMCSBiome a_Biome) { ASSERT((a_X >= 0) && (a_X < Width)); @@ -226,11 +226,11 @@ public: { if ((a_BlockIdx > -1) && (a_BlockIdx < NumBlocks)) { - if ((size_t)(a_BlockIdx / 2) >= a_Buffer.size()) + if (static_cast((a_BlockIdx / 2)) >= a_Buffer.size()) { return (a_IsSkyLightNibble ? 0xff : 0); } - return (a_Buffer[(size_t)(a_BlockIdx / 2)] >> ((a_BlockIdx & 1) * 4)) & 0x0f; + return (a_Buffer[static_cast(a_BlockIdx / 2)] >> ((a_BlockIdx & 1) * 4)) & 0x0f; } ASSERT(!"cChunkDef::GetNibble(): index out of chunk range!"); return 0; @@ -241,7 +241,7 @@ public: { if ((x < Width) && (x > -1) && (y < Height) && (y > -1) && (z < Width) && (z > -1)) { - size_t Index = (size_t)MakeIndexNoCheck(x, y, z); + size_t Index = static_cast(MakeIndexNoCheck(x, y, z)); if ((Index / 2) >= a_Buffer.size()) { return (a_IsSkyLightNibble ? 0xff : 0); @@ -258,7 +258,7 @@ public: if ((x < Width) && (x > -1) && (y < Height) && (y > -1) && (z < Width) && (z > -1)) { int Index = MakeIndexNoCheck(x, y, z); - return (a_Buffer[(size_t)(Index / 2)] >> ((Index & 1) * 4)) & 0x0f; + return (a_Buffer[static_cast(Index / 2)] >> ((Index & 1) * 4)) & 0x0f; } ASSERT(!"cChunkDef::GetNibble(): coords out of chunk range!"); return 0; @@ -272,11 +272,11 @@ public: ASSERT(!"cChunkDef::SetNibble(): index out of range!"); return; } - if ((size_t)(a_BlockIdx / 2) >= a_Buffer.size()) + if (static_cast(a_BlockIdx / 2) >= a_Buffer.size()) { - a_Buffer.resize((size_t)((a_BlockIdx / 2) + 1)); + a_Buffer.resize(static_cast((a_BlockIdx / 2) + 1)); } - a_Buffer[(size_t)(a_BlockIdx / 2)] = PackNibble(a_Buffer, (size_t)a_BlockIdx, a_Nibble); + a_Buffer[static_cast(a_BlockIdx / 2)] = PackNibble(a_Buffer, static_cast(a_BlockIdx), a_Nibble); } @@ -292,7 +292,7 @@ public: return; } - size_t Index = (size_t)MakeIndexNoCheck(x, y, z); + size_t Index = static_cast(MakeIndexNoCheck(x, y, z)); if ((Index / 2) >= a_Buffer.size()) { a_Buffer.resize(((Index / 2) + 1)); @@ -336,7 +336,7 @@ public: /// Called for clients that are in Chunk1 and not in Chunk2, virtual void Removed(cClientHandle * a_Client) = 0; - + /// Called for clients that are in Chunk2 and not in Chunk1. virtual void Added(cClientHandle * a_Client) = 0; } ; @@ -373,9 +373,9 @@ class cChunkCoords public: int m_ChunkX; int m_ChunkZ; - + cChunkCoords(int a_ChunkX, int a_ChunkZ) : m_ChunkX(a_ChunkX), m_ChunkZ(a_ChunkZ) {} - + bool operator == (const cChunkCoords & a_Other) const { return ((m_ChunkX == a_Other.m_ChunkX) && (m_ChunkZ == a_Other.m_ChunkZ)); @@ -432,12 +432,12 @@ public: int y; int z; X Data; - + cCoordWithData(int a_X, int a_Y, int a_Z) : x(a_X), y(a_Y), z(a_Z), Data() { } - + cCoordWithData(int a_X, int a_Y, int a_Z, const X & a_Data) : x(a_X), y(a_Y), z(a_Z), Data(a_Data) { @@ -478,7 +478,3 @@ public: typedef cCoordWithDoubleData cCoordWithBlockAndBool; typedef std::vector cCoordWithBlockAndBoolVector; - - - - diff --git a/src/Defines.h b/src/Defines.h index 6355b75b4..f1ff911e7 100644 --- a/src/Defines.h +++ b/src/Defines.h @@ -39,7 +39,7 @@ enum eBlockFace BLOCK_FACE_YP = 1, // Interacting with the Y+ face of the block BLOCK_FACE_ZM = 2, // Interacting with the Z- face of the block BLOCK_FACE_ZP = 3, // Interacting with the Z+ face of the block - + // Synonyms using the (deprecated) world directions: BLOCK_FACE_BOTTOM = BLOCK_FACE_YM, // Interacting with the bottom face of the block BLOCK_FACE_TOP = BLOCK_FACE_YP, // Interacting with the top face of the block @@ -101,7 +101,7 @@ enum eClickAction caDblClick, // Add new actions here caUnknown = 255, - + // Keep this list in sync with ClickActionToString() function below! } ; @@ -116,14 +116,14 @@ enum eGameMode eGameMode_Creative = 1, eGameMode_Adventure = 2, eGameMode_Spectator = 3, - + // Easier-to-use synonyms: gmNotSet = eGameMode_NotSet, gmSurvival = eGameMode_Survival, gmCreative = eGameMode_Creative, gmAdventure = eGameMode_Adventure, gmSpectator = eGameMode_Spectator, - + // These two are used to check GameMode for validity when converting from integers. gmMax, // Gets automatically assigned gmMin = 0, @@ -138,7 +138,7 @@ enum eWeather eWeather_Sunny = 0, eWeather_Rain = 1, eWeather_ThunderStorm = 2, - + // Easier-to-use synonyms: wSunny = eWeather_Sunny, wRain = eWeather_Rain, @@ -218,7 +218,7 @@ inline const char * ClickActionToString(eClickAction a_ClickAction) case caLeftPaintEnd: return "caLeftPaintEnd"; case caRightPaintEnd: return "caRightPaintEnd"; case caDblClick: return "caDblClick"; - + case caUnknown: return "caUnknown"; } ASSERT(!"Unknown click action"); @@ -472,7 +472,7 @@ inline void AddFaceDirection(int & a_BlockX, unsigned char & a_BlockY, int & a_B { int Y = a_BlockY; AddFaceDirection(a_BlockX, Y, a_BlockZ, a_BlockFace, a_bInverse); - a_BlockY = Clamp((unsigned char)Y, 0, 255); + a_BlockY = Clamp(static_cast(Y), 0, 255); } @@ -556,7 +556,7 @@ enum eMessageType mtPrivateMessage, // Player to player messaging identifier mtJoin, // A player has joined the server mtLeave, // A player has left the server - + // Common aliases: mtFail = mtFailure, mtError = mtFailure, @@ -626,9 +626,9 @@ namespace ItemCategory || (a_ItemID == E_ITEM_GOLD_HOE) || (a_ItemID == E_ITEM_DIAMOND_HOE); } - - - + + + inline bool IsShovel(short a_ItemID) { return (a_ItemID == E_ITEM_WOODEN_SHOVEL) @@ -648,9 +648,9 @@ namespace ItemCategory || IsHoe ( a_ItemID) || IsShovel ( a_ItemID); } - - - + + + inline bool IsHelmet(short a_ItemType) { return ( @@ -700,9 +700,9 @@ namespace ItemCategory (a_ItemType == E_ITEM_DIAMOND_BOOTS) ); } - - - + + + inline bool IsArmor(short a_ItemType) { return ( @@ -715,7 +715,3 @@ namespace ItemCategory } // tolua_end - - - - diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h index f0577aba2..858f760ce 100644 --- a/src/Entities/Entity.h +++ b/src/Entities/Entity.h @@ -84,13 +84,13 @@ public: etFloater, etItemFrame, etPainting, - + // Common variations etMob = etMonster, // DEPRECATED, use etMonster instead! } ; - + // tolua_end - + enum eEntityStatus { // TODO: Investiagate 0, 1, and 5 as Wiki.vg is not certain @@ -127,22 +127,22 @@ public: // Informs client to explode a firework based on its metadata esFireworkExploding = 17, } ; - + static const int FIRE_TICKS_PER_DAMAGE = 10; ///< Ticks to wait between damaging an entity when it stands in fire static const int FIRE_DAMAGE = 1; ///< Damage to deal when standing in fire static const int LAVA_TICKS_PER_DAMAGE = 10; ///< Ticks to wait between damaging an entity when it stands in lava static const int LAVA_DAMAGE = 5; ///< Damage to deal when standing in lava static const int BURN_TICKS_PER_DAMAGE = 20; ///< Ticks to wait between damaging an entity when it is burning static const int BURN_DAMAGE = 1; ///< Damage to deal when the entity is burning - + static const int BURN_TICKS = 200; ///< Ticks to keep an entity burning after it has stood in lava / fire - + static const int MAX_AIR_LEVEL = 300; ///< Maximum air an entity can have static const int DROWNING_TICKS = 20; ///< Number of ticks per heart of damage - + static const int VOID_BOUNDARY = -46; ///< Y position to begin applying void damage static const int FALL_DAMAGE_HEIGHT = 4; ///< Y difference after which fall damage is applied - + cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, double a_Width, double a_Height); virtual ~cEntity(); @@ -151,9 +151,9 @@ public: virtual bool Initialize(cWorld & a_World); // tolua_begin - + eEntityType GetEntityType(void) const { return m_EntityType; } - + bool IsEnderCrystal(void) const { return (m_EntityType == etEnderCrystal); } bool IsPlayer (void) const { return (m_EntityType == etPlayer); } bool IsPickup (void) const { return (m_EntityType == etPickup); } @@ -168,16 +168,16 @@ public: bool IsFloater (void) const { return (m_EntityType == etFloater); } bool IsItemFrame (void) const { return (m_EntityType == etItemFrame); } bool IsPainting (void) const { return (m_EntityType == etPainting); } - + /// Returns true if the entity is of the specified class or a subclass (cPawn's IsA("cEntity") returns true) virtual bool IsA(const char * a_ClassName) const; - + /// Returns the topmost class name for the object virtual const char * GetClass(void) const; - + // Returns the class name of this class static const char * GetClassStatic(void); - + /// Returns the topmost class's parent class name for the object. cEntity returns an empty string (no parent). virtual const char * GetParentClass(void) const; @@ -200,9 +200,9 @@ public: double GetSpeedY (void) const { return m_Speed.y; } double GetSpeedZ (void) const { return m_Speed.z; } double GetWidth (void) const { return m_Width; } - - int GetChunkX(void) const {return (int)floor(m_Pos.x / cChunkDef::Width); } - int GetChunkZ(void) const {return (int)floor(m_Pos.z / cChunkDef::Width); } + + int GetChunkX(void) const {return static_cast(floor(m_Pos.x / cChunkDef::Width)); } + int GetChunkZ(void) const {return static_cast(floor(m_Pos.z / cChunkDef::Width)); } void SetHeadYaw (double a_HeadYaw); void SetHeight (double a_Height); @@ -219,21 +219,21 @@ public: /** Sets the speed of the entity, measured in m / sec */ void SetSpeed(double a_SpeedX, double a_SpeedY, double a_SpeedZ); - + /** Sets the speed of the entity, measured in m / sec */ void SetSpeed(const Vector3d & a_Speed) { SetSpeed(a_Speed.x, a_Speed.y, a_Speed.z); } - + /** Sets the speed in the X axis, leaving the other speed components intact. Measured in m / sec. */ void SetSpeedX(double a_SpeedX); - + /** Sets the speed in the Y axis, leaving the other speed components intact. Measured in m / sec. */ void SetSpeedY(double a_SpeedY); - + /** Sets the speed in the Z axis, leaving the other speed components intact. Measured in m / sec. */ void SetSpeedZ(double a_SpeedZ); - + void SetWidth (double a_Width); - + void AddPosX (double a_AddPosX); void AddPosY (double a_AddPosY); void AddPosZ (double a_AddPosZ); @@ -244,7 +244,7 @@ public: void AddSpeedX (double a_AddSpeedX); void AddSpeedY (double a_AddSpeedY); void AddSpeedZ (double a_AddSpeedZ); - + virtual void HandleSpeedFromAttachee(float a_Forward, float a_Sideways); void SteerVehicle(float a_Forward, float a_Sideways); @@ -256,56 +256,56 @@ public: /// Makes this pawn take damage from an attack by a_Attacker. Damage values are calculated automatically and DoTakeDamage() called void TakeDamage(cEntity & a_Attacker); - + /// Makes this entity take the specified damage. The final damage is calculated using current armor, then DoTakeDamage() called void TakeDamage(eDamageType a_DamageType, cEntity * a_Attacker, int a_RawDamage, double a_KnockbackAmount); /// Makes this entity take the specified damage. The values are packed into a TDI, knockback calculated, then sent through DoTakeDamage() void TakeDamage(eDamageType a_DamageType, cEntity * a_Attacker, int a_RawDamage, int a_FinalDamage, double a_KnockbackAmount); - + float GetGravity(void) const { return m_Gravity; } - + void SetGravity(float a_Gravity) { m_Gravity = a_Gravity; } - + /// Sets the rotation to match the speed vector (entity goes "face-forward") void SetYawFromSpeed(void); - + /// Sets the pitch to match the speed vector (entity gies "face-forward") void SetPitchFromSpeed(void); - + // 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 receive any damage. */ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI); - + // tolua_begin /// Returns the hitpoints that this pawn can deal to a_Receiver using its equipped items virtual int GetRawDamageAgainst(const cEntity & a_Receiver); - + /** Returns whether armor will protect against the passed damage type **/ virtual bool ArmorCoversAgainst(eDamageType a_DamageType); - + /// Returns the hitpoints out of a_RawDamage that the currently equipped armor would cover virtual int GetArmorCoverAgainst(const cEntity * a_Attacker, eDamageType a_DamageType, int a_RawDamage); - + /// Returns the knockback amount that the currently equipped items would cause to a_Receiver on a hit virtual double GetKnockbackAmountAgainst(const cEntity & a_Receiver); - + /// Returns the curently equipped weapon; empty item if none virtual cItem GetEquippedWeapon(void) const { return cItem(); } - + /// Returns the currently equipped helmet; empty item if none virtual cItem GetEquippedHelmet(void) const { return cItem(); } - + /// Returns the currently equipped chestplate; empty item if none virtual cItem GetEquippedChestplate(void) const { return cItem(); } /// Returns the currently equipped leggings; empty item if none virtual cItem GetEquippedLeggings(void) const { return cItem(); } - + /// Returns the currently equipped boots; empty item if none virtual cItem GetEquippedBoots(void) const { return cItem(); } @@ -317,20 +317,20 @@ public: /// Heals the specified amount of HPs virtual void Heal(int a_HitPoints); - + /// Returns the health of this entity int GetHealth(void) const { return m_Health; } - + /// Sets the health of this entity; doesn't broadcast any hurt animation void SetHealth(int a_Health); - + // tolua_end virtual void Tick(float a_Dt, cChunk & a_Chunk); - + /// Handles the physics of the entity - updates position based on speed, updates speed based on environment virtual void HandlePhysics(float a_Dt, cChunk & a_Chunk); - + /// Updates the state related to this entity being on fire virtual void TickBurning(cChunk & a_Chunk); @@ -341,34 +341,34 @@ public: Returns true if MoveToWorld() was called, false if not */ virtual bool DetectPortal(void); - + /// Handles when the entity is in the void virtual void TickInVoid(cChunk & a_Chunk); /// Called when the entity starts burning virtual void OnStartedBurning(void); - + /// Called when the entity finishes burning virtual void OnFinishedBurning(void); - + // tolua_begin - + /// Sets the maximum value for the health void SetMaxHealth(int a_MaxHealth); int GetMaxHealth(void) const { return m_MaxHealth; } - + /// Sets whether the entity is fireproof void SetIsFireproof(bool a_IsFireproof); - + bool IsFireproof(void) const { return m_IsFireproof; } - + /// Puts the entity on fire for the specified amount of ticks void StartBurning(int a_TicksLeftBurning); - + /// Stops the entity from burning, resets all burning timers void StopBurning(void); - + // tolua_end /** Descendants override this function to send a command to the specified client to spawn the entity on the client. @@ -377,10 +377,10 @@ public: virtual void SpawnOn(cClientHandle & a_Client) = 0; // tolua_begin - + /// Teleports to the entity specified virtual void TeleportToEntity(cEntity & a_Entity); - + /// Teleports to the coordinates specified virtual void TeleportToCoords(double a_PosX, double a_PosY, double a_PosZ); @@ -389,7 +389,7 @@ public: /** Moves entity to specified world, taking a world name */ bool MoveToWorld(const AString & a_WorldName, bool a_ShouldSendRespawn = true); - + // tolua_end virtual bool DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn); @@ -399,16 +399,16 @@ public: /** Sets the world the entity will be leaving */ void SetWorldTravellingFrom(cWorld * a_World) { m_WorldTravellingFrom = a_World; } - + /// Updates clients of changes in the entity. virtual void BroadcastMovementUpdate(const cClientHandle * a_Exclude = NULL); - + /// Attaches to the specified entity; detaches from any previous one first void AttachTo(cEntity * a_AttachTo); - + /// Detaches from the currently attached entity, if any virtual void Detach(void); - + /// Makes sure head yaw is not over the specified range. void WrapHeadYaw(); @@ -417,9 +417,9 @@ public: /// Makes speed is not over 20. Max speed is 20 blocks / second void WrapSpeed(); - + // tolua_begin - + // COMMON metadata flags; descendants may override the defaults: virtual bool IsOnFire (void) const {return (m_TicksLeftBurning > 0); } virtual bool IsCrouched (void) const {return false; } @@ -437,15 +437,15 @@ public: /** Gets number of ticks this entity has existed for */ long int GetTicksAlive(void) const { return m_TicksAlive; } - + /** 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 - + /// Called when the specified player right-clicks this entity virtual void OnRightClicked(cPlayer & a_Player) {} @@ -462,38 +462,38 @@ public: protected: static cCriticalSection m_CSCount; static int m_EntityCount; - + /** Measured in meter/second (m/s) */ Vector3d m_Speed; int m_UniqueID; - + int m_Health; int m_MaxHealth; - + /// The entity to which this entity is attached (vehicle), NULL if none cEntity * m_AttachedTo; - + /// The entity which is attached to this entity (rider), NULL if none cEntity * m_Attachee; /** 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; @@ -508,31 +508,31 @@ protected: cWorld * m_WorldTravellingFrom; eEntityType m_EntityType; - + cWorld * m_World; - + /// Whether the entity is capable of taking fire or lava damage. bool m_IsFireproof; /// Time, in ticks, since the last damage dealt by being on fire. Valid only if on fire (IsOnFire()) int m_TicksSinceLastBurnDamage; - + /// Time, in ticks, since the last damage dealt by standing in lava. Reset to zero when moving out of lava. int m_TicksSinceLastLavaDamage; - + /// Time, in ticks, since the last damage dealt by standing in fire. Reset to zero when moving out of fire. int m_TicksSinceLastFireDamage; - + /// Time, in ticks, until the entity extinguishes its fire int m_TicksLeftBurning; - + /// Time, in ticks, since the last damage dealt by the void. Reset to zero when moving out of the void. int m_TicksSinceLastVoidDamage; - + /** Does the actual speed-setting. The default implementation just sets the member variable value; overrides can provide further processing, such as forcing players to move at the given speed. */ virtual void DoSetSpeed(double a_SpeedX, double a_SpeedY, double a_SpeedZ); - + virtual void Destroyed(void) {} // Called after the entity has been destroyed /** Applies friction to an entity @@ -543,7 +543,7 @@ protected: /** Called in each tick to handle air-related processing i.e. drowning */ virtual void HandleAir(void); - + /** Called once per tick to set IsSwimming and IsSubmerged */ virtual void SetSwimState(cChunk & a_Chunk); @@ -568,29 +568,29 @@ protected: /** Portal delay timer and cooldown boolean data */ sPortalCooldownData m_PortalCooldownData; - + /** The number of ticks this entity has been alive for */ long int m_TicksAlive; - + private: /** Measured in degrees, [-180, +180) */ double m_HeadYaw; - + /** Measured in degrees, [-180, +180) */ Vector3d m_Rot; - + /** Position of the entity's XZ center and Y bottom */ Vector3d m_Pos; - + /** Measured in meter / second */ Vector3d m_WaterSpeed; - + /** 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. */ double m_Width; - + /** Height of the entity (Y axis) */ double m_Height; @@ -600,7 +600,3 @@ private: } ; // tolua_export typedef std::list cEntityList; - - - - diff --git a/src/Entities/Pickup.h b/src/Entities/Pickup.h index 4d5250819..e3e0f61c7 100644 --- a/src/Entities/Pickup.h +++ b/src/Entities/Pickup.h @@ -19,7 +19,7 @@ class cPickup : public cEntity { typedef cEntity super; - + public: // tolua_end @@ -37,10 +37,10 @@ public: virtual void Tick(float a_Dt, cChunk & a_Chunk) override; /** Returns the number of ticks that this entity has existed */ - int GetAge(void) const { return (int)(m_Timer / 50); } // tolua_export + int GetAge(void) const { return static_cast(m_Timer / 50); } // tolua_export /** Set the number of ticks that this entity has existed */ - void SetAge(int a_Age) { m_Timer = (float)(a_Age * 50); } // tolua_export + void SetAge(int a_Age) { m_Timer = static_cast(a_Age * 50); } // tolua_export /** Returns true if the pickup has already been collected */ bool IsCollected(void) const { return m_bCollected; } // tolua_export @@ -59,7 +59,3 @@ private: bool m_bIsPlayerCreated; }; // tolua_export - - - - diff --git a/src/MersenneTwister.h b/src/MersenneTwister.h index 759b8a1ae..e83a470e2 100644 --- a/src/MersenneTwister.h +++ b/src/MersenneTwister.h @@ -19,11 +19,11 @@ // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, // Copyright (C) 2000 - 2009, Richard J. Wagner // All rights reserved. -// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: -// +// // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // @@ -31,10 +31,10 @@ // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // -// 3. The names of its contributors may not be used to endorse or promote -// products derived from this software without specific prior written +// 3. The names of its contributors may not be used to endorse or promote +// products derived from this software without specific prior written // permission. -// +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -63,13 +63,13 @@ class MTRand { // Data public: typedef UInt32 uint32; // unsigned integer type, at least 32 bits - + enum { N = 624 }; // length of state vector enum { SAVE = N + 1 }; // length of array for save() protected: enum { M = 397 }; // period parameter - + uint32 state[N]; // internal state uint32 *pNext; // next value to get from state uint32 left; // number of values left before reload needed @@ -80,11 +80,11 @@ public: MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or array MTRand(); // auto-initialize with /dev/urandom or time() and clock() MTRand( const MTRand& o ); // copy - + // Do NOT use for CRYPTOGRAPHY without securely hashing several returned // values together, otherwise the generator state can be learned after // reading 624 consecutive values. - + // Access to 32-bit random numbers uint32 randInt(); // integer in [0,2^32-1] uint32 randInt( const uint32 n ); // integer in [0,n] for n < 2^32 @@ -95,18 +95,18 @@ public: double randDblExc(); // real number in (0,1) double randDblExc( const double n ); // real number in (0,n) double operator()(); // same as rand() - + // Access to 53-bit random numbers (capacity of IEEE double precision) double rand53(); // real number in [0,1) - + // Access to nonuniform random number distributions double randNorm( const double mean = 0.0, const double stddev = 1.0 ); - + // Re-seeding functions with same behavior as initializers void seed( const uint32 oneSeed ); void seed( uint32 *const bigSeed, const uint32 seedLength = N ); void seed(); - + // Saving and loading generator state void save( uint32* saveArray ) const; // to array of size SAVE void load( uint32 *const loadArray ); // from such array @@ -136,9 +136,9 @@ inline MTRand::uint32 MTRand::hash( time_t t, clock_t c ) // Get a uint32 from t and c // Better than uint32(x) in case x is floating point in [0,1] // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) - + static uint32 differ = 0; // guarantee time-based seeds will change - + uint32 h1 = 0; unsigned char *p = (unsigned char *) &t; for( size_t i = 0; i < sizeof(t); ++i ) @@ -185,7 +185,7 @@ inline void MTRand::reload() for( i = M; --i; ++p ) *p = twist( p[MmN], p[0], p[1] ); *p = twist( p[MmN], p[0], state[0] ); - + left = N, pNext = state; } @@ -207,7 +207,7 @@ inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength ) initialize(19650218UL); uint32 i = 1; uint32 j = 0; - uint32 k = ( (uint32)N > seedLength ? (uint32)N : seedLength ); + uint32 k = ( static_cast(N) > seedLength ? static_cast(N) : seedLength ); for( ; k; --k ) { state[i] = @@ -235,7 +235,7 @@ inline void MTRand::seed() { // Seed the generator with an array from /dev/urandom if available // Otherwise use a hash of time() and clock() values - + // First try getting an array from /dev/urandom /* // Commented out by FakeTruth because doing this 200 times a tick is SUUUUPEERRR SLOW!!~~!\D5Ne @@ -252,7 +252,7 @@ inline void MTRand::seed() if( success ) { seed( bigSeed, N ); return; } } */ - + // Was not successful, so use time() and clock() instead seed( hash( time(NULL), clock() ) ); } @@ -280,10 +280,10 @@ inline MTRand::uint32 MTRand::randInt() { // Pull a 32-bit integer from the generator state // Every other access function simply transforms the numbers extracted here - + if( left == 0 ) reload(); --left; - + uint32 s1; s1 = *pNext++; s1 ^= (s1 >> 11); @@ -302,7 +302,7 @@ inline MTRand::uint32 MTRand::randInt( const uint32 n ) used |= used >> 4; used |= used >> 8; used |= used >> 16; - + // Draw numbers until one is found in [0,n] uint32 i; do diff --git a/src/Mobs/Monster.h b/src/Mobs/Monster.h index 9fd67d67c..f5ae2cb4d 100644 --- a/src/Mobs/Monster.h +++ b/src/Mobs/Monster.h @@ -35,12 +35,12 @@ public: mfNoSpawn, mfUnhandled, // Nothing. Be sure this is the last and the others are in order } ; - + // tolua_end - + enum MState{ATTACKING, IDLE, CHASING, ESCAPING} m_EMState; enum MPersonality{PASSIVE, AGGRESSIVE, COWARDLY} m_EMPersonality; - + /** Creates the mob object. If a_ConfigName is not empty, the configuration is loaded using GetMonsterConfig() a_MobType is the type of the mob (also used in the protocol ( http://wiki.vg/Entities#Mobs 2012_12_22)) @@ -49,47 +49,47 @@ public: cMonster(const AString & a_ConfigName, eMonsterType a_MobType, const AString & a_SoundHurt, const AString & a_SoundDeath, double a_Width, double a_Height); CLASS_PROTODEF(cMonster) - + virtual void SpawnOn(cClientHandle & a_ClientHandle) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override; - + virtual void KilledBy(TakeDamageInfo & a_TDI) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual void MoveToPosition(const Vector3d & a_Position); // tolua_export virtual bool ReachedDestination(void); - + // tolua_begin eMonsterType GetMobType(void) const {return m_MobType; } eFamily GetMobFamily(void) const; // tolua_end - + virtual void CheckEventSeePlayer(void); virtual void EventSeePlayer(cEntity * a_Player); - + /// Reads the monster configuration for the specified monster name and assigns it to this object. void GetMonsterConfig(const AString & a_Name); - + /** Returns whether this mob is undead (skeleton, zombie, etc.) */ virtual bool IsUndead(void); - + virtual void EventLosePlayer(void); virtual void CheckEventLostPlayer(void); - + virtual void InStateIdle (float a_Dt); virtual void InStateChasing (float a_Dt); virtual void InStateEscaping(float a_Dt); - - int GetAttackRate() { return (int)m_AttackRate; } + + int GetAttackRate() { return static_cast(m_AttackRate); } void SetAttackRate(float a_AttackRate) { m_AttackRate = a_AttackRate; } void SetAttackRange(int a_AttackRange) { m_AttackRange = a_AttackRange; } void SetAttackDamage(int a_AttackDamage) { m_AttackDamage = a_AttackDamage; } void SetSightDistance(int a_SightDistance) { m_SightDistance = a_SightDistance; } - + float GetDropChanceWeapon() { return m_DropChanceWeapon; } float GetDropChanceHelmet() { return m_DropChanceHelmet; } float GetDropChanceChestplate() { return m_DropChanceChestplate; } @@ -102,7 +102,7 @@ public: void SetDropChanceLeggings(float a_DropChanceLeggings) { m_DropChanceLeggings = a_DropChanceLeggings; } void SetDropChanceBoots(float a_DropChanceBoots) { m_DropChanceBoots = a_DropChanceBoots; } void SetCanPickUpLoot(bool a_CanPickUpLoot) { m_CanPickUpLoot = a_CanPickUpLoot; } - + /// Sets whether the mob burns in daylight. Only evaluated at next burn-decision tick void SetBurnsInDaylight(bool a_BurnsInDaylight) { m_BurnsInDaylight = a_BurnsInDaylight; } @@ -113,7 +113,7 @@ public: virtual bool IsBaby (void) const { return false; } virtual bool IsTame (void) const { return false; } virtual bool IsSitting (void) const { return false; } - + // tolua_begin /** Returns true if the monster has a custom name. */ @@ -135,10 +135,10 @@ public: /// Translates MobType enum to a string, empty string if unknown static AString MobTypeToString(eMonsterType a_MobType); - + /// Translates MobType string to the enum, mtInvalidType if not recognized static eMonsterType StringToMobType(const AString & a_MobTypeName); - + /// Returns the mob family based on the type static eFamily FamilyFromType(eMonsterType a_MobType); @@ -146,7 +146,7 @@ public: static int GetSpawnDelay(cMonster::eFamily a_MobFamily); // tolua_end - + /** Creates a new object of the specified mob. a_MobType is the type of the mob to be created Asserts and returns null if mob type is not specified @@ -154,7 +154,7 @@ public: static cMonster * NewMonsterFromType(eMonsterType a_MobType); protected: - + /* ======= PATHFINDING ======= */ /** A pointer to the entity this mobile is aiming to reach */ @@ -168,7 +168,7 @@ protected: /** Stores if mobile is currently moving towards the ultimate, final destination */ bool m_bMovingToDestination; - + /** Finds the first non-air block position (not the highest, as cWorld::GetHeight does) If current Y is nonsolid, goes down to try to find a solid block, then returns that + 1 If current Y is solid, goes up to find first nonsolid block, and returns that */ @@ -227,14 +227,14 @@ protected: int m_AttackRange; float m_AttackInterval; int m_SightDistance; - + float m_DropChanceWeapon; float m_DropChanceHelmet; float m_DropChanceChestplate; float m_DropChanceLeggings; float m_DropChanceBoots; bool m_CanPickUpLoot; - + void HandleDaylightBurning(cChunk & a_Chunk); bool m_BurnsInDaylight; @@ -242,22 +242,18 @@ protected: /** Adds a random number of a_Item between a_Min and a_Max to itemdrops a_Drops*/ void AddRandomDropItem(cItems & a_Drops, unsigned int a_Min, unsigned int a_Max, short a_Item, short a_ItemHealth = 0); - + /** Adds a item a_Item with the chance of a_Chance (in percent) to itemdrops a_Drops*/ void AddRandomUncommonDropItem(cItems & a_Drops, float a_Chance, short a_Item, short a_ItemHealth = 0); - + /** Adds one rare item out of the list of rare items a_Items modified by the looting level a_LootingLevel(I-III or custom) to the itemdrop a_Drops*/ void AddRandomRareDropItem(cItems & a_Drops, cItems & a_Items, short a_LootingLevel); - + /** Adds armor that is equipped with the chance saved in m_DropChance[...] (this will be greter than 1 if piccked up or 0.085 + (0.01 per LootingLevel) if born with) to the drop*/ void AddRandomArmorDropItem(cItems & a_Drops, short a_LootingLevel); - + /** Adds weapon that is equipped with the chance saved in m_DropChance[...] (this will be greter than 1 if piccked up or 0.085 + (0.01 per LootingLevel) if born with) to the drop*/ void AddRandomWeaponDropItem(cItems & a_Drops, short a_LootingLevel); - - -} ; // tolua_export - - +} ; // tolua_export diff --git a/src/OSSupport/IsThread.h b/src/OSSupport/IsThread.h index 5de5f31c4..5c8d28d2d 100644 --- a/src/OSSupport/IsThread.h +++ b/src/OSSupport/IsThread.h @@ -31,20 +31,20 @@ protected: /// The overriden Execute() method should check this value periodically and terminate if this is true volatile bool m_ShouldTerminate; - + public: cIsThread(const AString & iThreadName); virtual ~cIsThread(); - + /// Starts the thread; returns without waiting for the actual start bool Start(void); - + /// Signals the thread to terminate and waits until it's finished void Stop(void); - + /// Waits for the thread to finish. Doesn't signalize the ShouldTerminate flag bool Wait(void); - + /// Returns the OS-dependent thread ID for the caller's thread static unsigned long GetCurrentID(void); @@ -53,7 +53,7 @@ public: protected: AString m_ThreadName; - + // Value used for "no handle": #ifdef _WIN32 #define NULL_HANDLE NULL @@ -62,34 +62,34 @@ protected: #endif #ifdef _WIN32 - + DWORD m_ThreadID; HANDLE m_Handle; - + static DWORD __stdcall thrExecute(LPVOID a_Param) { // Create a window so that the thread can be identified by 3rd party tools: HWND IdentificationWnd = CreateWindowA("STATIC", ((cIsThread *)a_Param)->m_ThreadName.c_str(), 0, 0, 0, 0, WS_OVERLAPPED, NULL, NULL, NULL, NULL); - + // Run the thread: ((cIsThread *)a_Param)->Execute(); - + // Destroy the identification window: DestroyWindow(IdentificationWnd); - + return 0; } - + #else // _WIN32 - + pthread_t m_Handle; - + static void * thrExecute(void * a_Param) { - ((cIsThread *)a_Param)->Execute(); + (static_cast(a_Param))->Execute(); return NULL; } - + #endif // else _WIN32 } ; @@ -98,7 +98,3 @@ protected: #endif // CISTHREAD_H_INCLUDED - - - - diff --git a/src/World.h b/src/World.h index 90dada259..02d0a92b8 100644 --- a/src/World.h +++ b/src/World.h @@ -84,7 +84,7 @@ class cWorld : public: // tolua_end - + /** A simple RAII locker for the chunkmap - locks the chunkmap in its constructor, unlocks it in the destructor */ class cLock : public cCSLock @@ -94,7 +94,7 @@ public: cLock(cWorld & a_World); } ; - + /** A common ancestor for all tasks queued onto the tick thread */ class cTask { @@ -102,10 +102,10 @@ public: virtual ~cTask() {} virtual void Run(cWorld & a_World) = 0; } ; - + typedef std::vector cTasks; - + class cTaskSaveAllChunks : public cTask { @@ -113,7 +113,7 @@ public: // cTask overrides: virtual void Run(cWorld & a_World) override; } ; - + class cTaskUnloadUnusedChunks : public cTask @@ -142,7 +142,7 @@ public: { return "cWorld"; } - + // tolua_begin int GetTicksUntilWeatherChange(void) const { return m_WeatherInterval; } @@ -159,7 +159,7 @@ public: virtual Int64 GetWorldAge (void) const override { return m_WorldAge; } virtual int GetTimeOfDay(void) const override { return m_TimeOfDay; } - + void SetTicksUntilWeatherChange(int a_WeatherInterval) { m_WeatherInterval = a_WeatherInterval; @@ -168,42 +168,42 @@ public: virtual void SetTimeOfDay(int a_TimeOfDay) override { m_TimeOfDay = a_TimeOfDay; - m_TimeOfDaySecs = (double)a_TimeOfDay / 20.0; + m_TimeOfDaySecs = static_cast(a_TimeOfDay) / 20.0; UpdateSkyDarkness(); BroadcastTimeUpdate(); } - + /** Returns the default weather interval for the specific weather type. Returns -1 for any unknown weather. */ int GetDefaultWeatherInterval(eWeather a_Weather); - + /** Returns the current game mode. Partly OBSOLETE, you should use IsGameModeXXX() functions wherever applicable */ eGameMode GetGameMode(void) const { return m_GameMode; } /** Returns true if the world is in Creative mode */ bool IsGameModeCreative(void) const { return (m_GameMode == gmCreative); } - + /** Returns true if the world is in Survival mode */ bool IsGameModeSurvival(void) const { return (m_GameMode == gmSurvival); } - + /** Returns true if the world is in Adventure mode */ bool IsGameModeAdventure(void) const { return (m_GameMode == gmAdventure); } - + /** Returns true if the world is in Spectator mode */ bool IsGameModeSpectator(void) const { return (m_GameMode == gmSpectator); } - + bool IsPVPEnabled(void) const { return m_bEnabledPVP; } bool IsDeepSnowEnabled(void) const { return m_IsDeepSnowEnabled; } - + bool ShouldLavaSpawnFire(void) const { return m_ShouldLavaSpawnFire; } - + bool VillagersShouldHarvestCrops(void) const { return m_VillagersShouldHarvestCrops; } virtual eDimension GetDimension(void) const { return m_Dimension; } /** Returns the world height at the specified coords; waits for the chunk to get loaded / generated */ virtual int GetHeight(int a_BlockX, int a_BlockZ); - + // tolua_end /** Retrieves the world height at the specified coords; returns false if chunk not loaded / generated */ @@ -258,35 +258,35 @@ public: void BroadcastTimeUpdate (const cClientHandle * a_Exclude = NULL); virtual void BroadcastUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) override; void BroadcastWeather (eWeather a_Weather, const cClientHandle * a_Exclude = NULL); - + virtual cBroadcastInterface & GetBroadcastManager(void) override { return *this; } - + /** If there is a block entity at the specified coords, sends it to the client specified */ void SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client); - + void MarkRedstoneDirty(int a_ChunkX, int a_ChunkZ); void MarkChunkDirty (int a_ChunkX, int a_ChunkZ, bool a_MarkRedstoneDirty = false); void MarkChunkSaving(int a_ChunkX, int a_ChunkZ); void MarkChunkSaved (int a_ChunkX, int a_ChunkZ); - + /** Puts the chunk data into a queue to be set into the chunkmap in the tick thread. If the chunk data doesn't contain valid biomes, the biomes are calculated before adding the data into the queue. */ void QueueSetChunkData(const cSetChunkDataPtr & a_SetChunkData); - + void ChunkLighted( int a_ChunkX, int a_ChunkZ, const cChunkDef::BlockNibbles & a_BlockLight, const cChunkDef::BlockNibbles & a_SkyLight ); - + bool GetChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataCallback & a_Callback); - + /** Gets the chunk's blocks, only the block types */ bool GetChunkBlockTypes(int a_ChunkX, int a_ChunkZ, BLOCKTYPE * a_BlockTypes); - + /** Returns true iff the chunk is in the loader / generator queue. */ bool IsChunkQueued(int a_ChunkX, int a_ChunkZ) const; @@ -294,10 +294,10 @@ public: bool IsChunkValid(int a_ChunkX, int a_ChunkZ) const; bool HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) const; - + /** Queues a task to unload unused chunks onto the tick thread. The prefferred way of unloading*/ void QueueUnloadUnusedChunks(void); // tolua_export - + void CollectPickupsByPlayer(cPlayer * a_Player); /** Adds the player to the world. @@ -319,21 +319,21 @@ public: /** Finds a player from a partial or complete player name and calls the callback - case-insensitive */ bool FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << - + // TODO: This interface is dangerous - rewrite to DoWithClosestPlayer(pos, sight, action) cPlayer * FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, bool a_CheckLineOfSight = true); - + void SendPlayerList(cPlayer * a_DestPlayer); // Sends playerlist to the player /** Adds the entity into its appropriate chunk; takes ownership of the entity ptr. The entity is added lazily - this function only puts it in a queue that is then processed by the Tick thread. */ void AddEntity(cEntity * a_Entity); - + bool HasEntity(int a_UniqueID); - + /** Calls the callback for each entity in the entire world; returns true if all entities processed, false if the callback aborted by returning true */ bool ForEachEntity(cEntityCallback & a_Callback); // Exported in ManualBindings.cpp - + /** Calls the callback for each entity in the specified chunk; returns true if all entities processed, false if the callback aborted by returning true */ bool ForEachEntityInChunk(int a_ChunkX, int a_ChunkZ, cEntityCallback & a_Callback); // Exported in ManualBindings.cpp @@ -347,36 +347,36 @@ public: /** Compares clients of two chunks, calls the callback accordingly */ void CompareChunkClients(int a_ChunkX1, int a_ChunkZ1, int a_ChunkX2, int a_ChunkZ2, cClientDiffCallback & a_Callback); - + /** Adds client to a chunk, if not already present; returns true if added, false if present */ bool AddChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Removes client from the chunk specified */ void RemoveChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Removes the client from all chunks it is present in */ void RemoveClientFromChunks(cClientHandle * a_Client); - + /** Sends the chunk to the client specified, if the client doesn't have the chunk yet. If chunk not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ void SendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Sends the chunk to the client specified, even if the client already has the chunk. If the chunk's not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ void ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Removes client from ChunkSender's queue of chunks to be sent */ void RemoveClientFromChunkSender(cClientHandle * a_Client); - + /** Touches the chunk, causing it to be loaded or generated */ void TouchChunk(int a_ChunkX, int a_ChunkZ); - + /** Marks the chunk as failed-to-load: */ void ChunkLoadFailed(int a_ChunkX, int a_ChunkZ); - + /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be NULL. Returns true if sign text changed. Same as UpdateSign() */ bool SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = NULL); // Exported in ManualBindings.cpp - + /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be NULL. Returns true if sign text changed. Same as SetSignLines() */ bool UpdateSign(int a_X, int a_Y, int a_Z, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = NULL); // Exported in ManualBindings.cpp @@ -391,25 +391,25 @@ public: /** Regenerate the given chunk: */ void RegenerateChunk(int a_ChunkX, int a_ChunkZ); // tolua_export - + /** Generates the given chunk */ void GenerateChunk(int a_ChunkX, int a_ChunkZ); // tolua_export - + /** Queues a chunk for lighting; a_Callback is called after the chunk is lighted */ void QueueLightChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback = NULL); - + bool IsChunkLighted(int a_ChunkX, int a_ChunkZ); - + /** Calls the callback for each chunk in the coords specified (all cords are inclusive). Returns true if all chunks have been processed successfully */ virtual bool ForEachChunkInRect(int a_MinChunkX, int a_MaxChunkX, int a_MinChunkZ, int a_MaxChunkZ, cChunkDataCallback & a_Callback) override; // tolua_begin - + /** Sets the block at the specified coords to the specified value. Full processing, incl. updating neighbors, is performed. */ void SetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, bool a_SendToClients = true); - + /** Sets the block at the specified coords to the specified value. The replacement doesn't trigger block updates. The replaced blocks aren't checked for block entities (block entity is leaked if it exists at this block) @@ -418,7 +418,7 @@ public: { m_ChunkMap->FastSetBlock(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); } - + /** Queues a SetBlock() with the specified parameters after the specified number of ticks. Calls SetBlock(), so performs full processing of the replaced block. */ @@ -426,12 +426,12 @@ public: { m_ChunkMap->QueueSetBlock(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, GetWorldAge() + a_TickDelay, a_PreviousBlockType); } - + BLOCKTYPE GetBlock (int a_BlockX, int a_BlockY, int a_BlockZ) { return m_ChunkMap->GetBlock(a_BlockX, a_BlockY, a_BlockZ); } - + NIBBLETYPE GetBlockMeta (int a_BlockX, int a_BlockY, int a_BlockZ) { return m_ChunkMap->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); @@ -439,37 +439,37 @@ public: void SetBlockMeta (int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_MetaData); NIBBLETYPE GetBlockSkyLight (int a_BlockX, int a_BlockY, int a_BlockZ); NIBBLETYPE GetBlockBlockLight(int a_BlockX, int a_BlockY, int a_BlockZ); - + // tolua_end - + bool GetBlockTypeMeta (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta); // TODO: Exported in ManualBindings.cpp bool GetBlockInfo (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight); // TODO: Exported in ManualBindings.cpp // TODO: NIBBLETYPE GetBlockActualLight(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_begin - + // Vector3i variants: void FastSetBlock(const Vector3i & a_Pos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { FastSetBlock( a_Pos.x, a_Pos.y, a_Pos.z, a_BlockType, a_BlockMeta); } BLOCKTYPE GetBlock (const Vector3i & a_Pos) { return GetBlock( a_Pos.x, a_Pos.y, a_Pos.z); } NIBBLETYPE GetBlockMeta(const Vector3i & a_Pos) { return GetBlockMeta( a_Pos.x, a_Pos.y, a_Pos.z); } void SetBlockMeta(const Vector3i & a_Pos, NIBBLETYPE a_MetaData) { SetBlockMeta( a_Pos.x, a_Pos.y, a_Pos.z, a_MetaData); } // tolua_end - + /** Writes the block area into the specified coords. Returns true if all chunks have been processed. Prefer cBlockArea::Write() instead, this is the internal implementation; cBlockArea does error checking, too. a_DataTypes is a bitmask of cBlockArea::baXXX constants ORed together. */ virtual bool WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes) override; - + // tolua_begin /** Spawns item pickups for each item in the list. May compress pickups if too many entities: */ virtual void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_FlyAwaySpeed = 1.0, bool IsPlayerCreated = false) override; - + /** Spawns item pickups for each item in the list. May compress pickups if too many entities. All pickups get the speed specified: */ virtual void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_SpeedX, double a_SpeedY, double a_SpeedZ, bool IsPlayerCreated = false) override; - + /** Spawns an falling block entity at the given position. It returns the UniqueID of the spawned falling block. */ int SpawnFallingBlock(int a_X, int a_Y, int a_Z, BLOCKTYPE BlockType, NIBBLETYPE BlockMeta); @@ -486,10 +486,10 @@ public: /** Replaces world blocks with a_Blocks, if they are of type a_FilterBlockType */ void ReplaceBlocks(const sSetBlockVector & a_Blocks, BLOCKTYPE a_FilterBlockType); - + /** Retrieves block types of the specified blocks. If a chunk is not loaded, doesn't modify the block. Returns true if all blocks were read. */ bool GetBlocks(sSetBlockVector & a_Blocks, bool a_ContinueOnFailure); - + // tolua_begin bool DigBlock (int a_X, int a_Y, int a_Z); virtual void SendBlockTo(int a_X, int a_Y, int a_Z, cPlayer * a_Player) override; @@ -500,21 +500,21 @@ public: /** Wakes up the simulators for the specified block */ virtual void WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ) override; - + /** Wakes up the simulators for the specified area of blocks */ void WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_MinBlockY, int a_MaxBlockY, int a_MinBlockZ, int a_MaxBlockZ); // tolua_end inline cSimulatorManager * GetSimulatorManager(void) { return m_SimulatorManager; } - + inline cFluidSimulator * GetWaterSimulator(void) { return m_WaterSimulator; } inline cFluidSimulator * GetLavaSimulator (void) { return m_LavaSimulator; } inline cRedstoneSimulator * GetRedstoneSimulator(void) { return m_RedstoneSimulator; } - + /** Calls the callback for each block entity in the specified chunk; returns true if all block entities processed, false if the callback aborted by returning true */ bool ForEachBlockEntityInChunk(int a_ChunkX, int a_ChunkZ, cBlockEntityCallback & a_Callback); // Exported in ManualBindings.cpp - + /** Calls the callback for each chest in the specified chunk; returns true if all chests processed, false if the callback aborted by returning true */ bool ForEachChestInChunk(int a_ChunkX, int a_ChunkZ, cChestCallback & a_Callback); // Exported in ManualBindings.cpp @@ -529,7 +529,7 @@ public: /** Calls the callback for each furnace in the specified chunk; returns true if all furnaces processed, false if the callback aborted by returning true */ bool ForEachFurnaceInChunk(int a_ChunkX, int a_ChunkZ, cFurnaceCallback & a_Callback); // Exported in ManualBindings.cpp - + /** Does an explosion with the specified strength at the specified coordinate a_SourceData exact type depends on the a_Source: | esOther | void * | @@ -580,29 +580,29 @@ public: /** Retrieves the test on the sign at the specified coords; returns false if there's no sign at those coords, true if found */ bool GetSignLines (int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4); // Exported in ManualBindings.cpp - + /** a_Player is using block entity at [x, y, z], handle that: */ void UseBlockEntity(cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ) {m_ChunkMap->UseBlockEntity(a_Player, a_BlockX, a_BlockY, a_BlockZ); } // tolua_export - + /** Calls the callback for the chunk specified, with ChunkMapCS locked; returns false if the chunk doesn't exist, otherwise returns the same value as the callback */ bool DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback & a_Callback); void GrowTreeImage(const sSetBlockVector & a_Blocks); - + // tolua_begin /** Grows a tree at the specified coords, either from a sapling there, or based on the biome */ void GrowTree (int a_BlockX, int a_BlockY, int a_BlockZ); - + /** Grows a tree at the specified coords, based on the sapling meta provided */ void GrowTreeFromSapling(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_SaplingMeta); - + /** Grows a tree at the specified coords, based on the biome in the place */ void GrowTreeByBiome (int a_BlockX, int a_BlockY, int a_BlockZ); - + /** Grows the plant at the specified block to its ripe stage (bonemeal used); returns false if the block is not growable. If a_IsBonemeal is true, block is not grown if not allowed in world.ini */ bool GrowRipePlant(int a_BlockX, int a_BlockY, int a_BlockZ, bool a_IsByBonemeal = false); - + /** Grows a cactus present at the block specified by the amount of blocks specified, up to the max height specified in the config */ void GrowCactus(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBlocksToGrow); @@ -611,18 +611,18 @@ public: /** Grows a sugarcane present at the block specified by the amount of blocks specified, up to the max height specified in the config */ void GrowSugarcane(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBlocksToGrow); - + /** Returns the biome at the specified coords. Reads the biome from the chunk, if loaded, otherwise uses the world generator to provide the biome value */ EMCSBiome GetBiomeAt(int a_BlockX, int a_BlockZ); - + /** Sets the biome at the specified coords. Returns true if successful, false if not (chunk not loaded). Doesn't resend the chunk to clients, use ForceSendChunkTo() for that. */ bool SetBiomeAt(int a_BlockX, int a_BlockZ, EMCSBiome a_Biome); - + /** Sets the biome at the area. Returns true if successful, false if any subarea failed (chunk not loaded). (Re)sends the chunks to their relevant clients if successful. */ bool SetAreaBiome(int a_MinX, int a_MaxX, int a_MinZ, int a_MaxZ, EMCSBiome a_Biome); - + /** Sets the biome at the area. Returns true if successful, false if any subarea failed (chunk not loaded). (Re)sends the chunks to their relevant clients if successful. The cuboid needn't be sorted. */ @@ -630,7 +630,7 @@ public: /** Returns the name of the world */ const AString & GetName(void) const { return m_WorldName; } - + /** Returns the name of the world.ini file used by this world */ const AString & GetIniFileName(void) const {return m_IniFileName; } @@ -661,18 +661,18 @@ public: AString GetLinkedOverworldName(void) const { return m_OverworldName; } void SetLinkedOverworldName(const AString & a_Name) { m_OverworldName = a_Name; } - + // tolua_end - + /** Saves all chunks immediately. Dangerous interface, may deadlock, use QueueSaveAllChunks() instead */ void SaveAllChunks(void); - + /** Queues a task to save all chunks onto the tick thread. The prefferred way of saving chunks from external sources */ void QueueSaveAllChunks(void); // tolua_export - + /** Queues a task onto the tick thread. The task object will be deleted once the task is finished */ void QueueTask(cTask * a_Task); // Exported in ManualBindings.cpp - + /** Queues a task onto the tick thread, with the specified delay. The task object will be deleted once the task is finished */ void ScheduleTask(int a_DelayTicks, cTask * a_Task); @@ -690,13 +690,13 @@ public: inline size_t GetStorageSaveQueueLength(void) { return m_Storage.GetSaveQueueLength(); } // tolua_export void InitializeSpawn(void); - + /** Starts threads that belong to this world */ void Start(void); - + /** Stops threads that belong to this world (part of deinit) */ void Stop(void); - + /** Processes the blocks queued for ticking with a delay (m_BlockTickQueue[]) */ void TickQueuedBlocks(void); @@ -714,34 +714,34 @@ public: // tolua_begin /** Casts a thunderbolt at the specified coords */ void CastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ); - + /** Sets the specified weather; resets weather interval; asks and notifies plugins of the change */ void SetWeather(eWeather a_NewWeather); - + /** Forces a weather change in the next game tick */ void ChangeWeather(void); - + /** Returns the current weather. Instead of comparing values directly to the weather constants, use IsWeatherXXX() functions, if possible */ eWeather GetWeather(void) const { return m_Weather; } - + /** Returns true if the current weather is sun */ bool IsWeatherSunny(void) const { return (m_Weather == wSunny); } - + /** Returns true if it is sunny at the specified location. This takes into account biomes. */ bool IsWeatherSunnyAt(int a_BlockX, int a_BlockZ) { return (IsWeatherSunny() || IsBiomeNoDownfall(GetBiomeAt(a_BlockX, a_BlockZ))); } - + /** Returns true if the current weather is rain */ bool IsWeatherRain(void) const { return (m_Weather == wRain); } - + /** Returns true if it is raining at the specified location. This takes into account biomes. */ bool IsWeatherRainAt(int a_BlockX, int a_BlockZ) { return (IsWeatherRain() && !IsBiomeNoDownfall(GetBiomeAt(a_BlockX, a_BlockZ))); } - + /** Returns true if the current weather is stormy */ bool IsWeatherStorm(void) const { return (m_Weather == wStorm); } @@ -750,10 +750,10 @@ public: { return (IsWeatherStorm() && !IsBiomeNoDownfall(GetBiomeAt(a_BlockX, a_BlockZ))); } - + /** Returns true if the current weather has any precipitation - rain, storm or snow */ bool IsWeatherWet(void) const { return !IsWeatherSunny(); } - + /** Returns true if it is raining, stormy or snowing at the specified location. This takes into account biomes. */ virtual bool IsWeatherWetAt(int a_BlockX, int a_BlockZ) { @@ -765,33 +765,33 @@ public: cChunkGenerator & GetGenerator(void) { return m_Generator; } cWorldStorage & GetStorage (void) { return m_Storage; } cChunkMap * GetChunkMap (void) { return m_ChunkMap; } - + /** Sets the blockticking to start at the specified block. Only one blocktick per chunk may be set, second call overwrites the first call */ void SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_export - + int GetMaxSugarcaneHeight(void) const { return m_MaxSugarcaneHeight; } // tolua_export int GetMaxCactusHeight (void) const { return m_MaxCactusHeight; } // tolua_export bool IsBlockDirectlyWatered(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_export - + /** Spawns a mob of the specified type. Returns the mob's EntityID if recognized and spawned, <0 otherwise */ virtual int SpawnMob(double a_PosX, double a_PosY, double a_PosZ, eMonsterType 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 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! */ - int GetTickRandomNumber(unsigned a_Range) { return (int)(m_TickRand.randInt(a_Range)); } - + int GetTickRandomNumber(unsigned a_Range) { return static_cast(m_TickRand.randInt(a_Range)); } + /** Appends all usernames starting with a_Text (case-insensitive) into Results */ void TabCompleteUserName(const AString & a_Text, AStringVector & a_Results); /** Get the current darkness level based on the time */ NIBBLETYPE GetSkyDarkness() { return m_SkyDarkness; } - + /** Increments (a_AlwaysTicked == true) or decrements (false) the m_AlwaysTicked counter for the specified chunk. If the m_AlwaysTicked counter is greater than zero, the chunk is ticked in the tick-thread regardless of whether it has any clients or not. @@ -802,43 +802,43 @@ public: private: friend class cRoot; - + class cTickThread : public cIsThread { typedef cIsThread super; public: cTickThread(cWorld & a_World); - + protected: cWorld & m_World; - + // cIsThread overrides: virtual void Execute(void) override; } ; - - + + /** Implementation of the callbacks that the ChunkGenerator uses to store new chunks and interface to plugins */ class cChunkGeneratorCallbacks : public cChunkGenerator::cChunkSink, public cChunkGenerator::cPluginInterface { cWorld * m_World; - + // cChunkSink overrides: virtual void OnChunkGenerated (cChunkDesc & a_ChunkDesc) override; virtual bool IsChunkValid (int a_ChunkX, int a_ChunkZ) override; virtual bool HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) override; virtual bool IsChunkQueued (int a_ChunkX, int a_ChunkZ) override; - + // cPluginInterface overrides: virtual void CallHookChunkGenerating(cChunkDesc & a_ChunkDesc) override; virtual void CallHookChunkGenerated (cChunkDesc & a_ChunkDesc) override; - + public: cChunkGeneratorCallbacks(cWorld & a_World); } ; - + /** A container for tasks that have been scheduled for a specific game tick */ class cScheduledTask @@ -846,14 +846,14 @@ private: public: Int64 m_TargetTick; cTask * m_Task; - + /** Creates a new scheduled task; takes ownership of the task object passed to it. */ cScheduledTask(Int64 a_TargetTick, cTask * a_Task) : m_TargetTick(a_TargetTick), m_Task(a_Task) { } - + virtual ~cScheduledTask() { delete m_Task; @@ -872,15 +872,15 @@ private: AString m_OverworldName; AString m_IniFileName; - + /** Name of the storage schema used to load and save chunks */ AString m_StorageSchema; - + int m_StorageCompressionFactor; - + /** The dimension of the world, used by the client to provide correct lighting scheme */ eDimension m_Dimension; - + /** This random generator is to be used only in the Tick() method, and thus only in the World-Tick-thread (MTRand is not exactly thread-safe) */ MTRand m_TickRand; @@ -909,7 +909,7 @@ private: bool m_IsDeepSnowEnabled; bool m_ShouldLavaSpawnFire; bool m_VillagersShouldHarvestCrops; - + std::vector m_BlockTickQueue; std::vector m_BlockTickQueueCopy; // Second is for safely removing the objects from the queue @@ -919,12 +919,12 @@ private: cFluidSimulator * m_LavaSimulator; cFireSimulator * m_FireSimulator; cRedstoneSimulator * m_RedstoneSimulator; - + cCriticalSection m_CSPlayers; cPlayerList m_Players; cWorldStorage m_Storage; - + unsigned int m_MaxPlayers; cChunkMap * m_ChunkMap; @@ -934,7 +934,7 @@ private: eWeather m_Weather; int m_WeatherInterval; - + int m_MaxCactusHeight; int m_MaxSugarcaneHeight; bool m_IsCactusBonemealable; @@ -951,7 +951,7 @@ private: /** Whether command blocks are enabled or not */ bool m_bCommandBlocksEnabled; - + /** Whether prefixes such as [INFO] are prepended to SendMessageXXX() / BroadcastChatXXX() functions */ bool m_bUseChatPrefixes; @@ -965,43 +965,43 @@ private: /** Name of the end world */ AString m_EndWorldName; - + cChunkGenerator m_Generator; cScoreboard m_Scoreboard; cMapManager m_MapManager; - + /** The callbacks that the ChunkGenerator uses to store new chunks and interface to plugins */ cChunkGeneratorCallbacks m_GeneratorCallbacks; - + cChunkSender m_ChunkSender; cLightingThread m_Lighting; cTickThread m_TickThread; - + /** Guards the m_Tasks */ cCriticalSection m_CSTasks; - + /** Tasks that have been queued onto the tick thread; guarded by m_CSTasks */ cTasks m_Tasks; - + /** Guards the m_ScheduledTasks */ cCriticalSection m_CSScheduledTasks; - + /** Tasks that have been queued to be executed on the tick thread at target tick in the future. Ordered by increasing m_TargetTick. Guarded by m_CSScheduledTasks */ cScheduledTasks m_ScheduledTasks; - + /** Guards m_Clients */ cCriticalSection m_CSClients; - + /** List of clients in this world, these will be ticked by this world */ cClientHandleList m_Clients; - + /** Clients that are scheduled for removal (ticked in another world), waiting for TickClients() to remove them */ cClientHandleList m_ClientsToRemove; - + /** Clients that are scheduled for adding, waiting for TickClients to add them */ cClientHandleList m_ClientsToAdd; @@ -1016,10 +1016,10 @@ private: /** List of players that are scheduled for adding, waiting for the Tick thread to add them. */ cPlayerList m_PlayersToAdd; - + /** CS protecting m_SetChunkDataQueue. */ cCriticalSection m_CSSetChunkDataQueue; - + /** Queue for the chunk data to be set into m_ChunkMap by the tick thread. Protected by m_CSSetChunkDataQueue */ cSetChunkDataPtrs m_SetChunkDataQueue; @@ -1031,16 +1031,16 @@ private: /** Handles the weather in each tick */ void TickWeather(float a_Dt); - + /** Handles the mob spawning/moving/destroying each tick */ void TickMobs(float a_Dt); - + /** Executes all tasks queued onto the tick thread */ void TickQueuedTasks(void); - + /** Executes all tasks queued onto the tick thread */ void TickScheduledTasks(void); - + /** Ticks all clients that are in this world */ void TickClients(float a_Dt); @@ -1076,7 +1076,3 @@ private: void SetChunkData(cSetChunkData & a_SetChunkData); }; // tolua_export - - - - -- cgit v1.2.3 From dfd4e15ecb50621f6577c498113a463a7586b104 Mon Sep 17 00:00:00 2001 From: Steven Riehl Date: Sat, 11 Oct 2014 21:18:57 -0600 Subject: refactor an if block to std::min --- src/BlockEntities/BeaconEntity.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/BeaconEntity.cpp b/src/BlockEntities/BeaconEntity.cpp index de23f7e79..c744d12f4 100644 --- a/src/BlockEntities/BeaconEntity.cpp +++ b/src/BlockEntities/BeaconEntity.cpp @@ -227,10 +227,7 @@ void cBeaconEntity::GiveEffects(void) virtual bool Item(cPlayer * a_Player) { Vector3d PlayerPosition = Vector3d(a_Player->GetPosition()); - if (PlayerPosition.y > static_cast(m_PosY)) - { - PlayerPosition.y = static_cast(m_PosY); - } + PlayerPosition.y = std::min(m_PosY, static_cast(PlayerPosition.y)) // TODO: Vanilla minecraft uses an AABB check instead of a radius one Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ); -- cgit v1.2.3 From 4a257603632c10f491e4c2faa2b297ac63be9dfc Mon Sep 17 00:00:00 2001 From: Steven Riehl Date: Sat, 11 Oct 2014 21:36:40 -0600 Subject: fix std:min call, include algorithm and compare same type --- src/BlockEntities/BeaconEntity.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/BeaconEntity.cpp b/src/BlockEntities/BeaconEntity.cpp index c744d12f4..bcd7878a0 100644 --- a/src/BlockEntities/BeaconEntity.cpp +++ b/src/BlockEntities/BeaconEntity.cpp @@ -5,7 +5,7 @@ #include "../BlockArea.h" #include "../Entities/Player.h" - +#include @@ -227,7 +227,7 @@ void cBeaconEntity::GiveEffects(void) virtual bool Item(cPlayer * a_Player) { Vector3d PlayerPosition = Vector3d(a_Player->GetPosition()); - PlayerPosition.y = std::min(m_PosY, static_cast(PlayerPosition.y)) + PlayerPosition.y = std::min(static_cast(m_PosY), static_cast(PlayerPosition.y)); // TODO: Vanilla minecraft uses an AABB check instead of a radius one Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ); -- cgit v1.2.3 From 8dfeb6e3248af3870b578b7d48def9eb903d85af Mon Sep 17 00:00:00 2001 From: worktycho Date: Sun, 12 Oct 2014 12:15:52 +0100 Subject: Update World.cpp --- src/World.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/World.cpp b/src/World.cpp index f616063f5..8479cbf9e 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -1073,7 +1073,7 @@ void cWorld::TickScheduledTasks(void) std::find_if( m_ScheduledTasks.begin(), m_ScheduledTasks.end(), - [WorldAge] (std::unique_ptr& Task) { return Task->m_TargetTick < m_WorldAge;}), + [WorldAge] (std::unique_ptr& Task) { return Task->m_TargetTick < WorldAge;}), std::back_inserter(Tasks)); } -- cgit v1.2.3 From 6a448be88ce2d8eba3d127989978a1045b54ea6f Mon Sep 17 00:00:00 2001 From: worktycho Date: Sun, 12 Oct 2014 12:17:29 +0100 Subject: Fix spaces --- src/Globals.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Globals.h b/src/Globals.h index 5c5a8b3d2..b84607355 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -420,8 +420,8 @@ typename std::enable_if::value, C>::type CeilC(T a_Value) //temporary replacement for std::make_unique until we get c++14 -template< class T, class... Args > -std::unique_ptr make_unique( Args&&... args ) +template +std::unique_ptr make_unique(Args&&... args) { return std::unique_ptr(new T(args...)); } -- cgit v1.2.3 From daadde2077e9640482cc7786b89d93ef66ac7360 Mon Sep 17 00:00:00 2001 From: worktycho Date: Sun, 12 Oct 2014 12:18:52 +0100 Subject: Fix style --- src/World.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/World.cpp b/src/World.cpp index 8479cbf9e..0a0149e97 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -1063,7 +1063,7 @@ void cWorld::TickQueuedTasks(void) void cWorld::TickScheduledTasks(void) { - // Make a copy of the tasks to avoid deadlocks on accessing m_Tasks + // Move the tasks to be executed to a seperate vector to avoid deadlocks on accessing m_Tasks cScheduledTasks Tasks; { cCSLock Lock(m_CSScheduledTasks); @@ -1073,7 +1073,7 @@ void cWorld::TickScheduledTasks(void) std::find_if( m_ScheduledTasks.begin(), m_ScheduledTasks.end(), - [WorldAge] (std::unique_ptr& Task) { return Task->m_TargetTick < WorldAge;}), + [WorldAge] (std::unique_ptr & Task) { return Task->m_TargetTick < WorldAge;}), std::back_inserter(Tasks)); } -- cgit v1.2.3 From fff9e50109c53220b17a01bca8b422dcc066c07b Mon Sep 17 00:00:00 2001 From: worktycho Date: Sun, 12 Oct 2014 12:44:59 +0100 Subject: Aligned simulators --- src/World.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/World.h b/src/World.h index 66dd2494e..b2633d863 100644 --- a/src/World.h +++ b/src/World.h @@ -913,11 +913,11 @@ private: std::vector m_BlockTickQueue; std::vector m_BlockTickQueueCopy; // Second is for safely removing the objects from the queue - std::unique_ptr m_SimulatorManager; - std::unique_ptr m_SandSimulator; - cFluidSimulator * m_WaterSimulator; - cFluidSimulator * m_LavaSimulator; - std::unique_ptr m_FireSimulator; + std::unique_ptr m_SimulatorManager; + std::unique_ptr m_SandSimulator; + cFluidSimulator * m_WaterSimulator; + cFluidSimulator * m_LavaSimulator; + std::unique_ptr m_FireSimulator; cRedstoneSimulator * m_RedstoneSimulator; cCriticalSection m_CSPlayers; -- cgit v1.2.3 From 120b347fb5a29e14f19248275479d9a4d89eb370 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 13 Oct 2014 10:33:08 +0200 Subject: CheckBasicStyle ignores the Bindings.h generated file. --- src/CheckBasicStyle.lua | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/CheckBasicStyle.lua b/src/CheckBasicStyle.lua index b244b1fbc..76ae8c325 100644 --- a/src/CheckBasicStyle.lua +++ b/src/CheckBasicStyle.lua @@ -41,6 +41,7 @@ local g_ShouldProcessExt = --- The list of files not to be processed: local g_IgnoredFiles = { + "Bindings/Bindings.h", "Bindings/Bindings.cpp", "LeakFinder.cpp", "LeakFinder.h", -- cgit v1.2.3 From 1eae7d0ece72b2a2644916e43bbf34edebb538c6 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 13 Oct 2014 10:34:33 +0200 Subject: Fixed style. --- src/Entities/Minecart.h | 2 +- src/World.cpp | 6 ++++-- src/World.h | 3 ++- 3 files changed, 7 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Entities/Minecart.h b/src/Entities/Minecart.h index 6b6ad36b5..ab906fd06 100644 --- a/src/Entities/Minecart.h +++ b/src/Entities/Minecart.h @@ -127,7 +127,7 @@ public: ContentsWidth = 9, }; - const cItem & GetSlot(int a_Idx) const { return m_Contents.GetSlot(a_Idx); } + const cItem & GetSlot(int a_Idx) const { return m_Contents.GetSlot(a_Idx); } void SetSlot(size_t a_Idx, const cItem & a_Item) { m_Contents.SetSlot(a_Idx, a_Item); } protected: diff --git a/src/World.cpp b/src/World.cpp index 0a0149e97..d147b1c84 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -1073,8 +1073,10 @@ void cWorld::TickScheduledTasks(void) std::find_if( m_ScheduledTasks.begin(), m_ScheduledTasks.end(), - [WorldAge] (std::unique_ptr & Task) { return Task->m_TargetTick < WorldAge;}), - std::back_inserter(Tasks)); + [WorldAge] (cScheduledTaskPtr & Task) { return (Task->m_TargetTick < WorldAge);} + ), + std::back_inserter(Tasks) + ); } // Execute and delete each task: diff --git a/src/World.h b/src/World.h index b2633d863..640aa8bc3 100644 --- a/src/World.h +++ b/src/World.h @@ -861,7 +861,8 @@ private: } }; - typedef std::list> cScheduledTasks; + typedef std::unique_ptr cScheduledTaskPtr; + typedef std::list cScheduledTasks; AString m_WorldName; -- cgit v1.2.3 From 7f8118e0cbcea2b54b7c14119626772c88e42d94 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 13 Oct 2014 14:49:18 +0200 Subject: cWorld: Fixed scheduler. Fixes #1534. Added a test case into the Debuggers plugin. --- src/World.cpp | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/World.cpp b/src/World.cpp index d147b1c84..96afb8cc8 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -1068,15 +1068,24 @@ void cWorld::TickScheduledTasks(void) { cCSLock Lock(m_CSScheduledTasks); auto WorldAge = m_WorldAge; - std::move( - m_ScheduledTasks.begin(), - std::find_if( - m_ScheduledTasks.begin(), - m_ScheduledTasks.end(), - [WorldAge] (cScheduledTaskPtr & Task) { return (Task->m_TargetTick < WorldAge);} - ), - std::back_inserter(Tasks) - ); + + // Move all the due tasks from m_ScheduledTasks into Tasks: + for (auto itr = m_ScheduledTasks.begin(); itr != m_ScheduledTasks.end();) // Cannot use range-basd for, we're modifying the container + { + if ((*itr)->m_TargetTick < WorldAge) + { + auto next = itr; + ++next; + Tasks.push_back(std::move(*itr)); + m_ScheduledTasks.erase(itr); + itr = next; + } + else + { + // All the eligible tasks have been moved, bail out now + break; + } + } } // Execute and delete each task: -- cgit v1.2.3 From c6725f8d284c77b16f7e047e1c1b64d2e8f8a007 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Wed, 15 Oct 2014 13:41:23 +0200 Subject: Usernames are lowercased before generating offline UUID. This breaks previous offline UUIDs, but it guarantees that future offline UUIDs will be the same even for usernames with wrong capitalization. --- src/ClientHandle.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 3b677460b..b9adcc828 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -248,9 +248,12 @@ AString cClientHandle::GenerateOfflineUUID(const AString & a_Username) // xxxxxxxx-xxxx-3xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B // Note that we generate a short UUID (without the dashes) + // First make the username lowercase: + AString lcUsername = StrToLower(a_Username); + // Generate an md5 checksum, and use it as base for the ID: unsigned char MD5[16]; - md5((const unsigned char *)a_Username.c_str(), a_Username.length(), MD5); + md5((const unsigned char *)lcUsername.c_str(), lcUsername.length(), MD5); MD5[6] &= 0x0f; // Need to trim to 4 bits only... MD5[8] &= 0x0f; // ... otherwise %01x overflows into two chars return Printf("%02x%02x%02x%02x%02x%02x3%01x%02x8%01x%02x%02x%02x%02x%02x%02x%02x", -- cgit v1.2.3 From e3aa6e48577f3247653e94a76b68a4626a630c65 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 14:08:45 +0200 Subject: Enchanted books generate in MineShafts chests --- src/Enchantments.cpp | 6 +++++- src/Enchantments.h | 2 +- src/FastRandom.cpp | 11 +++++++++-- src/FastRandom.h | 2 +- src/ItemGrid.cpp | 15 ++++++++++++++- 5 files changed, 30 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Enchantments.cpp b/src/Enchantments.cpp index 264878c22..e106ef398 100644 --- a/src/Enchantments.cpp +++ b/src/Enchantments.cpp @@ -994,9 +994,13 @@ void cEnchantments::CheckEnchantmentConflictsFromVector(cWeightedEnchantments & -cEnchantments cEnchantments::GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments) +cEnchantments cEnchantments::GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed) { cFastRandom Random; + if (a_Seed != -1) + { + Random = cFastRandom(a_Seed); + } int AllWeights = 0; for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) diff --git a/src/Enchantments.h b/src/Enchantments.h index 824f6aa55..798d3bf61 100644 --- a/src/Enchantments.h +++ b/src/Enchantments.h @@ -126,7 +126,7 @@ public: static void CheckEnchantmentConflictsFromVector(cWeightedEnchantments & a_Enchantments, cEnchantments a_FirstEnchantment); /** Gets random enchantment from Vector and returns it */ - static cEnchantments GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments); + static cEnchantments GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed = -1); /** Returns true if a_Other doesn't contain exactly the same enchantments and levels */ bool operator !=(const cEnchantments & a_Other) const; diff --git a/src/FastRandom.cpp b/src/FastRandom.cpp index 42bf5f3f9..052d976da 100644 --- a/src/FastRandom.cpp +++ b/src/FastRandom.cpp @@ -90,10 +90,17 @@ int cFastRandom::m_SeedCounter = 0; -cFastRandom::cFastRandom(void) : - m_Seed(m_SeedCounter++), +cFastRandom::cFastRandom(int a_Seed) : m_Counter(0) { + if (a_Seed == -1) + { + m_Seed = m_SeedCounter++; + } + else + { + m_Seed = a_Seed; + } } diff --git a/src/FastRandom.h b/src/FastRandom.h index cebebad96..5a8ac097a 100644 --- a/src/FastRandom.h +++ b/src/FastRandom.h @@ -30,7 +30,7 @@ salts, the values they get will be different. class cFastRandom { public: - cFastRandom(void); + cFastRandom(int a_Seed = -1); /// Returns a random int in the range [0 .. a_Range - 1]; a_Range must be less than 1M int NextInt(int a_Range); diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 2344dc0a5..68e753e08 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -637,7 +637,20 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s int Rnd = (Noise.IntNoise1DInt(i) / 7); int LootRnd = Rnd % TotalProbab; Rnd >>= 8; - cItem CurrentLoot = cItem(E_ITEM_BOOK, 1, 0); // TODO: enchantment + cItem CurrentLoot = cItem(E_ITEM_ENCHANTED_BOOK, 1, 0); + + // Choose the enchantments + cWeightedEnchantments Enchantments; + cEnchantments::AddItemEnchantmentWeights(Enchantments, E_ITEM_BOOK, 24 + Noise.IntNoise2DInt(a_Seed, TotalProbab) % 7); + int NumEnchantments = Noise.IntNoise3DInt(TotalProbab, Rnd, a_Seed) % 5; // The number of enchantments this book wil get. + + for (int I = 0; I <= NumEnchantments; I++) + { + cEnchantments Enchantment = cEnchantments::GetRandomEnchantmentFromVector(Enchantments, a_Seed); + CurrentLoot.m_Enchantments.AddFromString(Enchantment.ToString()); + cEnchantments::RemoveEnchantmentWeightFromVector(Enchantments, Enchantment); + } + for (size_t j = 0; j < a_CountLootProbabs; j++) { LootRnd -= a_LootProbabs[i].m_Weight; -- cgit v1.2.3 From ff5f57514e172e3344d6d50fce6bd8ea84e7f32b Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 14:44:07 +0200 Subject: Returned cFastRandom and cEnchantment:GetRandomEnchantmentFromVector to before Added cEnchantment:GenerateEnchantmentFromVector that allows to get the same enchantments over and over. --- src/Enchantments.cpp | 32 ++++++++++++++++++++++++++++---- src/Enchantments.h | 5 ++++- src/FastRandom.cpp | 11 ++--------- src/FastRandom.h | 2 +- src/ItemGrid.cpp | 2 +- 5 files changed, 36 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/Enchantments.cpp b/src/Enchantments.cpp index e106ef398..3cddf37ae 100644 --- a/src/Enchantments.cpp +++ b/src/Enchantments.cpp @@ -6,6 +6,7 @@ #include "Enchantments.h" #include "WorldStorage/FastNBT.h" #include "FastRandom.h" +#include "Noise.h" @@ -994,20 +995,43 @@ void cEnchantments::CheckEnchantmentConflictsFromVector(cWeightedEnchantments & -cEnchantments cEnchantments::GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed) +cEnchantments cEnchantments::GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments) { cFastRandom Random; - if (a_Seed != -1) + + int AllWeights = 0; + for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) + { + AllWeights += (*it).m_Weight; + } + int RandomNumber = Random.GenerateRandomInteger(0, AllWeights - 1); + for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) { - Random = cFastRandom(a_Seed); + RandomNumber -= (*it).m_Weight; + if (RandomNumber < 0) + { + return (*it).m_Enchantments; + } } + return cEnchantments(); +} + + + + + +cEnchantments cEnchantments::GenerateEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed) +{ int AllWeights = 0; for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) { AllWeights += (*it).m_Weight; } - int RandomNumber = Random.GenerateRandomInteger(0, AllWeights - 1); + + cNoise Noise(a_Seed); + int RandomNumber = Noise.IntNoise1DInt(AllWeights) % AllWeights; + for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) { RandomNumber -= (*it).m_Weight; diff --git a/src/Enchantments.h b/src/Enchantments.h index 798d3bf61..e4390a5f2 100644 --- a/src/Enchantments.h +++ b/src/Enchantments.h @@ -126,7 +126,10 @@ public: static void CheckEnchantmentConflictsFromVector(cWeightedEnchantments & a_Enchantments, cEnchantments a_FirstEnchantment); /** Gets random enchantment from Vector and returns it */ - static cEnchantments GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed = -1); + static cEnchantments GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments); + + /** Returns an enchantment from a Vector using cNoise. Mostly used for generators.*/ + static cEnchantments GenerateEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed); /** Returns true if a_Other doesn't contain exactly the same enchantments and levels */ bool operator !=(const cEnchantments & a_Other) const; diff --git a/src/FastRandom.cpp b/src/FastRandom.cpp index 052d976da..42bf5f3f9 100644 --- a/src/FastRandom.cpp +++ b/src/FastRandom.cpp @@ -90,17 +90,10 @@ int cFastRandom::m_SeedCounter = 0; -cFastRandom::cFastRandom(int a_Seed) : +cFastRandom::cFastRandom(void) : + m_Seed(m_SeedCounter++), m_Counter(0) { - if (a_Seed == -1) - { - m_Seed = m_SeedCounter++; - } - else - { - m_Seed = a_Seed; - } } diff --git a/src/FastRandom.h b/src/FastRandom.h index 5a8ac097a..cebebad96 100644 --- a/src/FastRandom.h +++ b/src/FastRandom.h @@ -30,7 +30,7 @@ salts, the values they get will be different. class cFastRandom { public: - cFastRandom(int a_Seed = -1); + cFastRandom(void); /// Returns a random int in the range [0 .. a_Range - 1]; a_Range must be less than 1M int NextInt(int a_Range); diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 68e753e08..a5273c6da 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -646,7 +646,7 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s for (int I = 0; I <= NumEnchantments; I++) { - cEnchantments Enchantment = cEnchantments::GetRandomEnchantmentFromVector(Enchantments, a_Seed); + cEnchantments Enchantment = cEnchantments::GenerateEnchantmentFromVector(Enchantments, Noise.IntNoise2DInt(NumEnchantments, i)); CurrentLoot.m_Enchantments.AddFromString(Enchantment.ToString()); cEnchantments::RemoveEnchantmentWeightFromVector(Enchantments, Enchantment); } -- cgit v1.2.3 From e4ee71868e307c5d51ca910a97a36623efdfaff0 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 15:25:48 +0200 Subject: Renamed the counter to 'j' --- src/ItemGrid.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index a5273c6da..5621c00fd 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -644,7 +644,7 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s cEnchantments::AddItemEnchantmentWeights(Enchantments, E_ITEM_BOOK, 24 + Noise.IntNoise2DInt(a_Seed, TotalProbab) % 7); int NumEnchantments = Noise.IntNoise3DInt(TotalProbab, Rnd, a_Seed) % 5; // The number of enchantments this book wil get. - for (int I = 0; I <= NumEnchantments; I++) + for (int j = 0; j <= NumEnchantments; j++) { cEnchantments Enchantment = cEnchantments::GenerateEnchantmentFromVector(Enchantments, Noise.IntNoise2DInt(NumEnchantments, i)); CurrentLoot.m_Enchantments.AddFromString(Enchantment.ToString()); -- cgit v1.2.3 From 57f8d2a55e2a20e255a64d46746eb3e58944ef6b Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 15:31:06 +0200 Subject: Adding enchantments directly instead of first getting the name of it. --- src/ItemGrid.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 5621c00fd..cd77d52e1 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -647,7 +647,7 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s for (int j = 0; j <= NumEnchantments; j++) { cEnchantments Enchantment = cEnchantments::GenerateEnchantmentFromVector(Enchantments, Noise.IntNoise2DInt(NumEnchantments, i)); - CurrentLoot.m_Enchantments.AddFromString(Enchantment.ToString()); + CurrentLoot.m_Enchantments.Add(Enchantment); cEnchantments::RemoveEnchantmentWeightFromVector(Enchantments, Enchantment); } -- cgit v1.2.3 From 0cdd2b64ed9c99c171c0689ada24147732fb3d4b Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 15:42:45 +0200 Subject: IntNoise1DInt result gets devided by 7 first suggestion by xoft --- src/Enchantments.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Enchantments.cpp b/src/Enchantments.cpp index 3cddf37ae..10d23a8fb 100644 --- a/src/Enchantments.cpp +++ b/src/Enchantments.cpp @@ -1030,7 +1030,7 @@ cEnchantments cEnchantments::GenerateEnchantmentFromVector(cWeightedEnchantments } cNoise Noise(a_Seed); - int RandomNumber = Noise.IntNoise1DInt(AllWeights) % AllWeights; + int RandomNumber = Noise.IntNoise1DInt(AllWeights) / 7 % AllWeights; for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) { -- cgit v1.2.3 From fa6f8fb38e8bb4a2d047ff9dee3ee57b10b5cf1b Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 15:44:52 +0200 Subject: The code now prevents conflicting enchantments. --- src/ItemGrid.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index cd77d52e1..6a3d08679 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -649,6 +649,7 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s cEnchantments Enchantment = cEnchantments::GenerateEnchantmentFromVector(Enchantments, Noise.IntNoise2DInt(NumEnchantments, i)); CurrentLoot.m_Enchantments.Add(Enchantment); cEnchantments::RemoveEnchantmentWeightFromVector(Enchantments, Enchantment); + cEnchantments::CheckEnchantmentConflictsFromVector(Enchantments, Enchantment); } for (size_t j = 0; j < a_CountLootProbabs; j++) -- cgit v1.2.3 From 4038e1cb42e84f210826f22c6a55b13c440cf9fb Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 18:11:28 +0200 Subject: Using C++11 loops --- src/Enchantments.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Enchantments.cpp b/src/Enchantments.cpp index 10d23a8fb..80a9810b6 100644 --- a/src/Enchantments.cpp +++ b/src/Enchantments.cpp @@ -1024,20 +1024,20 @@ cEnchantments cEnchantments::GetRandomEnchantmentFromVector(cWeightedEnchantment cEnchantments cEnchantments::GenerateEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed) { int AllWeights = 0; - for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) + for (const auto Enchantment : a_Enchantments) { - AllWeights += (*it).m_Weight; + AllWeights += Enchantment.m_Weight; } cNoise Noise(a_Seed); int RandomNumber = Noise.IntNoise1DInt(AllWeights) / 7 % AllWeights; - for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) + for (const auto Enchantment : a_Enchantments) { - RandomNumber -= (*it).m_Weight; + RandomNumber -= Enchantment.m_Weight; if (RandomNumber < 0) { - return (*it).m_Enchantments; + return Enchantment.m_Enchantments; } } -- cgit v1.2.3 From eeb580a74e48829908c303f8145802bfa1805c68 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Wed, 15 Oct 2014 19:01:55 +0200 Subject: Functions in cPluginManager get references instead of pointers. --- src/Bindings/Plugin.h | 34 ++++++++-------- src/Bindings/PluginLua.cpp | 82 +++++++++++++++++++------------------- src/Bindings/PluginLua.h | 34 ++++++++-------- src/Bindings/PluginManager.cpp | 58 +++++++++++++-------------- src/Bindings/PluginManager.h | 38 +++++++++--------- src/BlockInServerPluginInterface.h | 20 +++++++++- src/Blocks/BlockDirt.h | 2 +- src/Blocks/BlockHandler.cpp | 2 +- src/Blocks/BlockPluginInterface.h | 11 ++++- src/Blocks/BlockVine.h | 12 +++++- src/Chunk.cpp | 10 ++--- src/Chunk.h | 2 +- src/ChunkMap.cpp | 14 ++++--- src/ChunkMap.h | 2 +- src/ClientHandle.cpp | 4 +- src/CraftingRecipes.cpp | 8 ++-- src/CraftingRecipes.h | 2 +- src/Entities/ArrowEntity.cpp | 14 ++++--- src/Entities/ArrowEntity.h | 2 +- src/Entities/Pickup.cpp | 16 ++++---- src/Entities/Pickup.h | 2 +- src/Entities/Player.cpp | 2 +- src/Entities/ProjectileEntity.cpp | 6 ++- src/Entities/ProjectileEntity.h | 2 +- src/Server.cpp | 2 +- src/Simulator/FireSimulator.cpp | 4 +- src/UI/SlotArea.cpp | 4 +- src/World.cpp | 10 ++--- src/World.h | 2 +- 29 files changed, 220 insertions(+), 181 deletions(-) (limited to 'src') diff --git a/src/Bindings/Plugin.h b/src/Bindings/Plugin.h index fb22dd33e..8cc9ff0cd 100644 --- a/src/Bindings/Plugin.h +++ b/src/Bindings/Plugin.h @@ -45,26 +45,26 @@ public: virtual void Tick(float a_Dt) = 0; /** Calls the specified hook with the params given. Returns the bool that the hook callback returns.*/ - virtual bool OnBlockSpread (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0; - virtual bool OnBlockToPickups (cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) = 0; - virtual bool OnChat (cPlayer * a_Player, AString & a_Message) = 0; - virtual bool OnChunkAvailable (cWorld * a_World, int a_ChunkX, int a_ChunkZ) = 0; - virtual bool OnChunkGenerated (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; - virtual bool OnChunkGenerating (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; - virtual bool OnChunkUnloaded (cWorld * a_World, int a_ChunkX, int a_ChunkZ) = 0; - 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 OnBlockSpread (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0; + virtual bool OnBlockToPickups (cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) = 0; + virtual bool OnChat (cPlayer & a_Player, AString & a_Message) = 0; + virtual bool OnChunkAvailable (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0; + virtual bool OnChunkGenerated (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; + virtual bool OnChunkGenerating (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; + virtual bool OnChunkUnloaded (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0; + 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 (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) = 0; virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) = 0; virtual bool OnEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier) = 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; - virtual bool OnHandshake (cClientHandle * a_Client, const AString & a_Username) = 0; + virtual bool OnHandshake (cClientHandle & a_Client, const AString & a_Username) = 0; virtual bool OnHopperPullingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_DstSlotNum, cBlockEntityWithItems & a_SrcEntity, int a_SrcSlotNum) = 0; virtual bool OnHopperPushingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_SrcSlotNum, cBlockEntityWithItems & a_DstEntity, int a_DstSlotNum) = 0; virtual bool OnKilling (cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI) = 0; - virtual bool OnLogin (cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) = 0; + virtual bool OnLogin (cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) = 0; virtual bool OnPlayerAnimation (cPlayer & a_Player, int a_Animation) = 0; virtual bool OnPlayerBreakingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0; virtual bool OnPlayerBrokenBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0; @@ -89,8 +89,8 @@ public: virtual bool OnPlayerUsingItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) = 0; virtual bool OnPluginMessage (cClientHandle & a_Client, const AString & a_Channel, const AString & a_Message) = 0; 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 OnPostCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0; + virtual bool OnPreCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0; virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Face, const Vector3d & a_BlockHitPos) = 0; virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) = 0; virtual bool OnServerPing (cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon) = 0; @@ -99,8 +99,8 @@ public: virtual bool OnSpawningEntity (cWorld & a_World, cEntity & a_Entity) = 0; virtual bool OnSpawningMonster (cWorld & a_World, cMonster & a_Monster) = 0; virtual bool OnTakeDamage (cEntity & a_Receiver, TakeDamageInfo & a_TakeDamageInfo) = 0; - virtual bool OnUpdatedSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) = 0; - virtual bool OnUpdatingSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) = 0; + virtual bool OnUpdatedSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) = 0; + virtual bool OnUpdatingSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) = 0; virtual bool OnWeatherChanged (cWorld & a_World) = 0; virtual bool OnWeatherChanging (cWorld & a_World, eWeather & a_NewWeather) = 0; virtual bool OnWorldStarted (cWorld & a_World) = 0; @@ -110,7 +110,7 @@ public: Command permissions have already been checked. Returns true if command handled successfully */ - virtual bool HandleCommand(const AStringVector & a_Split, cPlayer * a_Player) = 0; + virtual bool HandleCommand(const AStringVector & a_Split, cPlayer & a_Player) = 0; /** Handles the console command split into a_Split. Returns true if command handled successfully. Output is to be sent to the a_Output callback. diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp index 2629eb641..eec31e8a6 100644 --- a/src/Bindings/PluginLua.cpp +++ b/src/Bindings/PluginLua.cpp @@ -202,14 +202,14 @@ void cPluginLua::Tick(float a_Dt) -bool cPluginLua::OnBlockSpread(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) +bool cPluginLua::OnBlockSpread(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_BLOCK_SPREAD]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_BlockX, a_BlockY, a_BlockZ, a_Source, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_BlockX, a_BlockY, a_BlockZ, a_Source, cLuaState::Return, res); if (res) { return true; @@ -222,14 +222,14 @@ bool cPluginLua::OnBlockSpread(cWorld * a_World, int a_BlockX, int a_BlockY, int -bool cPluginLua::OnBlockToPickups(cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) +bool cPluginLua::OnBlockToPickups(cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_BLOCK_TO_PICKUPS]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, &a_Pickups, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, &a_Pickups, cLuaState::Return, res); if (res) { return true; @@ -242,14 +242,14 @@ bool cPluginLua::OnBlockToPickups(cWorld * a_World, cEntity * a_Digger, int a_Bl -bool cPluginLua::OnChat(cPlayer * a_Player, AString & a_Message) +bool cPluginLua::OnChat(cPlayer & a_Player, AString & a_Message) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHAT]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Message, cLuaState::Return, res, a_Message); + m_LuaState.Call((int)(**itr), &a_Player, a_Message, cLuaState::Return, res, a_Message); if (res) { return true; @@ -262,14 +262,14 @@ bool cPluginLua::OnChat(cPlayer * a_Player, AString & a_Message) -bool cPluginLua::OnChunkAvailable(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginLua::OnChunkAvailable(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_AVAILABLE]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); if (res) { return true; @@ -282,14 +282,14 @@ bool cPluginLua::OnChunkAvailable(cWorld * a_World, int a_ChunkX, int a_ChunkZ) -bool cPluginLua::OnChunkGenerated(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginLua::OnChunkGenerated(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_GENERATED]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); if (res) { return true; @@ -302,14 +302,14 @@ bool cPluginLua::OnChunkGenerated(cWorld * a_World, int a_ChunkX, int a_ChunkZ, -bool cPluginLua::OnChunkGenerating(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginLua::OnChunkGenerating(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_GENERATING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); if (res) { return true; @@ -322,14 +322,14 @@ bool cPluginLua::OnChunkGenerating(cWorld * a_World, int a_ChunkX, int a_ChunkZ, -bool cPluginLua::OnChunkUnloaded(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginLua::OnChunkUnloaded(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_UNLOADED]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); if (res) { return true; @@ -342,14 +342,14 @@ bool cPluginLua::OnChunkUnloaded(cWorld * a_World, int a_ChunkX, int a_ChunkZ) -bool cPluginLua::OnChunkUnloading(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginLua::OnChunkUnloading(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_UNLOADING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); if (res) { return true; @@ -362,14 +362,14 @@ bool cPluginLua::OnChunkUnloading(cWorld * a_World, int a_ChunkX, int a_ChunkZ) -bool cPluginLua::OnCollectingPickup(cPlayer * a_Player, cPickup * a_Pickup) +bool cPluginLua::OnCollectingPickup(cPlayer & a_Player, cPickup & a_Pickup) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_COLLECTING_PICKUP]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Pickup, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Pickup, cLuaState::Return, res); if (res) { return true; @@ -382,14 +382,14 @@ bool cPluginLua::OnCollectingPickup(cPlayer * a_Player, cPickup * a_Pickup) -bool cPluginLua::OnCraftingNoRecipe(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginLua::OnCraftingNoRecipe(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CRAFTING_NO_RECIPE]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), (cPlayer *)a_Player, a_Grid, a_Recipe, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Grid, &a_Recipe, cLuaState::Return, res); if (res) { return true; @@ -471,12 +471,12 @@ bool cPluginLua::OnExploded(cWorld & a_World, double a_ExplosionSize, bool a_Can { switch (a_Source) { - case esOther: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; - case esPrimedTNT: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cTNTEntity *)a_SourceData, cLuaState::Return, res); break; - case esMonster: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cMonster *)a_SourceData, cLuaState::Return, res); break; - case esBed: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; - case esEnderCrystal: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; - case esGhastFireball: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; + case esOther: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; + case esPrimedTNT: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cTNTEntity *)a_SourceData, cLuaState::Return, res); break; + case esMonster: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cMonster *)a_SourceData, cLuaState::Return, res); break; + case esBed: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; + case esEnderCrystal: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; + case esGhastFireball: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; case esWitherSkullBlack: case esWitherSkullBlue: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; case esWitherBirth: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; @@ -536,14 +536,14 @@ bool cPluginLua::OnExploding(cWorld & a_World, double & a_ExplosionSize, bool & -bool cPluginLua::OnHandshake(cClientHandle * a_Client, const AString & a_Username) +bool cPluginLua::OnHandshake(cClientHandle & a_Client, const AString & a_Username) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_HANDSHAKE]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Client, a_Username, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Client, a_Username, cLuaState::Return, res); if (res) { return true; @@ -617,14 +617,14 @@ bool cPluginLua::OnKilling(cEntity & a_Victim, cEntity * a_Killer, TakeDamageInf -bool cPluginLua::OnLogin(cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) +bool cPluginLua::OnLogin(cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_LOGIN]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Client, a_ProtocolVersion, a_Username, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Client, a_ProtocolVersion, a_Username, cLuaState::Return, res); if (res) { return true; @@ -784,7 +784,7 @@ bool cPluginLua::OnPlayerFishing(cPlayer & a_Player, cItems & a_Reward) cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_PLAYER_FISHING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), &a_Player, a_Reward, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Reward, cLuaState::Return, res); if (res) { return true; @@ -1115,14 +1115,14 @@ bool cPluginLua::OnPluginsLoaded(void) -bool cPluginLua::OnPostCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginLua::OnPostCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_POST_CRAFTING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Grid, a_Recipe, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Grid, &a_Recipe, cLuaState::Return, res); if (res) { return true; @@ -1135,14 +1135,14 @@ bool cPluginLua::OnPostCrafting(const cPlayer * a_Player, const cCraftingGrid * -bool cPluginLua::OnPreCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginLua::OnPreCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_PRE_CRAFTING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Grid, a_Recipe, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Grid, &a_Recipe, cLuaState::Return, res); if (res) { return true; @@ -1316,7 +1316,7 @@ bool cPluginLua::OnTakeDamage(cEntity & a_Receiver, TakeDamageInfo & a_TDI) bool cPluginLua::OnUpdatedSign( - cWorld * a_World, + cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player @@ -1327,7 +1327,7 @@ bool cPluginLua::OnUpdatedSign( cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_UPDATED_SIGN]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res); if (res) { return true; @@ -1341,7 +1341,7 @@ bool cPluginLua::OnUpdatedSign( bool cPluginLua::OnUpdatingSign( - cWorld * a_World, + cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player @@ -1352,7 +1352,7 @@ bool cPluginLua::OnUpdatingSign( cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_UPDATING_SIGN]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res, a_Line1, a_Line2, a_Line3, a_Line4); + m_LuaState.Call((int)(**itr), &a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res, a_Line1, a_Line2, a_Line3, a_Line4); if (res) { return true; @@ -1435,7 +1435,7 @@ bool cPluginLua::OnWorldTick(cWorld & a_World, float a_Dt, int a_LastTickDuratio -bool cPluginLua::HandleCommand(const AStringVector & a_Split, cPlayer * a_Player) +bool cPluginLua::HandleCommand(const AStringVector & a_Split, cPlayer & a_Player) { ASSERT(!a_Split.empty()); CommandMap::iterator cmd = m_Commands.find(a_Split[0]); @@ -1447,7 +1447,7 @@ bool cPluginLua::HandleCommand(const AStringVector & a_Split, cPlayer * a_Player cCSLock Lock(m_CriticalSection); bool res = false; - m_LuaState.Call(cmd->second, a_Split, a_Player, cLuaState::Return, res); + m_LuaState.Call(cmd->second, a_Split, &a_Player, cLuaState::Return, res); return res; } diff --git a/src/Bindings/PluginLua.h b/src/Bindings/PluginLua.h index eda65b76c..6bb134efc 100644 --- a/src/Bindings/PluginLua.h +++ b/src/Bindings/PluginLua.h @@ -69,26 +69,26 @@ public: virtual void Tick(float a_Dt) override; - virtual bool OnBlockSpread (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) override; - virtual bool OnBlockToPickups (cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) override; - virtual bool OnChat (cPlayer * a_Player, AString & a_Message) override; - virtual bool OnChunkAvailable (cWorld * a_World, int a_ChunkX, int a_ChunkZ) override; - virtual bool OnChunkGenerated (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; - virtual bool OnChunkGenerating (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; - virtual bool OnChunkUnloaded (cWorld * a_World, int a_ChunkX, int a_ChunkZ) override; - 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 OnBlockSpread (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) override; + virtual bool OnBlockToPickups (cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) override; + virtual bool OnChat (cPlayer & a_Player, AString & a_Message) override; + virtual bool OnChunkAvailable (cWorld & a_World, int a_ChunkX, int a_ChunkZ) override; + virtual bool OnChunkGenerated (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; + virtual bool OnChunkGenerating (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; + virtual bool OnChunkUnloaded (cWorld & a_World, int a_ChunkX, int a_ChunkZ) override; + 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 (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) override; virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) override; virtual bool OnEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier) 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; - virtual bool OnHandshake (cClientHandle * a_Client, const AString & a_Username) override; + virtual bool OnHandshake (cClientHandle & a_Client, const AString & a_Username) override; virtual bool OnHopperPullingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_DstSlotNum, cBlockEntityWithItems & a_SrcEntity, int a_SrcSlotNum) override; virtual bool OnHopperPushingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_SrcSlotNum, cBlockEntityWithItems & a_DstEntity, int a_DstSlotNum) override; virtual bool OnKilling (cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI) override; - virtual bool OnLogin (cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) override; + virtual bool OnLogin (cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) override; virtual bool OnPlayerAnimation (cPlayer & a_Player, int a_Animation) override; virtual bool OnPlayerBreakingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) override; virtual bool OnPlayerBrokenBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) override; @@ -113,8 +113,8 @@ public: virtual bool OnPlayerUsingItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) override; virtual bool OnPluginMessage (cClientHandle & a_Client, const AString & a_Channel, const AString & a_Message) override; 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 OnPostCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) override; + virtual bool OnPreCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) override; virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Face, const Vector3d & a_BlockHitPos) override; virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) override; virtual bool OnServerPing (cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon) override; @@ -123,14 +123,14 @@ public: virtual bool OnSpawningEntity (cWorld & a_World, cEntity & a_Entity) override; virtual bool OnSpawningMonster (cWorld & a_World, cMonster & a_Monster) override; virtual bool OnTakeDamage (cEntity & a_Receiver, TakeDamageInfo & a_TakeDamageInfo) override; - virtual bool OnUpdatedSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) override; - virtual bool OnUpdatingSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) override; + virtual bool OnUpdatedSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) override; + virtual bool OnUpdatingSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) override; virtual bool OnWeatherChanged (cWorld & a_World) override; virtual bool OnWeatherChanging (cWorld & a_World, eWeather & a_NewWeather) override; virtual bool OnWorldStarted (cWorld & a_World) override; virtual bool OnWorldTick (cWorld & a_World, float a_Dt, int a_LastTickDurationMSec) override; - virtual bool HandleCommand(const AStringVector & a_Split, cPlayer * a_Player) override; + virtual bool HandleCommand(const AStringVector & a_Split, cPlayer & a_Player) override; virtual bool HandleConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output) override; diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp index e0faa838a..43507a5fb 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -225,7 +225,7 @@ void cPluginManager::Tick(float a_Dt) -bool cPluginManager::CallHookBlockSpread(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) +bool cPluginManager::CallHookBlockSpread(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) { FIND_HOOK(HOOK_BLOCK_SPREAD); VERIFY_HOOK; @@ -245,7 +245,7 @@ bool cPluginManager::CallHookBlockSpread(cWorld * a_World, int a_BlockX, int a_B bool cPluginManager::CallHookBlockToPickups( - cWorld * a_World, cEntity * a_Digger, + cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups ) @@ -267,7 +267,7 @@ bool cPluginManager::CallHookBlockToPickups( -bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) +bool cPluginManager::CallHookChat(cPlayer & a_Player, AString & a_Message) { // Check if the message contains a command, execute it: switch (HandleCommand(a_Player, a_Message, true)) @@ -288,14 +288,14 @@ bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) case crError: { // An error in the plugin has prevented the command from executing. Report the error to the player: - a_Player->SendMessageFailure(Printf("Something went wrong while executing command \"%s\"", a_Message.c_str())); + a_Player.SendMessageFailure(Printf("Something went wrong while executing command \"%s\"", a_Message.c_str())); return true; } case crNoPermission: { // The player is not allowed to execute this command - a_Player->SendMessageFailure(Printf("Forbidden command; insufficient privileges: \"%s\"", a_Message.c_str())); + a_Player.SendMessageFailure(Printf("Forbidden command; insufficient privileges: \"%s\"", a_Message.c_str())); return true; } @@ -311,8 +311,8 @@ bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) { AStringVector Split(StringSplit(a_Message, " ")); ASSERT(!Split.empty()); // This should not happen - we know there's at least one char in the message so the split needs to be at least one item long - a_Player->SendMessageInfo(Printf("Unknown command: \"%s\"", a_Message.c_str())); - LOGINFO("Player %s issued an unknown command: \"%s\"", a_Player->GetName().c_str(), a_Message.c_str()); + a_Player.SendMessageInfo(Printf("Unknown command: \"%s\"", a_Message.c_str())); + LOGINFO("Player %s issued an unknown command: \"%s\"", a_Player.GetName().c_str(), a_Message.c_str()); return true; // Cancel sending } @@ -334,7 +334,7 @@ bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) -bool cPluginManager::CallHookChunkAvailable(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginManager::CallHookChunkAvailable(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { FIND_HOOK(HOOK_CHUNK_AVAILABLE); VERIFY_HOOK; @@ -353,7 +353,7 @@ bool cPluginManager::CallHookChunkAvailable(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookChunkGenerated(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginManager::CallHookChunkGenerated(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { FIND_HOOK(HOOK_CHUNK_GENERATED); VERIFY_HOOK; @@ -372,7 +372,7 @@ bool cPluginManager::CallHookChunkGenerated(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookChunkGenerating(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginManager::CallHookChunkGenerating(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { FIND_HOOK(HOOK_CHUNK_GENERATING); VERIFY_HOOK; @@ -391,7 +391,7 @@ bool cPluginManager::CallHookChunkGenerating(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookChunkUnloaded(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginManager::CallHookChunkUnloaded(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { FIND_HOOK(HOOK_CHUNK_UNLOADED); VERIFY_HOOK; @@ -410,7 +410,7 @@ bool cPluginManager::CallHookChunkUnloaded(cWorld * a_World, int a_ChunkX, int a -bool cPluginManager::CallHookChunkUnloading(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginManager::CallHookChunkUnloading(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { FIND_HOOK(HOOK_CHUNK_UNLOADING); VERIFY_HOOK; @@ -429,14 +429,14 @@ bool cPluginManager::CallHookChunkUnloading(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookCollectingPickup(cPlayer * a_Player, cPickup & a_Pickup) +bool cPluginManager::CallHookCollectingPickup(cPlayer & a_Player, cPickup & a_Pickup) { FIND_HOOK(HOOK_COLLECTING_PICKUP); VERIFY_HOOK; for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr) { - if ((*itr)->OnCollectingPickup(a_Player, &a_Pickup)) + if ((*itr)->OnCollectingPickup(a_Player, a_Pickup)) { return true; } @@ -448,7 +448,7 @@ bool cPluginManager::CallHookCollectingPickup(cPlayer * a_Player, cPickup & a_Pi -bool cPluginManager::CallHookCraftingNoRecipe(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginManager::CallHookCraftingNoRecipe(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) { FIND_HOOK(HOOK_CRAFTING_NO_RECIPE); VERIFY_HOOK; @@ -562,7 +562,7 @@ bool cPluginManager::CallHookExploding(cWorld & a_World, double & a_ExplosionSiz -bool cPluginManager::CallHookHandshake(cClientHandle * a_ClientHandle, const AString & a_Username) +bool cPluginManager::CallHookHandshake(cClientHandle & a_ClientHandle, const AString & a_Username) { FIND_HOOK(HOOK_HANDSHAKE); VERIFY_HOOK; @@ -638,7 +638,7 @@ bool cPluginManager::CallHookKilling(cEntity & a_Victim, cEntity * a_Killer, Tak -bool cPluginManager::CallHookLogin(cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) +bool cPluginManager::CallHookLogin(cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) { FIND_HOOK(HOOK_LOGIN); VERIFY_HOOK; @@ -1111,7 +1111,7 @@ bool cPluginManager::CallHookPluginsLoaded(void) -bool cPluginManager::CallHookPostCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginManager::CallHookPostCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { FIND_HOOK(HOOK_POST_CRAFTING); VERIFY_HOOK; @@ -1130,7 +1130,7 @@ bool cPluginManager::CallHookPostCrafting(const cPlayer * a_Player, const cCraft -bool cPluginManager::CallHookPreCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginManager::CallHookPreCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { FIND_HOOK(HOOK_PRE_CRAFTING); VERIFY_HOOK; @@ -1299,7 +1299,7 @@ bool cPluginManager::CallHookTakeDamage(cEntity & a_Receiver, TakeDamageInfo & a -bool cPluginManager::CallHookUpdatingSign(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) +bool cPluginManager::CallHookUpdatingSign(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) { FIND_HOOK(HOOK_UPDATING_SIGN); VERIFY_HOOK; @@ -1318,7 +1318,7 @@ bool cPluginManager::CallHookUpdatingSign(cWorld * a_World, int a_BlockX, int a_ -bool cPluginManager::CallHookUpdatedSign(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) +bool cPluginManager::CallHookUpdatedSign(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) { FIND_HOOK(HOOK_UPDATED_SIGN); VERIFY_HOOK; @@ -1413,10 +1413,8 @@ bool cPluginManager::CallHookWorldTick(cWorld & a_World, float a_Dt, int a_LastT -cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer * a_Player, const AString & a_Command, bool a_ShouldCheckPermissions) +cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer & a_Player, const AString & a_Command, bool a_ShouldCheckPermissions) { - ASSERT(a_Player != NULL); - AStringVector Split(StringSplit(a_Command, " ")); if (Split.empty()) { @@ -1431,19 +1429,19 @@ cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer * a_Player, } // Ask plugins first if a command is okay to execute the command: - if (CallHookExecuteCommand(a_Player, Split)) + if (CallHookExecuteCommand(&a_Player, Split)) { - LOGINFO("Player %s tried executing command \"%s\" that was stopped by the HOOK_EXECUTE_COMMAND hook", a_Player->GetName().c_str(), Split[0].c_str()); + LOGINFO("Player %s tried executing command \"%s\" that was stopped by the HOOK_EXECUTE_COMMAND hook", a_Player.GetName().c_str(), Split[0].c_str()); return crBlocked; } if ( a_ShouldCheckPermissions && !cmd->second.m_Permission.empty() && - !a_Player->HasPermission(cmd->second.m_Permission) + !a_Player.HasPermission(cmd->second.m_Permission) ) { - LOGINFO("Player %s tried to execute forbidden command: \"%s\"", a_Player->GetName().c_str(), Split[0].c_str()); + LOGINFO("Player %s tried to execute forbidden command: \"%s\"", a_Player.GetName().c_str(), Split[0].c_str()); return crNoPermission; } @@ -1652,7 +1650,7 @@ AString cPluginManager::GetCommandPermission(const AString & a_Command) -cPluginManager::CommandResult cPluginManager::ExecuteCommand(cPlayer * a_Player, const AString & a_Command) +cPluginManager::CommandResult cPluginManager::ExecuteCommand(cPlayer & a_Player, const AString & a_Command) { return HandleCommand(a_Player, a_Command, true); } @@ -1661,7 +1659,7 @@ cPluginManager::CommandResult cPluginManager::ExecuteCommand(cPlayer * a_Player, -cPluginManager::CommandResult cPluginManager::ForceExecuteCommand(cPlayer * a_Player, const AString & a_Command) +cPluginManager::CommandResult cPluginManager::ForceExecuteCommand(cPlayer & a_Player, const AString & a_Command) { return HandleCommand(a_Player, a_Command, false); } diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h index fff3bc323..c69850be6 100644 --- a/src/Bindings/PluginManager.h +++ b/src/Bindings/PluginManager.h @@ -178,26 +178,26 @@ public: size_t GetNumPlugins() const; // tolua_export // Calls for individual hooks. Each returns false if the action is to continue or true if the plugin wants to abort - bool CallHookBlockSpread (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source); - bool CallHookBlockToPickups (cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups); - bool CallHookChat (cPlayer * a_Player, AString & a_Message); - bool CallHookChunkAvailable (cWorld * a_World, int a_ChunkX, int a_ChunkZ); - bool CallHookChunkGenerated (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); - bool CallHookChunkGenerating (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); - bool CallHookChunkUnloaded (cWorld * a_World, int a_ChunkX, int a_ChunkZ); - 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 CallHookBlockSpread (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source); + bool CallHookBlockToPickups (cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups); + bool CallHookChat (cPlayer & a_Player, AString & a_Message); + bool CallHookChunkAvailable (cWorld & a_World, int a_ChunkX, int a_ChunkZ); + bool CallHookChunkGenerated (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); + bool CallHookChunkGenerating (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); + bool CallHookChunkUnloaded (cWorld & a_World, int a_ChunkX, int a_ChunkZ); + bool CallHookChunkUnloading (cWorld & a_World, int a_ChunkX, int a_ChunkZ); + bool CallHookCollectingPickup (cPlayer & a_Player, cPickup & a_Pickup); + bool CallHookCraftingNoRecipe (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe); bool CallHookDisconnect (cClientHandle & a_Client, const AString & a_Reason); bool CallHookEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier); 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); - bool CallHookHandshake (cClientHandle * a_ClientHandle, const AString & a_Username); + bool CallHookHandshake (cClientHandle & a_ClientHandle, const AString & a_Username); bool CallHookHopperPullingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_DstSlotNum, cBlockEntityWithItems & a_SrcEntity, int a_SrcSlotNum); bool CallHookHopperPushingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_SrcSlotNum, cBlockEntityWithItems & a_DstEntity, int a_DstSlotNum); bool CallHookKilling (cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI); - bool CallHookLogin (cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username); + bool CallHookLogin (cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username); bool CallHookPlayerAnimation (cPlayer & a_Player, int a_Animation); bool CallHookPlayerBreakingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); bool CallHookPlayerBrokenBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); @@ -222,8 +222,8 @@ public: bool CallHookPlayerUsingItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ); bool CallHookPluginMessage (cClientHandle & a_Client, const AString & a_Channel, const AString & a_Message); 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 CallHookPostCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe); + bool CallHookPreCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe); bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Face, const Vector3d & a_BlockHitPos); bool CallHookProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity); bool CallHookServerPing (cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon); @@ -232,8 +232,8 @@ public: bool CallHookSpawningEntity (cWorld & a_World, cEntity & a_Entity); bool CallHookSpawningMonster (cWorld & a_World, cMonster & a_Monster); bool CallHookTakeDamage (cEntity & a_Receiver, TakeDamageInfo & a_TDI); - bool CallHookUpdatedSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player); - bool CallHookUpdatingSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player); + bool CallHookUpdatedSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player); + bool CallHookUpdatingSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player); bool CallHookWeatherChanged (cWorld & a_World); bool CallHookWeatherChanging (cWorld & a_World, eWeather & a_NewWeather); bool CallHookWorldStarted (cWorld & a_World); @@ -264,10 +264,10 @@ public: AString GetCommandPermission(const AString & a_Command); // tolua_export /** Executes the command, as if it was requested by a_Player. Checks permissions first. Returns crExecuted if executed. */ - CommandResult ExecuteCommand(cPlayer * a_Player, const AString & a_Command); // tolua_export + CommandResult ExecuteCommand(cPlayer & a_Player, const AString & a_Command); // tolua_export /** Executes the command, as if it was requested by a_Player. Permisssions are not checked. Returns crExecuted if executed. */ - CommandResult ForceExecuteCommand(cPlayer * a_Player, const AString & a_Command); // tolua_export + CommandResult ForceExecuteCommand(cPlayer & a_Player, const AString & a_Command); // tolua_export /** Removes all console command bindings that the specified plugin has made */ void RemovePluginConsoleCommands(cPlugin * a_Plugin); @@ -341,7 +341,7 @@ private: bool AddPlugin(cPlugin * a_Plugin); /** Tries to match a_Command to the internal table of commands, if a match is found, the corresponding plugin is called. Returns crExecuted if the command is executed. */ - cPluginManager::CommandResult HandleCommand(cPlayer * a_Player, const AString & a_Command, bool a_ShouldCheckPermissions); + CommandResult HandleCommand(cPlayer & a_Player, const AString & a_Command, bool a_ShouldCheckPermissions); } ; // tolua_export diff --git a/src/BlockInServerPluginInterface.h b/src/BlockInServerPluginInterface.h index e82435364..70c9944a8 100644 --- a/src/BlockInServerPluginInterface.h +++ b/src/BlockInServerPluginInterface.h @@ -6,14 +6,30 @@ #include "Root.h" #include "Bindings/PluginManager.h" -class cBlockInServerPluginInterface : public cBlockPluginInterface + + + + +class cBlockInServerPluginInterface : + public cBlockPluginInterface { public: cBlockInServerPluginInterface(cWorld & a_World) : m_World(a_World) {} + + virtual bool CallHookBlockSpread(int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) + { + return cPluginManager::Get()->CallHookBlockSpread(m_World, a_BlockX, a_BlockY, a_BlockZ, a_Source); + } + virtual bool CallHookBlockToPickups(cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) override { - return cRoot::Get()->GetPluginManager()->CallHookBlockToPickups(&m_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups); + return cPluginManager::Get()->CallHookBlockToPickups(m_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups); } + private: cWorld & m_World; }; + + + + diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h index 19f889372..89dfc963d 100644 --- a/src/Blocks/BlockDirt.h +++ b/src/Blocks/BlockDirt.h @@ -89,7 +89,7 @@ public: Chunk->GetBlockTypeMeta(BlockX, BlockY + 1, BlockZ, AboveDest, AboveMeta); if (cBlockInfo::GetHandler(AboveDest)->CanDirtGrowGrass(AboveMeta)) { - if (!cRoot::Get()->GetPluginManager()->CallHookBlockSpread(Chunk->GetWorld(), Chunk->GetPosX() * cChunkDef::Width + BlockX, BlockY, Chunk->GetPosZ() * cChunkDef::Width + BlockZ, ssGrassSpread)) + if (!cRoot::Get()->GetPluginManager()->CallHookBlockSpread(*Chunk->GetWorld(), Chunk->GetPosX() * cChunkDef::Width + BlockX, BlockY, Chunk->GetPosZ() * cChunkDef::Width + BlockZ, ssGrassSpread)) { Chunk->FastSetBlock(BlockX, BlockY, BlockZ, E_BLOCK_GRASS, 0); } diff --git a/src/Blocks/BlockHandler.cpp b/src/Blocks/BlockHandler.cpp index 904e0a921..b6ef5dd6f 100644 --- a/src/Blocks/BlockHandler.cpp +++ b/src/Blocks/BlockHandler.cpp @@ -4,6 +4,7 @@ #include "../Item.h" #include "../World.h" #include "../Chunk.h" +#include "BlockPluginInterface.h" #include "BlockAnvil.h" #include "BlockBed.h" #include "BlockBigFlower.h" @@ -82,7 +83,6 @@ #include "BlockWorkbench.h" -#include "BlockPluginInterface.h" diff --git a/src/Blocks/BlockPluginInterface.h b/src/Blocks/BlockPluginInterface.h index 3a36c40b1..b769bcf3e 100644 --- a/src/Blocks/BlockPluginInterface.h +++ b/src/Blocks/BlockPluginInterface.h @@ -1,7 +1,11 @@ #pragma once -/** This interface is used to decouple block handlers from the cPluginManager dependancy through cWorld. + + + + +/** This interface is used to decouple block handlers from the cPluginManager dependency through cWorld. The block handlers call this interface, which is then implemented by the specific classes that the caller provides. */ @@ -10,5 +14,10 @@ class cBlockPluginInterface public: virtual ~cBlockPluginInterface() {} + virtual bool CallHookBlockSpread(int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0; virtual bool CallHookBlockToPickups(cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) = 0; }; + + + + diff --git a/src/Blocks/BlockVine.h b/src/Blocks/BlockVine.h index 06d84f2d4..213324cc1 100644 --- a/src/Blocks/BlockVine.h +++ b/src/Blocks/BlockVine.h @@ -166,23 +166,31 @@ public: return false; } + virtual void OnUpdate(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cBlockPluginInterface & a_BlockPluginInterface, cChunk & a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { UNUSED(a_ChunkInterface); UNUSED(a_WorldInterface); - UNUSED(a_BlockPluginInterface); + // Vine cannot grow down if at the bottom: + if (a_RelY < 1) + { + return; + } + + // Grow one block down, if possible: BLOCKTYPE Block; a_Chunk.UnboundedRelGetBlockType(a_RelX, a_RelY - 1, a_RelZ, Block); if (Block == E_BLOCK_AIR) { - if (!cRoot::Get()->GetPluginManager()->CallHookBlockSpread((cWorld*) &a_WorldInterface, a_RelX + a_Chunk.GetPosX() * cChunkDef::Width, a_RelY - 1, a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width, ssVineSpread)) + if (!a_BlockPluginInterface.CallHookBlockSpread(a_RelX + a_Chunk.GetPosX() * cChunkDef::Width, a_RelY - 1, a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width, ssVineSpread)) { a_Chunk.UnboundedRelSetBlock(a_RelX, a_RelY - 1, a_RelZ, E_BLOCK_VINES, a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ)); } } } + virtual NIBBLETYPE MetaRotateCCW(NIBBLETYPE a_Meta) override { return ((a_Meta >> 1) | (a_Meta << 3)) & 0x0f; // Rotate bits to the right diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 96b8eda4e..84da1fe12 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -119,7 +119,7 @@ cChunk::cChunk( cChunk::~cChunk() { - cPluginManager::Get()->CallHookChunkUnloaded(m_World, m_PosX, m_PosZ); + cPluginManager::Get()->CallHookChunkUnloaded(*m_World, m_PosX, m_PosZ); // LOGINFO("### delete cChunk() (%i, %i) from %p, thread 0x%x ###", m_PosX, m_PosZ, this, GetCurrentThreadId()); @@ -1750,11 +1750,11 @@ void cChunk::SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_Max -void cChunk::CollectPickupsByPlayer(cPlayer * a_Player) +void cChunk::CollectPickupsByPlayer(cPlayer & a_Player) { - double PosX = a_Player->GetPosX(); - double PosY = a_Player->GetPosY(); - double PosZ = a_Player->GetPosZ(); + double PosX = a_Player.GetPosX(); + double PosY = a_Player.GetPosY(); + double PosZ = a_Player.GetPosZ(); for (cEntityList::iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr) { diff --git a/src/Chunk.h b/src/Chunk.h index bc66b6528..42ec6f209 100644 --- a/src/Chunk.h +++ b/src/Chunk.h @@ -218,7 +218,7 @@ public: Sends the chunk to all relevant clients. */ void SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_MaxRelZ, EMCSBiome a_Biome); - void CollectPickupsByPlayer(cPlayer * a_Player); + void CollectPickupsByPlayer(cPlayer & a_Player); /** Sets the sign text. Returns true if successful. Also sends update packets to all clients in the chunk */ bool SetSignLines(int a_RelX, int a_RelY, int a_RelZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4); diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index 299fe0eca..6f56b23e0 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -954,7 +954,7 @@ void cChunkMap::SetChunkData(cSetChunkData & a_SetChunkData) } // Notify plugins of the chunk becoming available - cPluginManager::Get()->CallHookChunkAvailable(m_World, ChunkX, ChunkZ); + cPluginManager::Get()->CallHookChunkAvailable(*m_World, ChunkX, ChunkZ); } @@ -1145,11 +1145,11 @@ void cChunkMap::FastSetBlocks(sSetBlockList & a_BlockList) -void cChunkMap::CollectPickupsByPlayer(cPlayer * a_Player) +void cChunkMap::CollectPickupsByPlayer(cPlayer & a_Player) { - int BlockX = (int)(a_Player->GetPosX()); // Truncating doesn't matter much; we're scanning entire chunks anyway - int BlockY = (int)(a_Player->GetPosY()); - int BlockZ = (int)(a_Player->GetPosZ()); + int BlockX = (int)(a_Player.GetPosX()); // Truncating doesn't matter much; we're scanning entire chunks anyway + int BlockY = (int)(a_Player.GetPosY()); + int BlockZ = (int)(a_Player.GetPosZ()); int ChunkX = 0, ChunkZ = 0; cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); int OtherChunkX = ChunkX + ((BlockX > 8) ? 1 : -1); @@ -2973,7 +2973,7 @@ void cChunkMap::cChunkLayer::UnloadUnusedChunks(void) if ( (m_Chunks[i] != NULL) && // Is valid (m_Chunks[i]->CanUnload()) && // Can unload - !cPluginManager::Get()->CallHookChunkUnloading(m_Parent->GetWorld(), m_Chunks[i]->GetPosX(), m_Chunks[i]->GetPosZ()) // Plugins agree + !cPluginManager::Get()->CallHookChunkUnloading(*(m_Parent->GetWorld()), m_Chunks[i]->GetPosX(), m_Chunks[i]->GetPosZ()) // Plugins agree ) { // The cChunk destructor calls our GetChunk() while removing its entities @@ -2987,6 +2987,8 @@ void cChunkMap::cChunkLayer::UnloadUnusedChunks(void) + + void cChunkMap::FastSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { cCSLock Lock(m_CSFastSetBlock); diff --git a/src/ChunkMap.h b/src/ChunkMap.h index 6e92833f1..38e7f4052 100644 --- a/src/ChunkMap.h +++ b/src/ChunkMap.h @@ -144,7 +144,7 @@ public: void FastSetQueuedBlocks(); void FastSetBlocks (sSetBlockList & a_BlockList); - void CollectPickupsByPlayer(cPlayer * a_Player); + void CollectPickupsByPlayer(cPlayer & a_Player); BLOCKTYPE GetBlock (int a_BlockX, int a_BlockY, int a_BlockZ); NIBBLETYPE GetBlockMeta (int a_BlockX, int a_BlockY, int a_BlockZ); diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index b9adcc828..344b2f2c2 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -596,7 +596,7 @@ bool cClientHandle::HandleLogin(int a_ProtocolVersion, const AString & a_Usernam m_Username = a_Username; // Let the plugins know about this event, they may refuse the player: - if (cRoot::Get()->GetPluginManager()->CallHookLogin(this, a_ProtocolVersion, a_Username)) + if (cRoot::Get()->GetPluginManager()->CallHookLogin(*this, a_ProtocolVersion, a_Username)) { Destroy(); return false; @@ -1715,7 +1715,7 @@ void cClientHandle::HandleKeepAlive(int a_KeepAliveID) bool cClientHandle::HandleHandshake(const AString & a_Username) { - if (!cRoot::Get()->GetPluginManager()->CallHookHandshake(this, a_Username)) + if (!cRoot::Get()->GetPluginManager()->CallHookHandshake(*this, a_Username)) { if (cRoot::Get()->GetServer()->GetNumPlayers() >= cRoot::Get()->GetServer()->GetMaxPlayers()) { diff --git a/src/CraftingRecipes.cpp b/src/CraftingRecipes.cpp index ed3409207..0828a6c74 100644 --- a/src/CraftingRecipes.cpp +++ b/src/CraftingRecipes.cpp @@ -280,10 +280,10 @@ cCraftingRecipes::~cCraftingRecipes() -void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe) +void cCraftingRecipes::GetRecipe(cPlayer & a_Player, cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe) { // Allow plugins to intercept recipes using a pre-craft hook: - if (cRoot::Get()->GetPluginManager()->CallHookPreCrafting(a_Player, &a_CraftingGrid, &a_Recipe)) + if (cRoot::Get()->GetPluginManager()->CallHookPreCrafting(a_Player, a_CraftingGrid, a_Recipe)) { return; } @@ -294,7 +294,7 @@ void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & if (Recipe.get() == NULL) { // Allow plugins to intercept a no-recipe-found situation: - cRoot::Get()->GetPluginManager()->CallHookCraftingNoRecipe(a_Player, &a_CraftingGrid, &a_Recipe); + cRoot::Get()->GetPluginManager()->CallHookCraftingNoRecipe(a_Player, a_CraftingGrid, &a_Recipe); return; } for (cRecipeSlots::const_iterator itr = Recipe->m_Ingredients.begin(); itr != Recipe->m_Ingredients.end(); ++itr) @@ -304,7 +304,7 @@ void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & a_Recipe.SetResult(Recipe->m_Result); // Allow plugins to intercept recipes after they are processed: - cRoot::Get()->GetPluginManager()->CallHookPostCrafting(a_Player, &a_CraftingGrid, &a_Recipe); + cRoot::Get()->GetPluginManager()->CallHookPostCrafting(a_Player, a_CraftingGrid, a_Recipe); } diff --git a/src/CraftingRecipes.h b/src/CraftingRecipes.h index fe1e15817..5ebabe098 100644 --- a/src/CraftingRecipes.h +++ b/src/CraftingRecipes.h @@ -115,7 +115,7 @@ public: ~cCraftingRecipes(); /// Returns the recipe for current crafting grid. Doesn't modify the grid. Clears a_Recipe if no recipe found. - void GetRecipe(const cPlayer * a_Player, const cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe); + void GetRecipe(cPlayer & a_Player, cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe); protected: diff --git a/src/Entities/ArrowEntity.cpp b/src/Entities/ArrowEntity.cpp index c265c5043..7e429c62e 100644 --- a/src/Entities/ArrowEntity.cpp +++ b/src/Entities/ArrowEntity.cpp @@ -149,14 +149,14 @@ void cArrowEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) -void cArrowEntity::CollectedBy(cPlayer * a_Dest) +void cArrowEntity::CollectedBy(cPlayer & a_Dest) { - if (m_IsInGround && !m_bIsCollected && CanPickup(*a_Dest)) + if (m_IsInGround && !m_bIsCollected && CanPickup(a_Dest)) { // Do not add the arrow to the inventory when the player is in creative: - if (!a_Dest->IsGameModeCreative()) + if (!a_Dest.IsGameModeCreative()) { - int NumAdded = a_Dest->GetInventory().AddItem(E_ITEM_ARROW); + int NumAdded = a_Dest.GetInventory().AddItem(E_ITEM_ARROW); if (NumAdded == 0) { // No space in the inventory @@ -164,7 +164,7 @@ void cArrowEntity::CollectedBy(cPlayer * a_Dest) } } - GetWorld()->BroadcastCollectEntity(*this, *a_Dest); + GetWorld()->BroadcastCollectEntity(*this, a_Dest); GetWorld()->BroadcastSoundEffect("random.pop", GetPosX(), GetPosY(), GetPosZ(), 0.5, (float)(0.75 + ((float)((GetUniqueID() * 23) % 32)) / 64)); m_bIsCollected = true; } @@ -229,3 +229,7 @@ void cArrowEntity::Tick(float a_Dt, cChunk & a_Chunk) } } } + + + + diff --git a/src/Entities/ArrowEntity.h b/src/Entities/ArrowEntity.h index a1e7a17e7..1e4d8eebb 100644 --- a/src/Entities/ArrowEntity.h +++ b/src/Entities/ArrowEntity.h @@ -97,7 +97,7 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void CollectedBy(cPlayer * a_Player) override; + virtual void CollectedBy(cPlayer & a_Player) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; }; // tolua_export diff --git a/src/Entities/Pickup.cpp b/src/Entities/Pickup.cpp index 87b5bed07..e5e28446d 100644 --- a/src/Entities/Pickup.cpp +++ b/src/Entities/Pickup.cpp @@ -191,10 +191,8 @@ void cPickup::Tick(float a_Dt, cChunk & a_Chunk) -bool cPickup::CollectedBy(cPlayer * a_Dest) +bool cPickup::CollectedBy(cPlayer & a_Dest) { - ASSERT(a_Dest != NULL); - if (m_bCollected) { // LOG("Pickup %d cannot be collected by \"%s\", because it has already been collected.", m_UniqueID, a_Dest->GetName().c_str()); @@ -214,21 +212,21 @@ bool cPickup::CollectedBy(cPlayer * a_Dest) return false; } - int NumAdded = a_Dest->GetInventory().AddItem(m_Item); + int NumAdded = a_Dest.GetInventory().AddItem(m_Item); if (NumAdded > 0) { // Check achievements switch (m_Item.m_ItemType) { - case E_BLOCK_LOG: a_Dest->AwardAchievement(achMineWood); break; - case E_ITEM_LEATHER: a_Dest->AwardAchievement(achKillCow); break; - case E_ITEM_DIAMOND: a_Dest->AwardAchievement(achDiamonds); break; - case E_ITEM_BLAZE_ROD: a_Dest->AwardAchievement(achBlazeRod); break; + case E_BLOCK_LOG: a_Dest.AwardAchievement(achMineWood); break; + case E_ITEM_LEATHER: a_Dest.AwardAchievement(achKillCow); break; + case E_ITEM_DIAMOND: a_Dest.AwardAchievement(achDiamonds); break; + case E_ITEM_BLAZE_ROD: a_Dest.AwardAchievement(achBlazeRod); break; default: break; } m_Item.m_ItemCount -= NumAdded; - m_World->BroadcastCollectEntity(*this, *a_Dest); + m_World->BroadcastCollectEntity(*this, a_Dest); // Also send the "pop" sound effect with a somewhat random pitch (fast-random using EntityID ;) m_World->BroadcastSoundEffect("random.pop", GetPosX(), GetPosY(), GetPosZ(), 0.5, (float)(0.75 + ((float)((GetUniqueID() * 23) % 32)) / 64)); if (m_Item.m_ItemCount <= 0) diff --git a/src/Entities/Pickup.h b/src/Entities/Pickup.h index 4d5250819..b3cbeee0b 100644 --- a/src/Entities/Pickup.h +++ b/src/Entities/Pickup.h @@ -32,7 +32,7 @@ public: virtual void SpawnOn(cClientHandle & a_ClientHandle) override; - bool CollectedBy(cPlayer * a_Dest); // tolua_export + bool CollectedBy(cPlayer & a_Dest); // tolua_export virtual void Tick(float a_Dt, cChunk & a_Chunk) override; diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index f58a0a016..ecafe6341 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -245,7 +245,7 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk) if (m_Health > 0) // make sure player is alive { - m_World->CollectPickupsByPlayer(this); + m_World->CollectPickupsByPlayer(*this); if ((m_EatingFinishTick >= 0) && (m_EatingFinishTick <= m_World->GetWorldAge())) { diff --git a/src/Entities/ProjectileEntity.cpp b/src/Entities/ProjectileEntity.cpp index acc9bd674..ab25ac30c 100644 --- a/src/Entities/ProjectileEntity.cpp +++ b/src/Entities/ProjectileEntity.cpp @@ -424,8 +424,12 @@ void cProjectileEntity::SpawnOn(cClientHandle & a_Client) -void cProjectileEntity::CollectedBy(cPlayer * a_Dest) +void cProjectileEntity::CollectedBy(cPlayer & a_Dest) { // Overriden in arrow UNUSED(a_Dest); } + + + + diff --git a/src/Entities/ProjectileEntity.h b/src/Entities/ProjectileEntity.h index 990136a32..03eda9739 100644 --- a/src/Entities/ProjectileEntity.h +++ b/src/Entities/ProjectileEntity.h @@ -59,7 +59,7 @@ public: } /// Called by Chunk when the projectile is eligible for player collection - virtual void CollectedBy(cPlayer * a_Dest); + virtual void CollectedBy(cPlayer & a_Dest); // tolua_begin diff --git a/src/Server.cpp b/src/Server.cpp index 969ffd693..62f6ba35a 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -450,7 +450,7 @@ bool cServer::Start(void) bool cServer::Command(cClientHandle & a_Client, AString & a_Cmd) { - return cRoot::Get()->GetPluginManager()->CallHookChat(a_Client.GetPlayer(), a_Cmd); + return cRoot::Get()->GetPluginManager()->CallHookChat(*(a_Client.GetPlayer()), a_Cmd); } diff --git a/src/Simulator/FireSimulator.cpp b/src/Simulator/FireSimulator.cpp index 7ae84af7b..d3deee74a 100644 --- a/src/Simulator/FireSimulator.cpp +++ b/src/Simulator/FireSimulator.cpp @@ -333,7 +333,7 @@ void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int int a_PosX = x + a_Chunk->GetPosX() * cChunkDef::Width; int a_PosZ = z + a_Chunk->GetPosZ() * cChunkDef::Width; - if (cRoot::Get()->GetPluginManager()->CallHookBlockSpread(&m_World, a_PosX, y, a_PosZ, ssFireSpread)) + if (cRoot::Get()->GetPluginManager()->CallHookBlockSpread(m_World, a_PosX, y, a_PosZ, ssFireSpread)) { return; } @@ -382,7 +382,7 @@ void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_Rel } bool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance); - if (ShouldReplaceFuel && !cRoot::Get()->GetPluginManager()->CallHookBlockSpread(&m_World, AbsX, Y, AbsZ, ssFireSpread)) + if (ShouldReplaceFuel && !cRoot::Get()->GetPluginManager()->CallHookBlockSpread(m_World, AbsX, Y, AbsZ, ssFireSpread)) { Neighbour->SetBlock(X, Y, Z, E_BLOCK_FIRE, 0); } diff --git a/src/UI/SlotArea.cpp b/src/UI/SlotArea.cpp index 999bed989..88d9f44fc 100644 --- a/src/UI/SlotArea.cpp +++ b/src/UI/SlotArea.cpp @@ -714,7 +714,7 @@ void cSlotAreaCrafting::UpdateRecipe(cPlayer & a_Player) { cCraftingGrid Grid(GetPlayerSlots(a_Player) + 1, m_GridSize, m_GridSize); cCraftingRecipe & Recipe = GetRecipeForPlayer(a_Player); - cRoot::Get()->GetCraftingRecipes()->GetRecipe(&a_Player, Grid, Recipe); + cRoot::Get()->GetCraftingRecipes()->GetRecipe(a_Player, Grid, Recipe); SetSlot(0, a_Player, Recipe.GetResult()); m_ParentWindow.SendSlot(a_Player, this, 0); } @@ -736,7 +736,7 @@ cCraftingRecipe & cSlotAreaCrafting::GetRecipeForPlayer(cPlayer & a_Player) // Not found. Add a new one: cCraftingGrid Grid(GetPlayerSlots(a_Player) + 1, m_GridSize, m_GridSize); cCraftingRecipe Recipe(Grid); - cRoot::Get()->GetCraftingRecipes()->GetRecipe(&a_Player, Grid, Recipe); + cRoot::Get()->GetCraftingRecipes()->GetRecipe(a_Player, Grid, Recipe); m_Recipes.push_back(std::make_pair(a_Player.GetUniqueID(), Recipe)); return m_Recipes.back().second; } diff --git a/src/World.cpp b/src/World.cpp index 96afb8cc8..1f9361386 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -2607,7 +2607,7 @@ void cWorld::QueueUnloadUnusedChunks(void) -void cWorld::CollectPickupsByPlayer(cPlayer * a_Player) +void cWorld::CollectPickupsByPlayer(cPlayer & a_Player) { m_ChunkMap->CollectPickupsByPlayer(a_Player); } @@ -2909,13 +2909,13 @@ bool cWorld::SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AStrin AString Line2(a_Line2); AString Line3(a_Line3); AString Line4(a_Line4); - if (cRoot::Get()->GetPluginManager()->CallHookUpdatingSign(this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player)) + if (cRoot::Get()->GetPluginManager()->CallHookUpdatingSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player)) { return false; } if (m_ChunkMap->SetSignLines(a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4)) { - cRoot::Get()->GetPluginManager()->CallHookUpdatedSign(this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player); + cRoot::Get()->GetPluginManager()->CallHookUpdatedSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player); return true; } return false; @@ -3640,7 +3640,7 @@ bool cWorld::cChunkGeneratorCallbacks::HasChunkAnyClients(int a_ChunkX, int a_Ch void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerating(cChunkDesc & a_ChunkDesc) { cPluginManager::Get()->CallHookChunkGenerating( - m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc + *m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc ); } @@ -3651,7 +3651,7 @@ void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerating(cChunkDesc & a_Ch void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerated (cChunkDesc & a_ChunkDesc) { cPluginManager::Get()->CallHookChunkGenerated( - m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc + *m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc ); } diff --git a/src/World.h b/src/World.h index 640aa8bc3..bb43d7fba 100644 --- a/src/World.h +++ b/src/World.h @@ -298,7 +298,7 @@ public: /** Queues a task to unload unused chunks onto the tick thread. The prefferred way of unloading*/ void QueueUnloadUnusedChunks(void); // tolua_export - void CollectPickupsByPlayer(cPlayer * a_Player); + void CollectPickupsByPlayer(cPlayer & a_Player); /** Adds the player to the world. Uses a queue to store the player object until the Tick thread processes the addition event. -- cgit v1.2.3 From f58d44ea503c470558dbbaaf6c4e9a5aaac5718d Mon Sep 17 00:00:00 2001 From: Mattes D Date: Wed, 15 Oct 2014 18:50:32 +0200 Subject: cLuaState::Call() uses variadic templates. (doesn't compile) --- src/Bindings/LuaState.h | 78 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index ef87c3efc..b703959e0 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -240,10 +240,24 @@ public: /** Retrieve value at a_StackPos, if it is a valid cWorld class. If not, a_Value is unchanged */ void GetStackValue(int a_StackPos, pWorld & a_Value); + /** Call the specified Lua function. + Returns true if call succeeded, false if there was an error. + A special param of cRet & signifies the end of param list and the start of return values. + Example call: Call(Fn, Param1, Param2, Param3, cLuaState::Return, Ret1, Ret2) */ + template + bool Call(const FnT & a_Function, Args &... args) + { + PushFunction(a_Function); + return PushCallPop(args...); + } - // Include the cLuaState::Call() overload implementation that is generated by the gen_LuaState_Call.lua script: - #include "LuaState_Call.inc" - + /** Retrieves a list of values from the Lua stack, starting at the specified index. */ + template + inline void GetStackValues(int a_StartStackPos, T & a_Ret, Args &... args) + { + GetStackValue(a_StartStackPos, a_Ret); + GetStackValues(a_StartStackPos + 1, args...); + } /** Returns true if the specified parameters on the stack are of the specified usertable type; also logs warning if not. Used for static functions */ bool CheckParamUserTable(int a_StartParam, const char * a_UserTable, int a_EndParam = -1); @@ -310,6 +324,7 @@ public: static void LogStack(lua_State * a_LuaState, const char * a_Header = NULL); protected: + lua_State * m_LuaState; /** If true, the state is owned by this object and will be auto-Closed. False => attached state */ @@ -327,6 +342,63 @@ protected: int m_NumCurrentFunctionArgs; + /** Variadic template terminator: Counting zero args returns zero. */ + int CountArgs(void) + { + return 0; + } + + /** Variadic template: Counting args means add one to the count of the rest. */ + template + int CountArgs(T, Args... args) + { + return 1 + CountArgs(args...); + } + + /** Variadic template terminator: If there's nothing more to push / pop, just call the function. + Note that there are no return values either, because those are prefixed by a cRet value, so the arg list is never empty. */ + bool PushCallPop(void) + { + return CallFunction(0); + } + + /** Variadic template recursor: More params to push. Push them and recurse. */ + template + inline bool PushCallPop(T a_Param, Args &... args) + { + Push(a_Param); + return PushCallPop(args...); + } + + /** Variadic template terminator: If there's nothing more to push, but return values to collect, call the function and collect the returns. */ + template + bool PushCallPop(cLuaState::cRet, Args &... args) + { + // Calculate the number of return values (number of args left): + int NumReturns = CountArgs(args...); + + // Call the function: + if (!CallFunction(NumReturns)) + { + return false; + } + + // Collect the return values: + GetStackValues(-NumReturns, args...); + lua_pop(m_LuaState, NumReturns); + + // All successful: + return true; + } + + /** Variadic template terminator: If there are no more values to get, bail out. + This function is not available in the public API, because it's an error to request no values directly; only internal functions can do that. + If you get a compile error saying this function is not accessible, check your calling code, you aren't reading any stack values. */ + void GetStackValues(int a_StartingStackPos) + { + // Do nothing + } + /** Pushes the function of the specified name onto the stack. Returns true if successful. Logs a warning on failure (incl. m_SubsystemName) */ -- cgit v1.2.3 From 0bdd2768ffc88560de411b5224883e4f161519b4 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 19:46:43 +0200 Subject: Fixed possible crash It could crash if MinAmount - MaxAmount was 0 because it would execute (Number % 0) --- src/ItemGrid.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 6a3d08679..7ebc419cb 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -658,7 +658,14 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s if (LootRnd < 0) { CurrentLoot = a_LootProbabs[i].m_Item; - CurrentLoot.m_ItemCount = a_LootProbabs[i].m_MinAmount + (Rnd % (a_LootProbabs[i].m_MaxAmount - a_LootProbabs[i].m_MinAmount)); + if ((a_LootProbabs[i].m_MaxAmount - a_LootProbabs[i].m_MinAmount) > 0) + { + CurrentLoot.m_ItemCount = a_LootProbabs[i].m_MinAmount + (Rnd % (a_LootProbabs[i].m_MaxAmount - a_LootProbabs[i].m_MinAmount)); + } + else + { + CurrentLoot.m_ItemCount = a_LootProbabs[i].m_MinAmount; + } Rnd >>= 8; break; } -- cgit v1.2.3 From 08676128b0671612cd23c30b661b9908717f51c6 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 21:15:12 +0200 Subject: Added loot to dungeons. --- src/Generating/DungeonRoomsFinisher.cpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Generating/DungeonRoomsFinisher.cpp b/src/Generating/DungeonRoomsFinisher.cpp index f213455d6..de3a426a1 100644 --- a/src/Generating/DungeonRoomsFinisher.cpp +++ b/src/Generating/DungeonRoomsFinisher.cpp @@ -6,6 +6,7 @@ #include "Globals.h" #include "DungeonRoomsFinisher.h" #include "../FastRandom.h" +#include "../BlockEntities/ChestEntity.h" @@ -175,7 +176,32 @@ protected: } a_ChunkDesc.SetBlockTypeMeta(RelX, m_FloorHeight + 1, RelZ, E_BLOCK_CHEST, (NIBBLETYPE)a_Chest.y); - // TODO: Fill the chest with random loot + // Fill the chest with random loot + static const cLootProbab LootProbab[] = + { + // Item, MinAmount, MaxAmount, Weight + { cItem(E_ITEM_IRON), 1, 4, 10 }, + { cItem(E_ITEM_WHEAT), 1, 4, 10 }, + { cItem(E_ITEM_GUNPOWDER), 1, 4, 10 }, + { cItem(E_ITEM_STRING), 1, 4, 10 }, + { cItem(E_ITEM_REDSTONE_DUST), 1, 4, 10 }, + { cItem(E_ITEM_SADDLE), 1, 1, 10 }, + { cItem(E_ITEM_BUCKET), 1, 1, 10 }, + { cItem(E_ITEM_BREAD), 1, 1, 10 }, + { cItem(E_ITEM_NAME_TAG), 1, 1, 10 }, + { cItem(E_ITEM_IRON_HORSE_ARMOR), 1, 1, 5 }, + { cItem(E_ITEM_13_DISC), 1, 1, 4 }, + { cItem(E_ITEM_CAT_DISC), 1, 1, 4 }, + { cItem(E_ITEM_GOLD_HORSE_ARMOR), 1, 1, 2 }, + { cItem(E_ITEM_DIAMOND_HORSE_ARMOR), 1, 1, 1 }, + } ; + + cChestEntity * ChestEntity = (cChestEntity *)a_ChunkDesc.GetBlockEntity(RelX, m_FloorHeight + 1, RelZ); + ASSERT((ChestEntity != NULL) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); + cNoise Noise(a_ChunkDesc.GetChunkX() ^ a_ChunkDesc.GetChunkZ()); + int NumSlots = 3 + ((Noise.IntNoise3DInt(a_Chest.x, a_Chest.y, a_Chest.z) / 11) % 4); + int Seed = Noise.IntNoise2DInt(RelX, RelZ); + ChestEntity->GetContents().GenerateRandomLootWithBooks(LootProbab, ARRAYCOUNT(LootProbab), NumSlots, Seed); } -- cgit v1.2.3 From 3f0d4fe250288a97845bdc4ce8f4f20e00fee728 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Wed, 15 Oct 2014 22:10:14 +0200 Subject: Reversed the order of the loot For some reason the rare items weren't generating at all. Added forgotten Golden Apple --- src/Generating/DungeonRoomsFinisher.cpp | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/Generating/DungeonRoomsFinisher.cpp b/src/Generating/DungeonRoomsFinisher.cpp index de3a426a1..68c040fbe 100644 --- a/src/Generating/DungeonRoomsFinisher.cpp +++ b/src/Generating/DungeonRoomsFinisher.cpp @@ -180,6 +180,12 @@ protected: static const cLootProbab LootProbab[] = { // Item, MinAmount, MaxAmount, Weight + { cItem(E_ITEM_GOLDEN_APPLE), 1, 1, 1 }, + { cItem(E_ITEM_DIAMOND_HORSE_ARMOR), 1, 1, 1 }, + { cItem(E_ITEM_GOLD_HORSE_ARMOR), 1, 1, 2 }, + { cItem(E_ITEM_13_DISC), 1, 1, 4 }, + { cItem(E_ITEM_CAT_DISC), 1, 1, 4 }, + { cItem(E_ITEM_IRON_HORSE_ARMOR), 1, 1, 5 }, { cItem(E_ITEM_IRON), 1, 4, 10 }, { cItem(E_ITEM_WHEAT), 1, 4, 10 }, { cItem(E_ITEM_GUNPOWDER), 1, 4, 10 }, @@ -189,11 +195,6 @@ protected: { cItem(E_ITEM_BUCKET), 1, 1, 10 }, { cItem(E_ITEM_BREAD), 1, 1, 10 }, { cItem(E_ITEM_NAME_TAG), 1, 1, 10 }, - { cItem(E_ITEM_IRON_HORSE_ARMOR), 1, 1, 5 }, - { cItem(E_ITEM_13_DISC), 1, 1, 4 }, - { cItem(E_ITEM_CAT_DISC), 1, 1, 4 }, - { cItem(E_ITEM_GOLD_HORSE_ARMOR), 1, 1, 2 }, - { cItem(E_ITEM_DIAMOND_HORSE_ARMOR), 1, 1, 1 }, } ; cChestEntity * ChestEntity = (cChestEntity *)a_ChunkDesc.GetBlockEntity(RelX, m_FloorHeight + 1, RelZ); @@ -209,6 +210,9 @@ protected: // cGridStructGen::cStructure override: virtual void DrawIntoChunk(cChunkDesc & a_ChunkDesc) override { + int CenterX = (m_StartX + m_EndX) / 2 - a_ChunkDesc.GetChunkX() * cChunkDef::Width; + int CenterZ = (m_StartZ + m_EndZ) / 2 - a_ChunkDesc.GetChunkZ() * cChunkDef::Width; + if ( (m_EndX < a_ChunkDesc.GetChunkX() * cChunkDef::Width) || (m_StartX >= a_ChunkDesc.GetChunkX() * cChunkDef::Width + cChunkDef::Width) || @@ -219,6 +223,12 @@ protected: // The chunk is not intersecting the room at all, bail out return; } + + if (!cBlockInfo::CanBeTerraformed(a_ChunkDesc.GetBlockType(CenterX, m_FloorHeight + 1, CenterZ))) + { + return; + } + int b = m_FloorHeight + 1; // Bottom int t = m_FloorHeight + 1 + ROOM_HEIGHT; // Top ReplaceCuboidRandom(a_ChunkDesc, m_StartX, m_FloorHeight, m_StartZ, m_EndX + 1, b, m_EndZ + 1, E_BLOCK_MOSSY_COBBLESTONE, E_BLOCK_COBBLESTONE); // Floor @@ -235,8 +245,6 @@ protected: TryPlaceChest(a_ChunkDesc, m_Chest2); // Place the spawner: - int CenterX = (m_StartX + m_EndX) / 2 - a_ChunkDesc.GetChunkX() * cChunkDef::Width; - int CenterZ = (m_StartZ + m_EndZ) / 2 - a_ChunkDesc.GetChunkZ() * cChunkDef::Width; if ( (CenterX >= 0) && (CenterX < cChunkDef::Width) && (CenterZ >= 0) && (CenterZ < cChunkDef::Width) -- cgit v1.2.3 From 5ed6d280ce5d199f8b319429e281c0ed48b82af8 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Thu, 16 Oct 2014 10:26:17 +0200 Subject: Reversed wrong fix for #1517. --- src/Generating/DungeonRoomsFinisher.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Generating/DungeonRoomsFinisher.cpp b/src/Generating/DungeonRoomsFinisher.cpp index 68c040fbe..492bae129 100644 --- a/src/Generating/DungeonRoomsFinisher.cpp +++ b/src/Generating/DungeonRoomsFinisher.cpp @@ -210,9 +210,6 @@ protected: // cGridStructGen::cStructure override: virtual void DrawIntoChunk(cChunkDesc & a_ChunkDesc) override { - int CenterX = (m_StartX + m_EndX) / 2 - a_ChunkDesc.GetChunkX() * cChunkDef::Width; - int CenterZ = (m_StartZ + m_EndZ) / 2 - a_ChunkDesc.GetChunkZ() * cChunkDef::Width; - if ( (m_EndX < a_ChunkDesc.GetChunkX() * cChunkDef::Width) || (m_StartX >= a_ChunkDesc.GetChunkX() * cChunkDef::Width + cChunkDef::Width) || @@ -224,11 +221,6 @@ protected: return; } - if (!cBlockInfo::CanBeTerraformed(a_ChunkDesc.GetBlockType(CenterX, m_FloorHeight + 1, CenterZ))) - { - return; - } - int b = m_FloorHeight + 1; // Bottom int t = m_FloorHeight + 1 + ROOM_HEIGHT; // Top ReplaceCuboidRandom(a_ChunkDesc, m_StartX, m_FloorHeight, m_StartZ, m_EndX + 1, b, m_EndZ + 1, E_BLOCK_MOSSY_COBBLESTONE, E_BLOCK_COBBLESTONE); // Floor @@ -245,6 +237,8 @@ protected: TryPlaceChest(a_ChunkDesc, m_Chest2); // Place the spawner: + int CenterX = (m_StartX + m_EndX) / 2 - a_ChunkDesc.GetChunkX() * cChunkDef::Width; + int CenterZ = (m_StartZ + m_EndZ) / 2 - a_ChunkDesc.GetChunkZ() * cChunkDef::Width; if ( (CenterX >= 0) && (CenterX < cChunkDef::Width) && (CenterZ >= 0) && (CenterZ < cChunkDef::Width) -- cgit v1.2.3 From 799ae87d3fe17e37462cf26f902fdc3565e4b562 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 16 Oct 2014 11:00:15 +0200 Subject: BioGen: Fixed a compiler warning. --- src/Generating/BioGen.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 8924a7999..9b3d4e98d 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -760,8 +760,8 @@ void cBioGenTwoLevel::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap int DistortZ[cChunkDef::Width + 1][cChunkDef::Width + 1]; for (int x = 0; x <= 4; x++) for (int z = 0; z <= 4; z++) { - float BlockX = BaseX + x * 4; - float BlockZ = BaseZ + z * 4; + float BlockX = static_cast(BaseX + x * 4); + float BlockZ = static_cast(BaseZ + z * 4); double NoiseX = m_AmpX1 * m_Noise1.CubicNoise2D(BlockX * m_FreqX1, BlockZ * m_FreqX1); NoiseX += m_AmpX2 * m_Noise2.CubicNoise2D(BlockX * m_FreqX2, BlockZ * m_FreqX2); NoiseX += m_AmpX3 * m_Noise3.CubicNoise2D(BlockX * m_FreqX3, BlockZ * m_FreqX3); -- cgit v1.2.3 From 07b5ce0c54422d511b5030728b4d09e40338a866 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Thu, 16 Oct 2014 11:17:39 +0200 Subject: Changed i variable to j The server wasn't going over all the items before. --- src/ItemGrid.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 6a3d08679..0bd44bb0d 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -654,11 +654,18 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s for (size_t j = 0; j < a_CountLootProbabs; j++) { - LootRnd -= a_LootProbabs[i].m_Weight; + LootRnd -= a_LootProbabs[j].m_Weight; if (LootRnd < 0) { - CurrentLoot = a_LootProbabs[i].m_Item; - CurrentLoot.m_ItemCount = a_LootProbabs[i].m_MinAmount + (Rnd % (a_LootProbabs[i].m_MaxAmount - a_LootProbabs[i].m_MinAmount)); + CurrentLoot = a_LootProbabs[j].m_Item; + if ((a_LootProbabs[j].m_MaxAmount - a_LootProbabs[j].m_MinAmount) > 0) + { + CurrentLoot.m_ItemCount = a_LootProbabs[j].m_MinAmount + (Rnd % (a_LootProbabs[j].m_MaxAmount - a_LootProbabs[j].m_MinAmount)); + } + else + { + CurrentLoot.m_ItemCount = a_LootProbabs[j].m_MinAmount; + } Rnd >>= 8; break; } -- cgit v1.2.3 From 25ebedbe454c99d2f521e277202be76e6f45aee1 Mon Sep 17 00:00:00 2001 From: worktycho Date: Thu, 16 Oct 2014 15:11:35 +0100 Subject: Use universal references --- src/Bindings/LuaState.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index b703959e0..779760017 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -245,7 +245,7 @@ public: A special param of cRet & signifies the end of param list and the start of return values. Example call: Call(Fn, Param1, Param2, Param3, cLuaState::Return, Ret1, Ret2) */ template - bool Call(const FnT & a_Function, Args &... args) + bool Call(const FnT & a_Function, Args &&... args) { PushFunction(a_Function); return PushCallPop(args...); @@ -253,7 +253,7 @@ public: /** Retrieves a list of values from the Lua stack, starting at the specified index. */ template - inline void GetStackValues(int a_StartStackPos, T & a_Ret, Args &... args) + inline void GetStackValues(int a_StartStackPos, T & a_Ret, Args &&... args) { GetStackValue(a_StartStackPos, a_Ret); GetStackValues(a_StartStackPos + 1, args...); @@ -364,7 +364,7 @@ protected: /** Variadic template recursor: More params to push. Push them and recurse. */ template - inline bool PushCallPop(T a_Param, Args &... args) + inline bool PushCallPop(T a_Param, Args &&... args) { Push(a_Param); return PushCallPop(args...); @@ -372,7 +372,7 @@ protected: /** Variadic template terminator: If there's nothing more to push, but return values to collect, call the function and collect the returns. */ template - bool PushCallPop(cLuaState::cRet, Args &... args) + bool PushCallPop(cLuaState::cRet, Args &&... args) { // Calculate the number of return values (number of args left): int NumReturns = CountArgs(args...); -- cgit v1.2.3 From 818c7948b7be466c22152ef8d64b3d0d985ac45c Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Thu, 16 Oct 2014 19:08:22 +0100 Subject: Fixed a number of stylistic issues. --- src/BlockEntities/FurnaceEntity.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index 222b27637..e94ebf24d 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -5,7 +5,7 @@ #include "../UI/Window.h" #include "../Entities/Player.h" #include "../Root.h" -#include "Chunk.h" +#include "../Chunk.h" @@ -27,12 +27,12 @@ cFurnaceEntity::cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY super(E_BLOCK_FURNACE, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), m_BlockMeta(a_BlockMeta), m_CurrentRecipe(NULL), + m_IsDestroyed(false), m_IsCooking((a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ) == E_BLOCK_LIT_FURNACE)), m_NeedCookTime(0), m_TimeCooked(0), m_FuelBurnTime(0), - m_TimeBurned(0), - m_IsDestroyed(false) + m_TimeBurned(0) { m_Contents.AddListener(*this); } @@ -221,8 +221,8 @@ void cFurnaceEntity::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) ASSERT(a_ItemGrid == &m_Contents); switch (a_SlotNum) { - case fsInput: UpdateInput(); break; - case fsFuel: UpdateFuel(); break; + case fsInput: UpdateInput(); break; + case fsFuel: UpdateFuel(); break; case fsOutput: UpdateOutput(); break; default: ASSERT(!"Invalid furnace slot update!"); break; } @@ -347,11 +347,11 @@ void cFurnaceEntity::UpdateProgressBars(bool a_ForceUpdate) } int CurFuel = (m_FuelBurnTime > 0) ? 200 - (200 * m_TimeBurned / m_FuelBurnTime) : 0; - BroadcastProgress(PROGRESSBAR_FUEL, (short)CurFuel); + BroadcastProgress(PROGRESSBAR_FUEL, static_cast(CurFuel)); int CurCook = (m_NeedCookTime > 0) ? (200 * m_TimeCooked / m_NeedCookTime) : 0; BroadcastProgress(PROGRESSBAR_SMELTING_CONFIRM, 200); // Post 1.8, Mojang requires a random packet with an ID of three and value of 200. Wat. Wat. Wat. - BroadcastProgress(PROGRESSBAR_SMELTING, (short)CurCook); + BroadcastProgress(PROGRESSBAR_SMELTING, static_cast(CurCook)); } -- cgit v1.2.3 From 8c2a99711e98ccfc2f6f31777a8b4e74e40c616c Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 16 Oct 2014 21:12:26 +0200 Subject: Merged branch 'fix_chunks'. --- src/ClientHandle.cpp | 37 ++++++++++++++++++++++++++++++++++--- src/ClientHandle.h | 1 + 2 files changed, 35 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 344b2f2c2..f244e8fea 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -540,9 +540,11 @@ void cClientHandle::RemoveFromAllChunks() } { + // Reset all chunk lists: cCSLock Lock(m_CSChunkLists); m_LoadedChunks.clear(); m_ChunksToSend.clear(); + m_SentChunks.clear(); // Also reset the LastStreamedChunk coords to bogus coords, // so that all chunks are streamed in subsequent StreamChunks() call (FS #407) @@ -2027,7 +2029,17 @@ void cClientHandle::SendBlockBreakAnim(int a_EntityID, int a_BlockX, int a_Block void cClientHandle::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { - m_Protocol->SendBlockChange(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); + int ChunkX, ChunkZ = 0; + cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); + cChunkCoords ChunkCoords = cChunkCoords(ChunkX, ChunkZ); + + // Do not send block changes in chunks that weren't sent to the client yet: + cCSLock Lock(m_CSChunkLists); + if (std::find(m_SentChunks.begin(), m_SentChunks.end(), ChunkCoords) != m_SentChunks.end()) + { + Lock.Unlock(); + m_Protocol->SendBlockChange(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); + } } @@ -2037,8 +2049,15 @@ void cClientHandle::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BL void cClientHandle::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSetBlockVector & a_Changes) { ASSERT(!a_Changes.empty()); // We don't want to be sending empty change packets! - - m_Protocol->SendBlockChanges(a_ChunkX, a_ChunkZ, a_Changes); + + // Do not send block changes in chunks that weren't sent to the client yet: + cChunkCoords ChunkCoords = cChunkCoords(a_ChunkX, a_ChunkZ); + cCSLock Lock(m_CSChunkLists); + if (std::find(m_SentChunks.begin(), m_SentChunks.end(), ChunkCoords) != m_SentChunks.end()) + { + Lock.Unlock(); + m_Protocol->SendBlockChanges(a_ChunkX, a_ChunkZ, a_Changes); + } } @@ -2102,6 +2121,12 @@ void cClientHandle::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializ m_Protocol->SendChunkData(a_ChunkX, a_ChunkZ, a_Serializer); + // Add the chunk to the list of chunks sent to the player: + { + cCSLock Lock(m_CSChunkLists); + m_SentChunks.push_back(cChunkCoords(a_ChunkX, a_ChunkZ)); + } + // If it is the chunk the player's in, make them spawn (in the tick thread): if ((m_State == csAuthenticated) || (m_State == csDownloadingWorld)) { @@ -2631,6 +2656,12 @@ void cClientHandle::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_D void cClientHandle::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) { + // Remove the chunk from the list of chunks sent to the client: + { + cCSLock Lock(m_CSChunkLists); + m_SentChunks.remove(cChunkCoords(a_ChunkX, a_ChunkZ)); + } + m_Protocol->SendUnloadChunk(a_ChunkX, a_ChunkZ); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index a9cc29d50..1fc915280 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -343,6 +343,7 @@ private: cCriticalSection m_CSChunkLists; cChunkCoordsList m_LoadedChunks; // Chunks that the player belongs to cChunkCoordsList m_ChunksToSend; // Chunks that need to be sent to the player (queued because they weren't generated yet or there's not enough time to send them) + cChunkCoordsList m_SentChunks; // Store the coordinates of the chunks that the client has loaded cProtocol * m_Protocol; -- cgit v1.2.3 From 59902c28f2aa43a2f86aa1834b36f538ff4b85f0 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Thu, 16 Oct 2014 20:21:33 +0100 Subject: Nullptr? --- src/BlockEntities/FurnaceEntity.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index e94ebf24d..38c251d2c 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -58,13 +58,13 @@ cFurnaceEntity::~cFurnaceEntity() void cFurnaceEntity::UsedBy(cPlayer * a_Player) { cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenWindow(new cFurnaceWindow(m_PosX, m_PosY, m_PosZ, this)); Window = GetWindow(); } - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { -- cgit v1.2.3 From 803666d480317376cf8f6e964ef4996567dea59f Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 17 Oct 2014 13:17:56 +0200 Subject: LuaChunkStay: Fixed a crash on unused callback. --- src/Bindings/LuaChunkStay.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaChunkStay.cpp b/src/Bindings/LuaChunkStay.cpp index a3d3a8090..23da12f68 100644 --- a/src/Bindings/LuaChunkStay.cpp +++ b/src/Bindings/LuaChunkStay.cpp @@ -130,8 +130,11 @@ void cLuaChunkStay::Enable(cChunkMap & a_ChunkMap, int a_OnChunkAvailableStackPo void cLuaChunkStay::OnChunkAvailable(int a_ChunkX, int a_ChunkZ) { - cPluginLua::cOperation Op(m_Plugin); - Op().Call((int)m_OnChunkAvailable, a_ChunkX, a_ChunkZ); + if (m_OnChunkAvailable.IsValid()) + { + cPluginLua::cOperation Op(m_Plugin); + Op().Call((int)m_OnChunkAvailable, a_ChunkX, a_ChunkZ); + } } @@ -140,6 +143,7 @@ void cLuaChunkStay::OnChunkAvailable(int a_ChunkX, int a_ChunkZ) bool cLuaChunkStay::OnAllChunksAvailable(void) { + if (m_OnAllChunksAvailable.IsValid()) { // Call the callback: cPluginLua::cOperation Op(m_Plugin); -- cgit v1.2.3 From 687752241f97599c932ab30da449d7b9dec632c4 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 17 Oct 2014 13:57:18 +0200 Subject: cMojangAPI: Don't update data if server is in offline mode. --- src/Protocol/MojangAPI.cpp | 7 +++++-- src/Protocol/MojangAPI.h | 2 +- src/Root.cpp | 5 +++-- src/Server.cpp | 4 ++-- src/Server.h | 2 +- 5 files changed, 12 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp index 0a6716e6f..a4b4dbd3b 100644 --- a/src/Protocol/MojangAPI.cpp +++ b/src/Protocol/MojangAPI.cpp @@ -214,14 +214,17 @@ cMojangAPI::~cMojangAPI() -void cMojangAPI::Start(cIniFile & a_SettingsIni) +void cMojangAPI::Start(cIniFile & a_SettingsIni, bool a_ShouldAuth) { m_NameToUUIDServer = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDServer", DEFAULT_NAME_TO_UUID_SERVER); m_NameToUUIDAddress = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDAddress", DEFAULT_NAME_TO_UUID_ADDRESS); m_UUIDToProfileServer = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileServer", DEFAULT_UUID_TO_PROFILE_SERVER); m_UUIDToProfileAddress = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileAddress", DEFAULT_UUID_TO_PROFILE_ADDRESS); LoadCachesFromDisk(); - m_UpdateThread->Start(); + if (a_ShouldAuth) + { + m_UpdateThread->Start(); + } } diff --git a/src/Protocol/MojangAPI.h b/src/Protocol/MojangAPI.h index fa4c16e4e..393fd4baa 100644 --- a/src/Protocol/MojangAPI.h +++ b/src/Protocol/MojangAPI.h @@ -38,7 +38,7 @@ public: /** Initializes the API; reads the settings from the specified ini file. Loads cached results from disk. */ - void Start(cIniFile & a_SettingsIni); + void Start(cIniFile & a_SettingsIni, bool a_ShouldAuth); /** Connects to the specified server using SSL, sends the given request and receives the response. Checks Mojang certificates using the hard-coded Starfield root CA certificate. diff --git a/src/Root.cpp b/src/Root.cpp index aa3d43cba..2d08c2c70 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -142,8 +142,9 @@ void cRoot::Start(void) } LOG("Starting server..."); - m_MojangAPI.Start(IniFile); // Mojang API needs to be started before plugins, so that plugins may use it for DB upgrades on server init - if (!m_Server->InitServer(IniFile)) + bool ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true); + m_MojangAPI.Start(IniFile, ShouldAuthenticate); // Mojang API needs to be started before plugins, so that plugins may use it for DB upgrades on server init + if (!m_Server->InitServer(IniFile, ShouldAuthenticate)) { IniFile.WriteFile("settings.ini"); LOGERROR("Failure starting server, aborting..."); diff --git a/src/Server.cpp b/src/Server.cpp index 62f6ba35a..8e5755a75 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -196,7 +196,7 @@ void cServer::PlayerDestroying(const cPlayer * a_Player) -bool cServer::InitServer(cIniFile & a_SettingsIni) +bool cServer::InitServer(cIniFile & a_SettingsIni, bool a_ShouldAuth) { m_Description = a_SettingsIni.GetValueSet("Server", "Description", "MCServer - in C++!"); m_MaxPlayers = a_SettingsIni.GetValueSetI("Server", "MaxPlayers", 100); @@ -247,7 +247,7 @@ bool cServer::InitServer(cIniFile & a_SettingsIni) m_bIsConnected = true; m_ServerID = "-"; - m_ShouldAuthenticate = a_SettingsIni.GetValueSetB("Authentication", "Authenticate", true); + m_ShouldAuthenticate = a_ShouldAuth; if (m_ShouldAuthenticate) { MTRand mtrand1; diff --git a/src/Server.h b/src/Server.h index 6d659fa40..022794bbc 100644 --- a/src/Server.h +++ b/src/Server.h @@ -56,7 +56,7 @@ class cServer // tolua_export public: // tolua_export virtual ~cServer() {} - bool InitServer(cIniFile & a_SettingsIni); + bool InitServer(cIniFile & a_SettingsIni, bool a_ShouldAuth); // tolua_begin -- cgit v1.2.3 From f280c36f9d2e8ca0aabf5395d50f2982d39806a5 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Sat, 18 Oct 2014 16:12:12 +0100 Subject: Simpler code. --- src/BlockEntities/FurnaceEntity.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index 38c251d2c..898d348de 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -96,9 +96,8 @@ bool cFurnaceEntity::Tick(float a_Dt, cChunk & a_Chunk) if (m_FuelBurnTime <= 0) { - // Cooked time decreases twice as fast when ran out of fuel - m_TimeCooked -= 2; - m_TimeCooked = std::max(m_TimeCooked, 0); + // If a furnace is out of fuel, the progress bar reverses at twice the speed of cooking. + m_TimeCooked = std::max((m_TimeCooked - 2), 0); // Reset progressbars, block type, and bail out a_Chunk.FastSetBlock(GetRelX(), m_PosY, GetRelZ(), E_BLOCK_FURNACE, m_BlockMeta); -- cgit v1.2.3 From 6a22b63473d465027b8d328d2ab621c596d1ee84 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sat, 18 Oct 2014 19:54:34 +0100 Subject: Furnaces now update their block entity type Therefore improving cChunk's variable boundary checking. --- src/BlockEntities/FurnaceEntity.cpp | 6 ++++-- src/Chunk.cpp | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index 898d348de..284ac7de9 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -24,11 +24,11 @@ enum cFurnaceEntity::cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cWorld * a_World) : - super(E_BLOCK_FURNACE, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), + super(a_BlockType, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), m_BlockMeta(a_BlockMeta), m_CurrentRecipe(NULL), m_IsDestroyed(false), - m_IsCooking((a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ) == E_BLOCK_LIT_FURNACE)), + m_IsCooking(a_BlockType == E_BLOCK_LIT_FURNACE), m_NeedCookTime(0), m_TimeCooked(0), m_FuelBurnTime(0), @@ -100,6 +100,7 @@ bool cFurnaceEntity::Tick(float a_Dt, cChunk & a_Chunk) m_TimeCooked = std::max((m_TimeCooked - 2), 0); // Reset progressbars, block type, and bail out + m_BlockType = E_BLOCK_FURNACE; a_Chunk.FastSetBlock(GetRelX(), m_PosY, GetRelZ(), E_BLOCK_FURNACE, m_BlockMeta); UpdateProgressBars(); return false; @@ -368,6 +369,7 @@ void cFurnaceEntity::SetIsCooking(bool a_IsCooking) // Only light the furnace as it is extinguished only when the fuel runs out, not when cooking stops - handled in this::Tick() if (m_IsCooking) { + m_BlockType = E_BLOCK_LIT_FURNACE; m_World->FastSetBlock(m_PosX, m_PosY, m_PosZ, E_BLOCK_LIT_FURNACE, m_BlockMeta); } } diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 88ee9ba31..98c8bc66a 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -333,7 +333,7 @@ void cChunk::SetAllData(cSetChunkData & a_SetChunkData) { BLOCKTYPE EntityBlockType = (*itr)->GetBlockType(); BLOCKTYPE WorldBlockType = GetBlock((*itr)->GetRelX(), (*itr)->GetPosY(), (*itr)->GetRelZ()); - ASSERT((EntityBlockType == E_BLOCK_FURNACE) ? ((EntityBlockType == E_BLOCK_FURNACE) || (EntityBlockType == E_BLOCK_LIT_FURNACE)) : (WorldBlockType == EntityBlockType)); + ASSERT(WorldBlockType == EntityBlockType); } // for itr - m_BlockEntities #endif // _DEBUG -- cgit v1.2.3 From eb821ff240fabab6666705bd767e334c5220027a Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Sat, 18 Oct 2014 19:55:01 +0100 Subject: Fixed failure for cRankManager to restart --- src/Bindings/ManualBindings_RankManager.cpp | 68 ++++++++++++++--------------- src/Entities/Player.cpp | 12 ++--- src/Root.cpp | 3 +- src/Root.h | 4 +- 4 files changed, 44 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/Bindings/ManualBindings_RankManager.cpp b/src/Bindings/ManualBindings_RankManager.cpp index 3c58a0a92..66174bf86 100644 --- a/src/Bindings/ManualBindings_RankManager.cpp +++ b/src/Bindings/ManualBindings_RankManager.cpp @@ -34,7 +34,7 @@ static int tolua_cRankManager_AddGroup(lua_State * L) S.GetStackValue(2, GroupName); // Add the group: - cRoot::Get()->GetRankManager().AddGroup(GroupName); + cRoot::Get()->GetRankManager()->AddGroup(GroupName); return 0; } @@ -63,7 +63,7 @@ static int tolua_cRankManager_AddGroupToRank(lua_State * L) S.GetStackValues(2, GroupName, RankName); // Add the group to the rank: - S.Push(cRoot::Get()->GetRankManager().AddGroupToRank(GroupName, RankName)); + S.Push(cRoot::Get()->GetRankManager()->AddGroupToRank(GroupName, RankName)); return 1; } @@ -92,7 +92,7 @@ static int tolua_cRankManager_AddPermissionToGroup(lua_State * L) S.GetStackValues(2, Permission, GroupName); // Add the group to the rank: - S.Push(cRoot::Get()->GetRankManager().AddPermissionToGroup(Permission, GroupName)); + S.Push(cRoot::Get()->GetRankManager()->AddPermissionToGroup(Permission, GroupName)); return 1; } @@ -121,7 +121,7 @@ static int tolua_cRankManager_AddRank(lua_State * L) S.GetStackValues(2, RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); // Add the rank: - cRoot::Get()->GetRankManager().AddRank(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); + cRoot::Get()->GetRankManager()->AddRank(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); return 0; } @@ -142,7 +142,7 @@ static int tolua_cRankManager_ClearPlayerRanks(lua_State * L) } // Remove all players: - cRoot::Get()->GetRankManager().ClearPlayerRanks(); + cRoot::Get()->GetRankManager()->ClearPlayerRanks(); return 1; } @@ -166,7 +166,7 @@ static int tolua_cRankManager_GetAllGroups(lua_State * L) } // Get the groups: - AStringVector Groups = cRoot::Get()->GetRankManager().GetAllGroups(); + AStringVector Groups = cRoot::Get()->GetRankManager()->GetAllGroups(); // Push the results: S.Push(Groups); @@ -193,7 +193,7 @@ static int tolua_cRankManager_GetAllPermissions(lua_State * L) } // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetAllPermissions(); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetAllPermissions(); // Push the results: S.Push(Permissions); @@ -220,7 +220,7 @@ static int tolua_cRankManager_GetAllPlayerUUIDs(lua_State * L) } // Get the player uuid's: - AStringVector Players = cRoot::Get()->GetRankManager().GetAllPlayerUUIDs(); + AStringVector Players = cRoot::Get()->GetRankManager()->GetAllPlayerUUIDs(); // Push the results: S.Push(Players); @@ -247,7 +247,7 @@ static int tolua_cRankManager_GetAllRanks(lua_State * L) } // Get the ranks: - AStringVector Ranks = cRoot::Get()->GetRankManager().GetAllRanks(); + AStringVector Ranks = cRoot::Get()->GetRankManager()->GetAllRanks(); // Push the results: S.Push(Ranks); @@ -274,7 +274,7 @@ static int tolua_cRankManager_GetDefaultRank(lua_State * L) } // Return the rank name: - S.Push(cRoot::Get()->GetRankManager().GetDefaultRank()); + S.Push(cRoot::Get()->GetRankManager()->GetDefaultRank()); return 1; } @@ -303,7 +303,7 @@ static int tolua_cRankManager_GetGroupPermissions(lua_State * L) S.GetStackValue(2, GroupName); // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetGroupPermissions(GroupName); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetGroupPermissions(GroupName); // Push the results: S.Push(Permissions); @@ -335,7 +335,7 @@ static int tolua_cRankManager_GetPlayerGroups(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the groups: - AStringVector Groups = cRoot::Get()->GetRankManager().GetPlayerGroups(PlayerUUID); + AStringVector Groups = cRoot::Get()->GetRankManager()->GetPlayerGroups(PlayerUUID); // Push the results: S.Push(Groups); @@ -368,7 +368,7 @@ static int tolua_cRankManager_GetPlayerMsgVisuals(lua_State * L) // Get the permissions: AString MsgPrefix, MsgSuffix, MsgNameColorCode; - if (!cRoot::Get()->GetRankManager().GetPlayerMsgVisuals(PlayerUUID, MsgPrefix, MsgSuffix, MsgNameColorCode)) + if (!cRoot::Get()->GetRankManager()->GetPlayerMsgVisuals(PlayerUUID, MsgPrefix, MsgSuffix, MsgNameColorCode)) { return 0; } @@ -405,7 +405,7 @@ static int tolua_cRankManager_GetPlayerPermissions(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetPlayerPermissions(PlayerUUID); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetPlayerPermissions(PlayerUUID); // Push the results: S.Push(Permissions); @@ -437,7 +437,7 @@ static int tolua_cRankManager_GetPlayerRankName(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the rank name: - AString RankName = cRoot::Get()->GetRankManager().GetPlayerRankName(PlayerUUID); + AString RankName = cRoot::Get()->GetRankManager()->GetPlayerRankName(PlayerUUID); // Push the result: S.Push(RankName); @@ -469,7 +469,7 @@ static int tolua_cRankManager_GetPlayerName(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the player name: - AString PlayerName = cRoot::Get()->GetRankManager().GetPlayerName(PlayerUUID); + AString PlayerName = cRoot::Get()->GetRankManager()->GetPlayerName(PlayerUUID); // Push the result: S.Push(PlayerName); @@ -501,7 +501,7 @@ static int tolua_cRankManager_GetRankGroups(lua_State * L) S.GetStackValue(2, RankName); // Get the groups: - AStringVector Groups = cRoot::Get()->GetRankManager().GetRankGroups(RankName); + AStringVector Groups = cRoot::Get()->GetRankManager()->GetRankGroups(RankName); // Push the results: S.Push(Groups); @@ -533,7 +533,7 @@ static int tolua_cRankManager_GetRankPermissions(lua_State * L) S.GetStackValue(2, RankName); // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetRankPermissions(RankName); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetRankPermissions(RankName); // Push the results: S.Push(Permissions); @@ -566,7 +566,7 @@ static int tolua_cRankManager_GetRankVisuals(lua_State * L) // Get the visuals: AString MsgPrefix, MsgSuffix, MsgNameColorCode; - if (!cRoot::Get()->GetRankManager().GetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode)) + if (!cRoot::Get()->GetRankManager()->GetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode)) { // No such rank, return nothing: return 0; @@ -604,7 +604,7 @@ static int tolua_cRankManager_GroupExists(lua_State * L) S.GetStackValue(2, GroupName); // Get the response: - bool res = cRoot::Get()->GetRankManager().GroupExists(GroupName); + bool res = cRoot::Get()->GetRankManager()->GroupExists(GroupName); // Push the result: S.Push(res); @@ -636,7 +636,7 @@ static int tolua_cRankManager_IsGroupInRank(lua_State * L) S.GetStackValues(2, GroupName, RankName); // Get the response: - bool res = cRoot::Get()->GetRankManager().IsGroupInRank(GroupName, RankName); + bool res = cRoot::Get()->GetRankManager()->IsGroupInRank(GroupName, RankName); // Push the result: S.Push(res); @@ -668,7 +668,7 @@ static int tolua_cRankManager_IsPermissionInGroup(lua_State * L) S.GetStackValues(2, Permission, GroupName); // Get the response: - bool res = cRoot::Get()->GetRankManager().IsPermissionInGroup(Permission, GroupName); + bool res = cRoot::Get()->GetRankManager()->IsPermissionInGroup(Permission, GroupName); // Push the result: S.Push(res); @@ -700,7 +700,7 @@ static int tolua_cRankManager_IsPlayerRankSet(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the response: - bool res = cRoot::Get()->GetRankManager().IsPlayerRankSet(PlayerUUID); + bool res = cRoot::Get()->GetRankManager()->IsPlayerRankSet(PlayerUUID); // Push the result: S.Push(res); @@ -732,7 +732,7 @@ static int tolua_cRankManager_RankExists(lua_State * L) S.GetStackValue(2, RankName); // Get the response: - bool res = cRoot::Get()->GetRankManager().RankExists(RankName); + bool res = cRoot::Get()->GetRankManager()->RankExists(RankName); // Push the result: S.Push(res); @@ -764,7 +764,7 @@ static int tolua_cRankManager_RemoveGroup(lua_State * L) S.GetStackValue(2, GroupName); // Remove the group: - cRoot::Get()->GetRankManager().RemoveGroup(GroupName); + cRoot::Get()->GetRankManager()->RemoveGroup(GroupName); return 0; } @@ -793,7 +793,7 @@ static int tolua_cRankManager_RemoveGroupFromRank(lua_State * L) S.GetStackValues(2, GroupName, RankName); // Remove the group: - cRoot::Get()->GetRankManager().RemoveGroupFromRank(GroupName, RankName); + cRoot::Get()->GetRankManager()->RemoveGroupFromRank(GroupName, RankName); return 0; } @@ -822,7 +822,7 @@ static int tolua_cRankManager_RemovePermissionFromGroup(lua_State * L) S.GetStackValues(2, Permission, GroupName); // Remove the group: - cRoot::Get()->GetRankManager().RemovePermissionFromGroup(Permission, GroupName); + cRoot::Get()->GetRankManager()->RemovePermissionFromGroup(Permission, GroupName); return 0; } @@ -851,7 +851,7 @@ static int tolua_cRankManager_RemovePlayerRank(lua_State * L) S.GetStackValue(2, PlayerUUID); // Remove the player's rank: - cRoot::Get()->GetRankManager().RemovePlayerRank(PlayerUUID); + cRoot::Get()->GetRankManager()->RemovePlayerRank(PlayerUUID); return 0; } @@ -881,7 +881,7 @@ static int tolua_cRankManager_RemoveRank(lua_State * L) S.GetStackValues(2, RankName, ReplacementRankName); // Remove the rank: - cRoot::Get()->GetRankManager().RemoveRank(RankName, ReplacementRankName); + cRoot::Get()->GetRankManager()->RemoveRank(RankName, ReplacementRankName); return 0; } @@ -910,7 +910,7 @@ static int tolua_cRankManager_RenameGroup(lua_State * L) S.GetStackValues(2, OldName, NewName); // Remove the group: - bool res = cRoot::Get()->GetRankManager().RenameGroup(OldName, NewName); + bool res = cRoot::Get()->GetRankManager()->RenameGroup(OldName, NewName); // Push the result: S.Push(res); @@ -942,7 +942,7 @@ static int tolua_cRankManager_RenameRank(lua_State * L) S.GetStackValues(2, OldName, NewName); // Remove the rank: - bool res = cRoot::Get()->GetRankManager().RenameRank(OldName, NewName); + bool res = cRoot::Get()->GetRankManager()->RenameRank(OldName, NewName); // Push the result: S.Push(res); @@ -974,7 +974,7 @@ static int tolua_cRankManager_SetDefaultRank(lua_State * L) S.GetStackValue(2, RankName); // Set the rank, return the result: - S.Push(cRoot::Get()->GetRankManager().SetDefaultRank(RankName)); + S.Push(cRoot::Get()->GetRankManager()->SetDefaultRank(RankName)); return 1; } @@ -1003,7 +1003,7 @@ static int tolua_cRankManager_SetPlayerRank(lua_State * L) S.GetStackValues(2, PlayerUUID, PlayerName, RankName); // Set the rank: - cRoot::Get()->GetRankManager().SetPlayerRank(PlayerUUID, PlayerName, RankName); + cRoot::Get()->GetRankManager()->SetPlayerRank(PlayerUUID, PlayerName, RankName); return 0; } @@ -1032,7 +1032,7 @@ static int tolua_cRankManager_SetRankVisuals(lua_State * L) S.GetStackValues(2, RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); // Set the visuals: - cRoot::Get()->GetRankManager().SetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); + cRoot::Get()->GetRankManager()->SetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); return 0; } diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index f58a0a016..86ee4a32d 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -2134,19 +2134,19 @@ void cPlayer::ApplyFoodExhaustionFromMovement() void cPlayer::LoadRank(void) { // Load the values from cRankManager: - cRankManager & RankMgr = cRoot::Get()->GetRankManager(); - m_Rank = RankMgr.GetPlayerRankName(m_UUID); + cRankManager * RankMgr = cRoot::Get()->GetRankManager(); + m_Rank = RankMgr->GetPlayerRankName(m_UUID); if (m_Rank.empty()) { - m_Rank = RankMgr.GetDefaultRank(); + m_Rank = RankMgr->GetDefaultRank(); } else { // Update the name: - RankMgr.UpdatePlayerName(m_UUID, m_PlayerName); + RankMgr->UpdatePlayerName(m_UUID, m_PlayerName); } - m_Permissions = RankMgr.GetPlayerPermissions(m_UUID); - RankMgr.GetRankVisuals(m_Rank, m_MsgPrefix, m_MsgSuffix, m_MsgNameColorCode); + m_Permissions = RankMgr->GetPlayerPermissions(m_UUID); + RankMgr->GetRankVisuals(m_Rank, m_MsgPrefix, m_MsgSuffix, m_MsgNameColorCode); // Break up the individual permissions on each dot, into m_SplitPermissions: m_SplitPermissions.clear(); diff --git a/src/Root.cpp b/src/Root.cpp index aa3d43cba..b866e2369 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -154,7 +154,8 @@ void cRoot::Start(void) m_WebAdmin->Init(); LOGD("Loading settings..."); - m_RankManager.Initialize(m_MojangAPI); + m_RankManager = new cRankManager(); + m_RankManager->Initialize(m_MojangAPI); m_CraftingRecipes = new cCraftingRecipes; m_FurnaceRecipe = new cFurnaceRecipe(); diff --git a/src/Root.h b/src/Root.h index 84c6a98ec..020a6cff0 100644 --- a/src/Root.h +++ b/src/Root.h @@ -86,7 +86,7 @@ public: cPluginManager * GetPluginManager (void) { return m_PluginManager; } // tolua_export cAuthenticator & GetAuthenticator (void) { return m_Authenticator; } cMojangAPI & GetMojangAPI (void) { return m_MojangAPI; } - cRankManager & GetRankManager (void) { return m_RankManager; } + cRankManager * GetRankManager (void) { return m_RankManager; } /** Queues a console command for execution through the cServer class. The command will be executed in the tick thread @@ -185,7 +185,7 @@ private: cPluginManager * m_PluginManager; cAuthenticator m_Authenticator; cMojangAPI m_MojangAPI; - cRankManager m_RankManager; + cRankManager * m_RankManager; cHTTPServer m_HTTPServer; bool m_bStop; -- cgit v1.2.3 From fe153cc763add3addc56130914ce4dbc85ce5409 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 11:32:17 +0200 Subject: Bindings: Removed obsolete codegen files. LuaState_Call.inc is no longer needed, it was replaced with variadic templates. --- src/Bindings/CMakeLists.txt | 3 - src/Bindings/gen_LuaState_Call.lua | 224 ---------------------------------- src/Bindings/virtual_method_hooks.lua | 10 -- 3 files changed, 237 deletions(-) delete mode 100644 src/Bindings/gen_LuaState_Call.lua (limited to 'src') diff --git a/src/Bindings/CMakeLists.txt b/src/Bindings/CMakeLists.txt index 930ee9771..5c56231c6 100644 --- a/src/Bindings/CMakeLists.txt +++ b/src/Bindings/CMakeLists.txt @@ -37,14 +37,12 @@ SET (HDRS set (BINDING_OUTPUTS ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.h - ${CMAKE_CURRENT_SOURCE_DIR}/LuaState_Call.inc ) set(BINDING_DEPENDENCIES tolua ../Bindings/virtual_method_hooks.lua ../Bindings/AllToLua.pkg - ../Bindings/gen_LuaState_Call.lua ../Bindings/LuaFunctions.h ../Bindings/LuaWindow.h ../Bindings/Plugin.h @@ -127,7 +125,6 @@ if (NOT MSVC) endif () set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES GENERATED TRUE) set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.h PROPERTIES GENERATED TRUE) -set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/LuaState_Call.inc PROPERTIES GENERATED TRUE) set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES COMPILE_FLAGS -Wno-error) diff --git a/src/Bindings/gen_LuaState_Call.lua b/src/Bindings/gen_LuaState_Call.lua deleted file mode 100644 index 7f62573c7..000000000 --- a/src/Bindings/gen_LuaState_Call.lua +++ /dev/null @@ -1,224 +0,0 @@ - --- gen_LuaState_Call.lua - --- Generates the cLuaState::Call() function templates that are included from LuaState.h - ---[[ -The cLuaState::Call() family of functions provides a template-based system for calling any Lua function -either by name or by reference with almost any number of parameters and return values. This is done by -providing a number of overloads of the same name with variable number of template-type parameters. To -separate the arguments from the return values, a special type of cLuaState::cRet is used. ---]] - - - - -print("Generating LuaState_Call.inc . . .") - - - - --- List of combinations (# params, # returns) to generate: -local Combinations = -{ - -- no return values: - {0, 0}, - {1, 0}, - {2, 0}, - {3, 0}, - {4, 0}, - - -- 1 return value: - {0, 1}, - {1, 1}, - {2, 1}, - {3, 1}, - {4, 1}, - {5, 1}, - {6, 1}, - {7, 1}, - {8, 1}, - {9, 1}, - {10, 1}, - - -- 2 return values: - {0, 2}, - {1, 2}, - {2, 2}, - {3, 2}, - {4, 2}, - {5, 2}, - {6, 2}, - {7, 2}, - {8, 2}, - {9, 2}, - - -- Special combinations: - {5, 5}, - {7, 3}, - {8, 3}, - {9, 5}, -} - - - - ---- Writes a single overloaded function definition for the specified number of params and returns into f ---[[ -The format for the generated function is this: -/** Call the specified 3-param 2-return Lua function: -Returns true if call succeeded, false if there was an error. */ -template -bool Call(FnT a_Function, ParamT1 a_Param1, ParamT2 a_Param2, ParamT3 a_Param3, const cLuaState::cRet & a_RetMark, RetT1 & a_Ret1, RetT2 & a_Ret2) -{ - UNUSED(a_RetMark); - if (!PushFunction(a_Function)) - { - return false; - } - Push(a_Param1); - Push(a_Param2); - Push(a_Param3); - if (!CallFunction(2)) - { - return false; - } - GetStackValue(-2, a_Ret1); - GetStackValue(-1, a_Ret2); - lua_pop(m_LuaState, 2); - return true; -} -Note especially the negative numbers in GetStackValue() calls. ---]] -local function WriteOverload(f, a_NumParams, a_NumReturns) - -- Write the function doxy-comments: - f:write("/** Call the specified ", a_NumParams, "-param ", a_NumReturns, "-return Lua function:\n") - f:write("Returns true if call succeeded, false if there was an error. */\n") - - -- Write the template <...> line: - f:write("template 0) then - for i = 1, a_NumReturns do - f:write(", typename RetT", i) - end - end - f:write(">\n") - - -- Write the function signature: - f:write("bool Call(") - f:write("const FnT & a_Function") - for i = 1, a_NumParams do - f:write(", ParamT", i, " a_Param", i) - end - if (a_NumReturns > 0) then - f:write(", const cLuaState::cRet & a_RetMark") - for i = 1, a_NumReturns do - f:write(", RetT", i, " & a_Ret", i) - end - end - f:write(")\n") - - -- Common code: - f:write("{\n") - if (a_NumReturns > 0) then - f:write("\tUNUSED(a_RetMark);\n") - end - f:write("\tif (!PushFunction(a_Function))\n") - f:write("\t{\n") - f:write("\t\treturn false;\n") - f:write("\t}\n") - - -- Push the params: - for i = 1, a_NumParams do - f:write("\tPush(a_Param", i, ");\n") - end - - -- Call the function: - f:write("\tif (!CallFunction(", a_NumReturns, "))\n") - f:write("\t{\n") - f:write("\t\treturn false;\n") - f:write("\t}\n") - - -- Get the return values: - for i = 1, a_NumReturns do - f:write("\tGetStackValue(", -1 - a_NumReturns + i, ", a_Ret", i, ");\n") - end - - -- Pop the returns off the stack, if needed: - if (a_NumReturns > 0) then - f:write("\tlua_pop(m_LuaState, ", a_NumReturns, ");\n") - end - - -- Everything ok: - f:write("\treturn true;\n") - f:write("}\n") - - -- Separate from the next function: - f:write("\n\n\n\n\n") -end - - - - - -local f = assert(io.open("LuaState_Call.inc", "w")) - --- Write file header: -f:write([[ -// LuaState_Call.inc - -// This file is auto-generated by gen_LuaState_Call.lua -// Make changes to the generator instead of to this file! - -// This file contains the various overloads for the cLuaState::Call() function -// Each overload handles a different number of parameters / return values -]]) -f:write("\n\n\n\n\n") - --- Write out a template function for each overload: -for _, combination in ipairs(Combinations) do - WriteOverload(f, combination[1], combination[2]) -end - --- Generate the cLuaState::GetStackValues() multi-param templates: -for i = 2, 6 do - f:write("/** Reads ", i, " consecutive values off the stack */\ntemplate <\n") - - -- Write the template function header: - local txt = {} - for idx = 1, i do - table.insert(txt, "\ttypename ArgT" .. idx) - end - f:write(table.concat(txt, ",\n")) - - -- Write the argument declarations: - txt = {} - f:write("\n>\nvoid GetStackValues(\n\tint a_BeginPos,\n") - for idx = 1, i do - table.insert(txt, "\tArgT" .. idx .. " & Arg" .. idx) - end - f:write(table.concat(txt, ",\n")) - - -- Write the function body: - f:write("\n)\n{\n") - for idx = 1, i do - f:write("\tGetStackValue(a_BeginPos + ", idx - 1, ", Arg", idx, ");\n") - end - f:write("}\n\n\n\n\n\n") -end - --- Close the generated file -f:close() - - - - - -print("LuaState_Call.inc generated.") - - - - diff --git a/src/Bindings/virtual_method_hooks.lua b/src/Bindings/virtual_method_hooks.lua index 8ad30bf78..a52728ff8 100644 --- a/src/Bindings/virtual_method_hooks.lua +++ b/src/Bindings/virtual_method_hooks.lua @@ -7,16 +7,6 @@ local default_private_access = false --- Code generators used by the build --- Note that these are not exactly needed for the bindings, but rather we --- misuse tolua's Lua engine to process files for us -dofile("gen_LuaState_Call.lua") - - - - - - local access = {public = 0, protected = 1, private = 2} function preparse_hook(p) -- cgit v1.2.3 From ebd31ff1321aeb23b5698d74c08f599a2fa62988 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 11:46:38 +0200 Subject: LuaState: Pushing a cEntity pushes the correct class name. This makes Lua scripts easier, as they don't need to cast values from cEntity to the specific descendant. --- src/Bindings/LuaState.cpp | 4 +++- src/Entities/Entity.h | 10 +++++----- 2 files changed, 8 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 85e3f9fc5..63170660b 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -16,6 +16,8 @@ extern "C" #include "Bindings.h" #include "ManualBindings.h" #include "DeprecatedBindings.h" +#include "../Entities/Entity.h" +#include "../BlockEntities/BlockEntity.h" // fwd: SQLite/lsqlite3.c extern "C" @@ -556,7 +558,7 @@ void cLuaState::Push(cEntity * a_Entity) { ASSERT(IsValid()); - tolua_pushusertype(m_LuaState, a_Entity, "cEntity"); + tolua_pushusertype(m_LuaState, a_Entity, (a_Entity == nullptr) ? "cEntity" : a_Entity->GetClass()); m_NumCurrentFunctionArgs += 1; } diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h index f0577aba2..07754791d 100644 --- a/src/Entities/Entity.h +++ b/src/Entities/Entity.h @@ -172,13 +172,13 @@ public: /// Returns true if the entity is of the specified class or a subclass (cPawn's IsA("cEntity") returns true) virtual bool IsA(const char * a_ClassName) const; - /// Returns the topmost class name for the object - virtual const char * GetClass(void) const; - - // Returns the class name of this class + /** Returns the class name of this class */ static const char * GetClassStatic(void); - /// Returns the topmost class's parent class name for the object. cEntity returns an empty string (no parent). + /** Returns the topmost class name for the object */ + virtual const char * GetClass(void) const; + + /** Returns the topmost class's parent class name for the object. cEntity returns an empty string (no parent). */ virtual const char * GetParentClass(void) const; cWorld * GetWorld(void) const { return m_World; } -- cgit v1.2.3 From b0a59927fb7531f6c909e6f581035568c79b625c Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 12:46:25 +0200 Subject: cLuaState: cBlockEntity descendants are pushed with proper class type. --- src/Bindings/LuaState.cpp | 2 +- src/BlockEntities/BeaconEntity.h | 2 ++ src/BlockEntities/BlockEntity.h | 31 +++++++++++++++++++++++++++++++ src/BlockEntities/BlockEntityWithItems.h | 4 +++- src/BlockEntities/ChestEntity.h | 4 ++-- src/BlockEntities/CommandBlockEntity.h | 2 ++ src/BlockEntities/DispenserEntity.h | 4 ++-- src/BlockEntities/DropSpenserEntity.h | 4 ++-- src/BlockEntities/DropperEntity.h | 4 ++-- src/BlockEntities/EnderChestEntity.h | 4 ++-- src/BlockEntities/FlowerPotEntity.h | 4 ++-- src/BlockEntities/FurnaceEntity.h | 4 ++-- src/BlockEntities/HopperEntity.h | 4 ++-- src/BlockEntities/JukeboxEntity.h | 4 ++-- src/BlockEntities/MobHeadEntity.h | 4 ++-- src/BlockEntities/NoteEntity.h | 4 ++-- src/BlockEntities/SignEntity.h | 4 ++-- 17 files changed, 63 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 63170660b..49d643688 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -522,7 +522,7 @@ void cLuaState::Push(cBlockEntity * a_BlockEntity) { ASSERT(IsValid()); - tolua_pushusertype(m_LuaState, a_BlockEntity, "cBlockEntity"); + tolua_pushusertype(m_LuaState, a_BlockEntity, (a_BlockEntity == nullptr) ? "cBlockEntity" : a_BlockEntity->GetClass()); m_NumCurrentFunctionArgs += 1; } diff --git a/src/BlockEntities/BeaconEntity.h b/src/BlockEntities/BeaconEntity.h index 8c2dad254..d1db3a68f 100644 --- a/src/BlockEntities/BeaconEntity.h +++ b/src/BlockEntities/BeaconEntity.h @@ -32,6 +32,8 @@ class cBeaconEntity : public: // tolua_end + BLOCKENTITY_PROTODEF(cBeaconEntity); + cBeaconEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); // cBlockEntity overrides: diff --git a/src/BlockEntities/BlockEntity.h b/src/BlockEntities/BlockEntity.h index 54ab40f3e..b04d20340 100644 --- a/src/BlockEntities/BlockEntity.h +++ b/src/BlockEntities/BlockEntity.h @@ -5,6 +5,28 @@ +/** Place this macro in the declaration of each cBlockEntity descendant. */ +#define BLOCKENTITY_PROTODEF(classname) \ + virtual bool IsA(const char * a_ClassName) const override \ + { \ + return ((strcmp(a_ClassName, #classname) == 0) || super::IsA(a_ClassName)); \ + } \ + virtual const char * GetClass(void) const override \ + { \ + return #classname; \ + } \ + static const char * GetClassStatic(void) \ + { \ + return #classname; \ + } \ + virtual const char * GetParentClass(void) const override \ + { \ + return super::GetClass(); \ + } + + + + namespace Json { @@ -55,6 +77,15 @@ public: { return "cBlockEntity"; } + + /** Returns true if the object is the specified class, or its descendant. */ + virtual bool IsA(const char * a_ClassName) const { return (strcmp(a_ClassName, "cBlockEntity") == 0); } + + /** Returns the name of the tompost class (the most descendant). Used for Lua bindings to push the correct object type. */ + virtual const char * GetClass(void) const { return GetClassStatic(); } + + /** Returns the name of the parent class, or empty string if no parent class. */ + virtual const char * GetParentClass(void) const { return ""; } // tolua_begin diff --git a/src/BlockEntities/BlockEntityWithItems.h b/src/BlockEntities/BlockEntityWithItems.h index 00173cbcb..cb7bc2fb4 100644 --- a/src/BlockEntities/BlockEntityWithItems.h +++ b/src/BlockEntities/BlockEntityWithItems.h @@ -25,10 +25,12 @@ class cBlockEntityWithItems : public cBlockEntityWindowOwner { typedef cBlockEntity super; - + public: // tolua_end + BLOCKENTITY_PROTODEF(cBlockEntityWithItems); + cBlockEntityWithItems( BLOCKTYPE a_BlockType, // Type of the block that the entity represents int a_BlockX, int a_BlockY, int a_BlockZ, // Position of the block entity diff --git a/src/BlockEntities/ChestEntity.h b/src/BlockEntities/ChestEntity.h index af5d851a8..09fffb923 100644 --- a/src/BlockEntities/ChestEntity.h +++ b/src/BlockEntities/ChestEntity.h @@ -33,13 +33,13 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cChestEntity); + /** Constructor used for normal operation */ cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World, BLOCKTYPE a_Type); virtual ~cChestEntity(); - static const char * GetClassStatic(void) { return "cChestEntity"; } - // cBlockEntity overrides: virtual void SendTo(cClientHandle & a_Client) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/CommandBlockEntity.h b/src/BlockEntities/CommandBlockEntity.h index 939f38610..217390293 100644 --- a/src/BlockEntities/CommandBlockEntity.h +++ b/src/BlockEntities/CommandBlockEntity.h @@ -36,6 +36,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cCommandBlockEntity); + /// Creates a new empty command block entity cCommandBlockEntity(int a_X, int a_Y, int a_Z, cWorld * a_World); diff --git a/src/BlockEntities/DispenserEntity.h b/src/BlockEntities/DispenserEntity.h index b33d08342..5ba87b716 100644 --- a/src/BlockEntities/DispenserEntity.h +++ b/src/BlockEntities/DispenserEntity.h @@ -17,11 +17,11 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cDispenserEntity); + /** Constructor used for normal operation */ cDispenserEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); - static const char * GetClassStatic(void) { return "cDispenserEntity"; } - // tolua_begin /** Spawns a projectile of the given kind in front of the dispenser with the specified speed. */ diff --git a/src/BlockEntities/DropSpenserEntity.h b/src/BlockEntities/DropSpenserEntity.h index 23f0ae89a..f77a28c28 100644 --- a/src/BlockEntities/DropSpenserEntity.h +++ b/src/BlockEntities/DropSpenserEntity.h @@ -45,11 +45,11 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cDropSpenserEntity); + cDropSpenserEntity(BLOCKTYPE a_BlockType, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual ~cDropSpenserEntity(); - static const char * GetClassStatic(void) { return "cDropSpenserEntity"; } - // cBlockEntity overrides: virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void SendTo(cClientHandle & a_Client) override; diff --git a/src/BlockEntities/DropperEntity.h b/src/BlockEntities/DropperEntity.h index 8e07bc6f8..91adf660f 100644 --- a/src/BlockEntities/DropperEntity.h +++ b/src/BlockEntities/DropperEntity.h @@ -25,11 +25,11 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cDropperEntity); + /// Constructor used for normal operation cDropperEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); - static const char * GetClassStatic(void) { return "cDropperEntity"; } - protected: // cDropSpenserEntity overrides: virtual void DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) override; diff --git a/src/BlockEntities/EnderChestEntity.h b/src/BlockEntities/EnderChestEntity.h index 2719eb5e4..17abd880a 100644 --- a/src/BlockEntities/EnderChestEntity.h +++ b/src/BlockEntities/EnderChestEntity.h @@ -18,11 +18,11 @@ class cEnderChestEntity : public: // tolua_end + BLOCKENTITY_PROTODEF(cEnderChestEntity); + cEnderChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual ~cEnderChestEntity(); - static const char * GetClassStatic(void) { return "cEnderChestEntity"; } - // cBlockEntity overrides: virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle & a_Client) override { UNUSED(a_Client); } diff --git a/src/BlockEntities/FlowerPotEntity.h b/src/BlockEntities/FlowerPotEntity.h index b68d3b118..5b86621f5 100644 --- a/src/BlockEntities/FlowerPotEntity.h +++ b/src/BlockEntities/FlowerPotEntity.h @@ -36,6 +36,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cFlowerPotEntity); + /** Creates a new flowerpot entity at the specified block coords. a_World may be NULL */ cFlowerPotEntity(int a_BlocX, int a_BlockY, int a_BlockZ, cWorld * a_World); @@ -59,8 +61,6 @@ public: static bool IsFlower(short m_ItemType, short m_ItemData); - static const char * GetClassStatic(void) { return "cFlowerPotEntity"; } - private: cItem m_Item; diff --git a/src/BlockEntities/FurnaceEntity.h b/src/BlockEntities/FurnaceEntity.h index 14dadbec8..8e48810ba 100644 --- a/src/BlockEntities/FurnaceEntity.h +++ b/src/BlockEntities/FurnaceEntity.h @@ -38,13 +38,13 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cFurnaceEntity); + /** Constructor used for normal operation */ cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cWorld * a_World); virtual ~cFurnaceEntity(); - static const char * GetClassStatic() { return "cFurnaceEntity"; } - // cBlockEntity overrides: virtual void SendTo(cClientHandle & a_Client) override; virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; diff --git a/src/BlockEntities/HopperEntity.h b/src/BlockEntities/HopperEntity.h index 5d06581c2..7070bbad3 100644 --- a/src/BlockEntities/HopperEntity.h +++ b/src/BlockEntities/HopperEntity.h @@ -31,6 +31,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cHopperEntity); + /// Constructor used for normal operation cHopperEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); @@ -40,8 +42,6 @@ public: */ bool GetOutputBlockPos(NIBBLETYPE a_BlockMeta, int & a_OutputX, int & a_OutputY, int & a_OutputZ); - static const char * GetClassStatic(void) { return "cHopperEntity"; } - protected: Int64 m_LastMoveItemsInTick; diff --git a/src/BlockEntities/JukeboxEntity.h b/src/BlockEntities/JukeboxEntity.h index 49d2faa89..7a69d6499 100644 --- a/src/BlockEntities/JukeboxEntity.h +++ b/src/BlockEntities/JukeboxEntity.h @@ -26,6 +26,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cJukeboxEntity); + cJukeboxEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual ~cJukeboxEntity(); @@ -51,8 +53,6 @@ public: // tolua_end - static const char * GetClassStatic(void) { return "cJukeboxEntity"; } - virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle &) override {} diff --git a/src/BlockEntities/MobHeadEntity.h b/src/BlockEntities/MobHeadEntity.h index fcdeaa8a6..7f69bc5ad 100644 --- a/src/BlockEntities/MobHeadEntity.h +++ b/src/BlockEntities/MobHeadEntity.h @@ -34,6 +34,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cMobHeadEntity); + /** Creates a new mob head entity at the specified block coords. a_World may be NULL */ cMobHeadEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); @@ -62,8 +64,6 @@ public: virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle & a_Client) override; - static const char * GetClassStatic(void) { return "cMobHeadEntity"; } - private: eMobHeadType m_Type; diff --git a/src/BlockEntities/NoteEntity.h b/src/BlockEntities/NoteEntity.h index d1ffa126a..74dbde046 100644 --- a/src/BlockEntities/NoteEntity.h +++ b/src/BlockEntities/NoteEntity.h @@ -40,6 +40,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cNoteEntity); + /// Creates a new note entity. a_World may be NULL cNoteEntity(int a_X, int a_Y, int a_Z, cWorld * a_World); virtual ~cNoteEntity() {} @@ -64,8 +66,6 @@ public: } } - static const char * GetClassStatic(void) { return "cNoteEntity"; } - private: char m_Pitch; } ; // tolua_export diff --git a/src/BlockEntities/SignEntity.h b/src/BlockEntities/SignEntity.h index 53c43b758..be13c7a32 100644 --- a/src/BlockEntities/SignEntity.h +++ b/src/BlockEntities/SignEntity.h @@ -34,6 +34,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cSignEntity); + /// Creates a new empty sign entity at the specified block coords and block type (wall or standing). a_World may be NULL cSignEntity(BLOCKTYPE a_BlockType, int a_X, int a_Y, int a_Z, cWorld * a_World); @@ -53,8 +55,6 @@ public: virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle & a_Client) override; - static const char * GetClassStatic(void) { return "cSignEntity"; } - private: AString m_Line[4]; -- cgit v1.2.3 From d50bbf3899a1f28b23f98718e8acc76e294454a8 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 12:49:54 +0200 Subject: cLuaState: cMonster descendants don't push their specific type. The individual mob types aren't exported to Lua, so pushing them would crash the server. --- src/Bindings/LuaState.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 49d643688..2c4d89b01 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -558,7 +558,16 @@ void cLuaState::Push(cEntity * a_Entity) { ASSERT(IsValid()); - tolua_pushusertype(m_LuaState, a_Entity, (a_Entity == nullptr) ? "cEntity" : a_Entity->GetClass()); + if (a_Entity->IsMob()) + { + // Don't push specific mob types, as those are not exported in the API: + tolua_pushusertype(m_LuaState, a_Entity, "cMonster"); + } + else + { + // Push the specific class type: + tolua_pushusertype(m_LuaState, a_Entity, (a_Entity == nullptr) ? "cEntity" : a_Entity->GetClass()); + } m_NumCurrentFunctionArgs += 1; } -- cgit v1.2.3 From e0cfbc4d8526a1a1d3afa8fc0774358f4f18b7e2 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 14:01:59 +0200 Subject: Generator: Rewritten to use SharedPtrs. --- src/Generating/BioGen.cpp | 35 +++------ src/Generating/BioGen.h | 26 +++---- src/Generating/CompoGen.cpp | 6 +- src/Generating/CompoGen.h | 6 +- src/Generating/ComposableGenerator.cpp | 123 ++++++++++++-------------------- src/Generating/ComposableGenerator.h | 33 +++++---- src/Generating/DistortedHeightmap.cpp | 6 +- src/Generating/DistortedHeightmap.h | 13 ++-- src/Generating/DungeonRoomsFinisher.cpp | 4 +- src/Generating/DungeonRoomsFinisher.h | 4 +- src/Generating/HeiGen.cpp | 12 ++-- src/Generating/HeiGen.h | 10 +-- src/Generating/StructGen.cpp | 2 +- src/Generating/StructGen.h | 20 +++--- src/Generating/UnderwaterBaseGen.cpp | 4 +- src/Generating/UnderwaterBaseGen.h | 4 +- src/Generating/VillageGen.cpp | 12 ++-- src/Generating/VillageGen.h | 6 +- 18 files changed, 145 insertions(+), 181 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 9b3d4e98d..f5fe3e980 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -45,7 +45,7 @@ void cBioGenConstant::InitializeBiomeGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cBioGenCache: -cBioGenCache::cBioGenCache(cBiomeGen * a_BioGenToCache, int a_CacheSize) : +cBioGenCache::cBioGenCache(cBiomeGenPtr a_BioGenToCache, int a_CacheSize) : m_BioGenToCache(a_BioGenToCache), m_CacheSize(a_CacheSize), m_CacheOrder(new int[a_CacheSize]), @@ -145,25 +145,13 @@ void cBioGenCache::InitializeBiomeGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cBioGenMulticache: -cBioGenMulticache::cBioGenMulticache(cBiomeGen * a_BioGenToCache, size_t a_CacheSize, size_t a_CachesLength) : - m_CachesLength(a_CachesLength) +cBioGenMulticache::cBioGenMulticache(cBiomeGenPtr a_BioGenToCache, size_t a_SubCacheSize, size_t a_NumSubCaches) : + m_NumSubCaches(a_NumSubCaches) { - m_Caches.reserve(a_CachesLength); - for (size_t i = 0; i < a_CachesLength; i++) + m_Caches.reserve(a_NumSubCaches); + for (size_t i = 0; i < a_NumSubCaches; i++) { - m_Caches.push_back(new cBioGenCache(a_BioGenToCache, a_CacheSize)); - } -} - - - - - -cBioGenMulticache::~cBioGenMulticache() -{ - for (cBiomeGens::iterator it = m_Caches.begin(); it != m_Caches.end(); it++) - { - delete *it; + m_Caches.push_back(cBiomeGenPtr(new cBioGenCache(a_BioGenToCache, a_SubCacheSize))); } } @@ -174,7 +162,7 @@ cBioGenMulticache::~cBioGenMulticache() void cBioGenMulticache::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) { const size_t coefficient = 3; - const size_t cacheIdx = ((size_t)a_ChunkX + coefficient * (size_t)a_ChunkZ) % m_CachesLength; + const size_t cacheIdx = ((size_t)a_ChunkX + coefficient * (size_t)a_ChunkZ) % m_NumSubCaches; m_Caches[cacheIdx]->GenBiomes(a_ChunkX, a_ChunkZ, a_BiomeMap); } @@ -185,10 +173,9 @@ void cBioGenMulticache::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMa void cBioGenMulticache::InitializeBiomeGen(cIniFile & a_IniFile) { - for (cBiomeGens::iterator it = m_Caches.begin(); it != m_Caches.end(); it++) + for (auto itr : m_Caches) { - cBiomeGen * tmp = *it; - tmp->InitializeBiomeGen(a_IniFile); + itr->InitializeBiomeGen(a_IniFile); } } @@ -932,7 +919,7 @@ void cBioGenTwoLevel::InitializeBiomeGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cBiomeGen: -cBiomeGen * cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault) +cBiomeGenPtr cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault) { AString BiomeGenName = a_IniFile.GetValueSet("Generator", "BiomeGen", ""); if (BiomeGenName.empty()) @@ -988,7 +975,7 @@ cBiomeGen * cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a } res->InitializeBiomeGen(a_IniFile); - return res; + return cBiomeGenPtr(res); } diff --git a/src/Generating/BioGen.h b/src/Generating/BioGen.h index 22ddfae5c..5fd0844d9 100644 --- a/src/Generating/BioGen.h +++ b/src/Generating/BioGen.h @@ -48,12 +48,12 @@ class cBioGenCache : typedef cBiomeGen super; public: - cBioGenCache(cBiomeGen * a_BioGenToCache, int a_CacheSize); // Doesn't take ownership of a_BioGenToCache - ~cBioGenCache(); + cBioGenCache(cBiomeGenPtr a_BioGenToCache, int a_CacheSize); + virtual ~cBioGenCache(); protected: - cBiomeGen * m_BioGenToCache; + cBiomeGenPtr m_BioGenToCache; struct sCacheData { @@ -87,19 +87,21 @@ class cBioGenMulticache : typedef cBiomeGen super; public: - /* - a_CacheSize defines the size of each singular cache - a_CachesLength defines how many caches are used for the multicache - */ - cBioGenMulticache(cBiomeGen * a_BioGenToCache, size_t a_CacheSize, size_t a_CachesLength); // Doesn't take ownership of a_BioGenToCache - ~cBioGenMulticache(); + /* Creates a new multicache - a cache that divides the caching into several sub-caches based on the chunk coords. + This allows us to use shorter cache depths with faster lookups for more covered area. (#381) + a_SubCacheSize defines the size of each sub-cache + a_NumSubCaches defines how many sub-caches are used for the multicache. */ + cBioGenMulticache(cBiomeGenPtr a_BioGenToCache, size_t a_SubCacheSize, size_t a_NumSubCaches); protected: - typedef std::vector cBiomeGens; + typedef std::vector cBiomeGenPtrs; + + /** Number of sub-caches. Pulled out of m_Caches.size() for faster access. */ + size_t m_NumSubCaches; - size_t m_CachesLength; - cBiomeGens m_Caches; + /** Individual sub-caches. */ + cBiomeGenPtrs m_Caches; virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) override; diff --git a/src/Generating/CompoGen.cpp b/src/Generating/CompoGen.cpp index 178673e32..0105fdb70 100644 --- a/src/Generating/CompoGen.cpp +++ b/src/Generating/CompoGen.cpp @@ -663,7 +663,7 @@ void cCompoGenNether::InitializeCompoGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cCompoGenCache: -cCompoGenCache::cCompoGenCache(cTerrainCompositionGen & a_Underlying, int a_CacheSize) : +cCompoGenCache::cCompoGenCache(cTerrainCompositionGenPtr a_Underlying, int a_CacheSize) : m_Underlying(a_Underlying), m_CacheSize(a_CacheSize), m_CacheOrder(new int[a_CacheSize]), @@ -739,7 +739,7 @@ void cCompoGenCache::ComposeTerrain(cChunkDesc & a_ChunkDesc) // Not in the cache: m_NumMisses++; - m_Underlying.ComposeTerrain(a_ChunkDesc); + m_Underlying->ComposeTerrain(a_ChunkDesc); // Insert it as the first item in the MRU order: int Idx = m_CacheOrder[m_CacheSize - 1]; @@ -760,7 +760,7 @@ void cCompoGenCache::ComposeTerrain(cChunkDesc & a_ChunkDesc) void cCompoGenCache::InitializeCompoGen(cIniFile & a_IniFile) { - m_Underlying.InitializeCompoGen(a_IniFile); + m_Underlying->InitializeCompoGen(a_IniFile); } diff --git a/src/Generating/CompoGen.h b/src/Generating/CompoGen.h index 096b0fb5a..b145b6ba3 100644 --- a/src/Generating/CompoGen.h +++ b/src/Generating/CompoGen.h @@ -144,12 +144,12 @@ protected: -/// Caches most-recently-used chunk composition of another composition generator. Caches only the types and metas +/** Caches most-recently-used chunk composition of another composition generator. Caches only the types and metas */ class cCompoGenCache : public cTerrainCompositionGen { public: - cCompoGenCache(cTerrainCompositionGen & a_Underlying, int a_CacheSize); // Doesn't take ownership of a_Underlying + cCompoGenCache(cTerrainCompositionGenPtr a_Underlying, int a_CacheSize); // Doesn't take ownership of a_Underlying ~cCompoGenCache(); // cTerrainCompositionGen override: @@ -158,7 +158,7 @@ public: protected: - cTerrainCompositionGen & m_Underlying; + cTerrainCompositionGenPtr m_Underlying; struct sCacheData { diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 87461b944..358d97c92 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -39,7 +39,7 @@ //////////////////////////////////////////////////////////////////////////////// // cTerrainCompositionGen: -cTerrainCompositionGen * cTerrainCompositionGen::CreateCompositionGen(cIniFile & a_IniFile, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed) +cTerrainCompositionGenPtr cTerrainCompositionGen::CreateCompositionGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed) { AString CompoGenName = a_IniFile.GetValueSet("Generator", "CompositionGen", ""); if (CompoGenName.empty()) @@ -107,7 +107,7 @@ cTerrainCompositionGen * cTerrainCompositionGen::CreateCompositionGen(cIniFile & // Read the settings from the ini file: res->InitializeCompoGen(a_IniFile); - return res; + return cTerrainCompositionGenPtr(res); } @@ -119,12 +119,9 @@ cTerrainCompositionGen * cTerrainCompositionGen::CreateCompositionGen(cIniFile & cComposableGenerator::cComposableGenerator(cChunkGenerator & a_ChunkGenerator) : super(a_ChunkGenerator), - m_BiomeGen(NULL), - m_HeightGen(NULL), - m_CompositionGen(NULL), - m_UnderlyingBiomeGen(NULL), - m_UnderlyingHeightGen(NULL), - m_UnderlyingCompositionGen(NULL) + m_BiomeGen(nullptr), + m_HeightGen(nullptr), + m_CompositionGen(nullptr) { } @@ -132,33 +129,6 @@ cComposableGenerator::cComposableGenerator(cChunkGenerator & a_ChunkGenerator) : -cComposableGenerator::~cComposableGenerator() -{ - // Delete the generating composition: - for (cFinishGenList::const_iterator itr = m_FinishGens.begin(); itr != m_FinishGens.end(); ++itr) - { - delete *itr; - } - m_FinishGens.clear(); - - delete m_CompositionGen; - m_CompositionGen = NULL; - delete m_HeightGen; - m_HeightGen = NULL; - delete m_BiomeGen; - m_BiomeGen = NULL; - delete m_UnderlyingCompositionGen; - m_UnderlyingCompositionGen = NULL; - delete m_UnderlyingHeightGen; - m_UnderlyingHeightGen = NULL; - delete m_UnderlyingBiomeGen; - m_UnderlyingBiomeGen = NULL; -} - - - - - void cComposableGenerator::Initialize(cIniFile & a_IniFile) { super::Initialize(a_IniFile); @@ -245,15 +215,14 @@ void cComposableGenerator::InitBiomeGen(cIniFile & a_IniFile) CacheSize = 4; } LOGD("Using a cache for biomegen of size %d.", CacheSize); - m_UnderlyingBiomeGen = m_BiomeGen; if (MultiCacheLength > 0) { LOGD("Enabling multicache for biomegen of length %d.", MultiCacheLength); - m_BiomeGen = new cBioGenMulticache(m_UnderlyingBiomeGen, CacheSize, MultiCacheLength); + m_BiomeGen = cBiomeGenPtr(new cBioGenMulticache(m_BiomeGen, CacheSize, MultiCacheLength)); } else { - m_BiomeGen = new cBioGenCache(m_UnderlyingBiomeGen, CacheSize); + m_BiomeGen = cBiomeGenPtr(new cBioGenCache(m_BiomeGen, CacheSize)); } } @@ -264,7 +233,7 @@ void cComposableGenerator::InitBiomeGen(cIniFile & a_IniFile) void cComposableGenerator::InitHeightGen(cIniFile & a_IniFile) { bool CacheOffByDefault = false; - m_HeightGen = cTerrainHeightGen::CreateHeightGen(a_IniFile, *m_BiomeGen, m_ChunkGenerator.GetSeed(), CacheOffByDefault); + m_HeightGen = cTerrainHeightGen::CreateHeightGen(a_IniFile, m_BiomeGen, m_ChunkGenerator.GetSeed(), CacheOffByDefault); // Add a cache, if requested: int CacheSize = a_IniFile.GetValueSetI("Generator", "HeightGenCacheSize", CacheOffByDefault ? 0 : 64); @@ -278,8 +247,7 @@ void cComposableGenerator::InitHeightGen(cIniFile & a_IniFile) CacheSize = 4; } LOGD("Using a cache for Heightgen of size %d.", CacheSize); - m_UnderlyingHeightGen = m_HeightGen; - m_HeightGen = new cHeiGenCache(*m_UnderlyingHeightGen, CacheSize); + m_HeightGen = cTerrainHeightGenPtr(new cHeiGenCache(m_HeightGen, CacheSize)); } } @@ -289,13 +257,12 @@ void cComposableGenerator::InitHeightGen(cIniFile & a_IniFile) void cComposableGenerator::InitCompositionGen(cIniFile & a_IniFile) { - m_CompositionGen = cTerrainCompositionGen::CreateCompositionGen(a_IniFile, *m_BiomeGen, *m_HeightGen, m_ChunkGenerator.GetSeed()); + m_CompositionGen = cTerrainCompositionGen::CreateCompositionGen(a_IniFile, m_BiomeGen, *m_HeightGen, m_ChunkGenerator.GetSeed()); int CompoGenCacheSize = a_IniFile.GetValueSetI("Generator", "CompositionGenCacheSize", 64); if (CompoGenCacheSize > 1) { - m_UnderlyingCompositionGen = m_CompositionGen; - m_CompositionGen = new cCompoGenCache(*m_UnderlyingCompositionGen, 32); + m_CompositionGen = cTerrainCompositionGenPtr(new cCompoGenCache(m_CompositionGen, 32)); } } @@ -319,7 +286,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) { int DefaultBottomLavaLevel = (Dimension == dimNether) ? 30 : 10; int BottomLavaLevel = a_IniFile.GetValueSetI("Generator", "BottomLavaLevel", DefaultBottomLavaLevel); - m_FinishGens.push_back(new cFinishGenBottomLava(BottomLavaLevel)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenBottomLava(BottomLavaLevel))); } else if (NoCaseCompare(*itr, "DeadBushes") == 0) { @@ -341,20 +308,20 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) AllowedBlocks.push_back(E_BLOCK_HARDENED_CLAY); AllowedBlocks.push_back(E_BLOCK_STAINED_CLAY); - m_FinishGens.push_back(new cFinishGenSingleTopBlock(Seed, E_BLOCK_DEAD_BUSH, AllowedBiomes, 2, AllowedBlocks)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSingleTopBlock(Seed, E_BLOCK_DEAD_BUSH, AllowedBiomes, 2, AllowedBlocks))); } else if (NoCaseCompare(*itr, "DirectOverhangs") == 0) { - m_FinishGens.push_back(new cStructGenDirectOverhangs(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenDirectOverhangs(Seed))); } else if (NoCaseCompare(*itr, "DistortedMembraneOverhangs") == 0) { - m_FinishGens.push_back(new cStructGenDistortedMembraneOverhangs(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenDistortedMembraneOverhangs(Seed))); } else if (NoCaseCompare(*itr, "DualRidgeCaves") == 0) { float Threshold = (float)a_IniFile.GetValueSetF("Generator", "DualRidgeCavesThreshold", 0.3); - m_FinishGens.push_back(new cStructGenDualRidgeCaves(Seed, Threshold)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenDualRidgeCaves(Seed, Threshold))); } else if (NoCaseCompare(*itr, "DungeonRooms") == 0) { @@ -362,24 +329,24 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxSize = a_IniFile.GetValueSetI("Generator", "DungeonRoomsMaxSize", 7); int MinSize = a_IniFile.GetValueSetI("Generator", "DungeonRoomsMinSize", 5); AString HeightDistrib = a_IniFile.GetValueSet ("Generator", "DungeonRoomsHeightDistrib", "0, 0; 10, 10; 11, 500; 40, 500; 60, 40; 90, 1"); - m_FinishGens.push_back(new cDungeonRoomsFinisher(*m_HeightGen, Seed, GridSize, MaxSize, MinSize, HeightDistrib)); + m_FinishGens.push_back(cFinishGenPtr(new cDungeonRoomsFinisher(m_HeightGen, Seed, GridSize, MaxSize, MinSize, HeightDistrib))); } else if (NoCaseCompare(*itr, "Ice") == 0) { - m_FinishGens.push_back(new cFinishGenIce); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenIce)); } else if (NoCaseCompare(*itr, "LavaLakes") == 0) { int Probability = a_IniFile.GetValueSetI("Generator", "LavaLakesProbability", 10); - m_FinishGens.push_back(new cStructGenLakes(Seed * 5 + 16873, E_BLOCK_STATIONARY_LAVA, *m_HeightGen, Probability)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenLakes(Seed * 5 + 16873, E_BLOCK_STATIONARY_LAVA, m_HeightGen, Probability))); } else if (NoCaseCompare(*itr, "LavaSprings") == 0) { - m_FinishGens.push_back(new cFinishGenFluidSprings(Seed, E_BLOCK_LAVA, a_IniFile, Dimension)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenFluidSprings(Seed, E_BLOCK_LAVA, a_IniFile, Dimension))); } else if (NoCaseCompare(*itr, "MarbleCaves") == 0) { - m_FinishGens.push_back(new cStructGenMarbleCaves(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenMarbleCaves(Seed))); } else if (NoCaseCompare(*itr, "MineShafts") == 0) { @@ -389,10 +356,10 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int ChanceCorridor = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceCorridor", 600); int ChanceCrossing = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceCrossing", 200); int ChanceStaircase = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceStaircase", 200); - m_FinishGens.push_back(new cStructGenMineShafts( + m_FinishGens.push_back(cFinishGenPtr(new cStructGenMineShafts( Seed, GridSize, MaxOffset, MaxSystemSize, ChanceCorridor, ChanceCrossing, ChanceStaircase - )); + ))); } else if (NoCaseCompare(*itr, "Lilypads") == 0) { @@ -406,7 +373,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) AllowedBlocks.push_back(E_BLOCK_WATER); AllowedBlocks.push_back(E_BLOCK_STATIONARY_WATER); - m_FinishGens.push_back(new cFinishGenSingleTopBlock(Seed, E_BLOCK_LILY_PAD, AllowedBiomes, 4, AllowedBlocks)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSingleTopBlock(Seed, E_BLOCK_LILY_PAD, AllowedBiomes, 4, AllowedBlocks))); } else if (NoCaseCompare(*itr, "NaturalPatches") == 0) { @@ -455,18 +422,18 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) AndesiteVein.NestSize = 32; Ores.push_back(AndesiteVein); - m_FinishGens.push_back(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE))); } else if (NoCaseCompare(*itr, "NetherClumpFoliage") == 0) { - m_FinishGens.push_back(new cFinishGenNetherClumpFoliage(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenNetherClumpFoliage(Seed))); } else if (NoCaseCompare(*itr, "NetherForts") == 0) { int GridSize = a_IniFile.GetValueSetI("Generator", "NetherFortsGridSize", 512); int MaxOffset = a_IniFile.GetValueSetI("Generator", "NetherFortMaxOffset", 128); int MaxDepth = a_IniFile.GetValueSetI("Generator", "NetherFortsMaxDepth", 12); - m_FinishGens.push_back(new cNetherFortGen(Seed, GridSize, MaxOffset, MaxDepth)); + m_FinishGens.push_back(cFinishGenPtr(new cNetherFortGen(Seed, GridSize, MaxOffset, MaxDepth))); } else if (NoCaseCompare(*itr, "NetherOreNests") == 0) { @@ -480,7 +447,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) QuartzVein.NestSize = 8; Ores.push_back(QuartzVein); - m_FinishGens.push_back(new cStructGenOreNests(Seed, Ores, E_BLOCK_NETHERRACK)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenOreNests(Seed, Ores, E_BLOCK_NETHERRACK))); } else if (NoCaseCompare(*itr, "OreNests") == 0) @@ -535,11 +502,11 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) DiamondVein.NestSize = 4; Ores.push_back(DiamondVein); - m_FinishGens.push_back(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE))); } else if (NoCaseCompare(*itr, "POCPieces") == 0) { - m_FinishGens.push_back(new cPOCPieceGenerator(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cPOCPieceGenerator(Seed))); } else if (NoCaseCompare(*itr, "PreSimulator") == 0) { @@ -548,7 +515,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) bool PreSimulateWater = a_IniFile.GetValueSetB("Generator", "PreSimulatorWater", true); bool PreSimulateLava = a_IniFile.GetValueSetB("Generator", "PreSimulatorLava", true); - m_FinishGens.push_back(new cFinishGenPreSimulator(PreSimulateFallingBlocks, PreSimulateWater, PreSimulateLava)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenPreSimulator(PreSimulateFallingBlocks, PreSimulateWater, PreSimulateLava))); } else if (NoCaseCompare(*itr, "RainbowRoads") == 0) { @@ -556,11 +523,11 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxOffset = a_IniFile.GetValueSetI("Generator", "RainbowRoadsMaxOffset", 128); int MaxDepth = a_IniFile.GetValueSetI("Generator", "RainbowRoadsMaxDepth", 30); int MaxSize = a_IniFile.GetValueSetI("Generator", "RainbowRoadsMaxSize", 260); - m_FinishGens.push_back(new cRainbowRoadsGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize)); + m_FinishGens.push_back(cFinishGenPtr(new cRainbowRoadsGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize))); } else if (NoCaseCompare(*itr, "Ravines") == 0) { - m_FinishGens.push_back(new cStructGenRavines(Seed, 128)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenRavines(Seed, 128))); } else if (NoCaseCompare(*itr, "RoughRavines") == 0) { @@ -580,7 +547,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) double MinCeilingHeightEdge = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinCeilingHeightEdge", 38); double MaxCeilingHeightCenter = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxCeilingHeightCenter", 58); double MinCeilingHeightCenter = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinCeilingHeightCenter", 36); - m_FinishGens.push_back(new cRoughRavines( + m_FinishGens.push_back(cFinishGenPtr(new cRoughRavines( Seed, MaxSize, MinSize, (float)MaxCenterWidth, (float)MinCenterWidth, (float)MaxRoughness, (float)MinRoughness, @@ -589,27 +556,27 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) (float)MaxCeilingHeightEdge, (float)MinCeilingHeightEdge, (float)MaxCeilingHeightCenter, (float)MinCeilingHeightCenter, GridSize, MaxOffset - )); + ))); } else if (NoCaseCompare(*itr, "Snow") == 0) { - m_FinishGens.push_back(new cFinishGenSnow); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSnow)); } else if (NoCaseCompare(*itr, "SprinkleFoliage") == 0) { - m_FinishGens.push_back(new cFinishGenSprinkleFoliage(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSprinkleFoliage(Seed))); } else if (NoCaseCompare(*itr, "TallGrass") == 0) { - m_FinishGens.push_back(new cFinishGenTallGrass(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenTallGrass(Seed))); } else if (NoCaseCompare(*itr, "TestRails") == 0) { - m_FinishGens.push_back(new cTestRailsGen(Seed, 100, 1, 7, 50)); + m_FinishGens.push_back(cFinishGenPtr(new cTestRailsGen(Seed, 100, 1, 7, 50))); } else if (NoCaseCompare(*itr, "Trees") == 0) { - m_FinishGens.push_back(new cStructGenTrees(Seed, m_BiomeGen, m_HeightGen, m_CompositionGen)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenTrees(Seed, m_BiomeGen, m_HeightGen, m_CompositionGen))); } else if (NoCaseCompare(*itr, "UnderwaterBases") == 0) { @@ -617,7 +584,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxOffset = a_IniFile.GetValueSetI("Generator", "UnderwaterBaseMaxOffset", 128); int MaxDepth = a_IniFile.GetValueSetI("Generator", "UnderwaterBaseMaxDepth", 7); int MaxSize = a_IniFile.GetValueSetI("Generator", "UnderwaterBaseMaxSize", 128); - m_FinishGens.push_back(new cUnderwaterBaseGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, *m_BiomeGen)); + m_FinishGens.push_back(cFinishGenPtr(new cUnderwaterBaseGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, m_BiomeGen))); } else if (NoCaseCompare(*itr, "Villages") == 0) { @@ -627,23 +594,23 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxSize = a_IniFile.GetValueSetI("Generator", "VillageMaxSize", 128); int MinDensity = a_IniFile.GetValueSetI("Generator", "VillageMinDensity", 50); int MaxDensity = a_IniFile.GetValueSetI("Generator", "VillageMaxDensity", 80); - m_FinishGens.push_back(new cVillageGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, MinDensity, MaxDensity, *m_BiomeGen, *m_HeightGen)); + m_FinishGens.push_back(cFinishGenPtr(new cVillageGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, MinDensity, MaxDensity, m_BiomeGen, m_HeightGen))); } else if (NoCaseCompare(*itr, "WaterLakes") == 0) { int Probability = a_IniFile.GetValueSetI("Generator", "WaterLakesProbability", 25); - m_FinishGens.push_back(new cStructGenLakes(Seed * 3 + 652, E_BLOCK_STATIONARY_WATER, *m_HeightGen, Probability)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenLakes(Seed * 3 + 652, E_BLOCK_STATIONARY_WATER, m_HeightGen, Probability))); } else if (NoCaseCompare(*itr, "WaterSprings") == 0) { - m_FinishGens.push_back(new cFinishGenFluidSprings(Seed, E_BLOCK_WATER, a_IniFile, Dimension)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenFluidSprings(Seed, E_BLOCK_WATER, a_IniFile, Dimension))); } else if (NoCaseCompare(*itr, "WormNestCaves") == 0) { int Size = a_IniFile.GetValueSetI("Generator", "WormNestCavesSize", 64); int Grid = a_IniFile.GetValueSetI("Generator", "WormNestCavesGrid", 96); int MaxOffset = a_IniFile.GetValueSetI("Generator", "WormNestMaxOffset", 32); - m_FinishGens.push_back(new cStructGenWormNestCaves(Seed, Size, Grid, MaxOffset)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenWormNestCaves(Seed, Size, Grid, MaxOffset))); } else { diff --git a/src/Generating/ComposableGenerator.h b/src/Generating/ComposableGenerator.h index 6b7627d2e..a091f8d53 100644 --- a/src/Generating/ComposableGenerator.h +++ b/src/Generating/ComposableGenerator.h @@ -24,6 +24,16 @@ See http://forum.mc-server.org/showthread.php?tid=409 for details. +// Forward-declare the shared pointers to subgenerator classes: +class cBiomeGen; +class cTerrainHeightGen; +class cTerrainCompositionGen; +class cFinishGen; +typedef SharedPtr cBiomeGenPtr; +typedef SharedPtr cTerrainHeightGenPtr; +typedef SharedPtr cTerrainCompositionGenPtr; +typedef SharedPtr cFinishGenPtr; + // fwd: Noise3DGenerator.h class cNoise3DComposable; @@ -53,8 +63,7 @@ public: a_CacheOffByDefault gets set to whether the cache should be disabled by default. Used in BiomeVisualiser, too. Implemented in BioGen.cpp! */ - static cBiomeGen * CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault); - + static cBiomeGenPtr CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault); } ; @@ -83,7 +92,7 @@ public: a_CacheOffByDefault gets set to whether the cache should be disabled by default Implemented in HeiGen.cpp! */ - static cTerrainHeightGen * CreateHeightGen(cIniFile & a_IniFile, cBiomeGen & a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault); + static cTerrainHeightGenPtr CreateHeightGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault); } ; @@ -109,7 +118,7 @@ public: a_BiomeGen is the underlying biome generator, some composition generators may depend on it to generate more biomes a_HeightGen is the underlying height generator, some composition generators may depend on it providing additional values */ - static cTerrainCompositionGen * CreateCompositionGen(cIniFile & a_IniFile, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed); + static cTerrainCompositionGenPtr CreateCompositionGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed); } ; @@ -131,7 +140,7 @@ public: virtual void GenFinish(cChunkDesc & a_ChunkDesc) = 0; } ; -typedef std::list cFinishGenList; +typedef std::list cFinishGenList; @@ -144,7 +153,6 @@ class cComposableGenerator : public: cComposableGenerator(cChunkGenerator & a_ChunkGenerator); - virtual ~cComposableGenerator(); virtual void Initialize(cIniFile & a_IniFile) override; virtual void GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) override; @@ -152,15 +160,10 @@ public: protected: // The generation composition: - cBiomeGen * m_BiomeGen; - cTerrainHeightGen * m_HeightGen; - cTerrainCompositionGen * m_CompositionGen; - cFinishGenList m_FinishGens; - - // Generators underlying the caches: - cBiomeGen * m_UnderlyingBiomeGen; - cTerrainHeightGen * m_UnderlyingHeightGen; - cTerrainCompositionGen * m_UnderlyingCompositionGen; + cBiomeGenPtr m_BiomeGen; + cTerrainHeightGenPtr m_HeightGen; + cTerrainCompositionGenPtr m_CompositionGen; + cFinishGenList m_FinishGens; /** Reads the biome gen settings from the ini and initializes m_BiomeGen accordingly */ diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index bf8995dcb..e6849fadf 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -276,13 +276,13 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = -cDistortedHeightmap::cDistortedHeightmap(int a_Seed, cBiomeGen & a_BiomeGen) : +cDistortedHeightmap::cDistortedHeightmap(int a_Seed, cBiomeGenPtr a_BiomeGen) : m_NoiseDistortX(a_Seed + 1000), m_NoiseDistortZ(a_Seed + 2000), m_OceanFloorSelect(a_Seed + 3000), m_MesaFloor(a_Seed + 4000), m_BiomeGen(a_BiomeGen), - m_UnderlyingHeiGen(a_Seed, a_BiomeGen), + m_UnderlyingHeiGen(new cHeiGenBiomal(a_Seed, a_BiomeGen)), m_HeightGen(m_UnderlyingHeiGen, 64), m_IsInitialized(false) { @@ -577,7 +577,7 @@ void cDistortedHeightmap::UpdateDistortAmps(void) { for (int x = -1; x <= 1; x++) { - m_BiomeGen.GenBiomes(m_CurChunkX + x, m_CurChunkZ + z, Biomes[x + 1][z + 1]); + m_BiomeGen->GenBiomes(m_CurChunkX + x, m_CurChunkZ + z, Biomes[x + 1][z + 1]); } // for x } // for z diff --git a/src/Generating/DistortedHeightmap.h b/src/Generating/DistortedHeightmap.h index e6b3c9d3f..d073f29e4 100644 --- a/src/Generating/DistortedHeightmap.h +++ b/src/Generating/DistortedHeightmap.h @@ -35,7 +35,7 @@ public: NIBBLETYPE BlockMeta; } ; - cDistortedHeightmap(int a_Seed, cBiomeGen & a_BiomeGen); + cDistortedHeightmap(int a_Seed, cBiomeGenPtr a_BiomeGen); protected: typedef cChunkDef::BiomeMap BiomeNeighbors[3][3]; @@ -64,9 +64,14 @@ protected: int m_CurChunkZ; NOISE_DATATYPE m_DistortedHeightmap[17 * 257 * 17]; - cBiomeGen & m_BiomeGen; - cHeiGenBiomal m_UnderlyingHeiGen; // This generator provides us with base heightmap (before distortion) - cHeiGenCache m_HeightGen; // Cache above m_UnderlyingHeiGen + /** The bime generator to query for biomes. */ + cBiomeGenPtr m_BiomeGen; + + /** The generator that provides the base heightmap (before distortion). */ + cTerrainHeightGenPtr m_UnderlyingHeiGen; + + /** Cache for m_UnderlyingHeiGen. */ + cHeiGenCache m_HeightGen; /// Heightmap for the current chunk, before distortion (from m_HeightGen). Used for optimization. cChunkDef::HeightMap m_CurChunkHeights; diff --git a/src/Generating/DungeonRoomsFinisher.cpp b/src/Generating/DungeonRoomsFinisher.cpp index 492bae129..93fe8b472 100644 --- a/src/Generating/DungeonRoomsFinisher.cpp +++ b/src/Generating/DungeonRoomsFinisher.cpp @@ -258,7 +258,7 @@ protected: //////////////////////////////////////////////////////////////////////////////// // cDungeonRoomsFinisher: -cDungeonRoomsFinisher::cDungeonRoomsFinisher(cTerrainHeightGen & a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib) : +cDungeonRoomsFinisher::cDungeonRoomsFinisher(cTerrainHeightGenPtr a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib) : super(a_Seed + 100, a_GridSize, a_GridSize, a_GridSize, a_GridSize, a_MaxSize, a_MaxSize, 1024), m_HeightGen(a_HeightGen), m_MaxHalfSize((a_MaxSize + 1) / 2), @@ -294,7 +294,7 @@ cDungeonRoomsFinisher::cStructurePtr cDungeonRoomsFinisher::CreateStructure(int int RelX = a_OriginX, RelY = 0, RelZ = a_OriginZ; cChunkDef::AbsoluteToRelative(RelX, RelY, RelZ, ChunkX, ChunkZ); cChunkDef::HeightMap HeightMap; - m_HeightGen.GenHeightMap(ChunkX, ChunkZ, HeightMap); + m_HeightGen->GenHeightMap(ChunkX, ChunkZ, HeightMap); int Height = cChunkDef::GetHeight(HeightMap, RelX, RelZ); // Max room height at {a_OriginX, a_OriginZ} Height = Clamp(m_HeightProbability.MapValue(rnd % m_HeightProbability.GetSum()), 10, Height - 5); diff --git a/src/Generating/DungeonRoomsFinisher.h b/src/Generating/DungeonRoomsFinisher.h index 2b52c9de6..09dd0448a 100644 --- a/src/Generating/DungeonRoomsFinisher.h +++ b/src/Generating/DungeonRoomsFinisher.h @@ -26,12 +26,12 @@ public: a_HeightGen is the underlying height generator, so that the rooms can always be placed under the terrain. a_MaxSize and a_MinSize are the maximum and minimum sizes of the room's internal (air) area, in blocks across. a_HeightDistrib is the string defining the height distribution for the rooms (cProbabDistrib format). */ - cDungeonRoomsFinisher(cTerrainHeightGen & a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib); + cDungeonRoomsFinisher(cTerrainHeightGenPtr a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib); protected: /** The height gen that is used for limiting the rooms' Y coords */ - cTerrainHeightGen & m_HeightGen; + cTerrainHeightGenPtr m_HeightGen; /** Maximum half-size (from center to wall) of the dungeon room's inner (air) area. Default is 3 (vanilla). */ int m_MaxHalfSize; diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index 79d529a6a..23f589f55 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -19,7 +19,7 @@ //////////////////////////////////////////////////////////////////////////////// // cTerrainHeightGen: -cTerrainHeightGen * cTerrainHeightGen::CreateHeightGen(cIniFile &a_IniFile, cBiomeGen & a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault) +cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault) { AString HeightGenName = a_IniFile.GetValueSet("Generator", "HeightGen", ""); if (HeightGenName.empty()) @@ -84,7 +84,7 @@ cTerrainHeightGen * cTerrainHeightGen::CreateHeightGen(cIniFile &a_IniFile, cBio // Read the settings: res->InitializeHeightGen(a_IniFile); - return res; + return cTerrainHeightGenPtr(res); } @@ -118,7 +118,7 @@ void cHeiGenFlat::InitializeHeightGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cHeiGenCache: -cHeiGenCache::cHeiGenCache(cTerrainHeightGen & a_HeiGenToCache, int a_CacheSize) : +cHeiGenCache::cHeiGenCache(cTerrainHeightGenPtr a_HeiGenToCache, int a_CacheSize) : m_HeiGenToCache(a_HeiGenToCache), m_CacheSize(a_CacheSize), m_CacheOrder(new int[a_CacheSize]), @@ -190,7 +190,7 @@ void cHeiGenCache::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap // Not in the cache: m_NumMisses++; - m_HeiGenToCache.GenHeightMap(a_ChunkX, a_ChunkZ, a_HeightMap); + m_HeiGenToCache->GenHeightMap(a_ChunkX, a_ChunkZ, a_HeightMap); // Insert it as the first item in the MRU order: int Idx = m_CacheOrder[m_CacheSize - 1]; @@ -210,7 +210,7 @@ void cHeiGenCache::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap void cHeiGenCache::InitializeHeightGen(cIniFile & a_IniFile) { - m_HeiGenToCache.InitializeHeightGen(a_IniFile); + m_HeiGenToCache->InitializeHeightGen(a_IniFile); } @@ -479,7 +479,7 @@ void cHeiGenBiomal::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMa { for (int x = -1; x <= 1; x++) { - m_BiomeGen.GenBiomes(a_ChunkX + x, a_ChunkZ + z, Biomes[x + 1][z + 1]); + m_BiomeGen->GenBiomes(a_ChunkX + x, a_ChunkZ + z, Biomes[x + 1][z + 1]); } // for x } // for z diff --git a/src/Generating/HeiGen.h b/src/Generating/HeiGen.h index 5c106c7d9..9eab9a94f 100644 --- a/src/Generating/HeiGen.h +++ b/src/Generating/HeiGen.h @@ -45,7 +45,7 @@ class cHeiGenCache : public cTerrainHeightGen { public: - cHeiGenCache(cTerrainHeightGen & a_HeiGenToCache, int a_CacheSize); // Doesn't take ownership of a_HeiGenToCache + cHeiGenCache(cTerrainHeightGenPtr a_HeiGenToCache, int a_CacheSize); ~cHeiGenCache(); // cTerrainHeightGen overrides: @@ -57,7 +57,7 @@ public: protected: - cTerrainHeightGen & m_HeiGenToCache; + cTerrainHeightGenPtr m_HeiGenToCache; struct sCacheData { @@ -131,7 +131,7 @@ class cHeiGenBiomal : public cTerrainHeightGen { public: - cHeiGenBiomal(int a_Seed, cBiomeGen & a_BiomeGen) : + cHeiGenBiomal(int a_Seed, cBiomeGenPtr a_BiomeGen) : m_Noise(a_Seed), m_BiomeGen(a_BiomeGen) { @@ -141,8 +141,8 @@ protected: typedef cChunkDef::BiomeMap BiomeNeighbors[3][3]; - cNoise m_Noise; - cBiomeGen & m_BiomeGen; + cNoise m_Noise; + cBiomeGenPtr m_BiomeGen; // Per-biome terrain generator parameters: struct sGenParam diff --git a/src/Generating/StructGen.cpp b/src/Generating/StructGen.cpp index c23a72621..bdefcd8c1 100644 --- a/src/Generating/StructGen.cpp +++ b/src/Generating/StructGen.cpp @@ -411,7 +411,7 @@ void cStructGenLakes::CreateLakeImage(int a_ChunkX, int a_ChunkZ, cBlockArea & a // Find the minimum height in this chunk: cChunkDef::HeightMap HeightMap; - m_HeiGen.GenHeightMap(a_ChunkX, a_ChunkZ, HeightMap); + m_HeiGen->GenHeightMap(a_ChunkX, a_ChunkZ, HeightMap); HEIGHTTYPE MinHeight = HeightMap[0]; for (size_t i = 1; i < ARRAYCOUNT(HeightMap); i++) { diff --git a/src/Generating/StructGen.h b/src/Generating/StructGen.h index 96aa3e437..906fdd722 100644 --- a/src/Generating/StructGen.h +++ b/src/Generating/StructGen.h @@ -24,7 +24,7 @@ class cStructGenTrees : public cFinishGen { public: - cStructGenTrees(int a_Seed, cBiomeGen * a_BiomeGen, cTerrainHeightGen * a_HeightGen, cTerrainCompositionGen * a_CompositionGen) : + cStructGenTrees(int a_Seed, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen, cTerrainCompositionGenPtr a_CompositionGen) : m_Seed(a_Seed), m_Noise(a_Seed), m_BiomeGen(a_BiomeGen), @@ -36,9 +36,9 @@ protected: int m_Seed; cNoise m_Noise; - cBiomeGen * m_BiomeGen; - cTerrainHeightGen * m_HeightGen; - cTerrainCompositionGen * m_CompositionGen; + cBiomeGenPtr m_BiomeGen; + cTerrainHeightGenPtr m_HeightGen; + cTerrainCompositionGenPtr m_CompositionGen; /** Generates and applies an image of a single tree. Parts of the tree inside the chunk are applied to a_BlockX. @@ -124,7 +124,7 @@ class cStructGenLakes : public cFinishGen { public: - cStructGenLakes(int a_Seed, BLOCKTYPE a_Fluid, cTerrainHeightGen & a_HeiGen, int a_Probability) : + cStructGenLakes(int a_Seed, BLOCKTYPE a_Fluid, cTerrainHeightGenPtr a_HeiGen, int a_Probability) : m_Noise(a_Seed), m_Seed(a_Seed), m_Fluid(a_Fluid), @@ -134,11 +134,11 @@ public: } protected: - cNoise m_Noise; - int m_Seed; - BLOCKTYPE m_Fluid; - cTerrainHeightGen & m_HeiGen; - int m_Probability; ///< Chance, 0 .. 100, of a chunk having the lake + cNoise m_Noise; + int m_Seed; + BLOCKTYPE m_Fluid; + cTerrainHeightGenPtr m_HeiGen; + int m_Probability; ///< Chance, 0 .. 100, of a chunk having the lake // cFinishGen override: virtual void GenFinish(cChunkDesc & a_ChunkDesc) override; diff --git a/src/Generating/UnderwaterBaseGen.cpp b/src/Generating/UnderwaterBaseGen.cpp index 9278ea546..8916f4b5f 100644 --- a/src/Generating/UnderwaterBaseGen.cpp +++ b/src/Generating/UnderwaterBaseGen.cpp @@ -93,7 +93,7 @@ protected: -cUnderwaterBaseGen::cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGen & a_BiomeGen) : +cUnderwaterBaseGen::cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGenPtr a_BiomeGen) : super(a_Seed, a_GridSize, a_GridSize, a_MaxOffset, a_MaxOffset, a_MaxSize, a_MaxSize, 100), m_Noise(a_Seed + 1000), m_MaxDepth(a_MaxDepth), @@ -112,7 +112,7 @@ cGridStructGen::cStructurePtr cUnderwaterBaseGen::CreateStructure(int a_GridX, i int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_OriginX, a_OriginZ, ChunkX, ChunkZ); cChunkDef::BiomeMap Biomes; - m_BiomeGen.GenBiomes(ChunkX, ChunkZ, Biomes); + m_BiomeGen->GenBiomes(ChunkX, ChunkZ, Biomes); // Check if all the biomes are ocean: // If just one is not, no base is created, because it's likely that an unfriendly biome is too close diff --git a/src/Generating/UnderwaterBaseGen.h b/src/Generating/UnderwaterBaseGen.h index d6267b602..b24eb1075 100644 --- a/src/Generating/UnderwaterBaseGen.h +++ b/src/Generating/UnderwaterBaseGen.h @@ -22,7 +22,7 @@ class cUnderwaterBaseGen : typedef cGridStructGen super; public: - cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGen & a_BiomeGen); + cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGenPtr a_BiomeGen); protected: class cUnderwaterBase; // fwd: UnderwaterBaseGen.cpp @@ -38,7 +38,7 @@ protected: int m_MaxSize; /** The underlying biome generator that defines whether the base is created or not */ - cBiomeGen & m_BiomeGen; + cBiomeGenPtr m_BiomeGen; // cGridStructGen overrides: diff --git a/src/Generating/VillageGen.cpp b/src/Generating/VillageGen.cpp index a7f66b75e..1806fd427 100644 --- a/src/Generating/VillageGen.cpp +++ b/src/Generating/VillageGen.cpp @@ -116,7 +116,7 @@ public: int a_MaxSize, int a_Density, cPiecePool & a_Prefabs, - cTerrainHeightGen & a_HeightGen, + cTerrainHeightGenPtr a_HeightGen, BLOCKTYPE a_RoadBlock, BLOCKTYPE a_WaterRoadBlock ) : @@ -175,7 +175,7 @@ protected: cPiecePool & m_Prefabs; /** The underlying height generator, used for placing the structures on top of the terrain. */ - cTerrainHeightGen & m_HeightGen; + cTerrainHeightGenPtr m_HeightGen; /** The village pieces, placed by the generator. */ cPlacedPieces m_Pieces; @@ -194,7 +194,7 @@ protected: // Each intersecting prefab is placed on ground, then drawn // Each intersecting road is drawn by replacing top soil blocks with gravel / sandstone blocks cChunkDef::HeightMap HeightMap; // Heightmap for this chunk, used by roads - m_HeightGen.GenHeightMap(a_Chunk.GetChunkX(), a_Chunk.GetChunkZ(), HeightMap); + m_HeightGen->GenHeightMap(a_Chunk.GetChunkX(), a_Chunk.GetChunkZ(), HeightMap); for (cPlacedPieces::iterator itr = m_Pieces.begin(), end = m_Pieces.end(); itr != end; ++itr) { cPrefab & Prefab = (cPrefab &)((*itr)->GetPiece()); @@ -224,7 +224,7 @@ protected: int BlockY; cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cChunkDef::HeightMap HeightMap; - m_HeightGen.GenHeightMap(ChunkX, ChunkZ, HeightMap); + m_HeightGen->GenHeightMap(ChunkX, ChunkZ, HeightMap); int TerrainHeight = cChunkDef::GetHeight(HeightMap, BlockX, BlockZ); a_Piece.MoveToGroundBy(TerrainHeight - FirstConnector.m_Pos.y + 1); } @@ -359,7 +359,7 @@ static cVillagePiecePool * g_PlainsVillagePools[] = -cVillageGen::cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen) : +cVillageGen::cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen) : super(a_Seed, a_GridSize, a_GridSize, a_MaxOffset, a_MaxOffset, a_MaxSize, a_MaxSize, 100), m_Noise(a_Seed + 1000), m_MaxDepth(a_MaxDepth), @@ -381,7 +381,7 @@ cGridStructGen::cStructurePtr cVillageGen::CreateStructure(int a_GridX, int a_Gr int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_OriginX, a_OriginZ, ChunkX, ChunkZ); cChunkDef::BiomeMap Biomes; - m_BiomeGen.GenBiomes(ChunkX, ChunkZ, Biomes); + m_BiomeGen->GenBiomes(ChunkX, ChunkZ, Biomes); // Check if all the biomes are village-friendly: // If just one is not, no village is created, because it's likely that an unfriendly biome is too close diff --git a/src/Generating/VillageGen.h b/src/Generating/VillageGen.h index 694ea2358..ed8d739df 100644 --- a/src/Generating/VillageGen.h +++ b/src/Generating/VillageGen.h @@ -21,7 +21,7 @@ class cVillageGen : { typedef cGridStructGen super; public: - cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen); + cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen); protected: class cVillage; // fwd: VillageGen.cpp @@ -42,10 +42,10 @@ protected: int m_MaxDensity; /** The underlying biome generator that defines whether the village is created or not */ - cBiomeGen & m_BiomeGen; + cBiomeGenPtr m_BiomeGen; /** The underlying height generator, used to position the prefabs crossing chunk borders */ - cTerrainHeightGen & m_HeightGen; + cTerrainHeightGenPtr m_HeightGen; // cGridStructGen overrides: -- cgit v1.2.3 From 3ee47df1187da06c80a9ea69ec5cb8ee1c863375 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 14:35:49 +0200 Subject: Mountain height gen: Added ditches. --- src/Generating/HeiGen.cpp | 21 ++++++++++++++------- src/Generating/HeiGen.h | 3 ++- 2 files changed, 16 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index 23f589f55..b7d4b337c 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -317,7 +317,9 @@ void cHeiGenClassic::InitializeHeightGen(cIniFile & a_IniFile) cHeiGenMountains::cHeiGenMountains(int a_Seed) : m_Seed(a_Seed), - m_Noise(a_Seed) + m_MountainNoise(a_Seed + 100), + m_DitchNoise(a_Seed + 200), + m_Perlin(a_Seed + 300) { } @@ -332,9 +334,11 @@ void cHeiGenMountains::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Heigh NOISE_DATATYPE StartZ = (NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width); NOISE_DATATYPE EndZ = (NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width + cChunkDef::Width - 1); NOISE_DATATYPE Workspace[16 * 16]; - NOISE_DATATYPE Noise[16 * 16]; + NOISE_DATATYPE MountainNoise[16 * 16]; + NOISE_DATATYPE DitchNoise[16 * 16]; NOISE_DATATYPE PerlinNoise[16 * 16]; - m_Noise.Generate2D(Noise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); + m_MountainNoise.Generate2D(MountainNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); + m_DitchNoise.Generate2D(DitchNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); m_Perlin.Generate2D(PerlinNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); for (int z = 0; z < cChunkDef::Width; z++) { @@ -342,7 +346,7 @@ void cHeiGenMountains::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Heigh for (int x = 0; x < cChunkDef::Width; x++) { int idx = IdxZ + x; - int hei = 100 - (int)((Noise[idx] + PerlinNoise[idx]) * 15); + int hei = 100 - (int)((MountainNoise[idx] - DitchNoise[idx] + PerlinNoise[idx]) * 15); if (hei < 10) { hei = 10; @@ -363,9 +367,12 @@ void cHeiGenMountains::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Heigh void cHeiGenMountains::InitializeHeightGen(cIniFile & a_IniFile) { // TODO: Read the params from an INI file - m_Noise.AddOctave(0.1f, 0.1f); - m_Noise.AddOctave(0.05f, 0.5f); - m_Noise.AddOctave(0.02f, 1.5f); + m_MountainNoise.AddOctave(0.1f, 0.2f); + m_MountainNoise.AddOctave(0.05f, 0.4f); + m_MountainNoise.AddOctave(0.02f, 1.0f); + m_DitchNoise.AddOctave(0.1f, 0.2f); + m_DitchNoise.AddOctave(0.05f, 0.4f); + m_DitchNoise.AddOctave(0.02f, 1.0f); m_Perlin.AddOctave(0.01f, 1.5f); } diff --git a/src/Generating/HeiGen.h b/src/Generating/HeiGen.h index 9eab9a94f..6ae5ba362 100644 --- a/src/Generating/HeiGen.h +++ b/src/Generating/HeiGen.h @@ -115,7 +115,8 @@ public: protected: int m_Seed; - cRidgedMultiNoise m_Noise; + cRidgedMultiNoise m_MountainNoise; + cRidgedMultiNoise m_DitchNoise; cPerlinNoise m_Perlin; // cTerrainHeightGen overrides: -- cgit v1.2.3 From 403f8581cf4a10e8402a129eca3f595eb5c029ab Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Sun, 19 Oct 2014 15:01:01 +0200 Subject: Added mechanics placeable on halfslabs --- src/Blocks/BlockLever.h | 36 +++++++++++++++++++++++++++++------- src/Blocks/BlockRedstone.h | 27 +++++++++++++++++++++++++-- src/Blocks/BlockRedstoneRepeater.h | 25 ++++++++++++++++++++++++- src/Blocks/BlockSlab.h | 1 + 4 files changed, 79 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockLever.h b/src/Blocks/BlockLever.h index 3b63b396c..f5bedea6c 100644 --- a/src/Blocks/BlockLever.h +++ b/src/Blocks/BlockLever.h @@ -1,9 +1,9 @@ #pragma once #include "BlockHandler.h" +#include "../Chunk.h" #include "MetaRotator.h" - - +#include "BlockSlab.h" class cBlockLeverHandler : @@ -93,13 +93,35 @@ public: virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - NIBBLETYPE Meta; - a_Chunk.UnboundedRelGetBlockMeta(a_RelX, a_RelY, a_RelZ, Meta); + NIBBLETYPE Meta = a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ); + + eBlockFace Face = BlockMetaDataToBlockFace(Meta); + + AddFaceDirection(a_RelX, a_RelY, a_RelZ, Face, true); + + if ((a_RelY < 0) || (a_RelY >= cChunkDef::Height -1)) + { + return false; + } + + BLOCKTYPE BlockIsOn; + a_Chunk.UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockIsOn, Meta); - AddFaceDirection(a_RelX, a_RelY, a_RelZ, BlockMetaDataToBlockFace(Meta), true); - BLOCKTYPE BlockIsOn; a_Chunk.UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, BlockIsOn); - return (a_RelY > 0) && cBlockInfo::FullyOccupiesVoxel(BlockIsOn); + if (cBlockInfo::FullyOccupiesVoxel(BlockIsOn)) + { + return true; + } + else if (cBlockSlabHandler::IsAnySlabType(BlockIsOn)) + { + // Check if the slab is turned up side down + if (((Meta & 0x08) == 0x08) && (Face == BLOCK_FACE_TOP)) + { + return true; + } + } + + return false; } diff --git a/src/Blocks/BlockRedstone.h b/src/Blocks/BlockRedstone.h index 37d61ed73..2785eb479 100644 --- a/src/Blocks/BlockRedstone.h +++ b/src/Blocks/BlockRedstone.h @@ -3,6 +3,7 @@ #include "BlockHandler.h" #include "../World.h" +#include "BlockSlab.h" @@ -16,11 +17,33 @@ public: : cBlockHandler(a_BlockType) { } - + + virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - return ((a_RelY > 0) && cBlockInfo::FullyOccupiesVoxel(a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ))); + if (a_RelY <= 0) + { + return false; + } + + BLOCKTYPE BelowBlock; + NIBBLETYPE BelowBlockMeta; + a_Chunk.GetBlockTypeMeta(a_RelX, a_RelY - 1, a_RelZ, BelowBlock, BelowBlockMeta); + + if (cBlockInfo::FullyOccupiesVoxel(BelowBlock)) + { + return true; + } + else if (cBlockSlabHandler::IsAnySlabType(BelowBlock)) + { + // Check if the slab is turned up side down + if ((BelowBlockMeta & 0x08) == 0x08) + { + return true; + } + } + return false; } diff --git a/src/Blocks/BlockRedstoneRepeater.h b/src/Blocks/BlockRedstoneRepeater.h index 1eb67f714..e8262dc40 100644 --- a/src/Blocks/BlockRedstoneRepeater.h +++ b/src/Blocks/BlockRedstoneRepeater.h @@ -5,6 +5,7 @@ #include "Chunk.h" #include "MetaRotator.h" #include "ChunkInterface.h" +#include "BlockSlab.h" @@ -44,6 +45,7 @@ public: } + virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { // Reset meta to zero @@ -59,7 +61,28 @@ public: virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - return ((a_RelY > 0) && cBlockInfo::IsSolid(a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ))); + if (a_RelY <= 0) + { + return false; + } + + BLOCKTYPE BelowBlock; + NIBBLETYPE BelowBlockMeta; + a_Chunk.GetBlockTypeMeta(a_RelX, a_RelY - 1, a_RelZ, BelowBlock, BelowBlockMeta); + + if (cBlockInfo::FullyOccupiesVoxel(BelowBlock)) + { + return true; + } + else if (cBlockSlabHandler::IsAnySlabType(BelowBlock)) + { + // Check if the slab is turned up side down + if ((BelowBlockMeta & 0x08) == 0x08) + { + return true; + } + } + return false; } diff --git a/src/Blocks/BlockSlab.h b/src/Blocks/BlockSlab.h index ffe2414f7..d762154df 100644 --- a/src/Blocks/BlockSlab.h +++ b/src/Blocks/BlockSlab.h @@ -13,6 +13,7 @@ #include "../Items/ItemHandler.h" #include "Root.h" #include "ChunkInterface.h" +#include "../Entities/Player.h" -- cgit v1.2.3 From 3082f0d0460d84500259c854d9bf3b1997827d90 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Sun, 19 Oct 2014 15:11:53 +0200 Subject: Fixed error with non-const function --- src/Chunk.cpp | 2 +- src/Chunk.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Chunk.cpp b/src/Chunk.cpp index d03e0bf21..7d6d88b26 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -2614,7 +2614,7 @@ BLOCKTYPE cChunk::GetBlock(int a_RelX, int a_RelY, int a_RelZ) const -void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) +void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { a_BlockType = GetBlock(a_RelX, a_RelY, a_RelZ); a_BlockMeta = m_ChunkData.GetMeta(a_RelX, a_RelY, a_RelZ); diff --git a/src/Chunk.h b/src/Chunk.h index c50be263f..5f8fcaf7b 100644 --- a/src/Chunk.h +++ b/src/Chunk.h @@ -186,7 +186,7 @@ public: void FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, BLOCKTYPE a_BlockMeta, bool a_SendToClients = true); // 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(const Vector3i & a_RelCoords) const { return GetBlock(a_RelCoords.x, a_RelCoords.y, a_RelCoords.z); } - void GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta); + void GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const; void GetBlockInfo (int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight); /** Returns the chunk into which the specified block belongs, by walking the neighbors. -- cgit v1.2.3 From 262e6d06aa3ce18eb8f676a0fa659085ef11d9e4 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 16:07:29 +0200 Subject: TwoLevel BioGen: fixed swapped inside and outside biomes. --- src/Generating/BioGen.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index f5fe3e980..b9face1f8 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -772,7 +772,7 @@ void cBioGenTwoLevel::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap int BiomeGroup = m_VoronoiLarge.GetValueAt(DistortX[x][z], DistortZ[x][z], SeedX, SeedZ, MinDist2) / 7; int BiomeIdx = m_VoronoiSmall.GetValueAt(DistortX[x][z], DistortZ[x][z], SeedX, SeedZ, MinDist2) / 11; int MinDist1 = (DistortX[x][z] - SeedX) * (DistortX[x][z] - SeedX) + (DistortZ[x][z] - SeedZ) * (DistortZ[x][z] - SeedZ); - cChunkDef::SetBiome(a_BiomeMap, x, z, SelectBiome(BiomeGroup, BiomeIdx, (MinDist1 < MinDist2 / 4) ? 0 : 1)); + cChunkDef::SetBiome(a_BiomeMap, x, z, SelectBiome(BiomeGroup, BiomeIdx, (MinDist1 < MinDist2 / 4) ? 1 : 0)); } } } -- cgit v1.2.3 From cf73fee7e362134dc4caabc7c99f3a5bb0593a99 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 18:45:32 +0200 Subject: Fixed minor style issues. --- src/Bindings/LuaState.h | 2 +- src/ClientHandle.h | 2 +- src/ItemGrid.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index 779760017..899228a66 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -363,7 +363,7 @@ protected: } /** Variadic template recursor: More params to push. Push them and recurse. */ - template + template inline bool PushCallPop(T a_Param, Args &&... args) { Push(a_Param); diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 9733ff32d..80cf16963 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -343,7 +343,7 @@ private: cCriticalSection m_CSChunkLists; cChunkCoordsList m_LoadedChunks; // Chunks that the player belongs to cChunkCoordsList m_ChunksToSend; // Chunks that need to be sent to the player (queued because they weren't generated yet or there's not enough time to send them) - cChunkCoordsList m_SentChunks; // Store the coordinates of the chunks that the client has loaded + cChunkCoordsList m_SentChunks; // Chunks that are currently sent to the client cProtocol * m_Protocol; diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 0bd44bb0d..1977216d8 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -642,7 +642,7 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s // Choose the enchantments cWeightedEnchantments Enchantments; cEnchantments::AddItemEnchantmentWeights(Enchantments, E_ITEM_BOOK, 24 + Noise.IntNoise2DInt(a_Seed, TotalProbab) % 7); - int NumEnchantments = Noise.IntNoise3DInt(TotalProbab, Rnd, a_Seed) % 5; // The number of enchantments this book wil get. + int NumEnchantments = Noise.IntNoise3DInt(TotalProbab, Rnd, a_Seed) % 5; // The number of enchantments this book wil get. for (int j = 0; j <= NumEnchantments; j++) { -- cgit v1.2.3 From ee23fd5b9eb3e33a38a65c9a61592c45f1aa5ba0 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 19 Oct 2014 18:52:24 +0200 Subject: Removed obsolete tr1::shared_ptr. --- src/Globals.h | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/Globals.h b/src/Globals.h index b84607355..e0a25ed83 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -361,19 +361,8 @@ void inline LOGD(const char* a_Format, ...) #define assert_test(x) ( !!(x) || (assert(!#x), exit(1), 0)) #endif -// 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 (defined(_MSC_VER) || (__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 +// Unified shared ptr from before C++11. Also no silly undercores. +#define SharedPtr std::shared_ptr -- cgit v1.2.3 From 1a46feda43dff022d5a369fb85612b2670fe97e4 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Mon, 20 Oct 2014 14:46:24 +0200 Subject: Added error handling to load command --- src/Bindings/PluginManager.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp index 43507a5fb..ef9638339 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -1525,6 +1525,15 @@ bool cPluginManager::DisablePlugin(const AString & a_PluginName) bool cPluginManager::LoadPlugin(const AString & a_PluginName) { + PluginMap map = GetAllPlugins(); + + for(auto plugin_entry : map) + { + if(plugin_entry.first == a_PluginName) + { + return false; + } + } return AddPlugin(new cPluginLua(a_PluginName.c_str())); } @@ -1827,7 +1836,8 @@ bool cPluginManager::DoWithPlugin(const AString & a_PluginName, cPluginCallback bool cPluginManager::AddPlugin(cPlugin * a_Plugin) { - m_Plugins[a_Plugin->GetDirectory()] = a_Plugin; + m_Plugins[a_Plugin->GetDirectory()] = a_Plugin; + if (a_Plugin->Initialize()) { // Initialization OK -- cgit v1.2.3 From c2560cc1be9a41dc80733fa8c55b00ec6e15a7f0 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Mon, 20 Oct 2014 15:08:48 +0200 Subject: Added error message --- src/Bindings/PluginManager.cpp | 9 --------- src/Server.cpp | 11 +++++++++++ 2 files changed, 11 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp index ef9638339..0992ccec1 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -1525,15 +1525,6 @@ bool cPluginManager::DisablePlugin(const AString & a_PluginName) bool cPluginManager::LoadPlugin(const AString & a_PluginName) { - PluginMap map = GetAllPlugins(); - - for(auto plugin_entry : map) - { - if(plugin_entry.first == a_PluginName) - { - return false; - } - } return AddPlugin(new cPluginLua(a_PluginName.c_str())); } diff --git a/src/Server.cpp b/src/Server.cpp index 8e5755a75..67315c8cf 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -491,6 +491,17 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac { if (split.size() > 1) { + cPluginManager::PluginMap map = cPluginManager::Get()->GetAllPlugins(); + + for(auto plugin_entry : map) + { + if(plugin_entry.first == split[1]) + { + a_Output.Out("Error! Plugin is already loaded!"); + a_Output.Finished(); + return; + } + } a_Output.Out(cPluginManager::Get()->LoadPlugin(split[1]) ? "Plugin loaded" : "Error occurred loading plugin"); } else -- cgit v1.2.3 From d2cc1e0cd3dde8c748de8436be4f4ad8c92abb89 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Mon, 20 Oct 2014 15:58:08 +0200 Subject: Fix for fix #1552 --- src/Server.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Server.cpp b/src/Server.cpp index 67315c8cf..db3ab2ed4 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -493,9 +493,9 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac { cPluginManager::PluginMap map = cPluginManager::Get()->GetAllPlugins(); - for(auto plugin_entry : map) + for (auto plugin_entry : map) { - if(plugin_entry.first == split[1]) + if (plugin_entry.first == split[1]) { a_Output.Out("Error! Plugin is already loaded!"); a_Output.Finished(); -- cgit v1.2.3 From 4a58ce1df6add71ea0478c5cee887f3b7bc06ba1 Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Mon, 20 Oct 2014 16:00:33 +0200 Subject: Found it! --- src/Bindings/PluginManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp index 0992ccec1..479e71951 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -1827,7 +1827,7 @@ bool cPluginManager::DoWithPlugin(const AString & a_PluginName, cPluginCallback bool cPluginManager::AddPlugin(cPlugin * a_Plugin) { - m_Plugins[a_Plugin->GetDirectory()] = a_Plugin; + m_Plugins[a_Plugin->GetDirectory()] = a_Plugin; if (a_Plugin->Initialize()) { -- cgit v1.2.3 From b78078a3a677ee6aeabb55077a0db6604c5fe09d Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 20 Oct 2014 17:32:09 +0200 Subject: Fixed a potential crash in cEntity bindings. --- src/Bindings/LuaState.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 2c4d89b01..142242162 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -558,7 +558,11 @@ void cLuaState::Push(cEntity * a_Entity) { ASSERT(IsValid()); - if (a_Entity->IsMob()) + if (a_Entity == nullptr) + { + lua_pushnil(m_LuaState); + } + else if (a_Entity->IsMob()) { // Don't push specific mob types, as those are not exported in the API: tolua_pushusertype(m_LuaState, a_Entity, "cMonster"); @@ -566,7 +570,7 @@ void cLuaState::Push(cEntity * a_Entity) else { // Push the specific class type: - tolua_pushusertype(m_LuaState, a_Entity, (a_Entity == nullptr) ? "cEntity" : a_Entity->GetClass()); + tolua_pushusertype(m_LuaState, a_Entity, a_Entity->GetClass()); } m_NumCurrentFunctionArgs += 1; } -- cgit v1.2.3 From 48470c858b41f4e951a2f5b4f28dce3107a2911f Mon Sep 17 00:00:00 2001 From: Julian Laubstein Date: Mon, 20 Oct 2014 19:36:16 +0200 Subject: Fixed #1550 --- src/Generating/ChunkDesc.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Generating/ChunkDesc.cpp b/src/Generating/ChunkDesc.cpp index c0b646fd0..566332b1f 100644 --- a/src/Generating/ChunkDesc.cpp +++ b/src/Generating/ChunkDesc.cpp @@ -269,10 +269,10 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX LOGWARNING("%s: MaxRelX less than zero, adjusting to zero", __FUNCTION__); a_MaxRelX = 0; } - else if (a_MaxRelX >= cChunkDef::Width) + else if (a_MaxRelX > cChunkDef::Width) { LOGWARNING("%s: MaxRelX more than chunk width, adjusting to chunk width", __FUNCTION__); - a_MaxRelX = cChunkDef::Width - 1; + a_MaxRelX = cChunkDef::Width; } if (a_MinRelY < 0) @@ -290,10 +290,10 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX LOGWARNING("%s: MaxRelY less than zero, adjusting to zero", __FUNCTION__); a_MaxRelY = 0; } - else if (a_MaxRelY >= cChunkDef::Height) + else if (a_MaxRelY > cChunkDef::Height) { LOGWARNING("%s: MaxRelY more than chunk height, adjusting to chunk height", __FUNCTION__); - a_MaxRelY = cChunkDef::Height - 1; + a_MaxRelY = cChunkDef::Height; } if (a_MinRelZ < 0) @@ -311,10 +311,10 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX LOGWARNING("%s: MaxRelZ less than zero, adjusting to zero", __FUNCTION__); a_MaxRelZ = 0; } - else if (a_MaxRelZ >= cChunkDef::Width) + else if (a_MaxRelZ > cChunkDef::Width) { LOGWARNING("%s: MaxRelZ more than chunk width, adjusting to chunk width", __FUNCTION__); - a_MaxRelZ = cChunkDef::Width - 1; + a_MaxRelZ = cChunkDef::Width; } // Prepare the block area: -- cgit v1.2.3 From dc4185fb862ef762b34377907a3f01a4f537c4bc Mon Sep 17 00:00:00 2001 From: Mattes D Date: Tue, 21 Oct 2014 12:43:06 +0200 Subject: cLuaState: cEntity is pushed with specific type. --- src/Bindings/LuaState.cpp | 55 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 142242162..928436a2f 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -562,16 +562,57 @@ void cLuaState::Push(cEntity * a_Entity) { lua_pushnil(m_LuaState); } - else if (a_Entity->IsMob()) - { - // Don't push specific mob types, as those are not exported in the API: - tolua_pushusertype(m_LuaState, a_Entity, "cMonster"); - } else { - // Push the specific class type: - tolua_pushusertype(m_LuaState, a_Entity, a_Entity->GetClass()); + switch (a_Entity->GetEntityType()) + { + case cEntity::etMonster: + { + // Don't push specific mob types, as those are not exported in the API: + tolua_pushusertype(m_LuaState, a_Entity, "cMonster"); + break; + } + case cEntity::etPlayer: + { + tolua_pushusertype(m_LuaState, a_Entity, "cPlayer"); + break; + } + case cEntity::etPickup: + { + tolua_pushusertype(m_LuaState, a_Entity, "cPickup"); + break; + } + case cEntity::etTNT: + { + tolua_pushusertype(m_LuaState, a_Entity, "cTNTEntity"); + break; + } + case cEntity::etProjectile: + { + tolua_pushusertype(m_LuaState, a_Entity, "cProjectileEntity"); + break; + } + case cEntity::etFloater: + { + tolua_pushusertype(m_LuaState, a_Entity, "cFloater"); + break; + } + + case cEntity::etEntity: + case cEntity::etEnderCrystal: + case cEntity::etFallingBlock: + case cEntity::etMinecart: + case cEntity::etBoat: + case cEntity::etExpOrb: + case cEntity::etItemFrame: + case cEntity::etPainting: + { + // Push the generic entity class type: + tolua_pushusertype(m_LuaState, a_Entity, "cEntity"); + } + } // switch (EntityType) } + m_NumCurrentFunctionArgs += 1; } -- cgit v1.2.3 From a07456d7126d61d903eb7c14f88d436d20546474 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 21 Oct 2014 17:00:41 +0200 Subject: New c++11 stuff. --- src/ClientHandle.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index ec1bebe8d..28fcb0d37 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -430,13 +430,13 @@ bool cClientHandle::StreamNextChunk(void) cCSLock Lock(m_CSChunkLists); // High priority: Load the chunks that are in the view-direction of the player (with a radius of 3) - for (size_t Range = 0; Range < (size_t)m_ViewDistance; Range++) + for (int Range = 0; Range < m_ViewDistance; Range++) { Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; // Get the chunk from the x/z coords. int RangeX, RangeZ = 0; - cChunkDef::BlockToChunk((int)std::floor(Vector.x), (int)std::floor(Vector.z), RangeX, RangeZ); + cChunkDef::BlockToChunk(FloorC(Vector.x), FloorC(Vector.z), RangeX, RangeZ); for (size_t X = 0; X < 7; X++) { @@ -471,13 +471,13 @@ bool cClientHandle::StreamNextChunk(void) // Medium priority: Load the chunks that are behind the player LookVector = m_Player->GetLookVector() * -1; - for (size_t Range = 0; Range < 3; Range++) + for (int Range = 0; Range < 3; Range++) { Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; // Get the chunk from the x/z coords. int RangeX, RangeZ = 0; - cChunkDef::BlockToChunk((int)std::floor(Vector.x), (int)std::floor(Vector.z), RangeX, RangeZ); + cChunkDef::BlockToChunk(FloorC(Vector.x), FloorC(Vector.z), RangeX, RangeZ); for (size_t X = 0; X < 7; X++) { -- cgit v1.2.3 From b0988e65aadc1a9d33065cf6afefc05dbf768ef8 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 21 Oct 2014 17:35:23 +0200 Subject: Use two lists and 2 chunk send prioritys. --- src/Chunk.cpp | 2 +- src/ChunkSender.cpp | 48 +++++++++++++++++++++++++++++++++++------------- src/ChunkSender.h | 15 ++++----------- src/ClientHandle.cpp | 41 ----------------------------------------- 4 files changed, 40 insertions(+), 66 deletions(-) (limited to 'src') diff --git a/src/Chunk.cpp b/src/Chunk.cpp index e4fa9629f..bfa287f63 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -1742,7 +1742,7 @@ void cChunk::SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_Max // Re-send the chunk to all clients: for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr) { - m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::E_CHUNK_PRIORITY_MEDIUM, (*itr)); + m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::E_CHUNK_PRIORITY_HIGH, (*itr)); } // for itr - m_LoadedByClient[] } diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index 2a953db1f..680f34bce 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -95,18 +95,23 @@ void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a { ASSERT(a_Client != NULL); { - sSendChunk Chunk(a_ChunkX, a_ChunkZ, a_Priority, a_Client); + sSendChunk Chunk(a_ChunkX, a_ChunkZ, a_Client); cCSLock Lock(m_CS); - if (std::find(m_SendChunks.begin(), m_SendChunks.end(), Chunk) != m_SendChunks.end()) + if ( + std::find(m_SendChunksLowPriority.begin(), m_SendChunksLowPriority.end(), Chunk) != m_SendChunksLowPriority.end() || + std::find(m_SendChunksHighPriority.begin(), m_SendChunksHighPriority.end(), Chunk) != m_SendChunksHighPriority.end() + ) { // Already queued, bail out return; } - m_SendChunks.push_back(Chunk); - // Sort the list: - m_SendChunks.sort(); + if (a_Priority == E_CHUNK_PRIORITY_LOW) { + m_SendChunksLowPriority.push_back(Chunk); + } else if (a_Priority == E_CHUNK_PRIORITY_HIGH) { + m_SendChunksHighPriority.push_back(Chunk); + } } m_evtQueue.Set(); } @@ -119,15 +124,23 @@ void cChunkSender::RemoveClient(cClientHandle * a_Client) { { cCSLock Lock(m_CS); - for (sSendChunkList::iterator itr = m_SendChunks.begin(); itr != m_SendChunks.end();) + for (sSendChunkList::iterator itr = m_SendChunksLowPriority.begin(); itr != m_SendChunksLowPriority.end();) { if (itr->m_Client == a_Client) { - itr = m_SendChunks.erase(itr); + itr = m_SendChunksLowPriority.erase(itr); + continue; + } + ++itr; + } // for itr - m_SendChunksLowPriority[] + for (sSendChunkList::iterator itr = m_SendChunksHighPriority.begin(); itr != m_SendChunksHighPriority.end();) + { + if (itr->m_Client == a_Client) { + itr = m_SendChunksHighPriority.erase(itr); continue; } ++itr; - } // for itr - m_SendChunks[] + } // for itr - m_SendChunksHighPriority[] m_RemoveCount++; } m_evtQueue.Set(); @@ -143,7 +156,7 @@ void cChunkSender::Execute(void) while (!m_ShouldTerminate) { cCSLock Lock(m_CS); - while (m_ChunksReady.empty() && m_SendChunks.empty()) + while (m_ChunksReady.empty() && m_SendChunksLowPriority.empty() && m_SendChunksHighPriority.empty()) { int RemoveCount = m_RemoveCount; m_RemoveCount = 0; @@ -158,8 +171,17 @@ void cChunkSender::Execute(void) return; } } // while (empty) - - if (!m_ChunksReady.empty()) + + if (!m_SendChunksHighPriority.empty()) + { + // Take one from the queue: + sSendChunk Chunk(m_SendChunksHighPriority.front()); + m_SendChunksHighPriority.pop_front(); + Lock.Unlock(); + + SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, Chunk.m_Client); + } + else if (!m_ChunksReady.empty()) { // Take one from the queue: cChunkCoords Coords(m_ChunksReady.front()); @@ -171,8 +193,8 @@ void cChunkSender::Execute(void) else { // Take one from the queue: - sSendChunk Chunk(m_SendChunks.front()); - m_SendChunks.pop_front(); + sSendChunk Chunk(m_SendChunksLowPriority.front()); + m_SendChunksLowPriority.pop_front(); Lock.Unlock(); SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, Chunk.m_Client); diff --git a/src/ChunkSender.h b/src/ChunkSender.h index 3a1e1f5ea..bd489e2c4 100644 --- a/src/ChunkSender.h +++ b/src/ChunkSender.h @@ -79,8 +79,7 @@ public: enum eChunkPriority { E_CHUNK_PRIORITY_HIGH = 0, - E_CHUNK_PRIORITY_MEDIUM = 1, - E_CHUNK_PRIORITY_LOW = 2, + E_CHUNK_PRIORITY_LOW = 1, }; bool Start(cWorld * a_World); @@ -103,13 +102,11 @@ protected: { int m_ChunkX; int m_ChunkZ; - eChunkPriority m_Priority; cClientHandle * m_Client; - sSendChunk(int a_ChunkX, int a_ChunkZ, eChunkPriority a_Priority, cClientHandle * a_Client) : + sSendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) : m_ChunkX(a_ChunkX), m_ChunkZ(a_ChunkZ), - m_Priority(a_Priority), m_Client(a_Client) { } @@ -122,11 +119,6 @@ protected: (a_Other.m_Client == m_Client) ); } - - bool operator < (const sSendChunk & a_Other) - { - return (m_Priority < a_Other.m_Priority); - } } ; typedef std::list sSendChunkList; @@ -150,7 +142,8 @@ protected: cCriticalSection m_CS; cChunkCoordsList m_ChunksReady; - sSendChunkList m_SendChunks; + sSendChunkList m_SendChunksLowPriority; + sSendChunkList m_SendChunksHighPriority; cEvent m_evtQueue; // Set when anything is added to m_ChunksReady cEvent m_evtRemoved; // Set when removed clients are safe to be deleted int m_RemoveCount; // Number of threads waiting for a client removal (m_evtRemoved needs to be set this many times) diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 28fcb0d37..ce5056f30 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -469,47 +469,6 @@ bool cClientHandle::StreamNextChunk(void) } } - // Medium priority: Load the chunks that are behind the player - LookVector = m_Player->GetLookVector() * -1; - for (int Range = 0; Range < 3; Range++) - { - Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; - - // Get the chunk from the x/z coords. - int RangeX, RangeZ = 0; - cChunkDef::BlockToChunk(FloorC(Vector.x), FloorC(Vector.z), RangeX, RangeZ); - - for (size_t X = 0; X < 7; X++) - { - for (size_t Z = 0; Z < 7; Z++) - { - int ChunkX = RangeX + ((X >= 4) ? (3 - X) : X); - int ChunkZ = RangeZ + ((Z >= 4) ? (3 - Z) : Z); - cChunkCoords Coords(ChunkX, ChunkZ); - - // Checks if the chunk is in distance - if ((Diff(ChunkX, ChunkPosX) > m_ViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_ViewDistance)) - { - continue; - } - - // If the chunk already loading/loaded -> skip - if ( - (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || - (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) - ) - { - continue; - } - - // Unloaded chunk found -> Send it to the client. - Lock.Unlock(); - StreamChunk(ChunkX, ChunkZ, cChunkSender::E_CHUNK_PRIORITY_MEDIUM); - return false; - } - } - } - // Low priority: Add all chunks that are in range. (From the center out to the edge) for (int d = 0; d <= m_ViewDistance; ++d) // cycle through (square) distance, from nearest to furthest { -- cgit v1.2.3 From f800f3c99830ee4486602d69611f40f99e704b9f Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 21 Oct 2014 18:06:44 +0200 Subject: Moved tall grass pickups handle. --- src/Blocks/BlockTallGrass.h | 37 +++++++++++++++++++++++++++++++++++++ src/Items/ItemShears.h | 9 --------- 2 files changed, 37 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/Blocks/BlockTallGrass.h b/src/Blocks/BlockTallGrass.h index 3ef2d804d..8e821b899 100644 --- a/src/Blocks/BlockTallGrass.h +++ b/src/Blocks/BlockTallGrass.h @@ -2,6 +2,7 @@ #pragma once #include "BlockHandler.h" +#include "ChunkInterface.h" @@ -10,6 +11,7 @@ class cBlockTallGrassHandler : public cBlockHandler { + typedef cBlockHandler super; public: cBlockTallGrassHandler(BLOCKTYPE a_BlockType) : cBlockHandler(a_BlockType) @@ -34,6 +36,41 @@ public: } + virtual void DropBlock(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cBlockPluginInterface & a_BlockPluginInterface, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, bool a_CanDrop) override + { + if (a_CanDrop && (a_Digger != NULL) && (a_Digger->GetEquippedWeapon().m_ItemType == E_ITEM_SHEARS)) + { + NIBBLETYPE Meta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); + cItems Drops; + Drops.Add(m_BlockType, 1, Meta); + + // Allow plugins to modify the pickups: + a_BlockPluginInterface.CallHookBlockToPickups(a_Digger, a_BlockX, a_BlockY, a_BlockZ, m_BlockType, Meta, Drops); + + // Spawn the pickups: + if (!Drops.empty()) + { + MTRand r1; + + // Mid-block position first + double MicroX, MicroY, MicroZ; + MicroX = a_BlockX + 0.5; + MicroY = a_BlockY + 0.5; + MicroZ = a_BlockZ + 0.5; + + // Add random offset second + MicroX += r1.rand(1) - 0.5; + MicroZ += r1.rand(1) - 0.5; + + a_WorldInterface.SpawnItemPickups(Drops, MicroX, MicroY, MicroZ); + } + return; + } + + super::DropBlock(a_ChunkInterface, a_WorldInterface, a_BlockPluginInterface, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_CanDrop); + } + + virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { if (a_RelY <= 0) diff --git a/src/Items/ItemShears.h b/src/Items/ItemShears.h index e0c5c6623..73343f629 100644 --- a/src/Items/ItemShears.h +++ b/src/Items/ItemShears.h @@ -77,15 +77,6 @@ public: NIBBLETYPE BlockMeta; a_World->GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, BlockMeta); - if ((Block == E_BLOCK_TALL_GRASS) && !a_Player->IsGameModeCreative()) - { - cItems Drops; - Drops.Add(Block, 1, BlockMeta); - a_World->SpawnItemPickups(Drops, a_BlockX, a_BlockY, a_BlockZ); - a_Player->UseEquippedItem(); - return; - } - super::OnBlockDestroyed(a_World, a_Player, a_Item, a_BlockX, a_BlockY, a_BlockZ); switch (Block) { -- cgit v1.2.3 From 2d639675516cb563e3f7bf018ee3619970ef1edc Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 21 Oct 2014 18:32:02 +0200 Subject: style. --- src/ChunkSender.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index 680f34bce..fdcd485a9 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -135,7 +135,8 @@ void cChunkSender::RemoveClient(cClientHandle * a_Client) } // for itr - m_SendChunksLowPriority[] for (sSendChunkList::iterator itr = m_SendChunksHighPriority.begin(); itr != m_SendChunksHighPriority.end();) { - if (itr->m_Client == a_Client) { + if (itr->m_Client == a_Client) + { itr = m_SendChunksHighPriority.erase(itr); continue; } -- cgit v1.2.3 From 4fe41839ccaf9d78e8288c24a20448d469770f4e Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 21 Oct 2014 21:13:35 +0200 Subject: Reverted hook move. --- src/ClientHandle.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 1daa398bd..f15d845ef 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -1118,16 +1118,16 @@ void cClientHandle::HandleBlockDigFinished(int a_BlockX, int a_BlockY, int a_Blo cWorld * World = m_Player->GetWorld(); cItemHandler * ItemHandler = cItemHandler::GetItemHandler(m_Player->GetEquippedItem()); - if (a_OldBlock == E_BLOCK_AIR) + if (cRoot::Get()->GetPluginManager()->CallHookPlayerBreakingBlock(*m_Player, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_OldBlock, a_OldMeta)) { - LOGD("Dug air - what the function?"); + // A plugin doesn't agree with the breaking. Bail out. Send the block back to the client, so that it knows: + m_Player->GetWorld()->SendBlockTo(a_BlockX, a_BlockY, a_BlockZ, m_Player); return; } - if (cRoot::Get()->GetPluginManager()->CallHookPlayerBreakingBlock(*m_Player, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_OldBlock, a_OldMeta)) + if (a_OldBlock == E_BLOCK_AIR) { - // A plugin doesn't agree with the breaking. Bail out. Send the block back to the client, so that it knows: - m_Player->GetWorld()->SendBlockTo(a_BlockX, a_BlockY, a_BlockZ, m_Player); + LOGD("Dug air - what the function?"); return; } -- cgit v1.2.3 From 0c0c762412922b784aaf154b51a8d5d547d3f86f Mon Sep 17 00:00:00 2001 From: Mattes D Date: Tue, 21 Oct 2014 21:25:52 +0200 Subject: Exported individual projectile classes to Lua API. They used to be exported, but then they were moved to separate files and those werent' added to the ToLua processing list. --- src/Bindings/AllToLua.pkg | 12 +- src/Bindings/CMakeLists.txt | 206 ++++++++++++++++---------------- src/Entities/ArrowEntity.h | 45 +++---- src/Entities/ExpBottleEntity.h | 17 ++- src/Entities/FireChargeEntity.h | 15 ++- src/Entities/FireworkEntity.cpp | 13 +- src/Entities/FireworkEntity.h | 32 ++++- src/Entities/GhastFireballEntity.h | 15 ++- src/Entities/Painting.h | 13 +- src/Entities/ProjectileEntity.h | 20 ++-- src/Entities/SplashPotionEntity.h | 18 ++- src/Entities/ThrownEggEntity.cpp | 21 ++++ src/Entities/ThrownEggEntity.h | 34 +++--- src/Entities/ThrownEnderPearlEntity.cpp | 22 ++++ src/Entities/ThrownEnderPearlEntity.h | 34 +++--- src/Entities/ThrownSnowballEntity.cpp | 25 ++++ src/Entities/ThrownSnowballEntity.h | 34 +++--- src/Entities/WitherSkullEntity.h | 12 +- 18 files changed, 367 insertions(+), 221 deletions(-) (limited to 'src') diff --git a/src/Bindings/AllToLua.pkg b/src/Bindings/AllToLua.pkg index 73de98e22..179e9742f 100644 --- a/src/Bindings/AllToLua.pkg +++ b/src/Bindings/AllToLua.pkg @@ -33,15 +33,25 @@ $cfile "../StringUtils.h" $cfile "../Defines.h" $cfile "../ChatColor.h" $cfile "../ClientHandle.h" +$cfile "../Entities/ArrowEntity.h" $cfile "../Entities/Entity.h" +$cfile "../Entities/EntityEffect.h" +$cfile "../Entities/ExpBottleEntity.h" +$cfile "../Entities/FireChargeEntity.h" +$cfile "../Entities/FireworkEntity.h" $cfile "../Entities/Floater.h" +$cfile "../Entities/GhastFireballEntity.h" $cfile "../Entities/Pawn.h" $cfile "../Entities/Player.h" $cfile "../Entities/Painting.h" $cfile "../Entities/Pickup.h" $cfile "../Entities/ProjectileEntity.h" +$cfile "../Entities/SplashPotionEntity.h" +$cfile "../Entities/ThrownEggEntity.h" +$cfile "../Entities/ThrownEnderPearlEntity.h" +$cfile "../Entities/ThrownSnowballEntity.h" $cfile "../Entities/TNTEntity.h" -$cfile "../Entities/EntityEffect.h" +$cfile "../Entities/WitherSkullEntity.h" $cfile "../Server.h" $cfile "../World.h" $cfile "../Inventory.h" diff --git a/src/Bindings/CMakeLists.txt b/src/Bindings/CMakeLists.txt index 5c56231c6..6880a51dd 100644 --- a/src/Bindings/CMakeLists.txt +++ b/src/Bindings/CMakeLists.txt @@ -5,131 +5,131 @@ include_directories ("${PROJECT_SOURCE_DIR}/../") include_directories (".") SET (SRCS - Bindings.cpp - DeprecatedBindings.cpp - LuaChunkStay.cpp - LuaState.cpp - LuaWindow.cpp - ManualBindings.cpp - ManualBindings_RankManager.cpp - Plugin.cpp - PluginLua.cpp - PluginManager.cpp - WebPlugin.cpp + Bindings.cpp + DeprecatedBindings.cpp + LuaChunkStay.cpp + LuaState.cpp + LuaWindow.cpp + ManualBindings.cpp + ManualBindings_RankManager.cpp + Plugin.cpp + PluginLua.cpp + PluginManager.cpp + WebPlugin.cpp ) SET (HDRS - Bindings.h - DeprecatedBindings.h - LuaChunkStay.h - LuaFunctions.h - LuaState.h - LuaWindow.h - ManualBindings.h - Plugin.h - PluginLua.h - PluginManager.h - WebPlugin.h - tolua++.h + Bindings.h + DeprecatedBindings.h + LuaChunkStay.h + LuaFunctions.h + LuaState.h + LuaWindow.h + ManualBindings.h + Plugin.h + PluginLua.h + PluginManager.h + WebPlugin.h + tolua++.h ) # List all the files that are generated as part of the Bindings build process set (BINDING_OUTPUTS - ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.h + ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.h ) set(BINDING_DEPENDENCIES - tolua - ../Bindings/virtual_method_hooks.lua - ../Bindings/AllToLua.pkg - ../Bindings/LuaFunctions.h - ../Bindings/LuaWindow.h - ../Bindings/Plugin.h - ../Bindings/PluginLua.h - ../Bindings/PluginManager.h - ../Bindings/WebPlugin.h - ../BiomeDef.h - ../BlockArea.h + tolua + ../Bindings/virtual_method_hooks.lua + ../Bindings/AllToLua.pkg + ../Bindings/LuaFunctions.h + ../Bindings/LuaWindow.h + ../Bindings/Plugin.h + ../Bindings/PluginLua.h + ../Bindings/PluginManager.h + ../Bindings/WebPlugin.h + ../BiomeDef.h + ../BlockArea.h ../BlockEntities/BeaconEntity.h - ../BlockEntities/BlockEntity.h - ../BlockEntities/BlockEntityWithItems.h - ../BlockEntities/ChestEntity.h - ../BlockEntities/DispenserEntity.h - ../BlockEntities/DropSpenserEntity.h - ../BlockEntities/DropperEntity.h - ../BlockEntities/FurnaceEntity.h - ../BlockEntities/HopperEntity.h - ../BlockEntities/JukeboxEntity.h - ../BlockEntities/NoteEntity.h - ../BlockEntities/SignEntity.h - ../BlockEntities/MobHeadEntity.h - ../BlockEntities/FlowerPotEntity.h - ../BlockID.h - ../BoundingBox.h - ../ChatColor.h - ../ChunkDef.h - ../ClientHandle.h - ../CraftingRecipes.h - ../Cuboid.h - ../Defines.h - ../Enchantments.h - ../Entities/EntityEffect.h - ../Entities/Entity.h - ../Entities/Floater.h - ../Entities/Pawn.h - ../Entities/Painting.h - ../Entities/Pickup.h - ../Entities/Player.h - ../Entities/ProjectileEntity.h - ../Entities/ArrowEntity.h - ../Entities/ThrownEggEntity.h - ../Entities/ThrownEnderPearlEntity.h - ../Entities/ExpBottleEntity.h - ../Entities/ThrownSnowballEntity.h - ../Entities/FireChargeEntity.h - ../Entities/FireworkEntity.h - ../Entities/GhastFireballEntity.h - ../Entities/TNTEntity.h - ../Entities/ExpOrb.h - ../Entities/HangingEntity.h - ../Entities/ItemFrame.h - ../Generating/ChunkDesc.h - ../Inventory.h - ../Item.h - ../ItemGrid.h - ../Mobs/Monster.h - ../OSSupport/File.h - ../Root.h - ../Server.h - ../StringUtils.h - ../Tracer.h - ../UI/Window.h - ../Vector3.h - ../WebAdmin.h - ../World.h + ../BlockEntities/BlockEntity.h + ../BlockEntities/BlockEntityWithItems.h + ../BlockEntities/ChestEntity.h + ../BlockEntities/DispenserEntity.h + ../BlockEntities/DropSpenserEntity.h + ../BlockEntities/DropperEntity.h + ../BlockEntities/FurnaceEntity.h + ../BlockEntities/HopperEntity.h + ../BlockEntities/JukeboxEntity.h + ../BlockEntities/NoteEntity.h + ../BlockEntities/SignEntity.h + ../BlockEntities/MobHeadEntity.h + ../BlockEntities/FlowerPotEntity.h + ../BlockID.h + ../BoundingBox.h + ../ChatColor.h + ../ChunkDef.h + ../ClientHandle.h + ../CraftingRecipes.h + ../Cuboid.h + ../Defines.h + ../Enchantments.h + ../Entities/ArrowEntity.h + ../Entities/Entity.h + ../Entities/EntityEffect.h + ../Entities/ExpBottleEntity.h + ../Entities/FireChargeEntity.h + ../Entities/FireworkEntity.h + ../Entities/Floater.h + ../Entities/GhastFireballEntity.h + ../Entities/Pawn.h + ../Entities/Player.h + ../Entities/Painting.h + ../Entities/Pickup.h + ../Entities/ProjectileEntity.h + ../Entities/SplashPotionEntity.h + ../Entities/ThrownEggEntity.h + ../Entities/ThrownEnderPearlEntity.h + ../Entities/ThrownSnowballEntity.h + ../Entities/TNTEntity.h + ../Entities/WitherSkullEntity.h + ../Generating/ChunkDesc.h + ../Inventory.h + ../Item.h + ../ItemGrid.h + ../Mobs/Monster.h + ../OSSupport/File.h + ../Root.h + ../Server.h + ../StringUtils.h + ../Tracer.h + ../UI/Window.h + ../Vector3.h + ../WebAdmin.h + ../World.h ) if (NOT MSVC) - ADD_CUSTOM_COMMAND( - # add any new generated bindings here - OUTPUT ${BINDING_OUTPUTS} + ADD_CUSTOM_COMMAND( + # add any new generated bindings here + OUTPUT ${BINDING_OUTPUTS} - # Regenerate bindings: - COMMAND tolua -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + # Regenerate bindings: + COMMAND tolua -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - # add any new generation dependencies here - DEPENDS ${BINDING_DEPENDENCIES} - ) + # add any new generation dependencies here + DEPENDS ${BINDING_DEPENDENCIES} + ) endif () + set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES GENERATED TRUE) set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.h PROPERTIES GENERATED TRUE) set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES COMPILE_FLAGS -Wno-error) if(NOT MSVC) - add_library(Bindings ${SRCS} ${HDRS}) + add_library(Bindings ${SRCS} ${HDRS}) - target_link_libraries(Bindings lua sqlite tolualib polarssl) + target_link_libraries(Bindings lua sqlite tolualib polarssl) endif() diff --git a/src/Entities/ArrowEntity.h b/src/Entities/ArrowEntity.h index 1e4d8eebb..436ec0293 100644 --- a/src/Entities/ArrowEntity.h +++ b/src/Entities/ArrowEntity.h @@ -1,6 +1,11 @@ -// -// ArrowEntity.h -// + +// ArrowEntity.h + +// Declares the cArrowEntity representing the arrow that has been shot by the player or by a skeleton + + + + #pragma once @@ -19,7 +24,7 @@ class cArrowEntity : typedef cProjectileEntity super; public: - /// Determines when the arrow can be picked up (depending on player gamemode). Corresponds to the MCA file "pickup" field + /** Determines when the arrow can be picked up (depending on player gamemode). Corresponds to the MCA file "pickup" field */ enum ePickupState { psNoPickup = 0, @@ -31,33 +36,33 @@ public: CLASS_PROTODEF(cArrowEntity) - /// Creates a new arrow with psNoPickup state and default damage modifier coeff + /** Creates a new arrow with psNoPickup state and default damage modifier coeff */ cArrowEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const Vector3d & a_Speed); - /// Creates a new arrow as shot by a player, initializes it from the player object + /** Creates a new arrow as shot by a player, initializes it from the player object */ cArrowEntity(cPlayer & a_Player, double a_Force); // tolua_begin - /// Returns whether the arrow can be picked up by players + /** Returns whether the arrow can be picked up by players */ ePickupState GetPickupState(void) const { return m_PickupState; } - /// Sets a new pickup state + /** Sets a new pickup state */ void SetPickupState(ePickupState a_PickupState) { m_PickupState = a_PickupState; } - /// Returns the damage modifier coeff. + /** Returns the damage modifier coeff. */ double GetDamageCoeff(void) const { return m_DamageCoeff; } - /// Sets the damage modifier coeff + /** Sets the damage modifier coeff */ void SetDamageCoeff(double a_DamageCoeff) { m_DamageCoeff = a_DamageCoeff; } - /// Returns true if the specified player can pick the arrow up + /** Returns true if the specified player can pick the arrow up */ bool CanPickup(const cPlayer & a_Player) const; - /// Returns true if the arrow is set as critical + /** Returns true if the arrow is set as critical */ bool IsCritical(void) const { return m_IsCritical; } - /// Sets the IsCritical flag + /** Sets the IsCritical flag */ void SetIsCritical(bool a_IsCritical) { m_IsCritical = a_IsCritical; } /** Gets the block arrow is in */ @@ -70,28 +75,28 @@ public: protected: - /// Determines when the arrow can be picked up by players + /** Determines when the arrow can be picked up by players */ ePickupState m_PickupState; - /// The coefficient applied to the damage that the arrow will deal, based on the bow enchantment. 2.0 for normal arrow + /** The coefficient applied to the damage that the arrow will deal, based on the bow enchantment. 2.0 for normal arrow */ double m_DamageCoeff; - /// If true, the arrow deals more damage + /** If true, the arrow deals more damage */ bool m_IsCritical; - /// Timer for pickup collection animation or five minute timeout + /** Timer for pickup collection animation or five minute timeout */ float m_Timer; - /// Timer for client arrow position confirmation via TeleportEntity + /** Timer for client arrow position confirmation via TeleportEntity */ float m_HitGroundTimer; // Whether the arrow has already been teleported into the proper position in the ground. bool m_HasTeleported; - /// If true, the arrow is in the process of being collected - don't go to anyone else + /** If true, the arrow is in the process of being collected - don't go to anyone else */ bool m_bIsCollected; - /// Stores the block position that arrow is lodged into, sets m_IsInGround to false if it becomes air + /** Stores the block position that arrow is lodged into, sets m_IsInGround to false if it becomes air */ Vector3i m_HitBlockPos; // cProjectileEntity overrides: diff --git a/src/Entities/ExpBottleEntity.h b/src/Entities/ExpBottleEntity.h index d36110f97..715b9947e 100644 --- a/src/Entities/ExpBottleEntity.h +++ b/src/Entities/ExpBottleEntity.h @@ -1,6 +1,11 @@ -// -// ExpBottleEntity.h -// + +// ExpBottleEntity.h + +// Declares the cExpBottleEntity class representing the thrown exp bottle + + + + #pragma once @@ -33,6 +38,10 @@ protected: /** Breaks the bottle, fires its particle effects and sounds @param a_HitPos The position where the bottle will break */ - void Break(const Vector3d &a_HitPos); + void Break(const Vector3d & a_HitPos); }; // tolua_export + + + + diff --git a/src/Entities/FireChargeEntity.h b/src/Entities/FireChargeEntity.h index 5df55bec4..eb08f5324 100644 --- a/src/Entities/FireChargeEntity.h +++ b/src/Entities/FireChargeEntity.h @@ -1,6 +1,11 @@ -// -// FireChargeEntity.h -// + +// FireChargeEntity.h + +// Declares the cFireChargeEntity representing the fire charge shot by the blaze + + + + #pragma once @@ -34,3 +39,7 @@ protected: virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; } ; // tolua_export + + + + diff --git a/src/Entities/FireworkEntity.cpp b/src/Entities/FireworkEntity.cpp index 403a53c84..68d02640a 100644 --- a/src/Entities/FireworkEntity.cpp +++ b/src/Entities/FireworkEntity.cpp @@ -10,7 +10,7 @@ cFireworkEntity::cFireworkEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem & a_Item) : super(pkFirework, a_Creator, a_X, a_Y, a_Z, 0.25, 0.25), - m_ExplodeTimer(0), + m_TicksToExplosion(a_Item.m_FireworkItem.m_FlightTimeInTicks), m_FireworkItem(a_Item) { } @@ -27,7 +27,9 @@ void cFireworkEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk) if ((PosY < 0) || (PosY >= cChunkDef::Height)) { - goto setspeed; + AddSpeedY(1); + AddPosition(GetSpeed() * (a_Dt / 1000)); + return; } if (m_IsInGround) @@ -50,7 +52,6 @@ void cFireworkEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk) } } -setspeed: AddSpeedY(1); AddPosition(GetSpeed() * (a_Dt / 1000)); } @@ -63,11 +64,13 @@ void cFireworkEntity::Tick(float a_Dt, cChunk & a_Chunk) { super::Tick(a_Dt, a_Chunk); - if (m_ExplodeTimer == m_FireworkItem.m_FireworkItem.m_FlightTimeInTicks) + if (m_TicksToExplosion <= 0) { + // TODO: Notify the plugins m_World->BroadcastEntityStatus(*this, esFireworkExploding); Destroy(); + return; } - m_ExplodeTimer++; + m_TicksToExplosion -= 1; } diff --git a/src/Entities/FireworkEntity.h b/src/Entities/FireworkEntity.h index 20f18b6dc..300ec571e 100644 --- a/src/Entities/FireworkEntity.h +++ b/src/Entities/FireworkEntity.h @@ -1,6 +1,11 @@ -// -// FireworkEntity.h -// + +// FireworkEntity.h + +// Declares the cFireworkEntity class representing the flying firework rocket + + + + #pragma once @@ -24,7 +29,22 @@ public: CLASS_PROTODEF(cFireworkEntity) cFireworkEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem & a_Item); + + // tolua_begin + + /** Returns the item used to create the rocket (has all the firework effects on it) */ const cItem & GetItem(void) const { return m_FireworkItem; } + + /** Sets the item that is used to create the rocket (has all the firework effects on it) */ + void SetItem(const cItem & a_Item) { m_FireworkItem = a_Item; } + + /** Returns the number of ticks left until the firework explosion. */ + int GetTicksToExplosion(void) const { return m_TicksToExplosion; } + + /** Sets the number of ticks left until the firework explosion. */ + void SetTicksToExplosion(int a_TicksToExplosion) { m_TicksToExplosion = a_TicksToExplosion; } + + // tolua_end protected: @@ -34,7 +54,11 @@ protected: private: - int m_ExplodeTimer; + int m_TicksToExplosion; cItem m_FireworkItem; }; // tolua_export + + + + diff --git a/src/Entities/GhastFireballEntity.h b/src/Entities/GhastFireballEntity.h index 3ed72d9ef..bbce89d31 100644 --- a/src/Entities/GhastFireballEntity.h +++ b/src/Entities/GhastFireballEntity.h @@ -1,6 +1,11 @@ -// -// GhastFireballEntity.h -// + +// GhastFireballEntity.h + +// Declares the cGhastFireballEntity class representing the ghast fireball in flight. + + + + #pragma once @@ -36,3 +41,7 @@ protected: // TODO: Deflecting the fireballs by arrow- or sword- hits } ; // tolua_export + + + + diff --git a/src/Entities/Painting.h b/src/Entities/Painting.h index 9877c95c5..078270b42 100644 --- a/src/Entities/Painting.h +++ b/src/Entities/Painting.h @@ -11,15 +11,22 @@ class cPainting : public cEntity { - // tolua_end typedef cEntity super; public: + + // tolua_end + CLASS_PROTODEF(cPainting) cPainting(const AString & a_Name, int a_Direction, double a_X, double a_Y, double a_Z); - const AString & GetName(void) const { return m_Name; } // tolua_export - int GetDirection(void) const { return m_Direction; } // tolua_export + + // tolua_begin + + const AString & GetName(void) const { return m_Name; } + int GetDirection(void) const { return m_Direction; } + + // tolua_end private: diff --git a/src/Entities/ProjectileEntity.h b/src/Entities/ProjectileEntity.h index 03eda9739..b9d2dfa63 100644 --- a/src/Entities/ProjectileEntity.h +++ b/src/Entities/ProjectileEntity.h @@ -1,7 +1,7 @@ // ProjectileEntity.h -// Declares the cProjectileEntity class representing the common base class for projectiles, as well as individual projectile types +// Declares the cProjectileEntity class representing the common base class for projectiles @@ -23,7 +23,7 @@ class cProjectileEntity : typedef cEntity super; public: - /// The kind of the projectile. The numbers correspond to the network type ID used for spawning via the 0x17 packet. + /** The kind of the projectile. The numbers correspond to the network type ID used for spawning them in the protocol. */ enum eKind { pkArrow = 60, @@ -48,22 +48,22 @@ public: static cProjectileEntity * Create(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem * a_Item, const Vector3d * a_Speed = NULL); - /// Called by the physics blocktracer when the entity hits a solid block, the hit position and the face hit (BLOCK_FACE_) is given + /** Called by the physics blocktracer when the entity hits a solid block, the hit position and the face hit (BLOCK_FACE_) is given */ virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace); - /// Called by the physics blocktracer when the entity hits another entity + /** Called by the physics blocktracer when the entity hits another entity */ virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) { UNUSED(a_EntityHit); UNUSED(a_HitPos); } - /// Called by Chunk when the projectile is eligible for player collection + /** Called by Chunk when the projectile is eligible for player collection */ virtual void CollectedBy(cPlayer & a_Dest); // tolua_begin - /// Returns the kind of the projectile (fast class identification) + /** Returns the kind of the projectile (fast class identification) */ eKind GetProjectileKind(void) const { return m_ProjectileKind; } /** Returns the unique ID of the entity who created this projectile @@ -76,15 +76,15 @@ public: */ AString GetCreatorName(void) const { return m_CreatorData.m_Name; } - /// Returns the string that is used as the entity type (class name) in MCA files + /** Returns the string that is used as the entity type (class name) in MCA files */ AString GetMCAClassName(void) const; - /// Returns true if the projectile has hit the ground and is stuck there + /** Returns true if the projectile has hit the ground and is stuck there */ bool IsInGround(void) const { return m_IsInGround; } // tolua_end - /// Sets the internal InGround flag. To be used by MCA loader only! + /** Sets the internal InGround flag. To be used by MCA loader only! */ void SetIsInGround(bool a_IsInGround) { m_IsInGround = a_IsInGround; } protected: @@ -114,7 +114,7 @@ protected: */ CreatorData m_CreatorData; - /// True if the projectile has hit the ground and is stuck there + /** True if the projectile has hit the ground and is stuck there */ bool m_IsInGround; // cEntity overrides: diff --git a/src/Entities/SplashPotionEntity.h b/src/Entities/SplashPotionEntity.h index 4afc5f204..9302d8292 100644 --- a/src/Entities/SplashPotionEntity.h +++ b/src/Entities/SplashPotionEntity.h @@ -1,6 +1,11 @@ -// -// SplashPotionEntity.h -// + +// SplashPotionEntity.h + +// Declares the cSplashPotionEntity class representing a splash potion that has been thrown + + + + #pragma once @@ -32,6 +37,7 @@ public: const cItem & a_Item ); + // tolua_begin cEntityEffect::eType GetEntityEffectType(void) const { return m_EntityEffectType; } cEntityEffect GetEntityEffect(void) const { return m_EntityEffect; } int GetPotionColor(void) const { return m_PotionColor; } @@ -39,6 +45,8 @@ public: void SetEntityEffectType(cEntityEffect::eType a_EntityEffectType) { m_EntityEffectType = a_EntityEffectType; } void SetEntityEffect(cEntityEffect a_EntityEffect) { m_EntityEffect = a_EntityEffect; } void SetPotionColor(int a_PotionColor) { m_PotionColor = a_PotionColor; } + + // tolua_end protected: @@ -77,3 +85,7 @@ private: /** Time in ticks to wait for the hit animation to begin before destroying */ int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/ThrownEggEntity.cpp b/src/Entities/ThrownEggEntity.cpp index 5ae85bee8..24c946a9c 100644 --- a/src/Entities/ThrownEggEntity.cpp +++ b/src/Entities/ThrownEggEntity.cpp @@ -44,6 +44,27 @@ void cThrownEggEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_Hit +void cThrownEggEntity::Tick(float a_Dt, cChunk & a_Chunk) +{ + if (m_DestroyTimer > 0) + { + m_DestroyTimer--; + if (m_DestroyTimer == 0) + { + Destroy(); + return; + } + } + else + { + super::Tick(a_Dt, a_Chunk); + } +} + + + + + void cThrownEggEntity::TrySpawnChicken(const Vector3d & a_HitPos) { if (m_World->GetTickRandomNumber(7) == 1) diff --git a/src/Entities/ThrownEggEntity.h b/src/Entities/ThrownEggEntity.h index a0b7d5340..6ffedf5b5 100644 --- a/src/Entities/ThrownEggEntity.h +++ b/src/Entities/ThrownEggEntity.h @@ -1,6 +1,11 @@ -// -// ThrownEggEntity.h -// + +// ThrownEggEntity.h + +// Declares the cThrownEggEntity class representing a regular thrown egg + + + + #pragma once @@ -29,23 +34,8 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void Tick (float a_Dt, cChunk & a_Chunk) override - { - if (m_DestroyTimer > 0) - { - m_DestroyTimer--; - if (m_DestroyTimer == 0) - { - Destroy(); - return; - } - } - else - { - super::Tick(a_Dt, a_Chunk); - } - } + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void Tick(float a_Dt, cChunk & a_Chunk) override; // Randomly decides whether to spawn a chicken where the egg lands. void TrySpawnChicken(const Vector3d & a_HitPos); @@ -56,3 +46,7 @@ private: int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/ThrownEnderPearlEntity.cpp b/src/Entities/ThrownEnderPearlEntity.cpp index c7407e6ae..8f1b62934 100644 --- a/src/Entities/ThrownEnderPearlEntity.cpp +++ b/src/Entities/ThrownEnderPearlEntity.cpp @@ -1,3 +1,4 @@ + #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "ThrownEnderPearlEntity.h" @@ -45,6 +46,27 @@ void cThrownEnderPearlEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d +void cThrownEnderPearlEntity::Tick(float a_Dt, cChunk & a_Chunk) +{ + if (m_DestroyTimer > 0) + { + m_DestroyTimer--; + if (m_DestroyTimer == 0) + { + Destroy(); + return; + } + } + else + { + super::Tick(a_Dt, a_Chunk); + } +} + + + + + void cThrownEnderPearlEntity::TeleportCreator(const Vector3d & a_HitPos) { if (m_CreatorData.m_Name.empty()) diff --git a/src/Entities/ThrownEnderPearlEntity.h b/src/Entities/ThrownEnderPearlEntity.h index 436450013..475ebde87 100644 --- a/src/Entities/ThrownEnderPearlEntity.h +++ b/src/Entities/ThrownEnderPearlEntity.h @@ -1,6 +1,11 @@ -// -// ThrownEnderPearlEntity.h -// + +// ThrownEnderPearlEntity.h + +// Declares the cThrownEnderPeralEntity class representing an ender pearl being thrown + + + + #pragma once @@ -29,23 +34,8 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void Tick (float a_Dt, cChunk & a_Chunk) override - { - if (m_DestroyTimer > 0) - { - m_DestroyTimer--; - if (m_DestroyTimer == 0) - { - Destroy(); - return; - } - } - else - { - super::Tick(a_Dt, a_Chunk); - } - } + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void Tick(float a_Dt, cChunk & a_Chunk) override; /** Teleports the creator where the ender pearl lands */ void TeleportCreator(const Vector3d & a_HitPos); @@ -56,3 +46,7 @@ private: int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/ThrownSnowballEntity.cpp b/src/Entities/ThrownSnowballEntity.cpp index 496397100..88e39d22e 100644 --- a/src/Entities/ThrownSnowballEntity.cpp +++ b/src/Entities/ThrownSnowballEntity.cpp @@ -43,3 +43,28 @@ void cThrownSnowballEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & m_DestroyTimer = 5; } + + + + + +void cThrownSnowballEntity::Tick(float a_Dt, cChunk & a_Chunk) +{ + if (m_DestroyTimer > 0) + { + m_DestroyTimer--; + if (m_DestroyTimer == 0) + { + Destroy(); + return; + } + } + else + { + super::Tick(a_Dt, a_Chunk); + } +} + + + + diff --git a/src/Entities/ThrownSnowballEntity.h b/src/Entities/ThrownSnowballEntity.h index 8d195ced1..f806996cc 100644 --- a/src/Entities/ThrownSnowballEntity.h +++ b/src/Entities/ThrownSnowballEntity.h @@ -1,6 +1,11 @@ -// -// ThrownSnowballEntity.h -// + +// ThrownSnowballEntity.h + +// Declares the cThrownSnowballEntity representing a snowball that has been thrown + + + + #pragma once @@ -29,23 +34,8 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void Tick (float a_Dt, cChunk & a_Chunk) override - { - if (m_DestroyTimer > 0) - { - m_DestroyTimer--; - if (m_DestroyTimer == 0) - { - Destroy(); - return; - } - } - else - { - super::Tick(a_Dt, a_Chunk); - } - } + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void Tick(float a_Dt, cChunk & a_Chunk) override; private: @@ -53,3 +43,7 @@ private: int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/WitherSkullEntity.h b/src/Entities/WitherSkullEntity.h index c59acd807..43a520388 100644 --- a/src/Entities/WitherSkullEntity.h +++ b/src/Entities/WitherSkullEntity.h @@ -1,8 +1,12 @@ -// WitherSkullEntity.h +// WitherSkullEntity.h // Declares the cWitherSkullEntity class representing the entity used by both blue and black wither skulls + + + + #pragma once #include "ProjectileEntity.h" @@ -30,6 +34,10 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; } ; // tolua_export + + + + -- cgit v1.2.3 From 881bc66233a4937bdbd82275557e03936d2f9e2c Mon Sep 17 00:00:00 2001 From: Mattes D Date: Tue, 21 Oct 2014 22:00:31 +0200 Subject: Fixed trailing whitespace. --- src/BlockEntities/FurnaceEntity.cpp | 2 +- src/BlockEntities/FurnaceEntity.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index d8ca15c6c..ac71f1541 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -349,7 +349,7 @@ void cFurnaceEntity::UpdateProgressBars(bool a_ForceUpdate) int CurFuel = (m_FuelBurnTime > 0) ? 200 - (200 * m_TimeBurned / m_FuelBurnTime) : 0; BroadcastProgress(PROGRESSBAR_FUEL, static_cast(CurFuel)); - int CurCook = (m_NeedCookTime > 0) ? (200 * m_TimeCooked / m_NeedCookTime) : 0; + int CurCook = (m_NeedCookTime > 0) ? (200 * m_TimeCooked / m_NeedCookTime) : 0; BroadcastProgress(PROGRESSBAR_SMELTING_CONFIRM, 200); // Post 1.8, Mojang requires a random packet with an ID of three and value of 200. Wat. Wat. Wat. BroadcastProgress(PROGRESSBAR_SMELTING, static_cast(CurCook)); } diff --git a/src/BlockEntities/FurnaceEntity.h b/src/BlockEntities/FurnaceEntity.h index 8e48810ba..71c2fe127 100644 --- a/src/BlockEntities/FurnaceEntity.h +++ b/src/BlockEntities/FurnaceEntity.h @@ -133,7 +133,7 @@ protected: int m_FuelBurnTime; /** Amount of ticks that the current fuel has been burning */ - int m_TimeBurned; + int m_TimeBurned; /** Sends the specified progressbar value to all clients of the window */ void BroadcastProgress(short a_ProgressbarID, short a_Value); -- cgit v1.2.3 From a42fa071bc3ac1615e7c9b9d59fb4c882cc6097d Mon Sep 17 00:00:00 2001 From: Mattes D Date: Tue, 21 Oct 2014 22:02:30 +0200 Subject: Properly exported cItemFrame and cHangingEntity to Lua. --- src/Bindings/AllToLua.pkg | 2 ++ src/Bindings/CMakeLists.txt | 2 ++ src/Entities/HangingEntity.cpp | 30 ++++++++++++++--------- src/Entities/HangingEntity.h | 29 +++++++++++++--------- src/Entities/ItemFrame.cpp | 16 ++++++------ src/Entities/ItemFrame.h | 17 ++++++++----- src/Protocol/Protocol17x.cpp | 2 +- src/Protocol/Protocol18x.cpp | 2 +- src/WorldStorage/NBTChunkSerializer.cpp | 24 +++++++++--------- src/WorldStorage/WSSAnvil.cpp | 43 +++++++++++++++++++++------------ 10 files changed, 100 insertions(+), 67 deletions(-) (limited to 'src') diff --git a/src/Bindings/AllToLua.pkg b/src/Bindings/AllToLua.pkg index 179e9742f..1bff26b0e 100644 --- a/src/Bindings/AllToLua.pkg +++ b/src/Bindings/AllToLua.pkg @@ -41,6 +41,8 @@ $cfile "../Entities/FireChargeEntity.h" $cfile "../Entities/FireworkEntity.h" $cfile "../Entities/Floater.h" $cfile "../Entities/GhastFireballEntity.h" +$cfile "../Entities/HangingEntity.h" +$cfile "../Entities/ItemFrame.h" $cfile "../Entities/Pawn.h" $cfile "../Entities/Player.h" $cfile "../Entities/Painting.h" diff --git a/src/Bindings/CMakeLists.txt b/src/Bindings/CMakeLists.txt index 6880a51dd..d47579cd6 100644 --- a/src/Bindings/CMakeLists.txt +++ b/src/Bindings/CMakeLists.txt @@ -82,6 +82,8 @@ set(BINDING_DEPENDENCIES ../Entities/FireworkEntity.h ../Entities/Floater.h ../Entities/GhastFireballEntity.h + ../Entities/HangingEntity.h + ../Entities/ItemFrame.h ../Entities/Pawn.h ../Entities/Player.h ../Entities/Painting.h diff --git a/src/Entities/HangingEntity.cpp b/src/Entities/HangingEntity.cpp index 3276bc4a0..a6b9c40c8 100644 --- a/src/Entities/HangingEntity.cpp +++ b/src/Entities/HangingEntity.cpp @@ -9,9 +9,9 @@ -cHangingEntity::cHangingEntity(eEntityType a_EntityType, eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z) - : cEntity(a_EntityType, a_X, a_Y, a_Z, 0.8, 0.8) - , m_BlockFace(a_BlockFace) +cHangingEntity::cHangingEntity(eEntityType a_EntityType, eBlockFace a_Facing, double a_X, double a_Y, double a_Z) : + cEntity(a_EntityType, a_X, a_Y, a_Z, 0.8, 0.8), + m_Facing(a_Facing) { SetMaxHealth(1); SetHealth(1); @@ -21,15 +21,23 @@ cHangingEntity::cHangingEntity(eEntityType a_EntityType, eBlockFace a_BlockFace, -void cHangingEntity::SetDirection(eBlockFace a_BlockFace) +void cHangingEntity::SetFacing(eBlockFace a_Facing) { - if ((a_BlockFace < 2) || (a_BlockFace > 5)) + // Y-based faces are not allowed: + switch (a_Facing) { - ASSERT(!"Tried to set a bad direction!"); - return; + case BLOCK_FACE_NONE: + case BLOCK_FACE_YM: + case BLOCK_FACE_YP: + { + LOGWARNING("%s: Invalid facing: %d. Ignoring.", __FUNCTION__, a_Facing); + ASSERT(!"Tried to set a bad facing!"); + return; + } + default: break; } - m_BlockFace = a_BlockFace; + m_Facing = a_Facing; } @@ -41,7 +49,7 @@ void cHangingEntity::SpawnOn(cClientHandle & a_ClientHandle) int Dir = 0; // The client uses different values for item frame directions and block faces. Our constants are for the block faces, so we convert them here to item frame faces - switch (m_BlockFace) + switch (m_Facing) { case BLOCK_FACE_ZP: Dir = 0; break; case BLOCK_FACE_ZM: Dir = 2; break; @@ -49,8 +57,8 @@ void cHangingEntity::SpawnOn(cClientHandle & a_ClientHandle) case BLOCK_FACE_XP: Dir = 3; break; default: { - LOGINFO("Invalid face (%d) in a cHangingEntity at {%d, %d, %d}, adjusting to BLOCK_FACE_XP.", - m_BlockFace, (int)GetPosX(), (int)GetPosY(), (int)GetPosZ() + LOGINFO("Invalid facing (%d) in a cHangingEntity at {%d, %d, %d}, adjusting to BLOCK_FACE_XP.", + m_Facing, (int)GetPosX(), (int)GetPosY(), (int)GetPosZ() ); Dir = 3; } diff --git a/src/Entities/HangingEntity.h b/src/Entities/HangingEntity.h index 1cc0034e1..67146a20b 100644 --- a/src/Entities/HangingEntity.h +++ b/src/Entities/HangingEntity.h @@ -11,36 +11,41 @@ class cHangingEntity : public cEntity { - // tolua_end typedef cEntity super; public: + // tolua_end + CLASS_PROTODEF(cHangingEntity) cHangingEntity(eEntityType a_EntityType, eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z); - /** Returns the orientation from the hanging entity */ - eBlockFace GetDirection() const { return m_BlockFace; } // tolua_export + // tolua_begin + + /** Returns the direction in which the entity is facing. */ + eBlockFace GetFacing() const { return m_Facing; } - /** Set the orientation from the hanging entity */ - void SetDirection(eBlockFace a_BlockFace); // tolua_export + /** Set the direction in which the entity is facing. */ + void SetFacing(eBlockFace a_Facing); - /** Returns the X coord. */ - int GetTileX() const { return POSX_TOINT; } // tolua_export + /** Returns the X coord of the block in which the entity resides. */ + int GetBlockX() const { return POSX_TOINT; } - /** Returns the Y coord. */ - int GetTileY() const { return POSY_TOINT; } // tolua_export + /** Returns the Y coord of the block in which the entity resides. */ + int GetBlockY() const { return POSY_TOINT; } - /** Returns the Z coord. */ - int GetTileZ() const { return POSZ_TOINT; } // tolua_export + /** Returns the Z coord of the block in which the entity resides. */ + int GetBlockZ() const { return POSZ_TOINT; } + + // tolua_end private: virtual void SpawnOn(cClientHandle & a_ClientHandle) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override {} - eBlockFace m_BlockFace; + eBlockFace m_Facing; }; // tolua_export diff --git a/src/Entities/ItemFrame.cpp b/src/Entities/ItemFrame.cpp index f512324eb..6704c05b4 100644 --- a/src/Entities/ItemFrame.cpp +++ b/src/Entities/ItemFrame.cpp @@ -9,10 +9,10 @@ -cItemFrame::cItemFrame(eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z) - : cHangingEntity(etItemFrame, a_BlockFace, a_X, a_Y, a_Z) - , m_Item(E_BLOCK_AIR) - , m_Rotation(0) +cItemFrame::cItemFrame(eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z) : + cHangingEntity(etItemFrame, a_BlockFace, a_X, a_Y, a_Z), + m_Item(E_BLOCK_AIR), + m_ItemRotation(0) { } @@ -27,10 +27,10 @@ void cItemFrame::OnRightClicked(cPlayer & a_Player) if (!m_Item.IsEmpty()) { // Item not empty, rotate, clipping values to zero to three inclusive - m_Rotation++; - if (m_Rotation >= 8) + m_ItemRotation++; + if (m_ItemRotation >= 8) { - m_Rotation = 0; + m_ItemRotation = 0; } } else if (!a_Player.GetEquippedItem().IsEmpty()) @@ -72,7 +72,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI) SetHealth(GetMaxHealth()); m_Item.Empty(); - m_Rotation = 0; + m_ItemRotation = 0; SetInvulnerableTicks(0); GetWorld()->BroadcastEntityMetadata(*this); } diff --git a/src/Entities/ItemFrame.h b/src/Entities/ItemFrame.h index a63b78b70..3642662f9 100644 --- a/src/Entities/ItemFrame.h +++ b/src/Entities/ItemFrame.h @@ -11,26 +11,31 @@ class cItemFrame : public cHangingEntity { - // tolua_end typedef cHangingEntity super; public: + // tolua_end + CLASS_PROTODEF(cItemFrame) cItemFrame(eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z); + // tolua_begin + /** Returns the item in the frame */ - const cItem & GetItem(void) { return m_Item; } // tolua_export + const cItem & GetItem(void) { return m_Item; } /** Set the item in the frame */ - void SetItem(cItem & a_Item) { m_Item = a_Item; } // tolua_export + void SetItem(cItem & a_Item) { m_Item = a_Item; } /** Returns the rotation from the item in the frame */ - Byte GetRotation(void) const { return m_Rotation; } // tolua_export + Byte GetItemRotation(void) const { return m_ItemRotation; } /** Set the rotation from the item in the frame */ - void SetRotation(Byte a_Rotation) { m_Rotation = a_Rotation; } // tolua_export + void SetRotation(Byte a_ItemRotation) { m_ItemRotation = a_ItemRotation; } + + // tolua_end private: @@ -39,7 +44,7 @@ private: virtual void GetDrops(cItems & a_Items, cEntity * a_Killer) override; cItem m_Item; - Byte m_Rotation; + Byte m_ItemRotation; }; // tolua_export diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index 204691ede..f4779d83b 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -2803,7 +2803,7 @@ void cProtocol172::cPacketizer::WriteEntityMetadata(const cEntity & a_Entity) WriteByte(0xA2); WriteItem(Frame.GetItem()); WriteByte(0x3); - WriteByte(Frame.GetRotation() / 2); + WriteByte(Frame.GetItemRotation() / 2); break; } default: break; diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index c9118c239..39046e2ed 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -3109,7 +3109,7 @@ void cProtocol180::cPacketizer::WriteEntityMetadata(const cEntity & a_Entity) WriteByte(0xA8); WriteItem(Frame.GetItem()); WriteByte(0x09); - WriteByte(Frame.GetRotation()); + WriteByte(Frame.GetItemRotation()); break; } default: break; diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp index 28b9dd042..80d9ab6d2 100644 --- a/src/WorldStorage/NBTChunkSerializer.cpp +++ b/src/WorldStorage/NBTChunkSerializer.cpp @@ -685,21 +685,21 @@ void cNBTChunkSerializer::AddProjectileEntity(cProjectileEntity * a_Projectile) void cNBTChunkSerializer::AddHangingEntity(cHangingEntity * a_Hanging) { - m_Writer.AddByte("Direction", (unsigned char)a_Hanging->GetDirection()); - m_Writer.AddInt("TileX", a_Hanging->GetTileX()); - m_Writer.AddInt("TileY", a_Hanging->GetTileY()); - m_Writer.AddInt("TileZ", a_Hanging->GetTileZ()); - switch (a_Hanging->GetDirection()) + m_Writer.AddInt("TileX", a_Hanging->GetBlockX()); + m_Writer.AddInt("TileY", a_Hanging->GetBlockY()); + m_Writer.AddInt("TileZ", a_Hanging->GetBlockZ()); + switch (a_Hanging->GetFacing()) { - case BLOCK_FACE_YM: m_Writer.AddByte("Dir", (unsigned char)2); break; - case BLOCK_FACE_YP: m_Writer.AddByte("Dir", (unsigned char)1); break; - case BLOCK_FACE_ZM: m_Writer.AddByte("Dir", (unsigned char)0); break; - case BLOCK_FACE_ZP: m_Writer.AddByte("Dir", (unsigned char)3); break; + case BLOCK_FACE_XM: m_Writer.AddByte("Facing", 1); break; + case BLOCK_FACE_XP: m_Writer.AddByte("Facing", 3); break; + case BLOCK_FACE_ZM: m_Writer.AddByte("Facing", 2); break; + case BLOCK_FACE_ZP: m_Writer.AddByte("Facing", 0); break; - case BLOCK_FACE_XM: - case BLOCK_FACE_XP: + case BLOCK_FACE_YM: + case BLOCK_FACE_YP: case BLOCK_FACE_NONE: { + // These directions are invalid, but they may have been previously loaded, so keep them. break; } } @@ -740,7 +740,7 @@ void cNBTChunkSerializer::AddItemFrameEntity(cItemFrame * a_ItemFrame) AddBasicEntity(a_ItemFrame, "ItemFrame"); AddHangingEntity(a_ItemFrame); AddItem(a_ItemFrame->GetItem(), -1, "Item"); - m_Writer.AddByte("ItemRotation", (unsigned char)a_ItemFrame->GetRotation()); + m_Writer.AddByte("ItemRotation", (unsigned char)a_ItemFrame->GetItemRotation()); m_Writer.AddFloat("ItemDropChance", 1.0F); m_Writer.EndCompound(); } diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp index 092b9514c..eba21c659 100644 --- a/src/WorldStorage/WSSAnvil.cpp +++ b/src/WorldStorage/WSSAnvil.cpp @@ -1660,30 +1660,41 @@ void cWSSAnvil::LoadExpOrbFromNBT(cEntityList & a_Entities, const cParsedNBT & a void cWSSAnvil::LoadHangingFromNBT(cHangingEntity & a_Hanging, const cParsedNBT & a_NBT, int a_TagIdx) { - int Direction = a_NBT.FindChildByName(a_TagIdx, "Direction"); - if (Direction > 0) + // "Facing" tag is the prime source of the Facing; if not available, translate from older "Direction" or "Dir" + int Facing = a_NBT.FindChildByName(a_TagIdx, "Facing"); + if (Facing > 0) { - Direction = (int)a_NBT.GetByte(Direction); - if ((Direction < 2) || (Direction > 5)) + Facing = (int)a_NBT.GetByte(Facing); + if ((Facing >= 2) && (Facing <= 5)) { - a_Hanging.SetDirection(BLOCK_FACE_NORTH); - } - else - { - a_Hanging.SetDirection(static_cast(Direction)); + a_Hanging.SetFacing(static_cast(Facing)); } } else { - Direction = a_NBT.FindChildByName(a_TagIdx, "Dir"); - if (Direction > 0) + Facing = a_NBT.FindChildByName(a_TagIdx, "Direction"); + if (Facing > 0) + { + switch ((int)a_NBT.GetByte(Facing)) + { + case 0: a_Hanging.SetFacing(BLOCK_FACE_ZM); break; + case 1: a_Hanging.SetFacing(BLOCK_FACE_XM); break; + case 2: a_Hanging.SetFacing(BLOCK_FACE_ZP); break; + case 3: a_Hanging.SetFacing(BLOCK_FACE_XP); break; + } + } + else { - switch ((int)a_NBT.GetByte(Direction)) + Facing = a_NBT.FindChildByName(a_TagIdx, "Dir"); // Has values 0 and 2 swapped + if (Facing > 0) { - case 0: a_Hanging.SetDirection(BLOCK_FACE_NORTH); break; - case 1: a_Hanging.SetDirection(BLOCK_FACE_TOP); break; - case 2: a_Hanging.SetDirection(BLOCK_FACE_BOTTOM); break; - case 3: a_Hanging.SetDirection(BLOCK_FACE_SOUTH); break; + switch ((int)a_NBT.GetByte(Facing)) + { + case 0: a_Hanging.SetFacing(BLOCK_FACE_ZP); break; + case 1: a_Hanging.SetFacing(BLOCK_FACE_XM); break; + case 2: a_Hanging.SetFacing(BLOCK_FACE_ZM); break; + case 3: a_Hanging.SetFacing(BLOCK_FACE_XP); break; + } } } } -- cgit v1.2.3 From b979cad8931e6d107e18d424274aee4bd2e59b41 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Tue, 21 Oct 2014 22:32:17 +0200 Subject: cItemFrame: Fixed a forgotten rename. --- src/Entities/ItemFrame.h | 2 +- src/WorldStorage/WSSAnvil.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Entities/ItemFrame.h b/src/Entities/ItemFrame.h index 3642662f9..ced8c37af 100644 --- a/src/Entities/ItemFrame.h +++ b/src/Entities/ItemFrame.h @@ -33,7 +33,7 @@ public: Byte GetItemRotation(void) const { return m_ItemRotation; } /** Set the rotation from the item in the frame */ - void SetRotation(Byte a_ItemRotation) { m_ItemRotation = a_ItemRotation; } + void SetItemRotation(Byte a_ItemRotation) { m_ItemRotation = a_ItemRotation; } // tolua_end diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp index eba21c659..8ebcff936 100644 --- a/src/WorldStorage/WSSAnvil.cpp +++ b/src/WorldStorage/WSSAnvil.cpp @@ -1743,7 +1743,7 @@ void cWSSAnvil::LoadItemFrameFromNBT(cEntityList & a_Entities, const cParsedNBT int Rotation = a_NBT.FindChildByName(a_TagIdx, "ItemRotation"); if (Rotation > 0) { - ItemFrame->SetRotation((Byte)a_NBT.GetByte(Rotation)); + ItemFrame->SetItemRotation((Byte)a_NBT.GetByte(Rotation)); } a_Entities.push_back(ItemFrame.release()); -- cgit v1.2.3 From 7ed27c6b8034e5334eda88fe4515349405132cff Mon Sep 17 00:00:00 2001 From: Mattes D Date: Wed, 22 Oct 2014 16:06:16 +0200 Subject: LuaState: Projectiles are pushed using their full class. --- src/Bindings/LuaState.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 928436a2f..f8e026061 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -589,7 +589,7 @@ void cLuaState::Push(cEntity * a_Entity) } case cEntity::etProjectile: { - tolua_pushusertype(m_LuaState, a_Entity, "cProjectileEntity"); + tolua_pushusertype(m_LuaState, a_Entity, a_Entity->GetClass()); break; } case cEntity::etFloater: -- cgit v1.2.3 From 2ac3a807b77e0619f1dd6dcc8ef8948a7c967817 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Wed, 22 Oct 2014 22:58:21 +0200 Subject: ComposableGenerator: Removed nullptr initializers. --- src/Generating/ComposableGenerator.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 358d97c92..b5af4e96a 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -119,9 +119,9 @@ cTerrainCompositionGenPtr cTerrainCompositionGen::CreateCompositionGen(cIniFile cComposableGenerator::cComposableGenerator(cChunkGenerator & a_ChunkGenerator) : super(a_ChunkGenerator), - m_BiomeGen(nullptr), - m_HeightGen(nullptr), - m_CompositionGen(nullptr) + m_BiomeGen(), + m_HeightGen(), + m_CompositionGen() { } -- cgit v1.2.3 From a26541a7c3ced0569098edd0aae61c097c2912f4 Mon Sep 17 00:00:00 2001 From: Tiger Wang Date: Mon, 20 Oct 2014 21:55:07 +0100 Subject: En masse NULL -> nullptr replace --- src/AllocationPool.h | 6 +- src/Bindings/DeprecatedBindings.cpp | 36 +-- src/Bindings/LuaChunkStay.cpp | 2 +- src/Bindings/LuaState.cpp | 54 ++-- src/Bindings/LuaState.h | 6 +- src/Bindings/LuaWindow.cpp | 14 +- src/Bindings/ManualBindings.cpp | 270 ++++++++++---------- src/Bindings/ManualBindings_RankManager.cpp | 2 +- src/Bindings/PluginLua.cpp | 14 +- src/Bindings/PluginManager.cpp | 32 +-- src/Bindings/PluginManager.h | 4 +- src/Bindings/WebPlugin.cpp | 8 +- src/BlockArea.cpp | 88 +++---- src/BlockArea.h | 144 +++++------ src/BlockEntities/BeaconEntity.cpp | 24 +- src/BlockEntities/BlockEntity.cpp | 2 +- src/BlockEntities/BlockEntity.h | 4 +- src/BlockEntities/BlockEntityWithItems.h | 6 +- src/BlockEntities/ChestEntity.cpp | 6 +- src/BlockEntities/CommandBlockEntity.cpp | 2 +- src/BlockEntities/DispenserEntity.cpp | 4 +- src/BlockEntities/DropSpenserEntity.cpp | 22 +- src/BlockEntities/EnderChestEntity.cpp | 6 +- src/BlockEntities/FlowerPotEntity.cpp | 2 +- src/BlockEntities/FlowerPotEntity.h | 2 +- src/BlockEntities/FurnaceEntity.cpp | 8 +- src/BlockEntities/HopperEntity.cpp | 24 +- src/BlockEntities/MobHeadEntity.h | 2 +- src/BlockEntities/NoteEntity.h | 2 +- src/BlockEntities/SignEntity.h | 2 +- src/BlockInfo.cpp | 4 +- src/BlockInfo.h | 2 +- src/Blocks/BlockDirt.h | 2 +- src/Blocks/BlockHandler.cpp | 8 +- src/Blocks/BlockHandler.h | 2 +- src/Blocks/BlockLeaves.h | 2 +- src/Blocks/BlockPiston.cpp | 2 +- src/Blocks/BlockVine.h | 2 +- src/Blocks/BroadcastInterface.h | 4 +- src/ByteBuffer.cpp | 2 +- src/Chunk.cpp | 102 ++++---- src/Chunk.h | 48 ++-- src/ChunkData.cpp | 52 ++-- src/ChunkData.h | 6 +- src/ChunkMap.cpp | 278 ++++++++++----------- src/ChunkMap.h | 50 ++-- src/ChunkSender.cpp | 16 +- src/ChunkSender.h | 2 +- src/ChunkStay.cpp | 14 +- src/ClientHandle.cpp | 52 ++-- src/CraftingRecipes.cpp | 18 +- src/CraftingRecipes.h | 4 +- src/Defines.h | 12 +- src/Entities/ArrowEntity.cpp | 2 +- src/Entities/Boat.cpp | 4 +- src/Entities/Entity.cpp | 56 ++--- src/Entities/Entity.h | 196 ++++++++------- src/Entities/EntityEffect.cpp | 10 +- src/Entities/ExpOrb.cpp | 2 +- src/Entities/Floater.cpp | 2 +- src/Entities/ItemFrame.cpp | 4 +- src/Entities/Minecart.cpp | 14 +- src/Entities/Minecart.h | 4 +- src/Entities/Painting.cpp | 2 +- src/Entities/Player.cpp | 60 ++--- src/Entities/Player.h | 4 +- src/Entities/ProjectileEntity.cpp | 16 +- src/Entities/ProjectileEntity.h | 4 +- src/FurnaceRecipe.cpp | 8 +- src/FurnaceRecipe.h | 2 +- src/Generating/BioGen.cpp | 6 +- src/Generating/ChunkDesc.cpp | 4 +- src/Generating/ChunkDesc.h | 2 +- src/Generating/ChunkGenerator.cpp | 18 +- src/Generating/CompoGen.cpp | 4 +- src/Generating/ComposableGenerator.cpp | 6 +- src/Generating/DungeonRoomsFinisher.cpp | 2 +- src/Generating/GridStructGen.cpp | 2 +- src/Generating/HeiGen.cpp | 6 +- src/Generating/MineShafts.cpp | 18 +- src/Generating/PieceGenerator.cpp | 4 +- src/Generating/Prefab.cpp | 6 +- src/Generating/PrefabPiecePool.cpp | 6 +- src/Generating/VillageGen.cpp | 4 +- src/HTTPServer/HTTPConnection.cpp | 16 +- src/HTTPServer/HTTPConnection.h | 6 +- src/HTTPServer/HTTPFormParser.cpp | 4 +- src/HTTPServer/HTTPMessage.cpp | 2 +- src/HTTPServer/HTTPServer.cpp | 10 +- src/Inventory.cpp | 12 +- src/Inventory.h | 4 +- src/Item.cpp | 2 +- src/ItemGrid.cpp | 2 +- src/Items/ItemBow.h | 8 +- src/Items/ItemEmptyMap.h | 2 +- src/Items/ItemHandler.cpp | 4 +- src/Items/ItemItemFrame.h | 2 +- src/Items/ItemMap.h | 2 +- src/Items/ItemMinecart.h | 2 +- src/LeakFinder.h | 8 +- src/LightingThread.cpp | 8 +- src/LightingThread.h | 2 +- src/LineBlockTracer.cpp | 4 +- src/LinearUpscale.h | 8 +- src/LoggerListeners.cpp | 2 +- src/Map.cpp | 18 +- src/MapManager.cpp | 8 +- src/MapManager.h | 4 +- src/MobSpawner.cpp | 2 +- src/Mobs/AggressiveMonster.cpp | 6 +- src/Mobs/Blaze.cpp | 8 +- src/Mobs/Blaze.h | 2 +- src/Mobs/CaveSpider.cpp | 4 +- src/Mobs/CaveSpider.h | 2 +- src/Mobs/Chicken.cpp | 2 +- src/Mobs/Chicken.h | 2 +- src/Mobs/Cow.cpp | 2 +- src/Mobs/Cow.h | 2 +- src/Mobs/Creeper.cpp | 4 +- src/Mobs/Creeper.h | 2 +- src/Mobs/EnderDragon.h | 2 +- src/Mobs/Enderman.cpp | 10 +- src/Mobs/Enderman.h | 2 +- src/Mobs/Ghast.cpp | 8 +- src/Mobs/Ghast.h | 2 +- src/Mobs/Giant.h | 2 +- src/Mobs/Horse.cpp | 6 +- src/Mobs/Horse.h | 2 +- src/Mobs/IronGolem.h | 2 +- src/Mobs/MagmaCube.h | 2 +- src/Mobs/Monster.cpp | 28 +-- src/Mobs/Mooshroom.cpp | 2 +- src/Mobs/Mooshroom.h | 2 +- src/Mobs/PassiveAggressiveMonster.cpp | 2 +- src/Mobs/PassiveMonster.cpp | 4 +- src/Mobs/Pig.cpp | 6 +- src/Mobs/Pig.h | 2 +- src/Mobs/Sheep.cpp | 2 +- src/Mobs/Sheep.h | 2 +- src/Mobs/Skeleton.cpp | 8 +- src/Mobs/Skeleton.h | 2 +- src/Mobs/Slime.cpp | 2 +- src/Mobs/Slime.h | 2 +- src/Mobs/SnowGolem.h | 2 +- src/Mobs/Spider.cpp | 4 +- src/Mobs/Spider.h | 2 +- src/Mobs/Squid.cpp | 2 +- src/Mobs/Squid.h | 2 +- src/Mobs/Villager.cpp | 2 +- src/Mobs/Witch.cpp | 2 +- src/Mobs/Witch.h | 2 +- src/Mobs/Wither.h | 2 +- src/Mobs/Wolf.cpp | 4 +- src/Mobs/Zombie.cpp | 2 +- src/Mobs/Zombie.h | 2 +- src/Mobs/ZombiePigman.cpp | 4 +- src/Mobs/ZombiePigman.h | 2 +- src/MonsterConfig.cpp | 2 +- src/Noise.cpp | 16 +- src/Noise.h | 12 +- src/OSSupport/Errors.cpp | 4 +- src/OSSupport/Event.cpp | 6 +- src/OSSupport/File.cpp | 22 +- src/OSSupport/GZipFile.cpp | 14 +- src/OSSupport/ListenThread.cpp | 2 +- src/OSSupport/Semaphore.cpp | 4 +- src/OSSupport/Socket.cpp | 2 +- src/OSSupport/SocketThreads.cpp | 14 +- src/OSSupport/SocketThreads.h | 2 +- src/PolarSSL++/BlockingSslClientSocket.cpp | 4 +- src/PolarSSL++/CallbackSslContext.cpp | 6 +- src/PolarSSL++/CryptoKey.cpp | 2 +- src/PolarSSL++/SslContext.cpp | 8 +- src/Protocol/MojangAPI.cpp | 16 +- src/Protocol/MojangAPI.h | 6 +- src/Protocol/Protocol17x.cpp | 6 +- src/Protocol/Protocol18x.cpp | 6 +- src/Protocol/ProtocolRecognizer.cpp | 154 ++++++------ src/RCONServer.cpp | 8 +- src/RankManager.cpp | 6 +- src/RankManager.h | 2 +- src/Root.cpp | 44 ++-- src/Scoreboard.cpp | 20 +- src/Scoreboard.h | 8 +- src/Server.cpp | 22 +- src/SetChunkData.cpp | 10 +- src/SetChunkData.h | 2 +- src/Simulator/DelayedFluidSimulator.cpp | 4 +- src/Simulator/FireSimulator.cpp | 4 +- src/Simulator/FloodyFluidSimulator.cpp | 4 +- src/Simulator/FluidSimulator.cpp | 2 +- src/Simulator/FluidSimulator.h | 2 +- src/Simulator/NoopRedstoneSimulator.h | 2 +- src/Simulator/SandSimulator.cpp | 2 +- src/Simulator/VaporizeFluidSimulator.cpp | 2 +- src/StackWalker.h | 12 +- src/StringUtils.cpp | 4 +- src/UI/SlotArea.cpp | 40 +-- src/UI/Window.cpp | 38 +-- src/UI/Window.h | 6 +- src/UI/WindowOwner.h | 4 +- src/WebAdmin.cpp | 10 +- src/World.cpp | 70 +++--- src/World.h | 374 ++++++++++++++-------------- src/WorldStorage/NBTChunkSerializer.cpp | 2 +- src/WorldStorage/ScoreboardSerializer.cpp | 6 +- src/WorldStorage/WSSAnvil.cpp | 88 +++---- src/WorldStorage/WSSAnvil.h | 6 +- src/WorldStorage/WorldStorage.cpp | 4 +- src/XMLParser.h | 116 ++++----- src/main.cpp | 8 +- 211 files changed, 1768 insertions(+), 1746 deletions(-) (limited to 'src') diff --git a/src/AllocationPool.h b/src/AllocationPool.h index 61431a548..7c358cc84 100644 --- a/src/AllocationPool.h +++ b/src/AllocationPool.h @@ -45,7 +45,7 @@ class cListAllocationPool : public cAllocationPool for (size_t i = 0; i < NumElementsInReserve; i++) { void * space = malloc(sizeof(T)); - if (space == NULL) + if (space == nullptr) { m_Callbacks->OnStartUsingReserve(); break; @@ -68,7 +68,7 @@ class cListAllocationPool : public cAllocationPool if (m_FreeList.size() <= NumElementsInReserve) { void * space = malloc(sizeof(T)); - if (space != NULL) + if (space != nullptr) { return new(space) T; } @@ -90,7 +90,7 @@ class cListAllocationPool : public cAllocationPool } virtual void Free(T * a_ptr) override { - if (a_ptr == NULL) + if (a_ptr == nullptr) { return; } diff --git a/src/Bindings/DeprecatedBindings.cpp b/src/Bindings/DeprecatedBindings.cpp index 02aa15be4..ded7a0142 100644 --- a/src/Bindings/DeprecatedBindings.cpp +++ b/src/Bindings/DeprecatedBindings.cpp @@ -29,7 +29,7 @@ static int tolua_get_AllToLua_g_BlockLightValue(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushnumber(tolua_S, (lua_Number)cBlockInfo::GetLightValue((BLOCKTYPE)BlockType)); return 1; @@ -55,7 +55,7 @@ static int tolua_get_AllToLua_g_BlockSpreadLightFalloff(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushnumber(tolua_S, (lua_Number)cBlockInfo::GetSpreadLightFalloff((BLOCKTYPE)BlockType)); return 1; @@ -81,7 +81,7 @@ static int tolua_get_AllToLua_g_BlockTransparent(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsTransparent((BLOCKTYPE)BlockType)); return 1; @@ -107,7 +107,7 @@ static int tolua_get_AllToLua_g_BlockOneHitDig(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsOneHitDig((BLOCKTYPE)BlockType)); return 1; @@ -133,7 +133,7 @@ static int tolua_get_AllToLua_g_BlockPistonBreakable(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsPistonBreakable((BLOCKTYPE)BlockType)); return 1; @@ -159,7 +159,7 @@ static int tolua_get_AllToLua_g_BlockIsSnowable(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsSnowable((BLOCKTYPE)BlockType)); return 1; @@ -185,7 +185,7 @@ static int tolua_get_AllToLua_g_BlockIsSolid(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, (bool)cBlockInfo::IsSolid((BLOCKTYPE)BlockType)); return 1; @@ -211,7 +211,7 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, (bool)cBlockInfo::FullyOccupiesVoxel((BLOCKTYPE)BlockType)); return 1; @@ -224,16 +224,16 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S) void DeprecatedBindings::Bind(lua_State * tolua_S) { - tolua_beginmodule(tolua_S, NULL); - - tolua_array(tolua_S, "g_BlockLightValue", tolua_get_AllToLua_g_BlockLightValue, NULL); - tolua_array(tolua_S, "g_BlockSpreadLightFalloff", tolua_get_AllToLua_g_BlockSpreadLightFalloff, NULL); - tolua_array(tolua_S, "g_BlockTransparent", tolua_get_AllToLua_g_BlockTransparent, NULL); - tolua_array(tolua_S, "g_BlockOneHitDig", tolua_get_AllToLua_g_BlockOneHitDig, NULL); - tolua_array(tolua_S, "g_BlockPistonBreakable", tolua_get_AllToLua_g_BlockPistonBreakable, NULL); - tolua_array(tolua_S, "g_BlockIsSnowable", tolua_get_AllToLua_g_BlockIsSnowable, NULL); - tolua_array(tolua_S, "g_BlockIsSolid", tolua_get_AllToLua_g_BlockIsSolid, NULL); - tolua_array(tolua_S, "g_BlockFullyOccupiesVoxel", tolua_get_AllToLua_g_BlockFullyOccupiesVoxel, NULL); + tolua_beginmodule(tolua_S, nullptr); + + tolua_array(tolua_S, "g_BlockLightValue", tolua_get_AllToLua_g_BlockLightValue, nullptr); + tolua_array(tolua_S, "g_BlockSpreadLightFalloff", tolua_get_AllToLua_g_BlockSpreadLightFalloff, nullptr); + tolua_array(tolua_S, "g_BlockTransparent", tolua_get_AllToLua_g_BlockTransparent, nullptr); + tolua_array(tolua_S, "g_BlockOneHitDig", tolua_get_AllToLua_g_BlockOneHitDig, nullptr); + tolua_array(tolua_S, "g_BlockPistonBreakable", tolua_get_AllToLua_g_BlockPistonBreakable, nullptr); + tolua_array(tolua_S, "g_BlockIsSnowable", tolua_get_AllToLua_g_BlockIsSnowable, nullptr); + tolua_array(tolua_S, "g_BlockIsSolid", tolua_get_AllToLua_g_BlockIsSolid, nullptr); + tolua_array(tolua_S, "g_BlockFullyOccupiesVoxel", tolua_get_AllToLua_g_BlockFullyOccupiesVoxel, nullptr); tolua_endmodule(tolua_S); } diff --git a/src/Bindings/LuaChunkStay.cpp b/src/Bindings/LuaChunkStay.cpp index 23da12f68..e50ffb75b 100644 --- a/src/Bindings/LuaChunkStay.cpp +++ b/src/Bindings/LuaChunkStay.cpp @@ -13,7 +13,7 @@ cLuaChunkStay::cLuaChunkStay(cPluginLua & a_Plugin) : m_Plugin(a_Plugin), - m_LuaState(NULL) + m_LuaState(nullptr) { } diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index f8e026061..2f5d173fd 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -46,7 +46,7 @@ const cLuaState::cRet cLuaState::Return = {}; // cLuaState: cLuaState::cLuaState(const AString & a_SubsystemName) : - m_LuaState(NULL), + m_LuaState(nullptr), m_IsOwned(false), m_SubsystemName(a_SubsystemName), m_NumCurrentFunctionArgs(-1) @@ -90,7 +90,7 @@ cLuaState::~cLuaState() void cLuaState::Create(void) { - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { LOGWARNING("%s: Trying to create an already-existing LuaState, ignoring.", __FUNCTION__); return; @@ -119,7 +119,7 @@ void cLuaState::RegisterAPILibs(void) void cLuaState::Close(void) { - if (m_LuaState == NULL) + if (m_LuaState == nullptr) { LOGWARNING("%s: Trying to close an invalid LuaState, ignoring.", __FUNCTION__); return; @@ -134,7 +134,7 @@ void cLuaState::Close(void) return; } lua_close(m_LuaState); - m_LuaState = NULL; + m_LuaState = nullptr; m_IsOwned = false; } @@ -144,7 +144,7 @@ void cLuaState::Close(void) void cLuaState::Attach(lua_State * a_State) { - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { LOGINFO("%s: Already contains a LuaState (0x%p), will be closed / detached.", __FUNCTION__, m_LuaState); if (m_IsOwned) @@ -166,7 +166,7 @@ void cLuaState::Attach(lua_State * a_State) void cLuaState::Detach(void) { - if (m_LuaState == NULL) + if (m_LuaState == nullptr) { return; } @@ -179,7 +179,7 @@ void cLuaState::Detach(void) Close(); return; } - m_LuaState = NULL; + m_LuaState = nullptr; } @@ -869,7 +869,7 @@ void cLuaState::GetStackValue(int a_StackPos, AString & a_Value) { size_t len = 0; const char * data = lua_tolstring(m_LuaState, a_StackPos, &len); - if (data != NULL) + if (data != nullptr) { a_Value.assign(data, len); } @@ -919,7 +919,7 @@ void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { - a_ReturnedVal = NULL; + a_ReturnedVal = nullptr; return; } tolua_Error err; @@ -937,7 +937,7 @@ void cLuaState::GetStackValue(int a_StackPos, pWorld & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { - a_ReturnedVal = NULL; + a_ReturnedVal = nullptr; return; } tolua_Error err; @@ -1002,7 +1002,7 @@ bool cLuaState::CheckParamUserTable(int a_StartParam, const char * a_UserTable, lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1035,7 +1035,7 @@ bool cLuaState::CheckParamUserType(int a_StartParam, const char * a_UserType, in lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1068,7 +1068,7 @@ bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1101,7 +1101,7 @@ bool cLuaState::CheckParamNumber(int a_StartParam, int a_EndParam) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1134,7 +1134,7 @@ bool cLuaState::CheckParamString(int a_StartParam, int a_EndParam) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1167,7 +1167,7 @@ bool cLuaState::CheckParamFunction(int a_StartParam, int a_EndParam) VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s", - (entry.name != NULL) ? entry.name : "?", i, GetTypeText(i).c_str() + (entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str() ); return false; } // for i - Param @@ -1200,7 +1200,7 @@ bool cLuaState::CheckParamFunctionOrNil(int a_StartParam, int a_EndParam) VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s", - (entry.name != NULL) ? entry.name : "?", i, GetTypeText(i).c_str() + (entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str() ); return false; } // for i - Param @@ -1224,7 +1224,7 @@ bool cLuaState::CheckParamEnd(int a_Param) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } @@ -1403,7 +1403,7 @@ int cLuaState::CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_Sr case LUA_TUSERDATA: { // Get the class name: - const char * type = NULL; + const char * type = nullptr; if (lua_getmetatable(a_SrcLuaState, i) == 0) { LOGWARNING("%s: Unknown class in pos %d, cannot copy.", __FUNCTION__, i); @@ -1415,7 +1415,7 @@ int cLuaState::CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_Sr lua_pop(a_SrcLuaState, 1); // Stack -1 // Copy the value: - void * ud = tolua_touserdata(a_SrcLuaState, i, NULL); + void * ud = tolua_touserdata(a_SrcLuaState, i, nullptr); tolua_pushusertype(m_LuaState, ud, type); break; } @@ -1441,7 +1441,7 @@ void cLuaState::ToString(int a_StackPos, AString & a_String) { size_t len; const char * s = lua_tolstring(m_LuaState, a_StackPos, &len); - if (s != NULL) + if (s != nullptr) { a_String.assign(s, len); } @@ -1463,7 +1463,7 @@ void cLuaState::LogStack(const char * a_Header) void cLuaState::LogStack(lua_State * a_LuaState, const char * a_Header) { // Format string consisting only of %s is used to appease the compiler - LOG("%s", (a_Header != NULL) ? a_Header : "Lua C API Stack contents:"); + LOG("%s", (a_Header != nullptr) ? a_Header : "Lua C API Stack contents:"); for (int i = lua_gettop(a_LuaState); i > 0; i--) { AString Value; @@ -1500,7 +1500,7 @@ int cLuaState::ReportFnCallErrors(lua_State * a_LuaState) // cLuaState::cRef: cLuaState::cRef::cRef(void) : - m_LuaState(NULL), + m_LuaState(nullptr), m_Ref(LUA_REFNIL) { } @@ -1510,7 +1510,7 @@ cLuaState::cRef::cRef(void) : cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) : - m_LuaState(NULL), + m_LuaState(nullptr), m_Ref(LUA_REFNIL) { RefStack(a_LuaState, a_StackPos); @@ -1522,7 +1522,7 @@ cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) : cLuaState::cRef::~cRef() { - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { UnRef(); } @@ -1535,7 +1535,7 @@ cLuaState::cRef::~cRef() void cLuaState::cRef::RefStack(cLuaState & a_LuaState, int a_StackPos) { ASSERT(a_LuaState.IsValid()); - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { UnRef(); } @@ -1556,7 +1556,7 @@ void cLuaState::cRef::UnRef(void) { luaL_unref(*m_LuaState, LUA_REGISTRYINDEX, m_Ref); } - m_LuaState = NULL; + m_LuaState = nullptr; m_Ref = LUA_REFNIL; } diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index 899228a66..d1e9923b4 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -164,7 +164,7 @@ public: void Detach(void); /** Returns true if the m_LuaState is valid */ - bool IsValid(void) const { return (m_LuaState != NULL); } + bool IsValid(void) const { return (m_LuaState != nullptr); } /** Adds the specified path to package. */ void AddPackagePath(const AString & a_PathVariable, const AString & a_Path); @@ -318,10 +318,10 @@ public: void ToString(int a_StackPos, AString & a_String); /** Logs all the elements' types on the API stack, with an optional header for the listing. */ - void LogStack(const char * a_Header = NULL); + void LogStack(const char * a_Header = nullptr); /** Logs all the elements' types on the API stack, with an optional header for the listing. */ - static void LogStack(lua_State * a_LuaState, const char * a_Header = NULL); + static void LogStack(lua_State * a_LuaState, const char * a_Header = nullptr); protected: diff --git a/src/Bindings/LuaWindow.cpp b/src/Bindings/LuaWindow.cpp index c4d03b86b..35730878d 100644 --- a/src/Bindings/LuaWindow.cpp +++ b/src/Bindings/LuaWindow.cpp @@ -18,7 +18,7 @@ cLuaWindow::cLuaWindow(cWindow::WindowType a_WindowType, int a_SlotsX, int a_SlotsY, const AString & a_Title) : super(a_WindowType, a_Title), m_Contents(a_SlotsX, a_SlotsY), - m_Plugin(NULL), + m_Plugin(nullptr), m_LuaRef(LUA_REFNIL), m_OnClosingFnRef(LUA_REFNIL), m_OnSlotChangedFnRef(LUA_REFNIL) @@ -70,7 +70,7 @@ cLuaWindow::~cLuaWindow() void cLuaWindow::SetLuaRef(cPluginLua * a_Plugin, int a_LuaRef) { // Either m_Plugin is not set or equal to the passed plugin; only one plugin can use one cLuaWindow object - ASSERT((m_Plugin == NULL) || (m_Plugin == a_Plugin)); + ASSERT((m_Plugin == nullptr) || (m_Plugin == a_Plugin)); ASSERT(m_LuaRef == LUA_REFNIL); m_Plugin = a_Plugin; m_LuaRef = a_LuaRef; @@ -82,7 +82,7 @@ void cLuaWindow::SetLuaRef(cPluginLua * a_Plugin, int a_LuaRef) bool cLuaWindow::IsLuaReferenced(void) const { - return ((m_Plugin != NULL) && (m_LuaRef != LUA_REFNIL)); + return ((m_Plugin != nullptr) && (m_LuaRef != LUA_REFNIL)); } @@ -92,7 +92,7 @@ bool cLuaWindow::IsLuaReferenced(void) const void cLuaWindow::SetOnClosing(cPluginLua * a_Plugin, int a_FnRef) { // Either m_Plugin is not set or equal to the passed plugin; only one plugin can use one cLuaWindow object - ASSERT((m_Plugin == NULL) || (m_Plugin == a_Plugin)); + ASSERT((m_Plugin == nullptr) || (m_Plugin == a_Plugin)); // If there already was a function, unreference it first if (m_OnClosingFnRef != LUA_REFNIL) @@ -112,7 +112,7 @@ void cLuaWindow::SetOnClosing(cPluginLua * a_Plugin, int a_FnRef) void cLuaWindow::SetOnSlotChanged(cPluginLua * a_Plugin, int a_FnRef) { // Either m_Plugin is not set or equal to the passed plugin; only one plugin can use one cLuaWindow object - ASSERT((m_Plugin == NULL) || (m_Plugin == a_Plugin)); + ASSERT((m_Plugin == nullptr) || (m_Plugin == a_Plugin)); // If there already was a function, unreference it first if (m_OnSlotChangedFnRef != LUA_REFNIL) @@ -134,7 +134,7 @@ bool cLuaWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) // First notify the plugin through the registered callback: if (m_OnClosingFnRef != LUA_REFNIL) { - ASSERT(m_Plugin != NULL); + ASSERT(m_Plugin != nullptr); if (m_Plugin->CallbackWindowClosing(m_OnClosingFnRef, *this, a_Player, a_CanRefuse)) { // The callback disagrees (the higher levels check the CanRefuse flag compliance) @@ -153,7 +153,7 @@ void cLuaWindow::Destroy(void) { super::Destroy(); - if ((m_LuaRef != LUA_REFNIL) && (m_Plugin != NULL)) + if ((m_LuaRef != LUA_REFNIL) && (m_Plugin != nullptr)) { // The object is referenced by Lua, un-reference it m_Plugin->Unreference(m_LuaRef); diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index 0558533ce..a4a5d79b4 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -145,13 +145,13 @@ static AString GetLogMessage(lua_State * tolua_S) tolua_Error err; if (tolua_isusertype(tolua_S, 1, "cCompositeChat", false, &err)) { - return ((cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL))->ExtractText(); + return ((cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr))->ExtractText(); } else { size_t len = 0; const char * str = lua_tolstring(tolua_S, 1, &len); - if (str != NULL) + if (str != nullptr) { return AString(str, len); } @@ -170,7 +170,7 @@ static int tolua_LOG(lua_State * tolua_S) tolua_Error err; if (tolua_isusertype(tolua_S, 1, "cCompositeChat", false, &err)) { - LogLevel = cCompositeChat::MessageTypeToLogLevel(((cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL))->GetMessageType()); + LogLevel = cCompositeChat::MessageTypeToLogLevel(((cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr))->GetMessageType()); } // Log the message: @@ -264,7 +264,7 @@ static cPluginLua * GetLuaPlugin(lua_State * L) { LOGWARNING("%s: cannot get plugin instance, what have you done to my Lua state?", __FUNCTION__); lua_pop(L, 1); - return NULL; + return nullptr; } cPluginLua * Plugin = (cPluginLua *)lua_topointer(L, -1); lua_pop(L, 1); @@ -312,10 +312,10 @@ static int tolua_DoWith(lua_State* tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, nullptr); const char * ItemName = tolua_tocppstring(tolua_S, 2, ""); - if ((ItemName == NULL) || (ItemName[0] == 0)) + if ((ItemName == nullptr) || (ItemName[0] == 0)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1", NumArgs); } @@ -406,7 +406,7 @@ static int tolua_DoWithID(lua_State* tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, nullptr); int ItemID = (int)tolua_tonumber(tolua_S, 2, 0); if (!lua_isfunction(tolua_S, 3)) @@ -496,7 +496,7 @@ static int tolua_DoWithXYZ(lua_State* tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 4 or 5 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, nullptr); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3) || !lua_isnumber(tolua_S, 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1, #2 and #3"); @@ -591,7 +591,7 @@ static int tolua_ForEachInChunk(lua_State * tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 3 or 4 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, nullptr); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1 and #2"); @@ -694,10 +694,10 @@ static int tolua_ForEachInBox(lua_State * tolua_S) } // Get the params: - Ty1 * Self = NULL; - cBoundingBox * Box = NULL; + Ty1 * Self = nullptr; + cBoundingBox * Box = nullptr; L.GetStackValues(1, Self, Box); - if ((Self == NULL) || (Box == NULL)) + if ((Self == nullptr) || (Box == nullptr)) { LOGWARNING("Invalid world (%p) or boundingbox (%p)", Self, Box); L.LogStackTrace(); @@ -760,8 +760,8 @@ static int tolua_ForEach(lua_State * tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 1 or 2 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } @@ -857,14 +857,14 @@ static int tolua_cWorld_GetBlockInfo(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'GetBlockInfo'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'GetBlockInfo'", nullptr); } #endif { @@ -912,14 +912,14 @@ static int tolua_cWorld_GetBlockTypeMeta(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'GetBlockTypeMeta'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'GetBlockTypeMeta'", nullptr); } #endif { @@ -964,14 +964,14 @@ static int tolua_cWorld_GetSignLines(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'GetSignLines'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'GetSignLines'", nullptr); } #endif { @@ -1022,7 +1022,7 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); @@ -1030,11 +1030,11 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) const AString Line2 = tolua_tocppstring(tolua_S, 6, 0); const AString Line3 = tolua_tocppstring(tolua_S, 7, 0); const AString Line4 = tolua_tocppstring(tolua_S, 8, 0); - cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, NULL); + cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, nullptr); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines' / 'UpdateSign'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines' / 'UpdateSign'", nullptr); } #endif { @@ -1071,13 +1071,13 @@ static int tolua_cWorld_TryGetHeight(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 3, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "Invalid 'self' in function 'TryGetHeight'", NULL); + tolua_error(tolua_S, "Invalid 'self' in function 'TryGetHeight'", nullptr); } #endif { @@ -1136,15 +1136,15 @@ static int tolua_cWorld_QueueTask(lua_State * tolua_S) // Retrieve the cPlugin from the LuaState: cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has been already printed in GetLuaPlugin() return 0; } // Retrieve the args: - cWorld * self = (cWorld *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cWorld * self = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } @@ -1200,7 +1200,7 @@ static int tolua_cWorld_ScheduleTask(lua_State * tolua_S) // Retrieve the cPlugin from the LuaState: cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has been already printed in GetLuaPlugin() return 0; @@ -1216,8 +1216,8 @@ static int tolua_cWorld_ScheduleTask(lua_State * tolua_S) { return 0; } - cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, NULL); - if (World == NULL) + cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr); + if (World == nullptr) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } @@ -1241,7 +1241,7 @@ static int tolua_cWorld_ScheduleTask(lua_State * tolua_S) static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) { - cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, NULL); + cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, nullptr); const cPluginManager::PluginMap & AllPlugins = self->GetAllPlugins(); @@ -1252,7 +1252,7 @@ static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) { const cPlugin* Plugin = iter->second; tolua_pushstring(tolua_S, iter->first.c_str()); - if (Plugin != NULL) + if (Plugin != nullptr) { tolua_pushusertype(tolua_S, (void *)Plugin, "const cPlugin"); } @@ -1274,7 +1274,7 @@ static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) static int tolua_cPluginManager_GetCurrentPlugin(lua_State * S) { cPluginLua * Plugin = GetLuaPlugin(S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has already been printed in GetLuaPlugin() return 0; @@ -1305,7 +1305,7 @@ static int tolua_cPluginManager_AddHook_FnRef(cPluginManager * a_PluginManager, // Retrieve the cPlugin from the LuaState: cPluginLua * Plugin = GetLuaPlugin(S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has been already printed in GetLuaPlugin() return 0; @@ -1344,8 +1344,8 @@ static int tolua_cPluginManager_AddHook_DefFn(cPluginManager * a_PluginManager, // The arg types have already been checked // Retrieve and check the cPlugin parameter - cPluginLua * Plugin = (cPluginLua *)tolua_tousertype(S, a_ParamIdx, NULL); - if (Plugin == NULL) + cPluginLua * Plugin = (cPluginLua *)tolua_tousertype(S, a_ParamIdx, nullptr); + if (Plugin == nullptr) { LOGWARNING("cPluginManager.AddHook(): Invalid Plugin parameter, expected a valid cPlugin object. Hook not added"); S.LogStackTrace(); @@ -1370,7 +1370,7 @@ static int tolua_cPluginManager_AddHook_DefFn(cPluginManager * a_PluginManager, // Get the standard name for the callback function: const char * FnName = cPluginLua::GetHookFnName(HookType); - if (FnName == NULL) + if (FnName == nullptr) { LOGWARNING("cPluginManager.AddHook(): Unknown hook type (%d). Hook not added.", HookType); S.LogStackTrace(); @@ -1417,8 +1417,8 @@ static int tolua_cPluginManager_AddHook(lua_State * tolua_S) if (tolua_isusertype(S, 1, "cPluginManager", 0, &err)) { // Style 2 or 3, retrieve the PlgMgr instance - PlgMgr = (cPluginManager *)tolua_tousertype(S, 1, NULL); - if (PlgMgr == NULL) + PlgMgr = (cPluginManager *)tolua_tousertype(S, 1, nullptr); + if (PlgMgr == nullptr) { LOGWARNING("Malformed plugin, use cPluginManager.AddHook(HOOK_TYPE, CallbackFunction). Fixing the call for you."); S.LogStackTrace(); @@ -1465,8 +1465,8 @@ static int tolua_cPluginManager_ForEachCommand(lua_State * tolua_S) return 0; } - cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARN("Error in function call 'ForEachCommand': Not called on an object instance"); return 0; @@ -1542,8 +1542,8 @@ static int tolua_cPluginManager_ForEachConsoleCommand(lua_State * tolua_S) return 0; } - cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARN("Error in function call 'ForEachConsoleCommand': Not called on an object instance"); return 0; @@ -1617,7 +1617,7 @@ static int tolua_cPluginManager_BindCommand(lua_State * L) cPluginManager.BindCommand(Command, Permission, Function, HelpString) -- without the "self" param */ cPluginLua * Plugin = GetLuaPlugin(L); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } @@ -1687,7 +1687,7 @@ static int tolua_cPluginManager_BindConsoleCommand(lua_State * L) // Get the plugin identification out of LuaState: cPluginLua * Plugin = GetLuaPlugin(L); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } @@ -1775,7 +1775,7 @@ static int tolua_cPluginManager_CallPlugin(lua_State * tolua_S) // If requesting calling the current plugin, refuse: cPluginLua * ThisPlugin = GetLuaPlugin(L); - if (ThisPlugin == NULL) + if (ThisPlugin == nullptr) { return 0; } @@ -1843,14 +1843,14 @@ static int tolua_cWorld_ChunkStay(lua_State * tolua_S) } cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } // Read the params: - cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, NULL); - if (World == NULL) + cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr); + if (World == nullptr) { LOGWARNING("World:ChunkStay(): invalid world parameter"); L.LogStackTrace(); @@ -1862,7 +1862,7 @@ static int tolua_cWorld_ChunkStay(lua_State * tolua_S) if (!ChunkStay->AddChunks(2)) { delete ChunkStay; - ChunkStay = NULL; + ChunkStay = nullptr; return 0; } @@ -1889,8 +1889,8 @@ static int tolua_cPlayer_GetPermissions(lua_State * tolua_S) } // Get the params: - cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARNING("%s: invalid self (%p)", __FUNCTION__, self); return 0; @@ -1911,15 +1911,15 @@ static int tolua_cPlayer_OpenWindow(lua_State * tolua_S) // Retrieve the plugin instance from the Lua state cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } // Get the parameters: - cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL); - cWindow * wnd = (cWindow *)tolua_tousertype(tolua_S, 2, NULL); - if ((self == NULL) || (wnd == NULL)) + cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, nullptr); + cWindow * wnd = (cWindow *)tolua_tousertype(tolua_S, 2, nullptr); + if ((self == nullptr) || (wnd == nullptr)) { LOGWARNING("%s: invalid self (%p) or wnd (%p)", __FUNCTION__, self, wnd); return 0; @@ -1992,15 +1992,15 @@ static int tolua_SetObjectCallback(lua_State * tolua_S) // Retrieve the plugin instance from the Lua state cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { // Warning message has already been printed by GetLuaPlugin(), bail out silently return 0; } // Get the parameters - self and the function reference: - OBJTYPE * self = (OBJTYPE *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + OBJTYPE * self = (OBJTYPE *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARNING("%s: invalid self (%p)", __FUNCTION__, self); return 0; @@ -2023,7 +2023,7 @@ static int tolua_SetObjectCallback(lua_State * tolua_S) static int tolua_cPluginLua_AddWebTab(lua_State * tolua_S) { - cPluginLua * self = (cPluginLua *)tolua_tousertype(tolua_S, 1, NULL); + cPluginLua * self = (cPluginLua *)tolua_tousertype(tolua_S, 1, nullptr); tolua_Error tolua_err; tolua_err.array = 0; @@ -2067,7 +2067,7 @@ static int tolua_cPluginLua_AddWebTab(lua_State * tolua_S) static int tolua_cPluginLua_AddTab(lua_State* tolua_S) { - cPluginLua * self = (cPluginLua *) tolua_tousertype(tolua_S, 1, NULL); + cPluginLua * self = (cPluginLua *) tolua_tousertype(tolua_S, 1, nullptr); LOGWARN("WARNING: Using deprecated function AddTab()! Use AddWebTab() instead. (plugin \"%s\" in folder \"%s\")", self->GetName().c_str(), self->GetDirectory().c_str() ); @@ -2087,7 +2087,7 @@ static int tolua_cPlugin_Call(lua_State * tolua_S) L.LogStackTrace(); // Retrieve the params: plugin and the function name to call - cPluginLua * TargetPlugin = (cPluginLua *) tolua_tousertype(tolua_S, 1, NULL); + cPluginLua * TargetPlugin = (cPluginLua *) tolua_tousertype(tolua_S, 1, nullptr); AString FunctionName = tolua_tostring(tolua_S, 2, ""); // Call the function: @@ -2142,7 +2142,7 @@ static int tolua_push_StringStringMap(lua_State* tolua_S, std::map< std::string, static int tolua_get_HTTPRequest_Params(lua_State* tolua_S) { - HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, NULL); + HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, nullptr); return tolua_push_StringStringMap(tolua_S, self->Params); } @@ -2152,7 +2152,7 @@ static int tolua_get_HTTPRequest_Params(lua_State* tolua_S) static int tolua_get_HTTPRequest_PostParams(lua_State* tolua_S) { - HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, NULL); + HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, nullptr); return tolua_push_StringStringMap(tolua_S, self->PostParams); } @@ -2162,7 +2162,7 @@ static int tolua_get_HTTPRequest_PostParams(lua_State* tolua_S) static int tolua_get_HTTPRequest_FormData(lua_State* tolua_S) { - HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, NULL); + HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, nullptr); std::map< std::string, HTTPFormData >& FormData = self->FormData; lua_newtable(tolua_S); @@ -2185,7 +2185,7 @@ 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, nullptr); const cWebAdmin::PluginList & AllPlugins = self->GetPlugins(); @@ -2266,7 +2266,7 @@ static int tolua_AllToLua_cWebAdmin_GetURLEncodedString(lua_State * tolua_S) static int tolua_cWebPlugin_GetTabNames(lua_State * tolua_S) { - cWebPlugin* self = (cWebPlugin*) tolua_tousertype(tolua_S, 1, NULL); + cWebPlugin* self = (cWebPlugin*) tolua_tousertype(tolua_S, 1, nullptr); const cWebPlugin::TabNameList & TabNames = self->GetTabNames(); @@ -2302,8 +2302,8 @@ static int tolua_cClientHandle_SendPluginMessage(lua_State * L) { return 0; } - cClientHandle * Client = (cClientHandle *)tolua_tousertype(L, 1, NULL); - if (Client == NULL) + cClientHandle * Client = (cClientHandle *)tolua_tousertype(L, 1, nullptr); + if (Client == nullptr) { LOGWARNING("ClientHandle is nil in cClientHandle:SendPluginMessage()"); S.LogStackTrace(); @@ -2548,11 +2548,11 @@ static int Lua_ItemGrid_GetSlotCoords(lua_State * L) } { - const cItemGrid * self = (const cItemGrid *)tolua_tousertype(L, 1, NULL); + const cItemGrid * self = (const cItemGrid *)tolua_tousertype(L, 1, nullptr); int SlotNum = (int)tolua_tonumber(L, 2, 0); - if (self == NULL) + if (self == nullptr) { - tolua_error(L, "invalid 'self' in function 'cItemGrid:GetSlotCoords'", NULL); + tolua_error(L, "invalid 'self' in function 'cItemGrid:GetSlotCoords'", nullptr); return 0; } int X, Y; @@ -2689,7 +2689,7 @@ static int tolua_cLineBlockTracer_Trace(lua_State * tolua_S) } // Trace: - cWorld * World = (cWorld *)tolua_tousertype(L, idx, NULL); + cWorld * World = (cWorld *)tolua_tousertype(L, idx, nullptr); cLuaBlockTracerCallbacks Callbacks(L, idx + 1); double StartX = tolua_tonumber(L, idx + 2, 0); double StartY = tolua_tonumber(L, idx + 3, 0); @@ -2719,8 +2719,8 @@ static int tolua_cRoot_GetFurnaceRecipe(lua_State * tolua_S) } // Check the input param: - cItem * Input = (cItem *)tolua_tousertype(L, 2, NULL); - if (Input == NULL) + cItem * Input = (cItem *)tolua_tousertype(L, 2, nullptr); + if (Input == nullptr) { LOGWARNING("cRoot:GetFurnaceRecipe: the Input parameter is nil or missing."); return 0; @@ -2729,7 +2729,7 @@ static int tolua_cRoot_GetFurnaceRecipe(lua_State * tolua_S) // Get the recipe for the input cFurnaceRecipe * FR = cRoot::Get()->GetFurnaceRecipe(); const cFurnaceRecipe::cRecipe * Recipe = FR->GetRecipeFrom(*Input); - if (Recipe == NULL) + if (Recipe == nullptr) { // There is no such furnace recipe for this input, return no value return 0; @@ -2760,10 +2760,10 @@ static int tolua_cHopperEntity_GetOutputBlockPos(lua_State * tolua_S) { return 0; } - cHopperEntity * self = (cHopperEntity *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cHopperEntity * self = (cHopperEntity *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cHopperEntity::GetOutputBlockPos()'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cHopperEntity::GetOutputBlockPos()'", nullptr); return 0; } @@ -2800,10 +2800,10 @@ static int tolua_cBlockArea_GetBlockTypeMeta(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", nullptr); return 0; } int BlockX = (int)tolua_tonumber(tolua_S, 2, 0); @@ -2834,10 +2834,10 @@ static int tolua_cBlockArea_GetOrigin(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetOrigin'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetOrigin'", nullptr); return 0; } @@ -2866,10 +2866,10 @@ static int tolua_cBlockArea_GetRelBlockTypeMeta(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", nullptr); return 0; } int BlockX = (int)tolua_tonumber(tolua_S, 2, 0); @@ -2900,10 +2900,10 @@ static int tolua_cBlockArea_GetSize(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", nullptr); return 0; } @@ -2931,10 +2931,10 @@ static int tolua_cBlockArea_GetCoordRange(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", nullptr); return 0; } @@ -2962,10 +2962,10 @@ static int tolua_cBlockArea_LoadFromSchematicFile(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", nullptr); return 0; } @@ -2992,10 +2992,10 @@ static int tolua_cBlockArea_LoadFromSchematicString(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", nullptr); return 0; } @@ -3023,10 +3023,10 @@ static int tolua_cBlockArea_SaveToSchematicFile(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", nullptr); return 0; } AString Filename = tolua_tostring(tolua_S, 2, 0); @@ -3051,10 +3051,10 @@ static int tolua_cBlockArea_SaveToSchematicString(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", nullptr); return 0; } @@ -3085,10 +3085,10 @@ static int tolua_cCompositeChat_AddRunCommandPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddRunCommandPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddRunCommandPart'", nullptr); return 0; } @@ -3122,10 +3122,10 @@ static int tolua_cCompositeChat_AddSuggestCommandPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddSuggestCommandPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddSuggestCommandPart'", nullptr); return 0; } @@ -3159,10 +3159,10 @@ static int tolua_cCompositeChat_AddTextPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddTextPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddTextPart'", nullptr); return 0; } @@ -3195,10 +3195,10 @@ static int tolua_cCompositeChat_AddUrlPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddUrlPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddUrlPart'", nullptr); return 0; } @@ -3232,10 +3232,10 @@ static int tolua_cCompositeChat_ParseText(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:ParseText'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:ParseText'", nullptr); return 0; } @@ -3267,10 +3267,10 @@ static int tolua_cCompositeChat_SetMessageType(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:SetMessageType'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:SetMessageType'", nullptr); return 0; } @@ -3299,10 +3299,10 @@ static int tolua_cCompositeChat_UnderlineUrls(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:UnderlineUrls'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:UnderlineUrls'", nullptr); return 0; } @@ -3320,7 +3320,7 @@ static int tolua_cCompositeChat_UnderlineUrls(lua_State * tolua_S) void ManualBindings::Bind(lua_State * tolua_S) { - tolua_beginmodule(tolua_S, NULL); + tolua_beginmodule(tolua_S, nullptr); tolua_function(tolua_S, "Clamp", tolua_Clamp); tolua_function(tolua_S, "StringSplit", tolua_StringSplit); tolua_function(tolua_S, "StringSplitAndTrim", tolua_StringSplitAndTrim); @@ -3447,7 +3447,7 @@ void ManualBindings::Bind(lua_State * tolua_S) tolua_function(tolua_S, "AddWebTab", tolua_cPluginLua_AddWebTab); tolua_endmodule(tolua_S); - tolua_cclass(tolua_S, "HTTPRequest", "HTTPRequest", "", NULL); + tolua_cclass(tolua_S, "HTTPRequest", "HTTPRequest", "", nullptr); tolua_beginmodule(tolua_S, "HTTPRequest"); // tolua_variable(tolua_S, "Method", tolua_get_HTTPRequest_Method, tolua_set_HTTPRequest_Method); // tolua_variable(tolua_S, "Path", tolua_get_HTTPRequest_Path, tolua_set_HTTPRequest_Path); diff --git a/src/Bindings/ManualBindings_RankManager.cpp b/src/Bindings/ManualBindings_RankManager.cpp index 66174bf86..fa1b88b6a 100644 --- a/src/Bindings/ManualBindings_RankManager.cpp +++ b/src/Bindings/ManualBindings_RankManager.cpp @@ -1044,7 +1044,7 @@ void ManualBindings::BindRankManager(lua_State * tolua_S) { // Create the cRankManager class in the API: tolua_usertype(tolua_S, "cRankManager"); - tolua_cclass(tolua_S, "cRankManager", "cRankManager", "", NULL); + tolua_cclass(tolua_S, "cRankManager", "cRankManager", "", nullptr); // Fill in the functions (alpha-sorted): tolua_beginmodule(tolua_S, "cRankManager"); diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp index eec31e8a6..391d8bcbe 100644 --- a/src/Bindings/PluginLua.cpp +++ b/src/Bindings/PluginLua.cpp @@ -1487,7 +1487,7 @@ void cPluginLua::ClearCommands(void) cCSLock Lock(m_CriticalSection); // Unreference the bound functions so that Lua can GC them - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { for (CommandMap::iterator itr = m_Commands.begin(), end = m_Commands.end(); itr != end; ++itr) { @@ -1506,7 +1506,7 @@ void cPluginLua::ClearConsoleCommands(void) cCSLock Lock(m_CriticalSection); // Unreference the bound functions so that Lua can GC them - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { for (CommandMap::iterator itr = m_ConsoleCommands.begin(), end = m_ConsoleCommands.end(); itr != end; ++itr) { @@ -1523,7 +1523,7 @@ void cPluginLua::ClearConsoleCommands(void) bool cPluginLua::CanAddOldStyleHook(int a_HookType) { const char * FnName = GetHookFnName(a_HookType); - if (FnName == NULL) + if (FnName == nullptr) { // Unknown hook ID LOGWARNING("Plugin %s wants to add an unknown hook ID (%d). The plugin need not work properly.", @@ -1614,7 +1614,7 @@ const char * cPluginLua::GetHookFnName(int a_HookType) } // switch (a_Hook) LOGWARNING("Requested name of an unknown hook type function: %d (max is %d)", a_HookType, cPluginManager::HOOK_MAX); ASSERT(!"Unknown hook requested!"); - return NULL; + return nullptr; } @@ -1627,12 +1627,12 @@ bool cPluginLua::AddHookRef(int a_HookType, int a_FnRefIdx) // Check if the function reference is valid: cLuaState::cRef * Ref = new cLuaState::cRef(m_LuaState, a_FnRefIdx); - if ((Ref == NULL) || !Ref->IsValid()) + if ((Ref == nullptr) || !Ref->IsValid()) { LOGWARNING("Plugin %s tried to add a hook %d with bad handler function.", GetName().c_str(), a_HookType); m_LuaState.LogStackTrace(); delete Ref; - Ref = NULL; + Ref = nullptr; return false; } @@ -1700,7 +1700,7 @@ AString cPluginLua::HandleWebRequest(const HTTPRequest * a_Request) } } - if (Tab != NULL) + if (Tab != nullptr) { AString Contents = Printf("WARNING: WebPlugin tab '%s' did not return a string!", Tab->Title.c_str()); if (!m_LuaState.Call(Tab->UserData, a_Request, cLuaState::Return, Contents)) diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp index 479e71951..e549aefa3 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -66,7 +66,7 @@ void cPluginManager::FindPlugins(void) // First get a clean list of only the currently running plugins, we don't want to mess those up for (PluginMap::iterator itr = m_Plugins.begin(); itr != m_Plugins.end();) { - if (itr->second == NULL) + if (itr->second == nullptr) { PluginMap::iterator thiz = itr; ++thiz; @@ -89,7 +89,7 @@ void cPluginManager::FindPlugins(void) // Add plugin name/directory to the list if (m_Plugins.find(*itr) == m_Plugins.end()) { - m_Plugins[*itr] = NULL; + m_Plugins[*itr] = nullptr; } } } @@ -151,7 +151,7 @@ void cPluginManager::ReloadPluginsNow(cIniFile & a_SettingsIni) // Remove invalid plugins from the PluginMap. for (PluginMap::iterator itr = m_Plugins.begin(); itr != m_Plugins.end();) { - if (itr->second == NULL) + if (itr->second == nullptr) { PluginMap::iterator thiz = itr; ++thiz; @@ -1445,7 +1445,7 @@ cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer & a_Player, return crNoPermission; } - ASSERT(cmd->second.m_Plugin != NULL); + ASSERT(cmd->second.m_Plugin != nullptr); if (!cmd->second.m_Plugin->HandleCommand(Split, a_Player)) { @@ -1463,7 +1463,7 @@ cPlugin * cPluginManager::GetPlugin( const AString & a_Plugin) const { for (PluginMap::const_iterator itr = m_Plugins.begin(); itr != m_Plugins.end(); ++itr) { - if (itr->second == NULL) continue; + if (itr->second == nullptr) continue; if (itr->second->GetName().compare(a_Plugin) == 0) { return itr->second; @@ -1513,7 +1513,7 @@ bool cPluginManager::DisablePlugin(const AString & a_PluginName) if (itr->first.compare(a_PluginName) == 0) // _X 2013_02_01: wtf? Isn't this supposed to be what find() does? { m_DisablePluginList.push_back(itr->second); - itr->second = NULL; // Get rid of this thing right away + itr->second = nullptr; // Get rid of this thing right away return true; } return false; @@ -1558,12 +1558,12 @@ void cPluginManager::RemovePlugin(cPlugin * a_Plugin) RemovePluginCommands(a_Plugin); RemovePluginConsoleCommands(a_Plugin); RemoveHooks(a_Plugin); - if (a_Plugin != NULL) + if (a_Plugin != nullptr) { a_Plugin->OnDisable(); } delete a_Plugin; - a_Plugin = NULL; + a_Plugin = nullptr; } @@ -1572,7 +1572,7 @@ void cPluginManager::RemovePlugin(cPlugin * a_Plugin) void cPluginManager::RemovePluginCommands(cPlugin * a_Plugin) { - if (a_Plugin != NULL) + if (a_Plugin != nullptr) { a_Plugin->ClearCommands(); } @@ -1670,7 +1670,7 @@ cPluginManager::CommandResult cPluginManager::ForceExecuteCommand(cPlayer & a_Pl void cPluginManager::RemovePluginConsoleCommands(cPlugin * a_Plugin) { - if (a_Plugin != NULL) + if (a_Plugin != nullptr) { a_Plugin->ClearConsoleCommands(); } @@ -1699,7 +1699,7 @@ bool cPluginManager::BindConsoleCommand(const AString & a_Command, cPlugin * a_P CommandMap::iterator cmd = m_ConsoleCommands.find(a_Command); if (cmd != m_ConsoleCommands.end()) { - if (cmd->second.m_Plugin == NULL) + if (cmd->second.m_Plugin == nullptr) { LOGWARNING("Console command \"%s\" is already bound internally by MCServer, cannot bind in plugin \"%s\".", a_Command.c_str(), a_Plugin->GetName().c_str()); } @@ -1759,14 +1759,14 @@ bool cPluginManager::ExecuteConsoleCommand(const AStringVector & a_Split, cComma return false; } - if (cmd->second.m_Plugin == NULL) + if (cmd->second.m_Plugin == nullptr) { // This is a built-in command return false; } // Ask plugins first if a command is okay to execute the console command: - if (CallHookExecuteCommand(NULL, a_Split)) + if (CallHookExecuteCommand(nullptr, a_Split)) { a_Output.Out("Command \"%s\" was stopped by the HOOK_EXECUTE_COMMAND hook", a_Split[0].c_str()); return false; @@ -1788,7 +1788,7 @@ void cPluginManager::TabCompleteCommand(const AString & a_Text, AStringVector & // Command name doesn't match continue; } - if ((a_Player != NULL) && !a_Player->HasPermission(itr->second.m_Permission)) + if ((a_Player != nullptr) && !a_Player->HasPermission(itr->second.m_Permission)) { // Player doesn't have permission for the command continue; @@ -1814,7 +1814,7 @@ bool cPluginManager::DoWithPlugin(const AString & a_PluginName, cPluginCallback { // TODO: Implement locking for plugins PluginMap::iterator itr = m_Plugins.find(a_PluginName); - if ((itr == m_Plugins.end()) || (itr->second == NULL)) + if ((itr == m_Plugins.end()) || (itr->second == nullptr)) { return false; } @@ -1848,7 +1848,7 @@ void cPluginManager::AddHook(cPlugin * a_Plugin, int a_Hook) { if (!a_Plugin) { - LOGWARN("Called cPluginManager::AddHook() with a_Plugin == NULL"); + LOGWARN("Called cPluginManager::AddHook() with a_Plugin == nullptr"); return; } PluginList & Plugins = m_Hooks[a_Hook]; diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h index c69850be6..bc8c1f5e6 100644 --- a/src/Bindings/PluginManager.h +++ b/src/Bindings/PluginManager.h @@ -190,7 +190,7 @@ public: bool CallHookCraftingNoRecipe (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe); bool CallHookDisconnect (cClientHandle & a_Client, const AString & a_Reason); bool CallHookEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier); - bool CallHookExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split); // If a_Player == NULL, it is a console cmd + bool CallHookExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split); // If a_Player == nullptr, 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); bool CallHookHandshake (cClientHandle & a_ClientHandle, const AString & a_Username); @@ -285,7 +285,7 @@ public: bool ExecuteConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output); /** Appends all commands beginning with a_Text (case-insensitive) into a_Results. - If a_Player is not NULL, only commands for which the player has permissions are added. + If a_Player is not nullptr, only commands for which the player has permissions are added. */ void TabCompleteCommand(const AString & a_Text, AStringVector & a_Results, cPlayer * a_Player); diff --git a/src/Bindings/WebPlugin.cpp b/src/Bindings/WebPlugin.cpp index eca1c74e6..5759b20e7 100644 --- a/src/Bindings/WebPlugin.cpp +++ b/src/Bindings/WebPlugin.cpp @@ -12,7 +12,7 @@ cWebPlugin::cWebPlugin() { cWebAdmin * WebAdmin = cRoot::Get()->GetWebAdmin(); - if (WebAdmin != NULL) + if (WebAdmin != nullptr) { WebAdmin->AddPlugin(this); } @@ -25,7 +25,7 @@ cWebPlugin::cWebPlugin() cWebPlugin::~cWebPlugin() { cWebAdmin * WebAdmin = cRoot::Get()->GetWebAdmin(); - if (WebAdmin != NULL) + if (WebAdmin != nullptr) { WebAdmin->RemovePlugin(this); } @@ -65,7 +65,7 @@ std::pair< AString, AString > cWebPlugin::GetTabNameForRequest(const HTTPRequest if (Split.size() > 1) { - sWebPluginTab * Tab = NULL; + sWebPluginTab * Tab = nullptr; if (Split.size() > 2) // If we got the tab name, show that page { for (TabList::iterator itr = GetTabs().begin(); itr != GetTabs().end(); ++itr) @@ -85,7 +85,7 @@ std::pair< AString, AString > cWebPlugin::GetTabNameForRequest(const HTTPRequest } } - if (Tab != NULL) + if (Tab != nullptr) { Names.first = Tab->Title; Names.second = Tab->SafeTitle; diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp index ba55528b8..4c3da0535 100644 --- a/src/BlockArea.cpp +++ b/src/BlockArea.cpp @@ -273,10 +273,10 @@ void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE // cBlockArea: cBlockArea::cBlockArea(void) : - m_BlockTypes(NULL), - m_BlockMetas(NULL), - m_BlockLight(NULL), - m_BlockSkyLight(NULL) + m_BlockTypes(nullptr), + m_BlockMetas(nullptr), + m_BlockLight(nullptr), + m_BlockSkyLight(nullptr) { } @@ -295,10 +295,10 @@ cBlockArea::~cBlockArea() void cBlockArea::Clear(void) { - delete[] m_BlockTypes; m_BlockTypes = NULL; - delete[] m_BlockMetas; m_BlockMetas = NULL; - delete[] m_BlockLight; m_BlockLight = NULL; - delete[] m_BlockSkyLight; m_BlockSkyLight = NULL; + delete[] m_BlockTypes; m_BlockTypes = nullptr; + delete[] m_BlockMetas; m_BlockMetas = nullptr; + delete[] m_BlockLight; m_BlockLight = nullptr; + delete[] m_BlockSkyLight; m_BlockSkyLight = nullptr; m_Origin.Set(0, 0, 0); m_Size.Set(0, 0, 0); } @@ -711,7 +711,7 @@ void cBlockArea::Merge(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_R const NIBBLETYPE * SrcMetas = a_Src.GetBlockMetas(); NIBBLETYPE * DstMetas = m_BlockMetas; - bool IsDummyMetas = ((SrcMetas == NULL) || (DstMetas == NULL)); + bool IsDummyMetas = ((SrcMetas == nullptr) || (DstMetas == nullptr)); if (IsDummyMetas) { @@ -1013,8 +1013,8 @@ void cBlockArea::RotateCCW(void) } // for x std::swap(m_BlockTypes, NewTypes); std::swap(m_BlockMetas, NewMetas); - delete[] NewTypes; NewTypes = NULL; - delete[] NewMetas; NewMetas = NULL; + delete[] NewTypes; NewTypes = nullptr; + delete[] NewMetas; NewMetas = nullptr; std::swap(m_Size.x, m_Size.z); } @@ -1058,8 +1058,8 @@ void cBlockArea::RotateCW(void) } // for x std::swap(m_BlockTypes, NewTypes); std::swap(m_BlockMetas, NewMetas); - delete[] NewTypes; NewTypes = NULL; - delete[] NewMetas; NewMetas = NULL; + delete[] NewTypes; NewTypes = nullptr; + delete[] NewMetas; NewMetas = nullptr; std::swap(m_Size.x, m_Size.z); } @@ -1206,7 +1206,7 @@ void cBlockArea::RotateCCWNoMeta(void) } // for z } // for x std::swap(m_BlockTypes, NewTypes); - delete[] NewTypes; NewTypes = NULL; + delete[] NewTypes; NewTypes = nullptr; } if (HasBlockMetas()) { @@ -1224,7 +1224,7 @@ void cBlockArea::RotateCCWNoMeta(void) } // for z } // for x std::swap(m_BlockMetas, NewMetas); - delete[] NewMetas; NewMetas = NULL; + delete[] NewMetas; NewMetas = nullptr; } std::swap(m_Size.x, m_Size.z); } @@ -1251,7 +1251,7 @@ void cBlockArea::RotateCWNoMeta(void) } // for x } // for z std::swap(m_BlockTypes, NewTypes); - delete[] NewTypes; NewTypes = NULL; + delete[] NewTypes; NewTypes = nullptr; } if (HasBlockMetas()) { @@ -1269,7 +1269,7 @@ void cBlockArea::RotateCWNoMeta(void) } // for x } // for z std::swap(m_BlockMetas, NewMetas); - delete[] NewMetas; NewMetas = NULL; + delete[] NewMetas; NewMetas = nullptr; } std::swap(m_Size.x, m_Size.z); } @@ -1391,7 +1391,7 @@ void cBlockArea::MirrorYZNoMeta(void) void cBlockArea::SetRelBlockType(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType) { - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("cBlockArea: BlockTypes have not been read!"); return; @@ -1468,7 +1468,7 @@ void cBlockArea::SetBlockSkyLight(int a_BlockX, int a_BlockY, int a_BlockZ, NIBB BLOCKTYPE cBlockArea::GetRelBlockType(int a_RelX, int a_RelY, int a_RelZ) const { - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("cBlockArea: BlockTypes have not been read!"); return E_BLOCK_AIR; @@ -1555,7 +1555,7 @@ void cBlockArea::SetBlockTypeMeta(int a_BlockX, int a_BlockY, int a_BlockZ, BLOC void cBlockArea::SetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { int idx = MakeIndex(a_RelX, a_RelY, a_RelZ); - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("%s: BlockTypes not available but requested to be written to.", __FUNCTION__); } @@ -1563,7 +1563,7 @@ void cBlockArea::SetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, B { m_BlockTypes[idx] = a_BlockType; } - if (m_BlockMetas == NULL) + if (m_BlockMetas == nullptr) { LOGWARNING("%s: BlockMetas not available but requested to be written to.", __FUNCTION__); } @@ -1589,7 +1589,7 @@ void cBlockArea::GetBlockTypeMeta(int a_BlockX, int a_BlockY, int a_BlockZ, BLOC void cBlockArea::GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { int idx = MakeIndex(a_RelX, a_RelY, a_RelZ); - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("cBlockArea: BlockTypes have not been read!"); a_BlockType = E_BLOCK_AIR; @@ -1599,7 +1599,7 @@ void cBlockArea::GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTY a_BlockType = m_BlockTypes[idx]; } - if (m_BlockMetas == NULL) + if (m_BlockMetas == nullptr) { LOGWARNING("cBlockArea: BlockMetas have not been read!"); a_BlockMeta = 0; @@ -1617,19 +1617,19 @@ void cBlockArea::GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTY int cBlockArea::GetDataTypes(void) const { int res = 0; - if (m_BlockTypes != NULL) + if (m_BlockTypes != nullptr) { res |= baTypes; } - if (m_BlockMetas != NULL) + if (m_BlockMetas != nullptr) { res |= baMetas; } - if (m_BlockLight != NULL) + if (m_BlockLight != nullptr) { res |= baLight; } - if (m_BlockSkyLight != NULL) + if (m_BlockSkyLight != nullptr) { res |= baSkyLight; } @@ -1642,12 +1642,12 @@ int cBlockArea::GetDataTypes(void) const bool cBlockArea::SetSize(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes) { - ASSERT(m_BlockTypes == NULL); // Has been cleared + ASSERT(m_BlockTypes == nullptr); // Has been cleared if (a_DataTypes & baTypes) { m_BlockTypes = new BLOCKTYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { return false; } @@ -1655,36 +1655,36 @@ bool cBlockArea::SetSize(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes) if (a_DataTypes & baMetas) { m_BlockMetas = new NIBBLETYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockMetas == NULL) + if (m_BlockMetas == nullptr) { delete[] m_BlockTypes; - m_BlockTypes = NULL; + m_BlockTypes = nullptr; return false; } } if (a_DataTypes & baLight) { m_BlockLight = new NIBBLETYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockLight == NULL) + if (m_BlockLight == nullptr) { delete[] m_BlockMetas; - m_BlockMetas = NULL; + m_BlockMetas = nullptr; delete[] m_BlockTypes; - m_BlockTypes = NULL; + m_BlockTypes = nullptr; return false; } } if (a_DataTypes & baSkyLight) { m_BlockSkyLight = new NIBBLETYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockSkyLight == NULL) + if (m_BlockSkyLight == nullptr) { delete[] m_BlockLight; - m_BlockLight = NULL; + m_BlockLight = nullptr; delete[] m_BlockMetas; - m_BlockMetas = NULL; + m_BlockMetas = nullptr; delete[] m_BlockTypes; - m_BlockTypes = NULL; + m_BlockTypes = nullptr; return false; } } @@ -1714,7 +1714,7 @@ int cBlockArea::MakeIndex(int a_RelX, int a_RelY, int a_RelZ) const void cBlockArea::SetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Value, NIBBLETYPE * a_Array) { - if (a_Array == NULL) + if (a_Array == nullptr) { LOGWARNING("cBlockArea: datatype has not been read!"); return; @@ -1737,7 +1737,7 @@ void cBlockArea::SetNibble(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE NIBBLETYPE cBlockArea::GetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE * a_Array) const { - if (a_Array == NULL) + if (a_Array == nullptr) { LOGWARNING("cBlockArea: datatype has not been read!"); return 16; @@ -1896,7 +1896,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the blocktypes: - if (m_Area.m_BlockTypes != NULL) + if (m_Area.m_BlockTypes != nullptr) { for (int y = 0; y < SizeY; y++) { @@ -1917,7 +1917,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the block metas: - if (m_Area.m_BlockMetas != NULL) + if (m_Area.m_BlockMetas != nullptr) { for (int y = 0; y < SizeY; y++) { @@ -1938,7 +1938,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the blocklight: - if (m_Area.m_BlockLight != NULL) + if (m_Area.m_BlockLight != nullptr) { for (int y = 0; y < SizeY; y++) { @@ -1959,7 +1959,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the skylight: - if (m_Area.m_BlockSkyLight != NULL) + if (m_Area.m_BlockSkyLight != nullptr) { for (int y = 0; y < SizeY; y++) { diff --git a/src/BlockArea.h b/src/BlockArea.h index 003872635..348e960dd 100644 --- a/src/BlockArea.h +++ b/src/BlockArea.h @@ -32,7 +32,7 @@ class cBlockArea // tolua_end DISALLOW_COPY_AND_ASSIGN(cBlockArea); // tolua_begin - + public: /** What data is to be queried (bit-mask) */ @@ -43,7 +43,7 @@ public: baLight = 4, baSkyLight = 8, } ; - + /** The per-block strategy to use when merging another block area into this object. See the Merge function for the description of these */ enum eMergeStrategy @@ -56,64 +56,64 @@ public: msDifference, msMask, } ; - + cBlockArea(void); ~cBlockArea(); - + /** Clears the data stored to reclaim memory */ void Clear(void); - + /** Creates a new area of the specified size and contents. Origin is set to all zeroes. BlockTypes are set to air, block metas to zero, blocklights to zero and skylights to full light. */ void Create(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes = baTypes | baMetas); - + /** Creates a new area of the specified size and contents. Origin is set to all zeroes. BlockTypes are set to air, block metas to zero, blocklights to zero and skylights to full light. */ void Create(const Vector3i & a_Size, int a_DataTypes = baTypes | baMetas); - + /** Resets the origin. No other changes are made, contents are untouched. */ void SetOrigin(int a_OriginX, int a_OriginY, int a_OriginZ); - + /** Resets the origin. No other changes are made, contents are untouched. */ void SetOrigin(const Vector3i & a_Origin); - + /** Reads an area of blocks specified. Returns true if successful. All coords are inclusive. */ bool Read(cForEachChunkProvider * a_ForEachChunkProvider, int a_MinBlockX, int a_MaxBlockX, int a_MinBlockY, int a_MaxBlockY, int a_MinBlockZ, int a_MaxBlockZ, int a_DataTypes = baTypes | baMetas); - + /** Reads an area of blocks specified. Returns true if successful. The bounds are included in the read area. */ bool Read(cForEachChunkProvider * a_ForEachChunkProvider, const cCuboid & a_Bounds, int a_DataTypes = baTypes | baMetas); - + /** Reads an area of blocks specified. Returns true if successful. The bounds are included in the read area. */ bool Read(cForEachChunkProvider * a_ForEachChunkProvider, const Vector3i & a_Point1, const Vector3i & a_Point2, int a_DataTypes = baTypes | baMetas); - + // TODO: Write() is not too good an interface: if it fails, there's no way to repeat only for the parts that didn't write // A better way may be to return a list of cBlockAreas for each part that didn't succeed writing, so that the caller may try again - + /** Writes the area back into cWorld at the coords specified. Returns true if successful in all chunks, false if only partially / not at all */ bool Write(cForEachChunkProvider * a_ForEachChunkProvider, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes = baTypes | baMetas); - + /** Writes the area back into cWorld at the coords specified. Returns true if successful in all chunks, false if only partially / not at all */ bool Write(cForEachChunkProvider * a_ForEachChunkProvider, const Vector3i & a_MinCoords, int a_DataTypes = baTypes | baMetas); - + /** Copies this object's contents into the specified BlockArea. */ void CopyTo(cBlockArea & a_Into) const; - + /** Copies the contents from the specified BlockArea into this object. */ void CopyFrom(const cBlockArea & a_From); - + /** For testing purposes only, dumps the area into a file. */ void DumpToRawFile(const AString & a_FileName); - + /** Crops the internal contents by the specified amount of blocks from each border. */ void Crop(int a_AddMinX, int a_SubMaxX, int a_AddMinY, int a_SubMaxY, int a_AddMinZ, int a_SubMaxZ); - + /** Expands the internal contents by the specified amount of blocks from each border */ void Expand(int a_SubMinX, int a_AddMaxX, int a_SubMinY, int a_AddMaxY, int a_SubMinZ, int a_AddMaxZ); - + /** Merges another block area into this one, using the specified block combinating strategy This function combines another BlockArea into the current object. The strategy parameter specifies how individual blocks are combined together, using the table below. @@ -125,7 +125,7 @@ public: | A | air | air | A | A | | air | B | B | B | B | | A | B | B | A | B | - + So to sum up: - msOverwrite completely overwrites all blocks with the Src's blocks - msFillAir overwrites only those blocks that were air @@ -147,7 +147,7 @@ public: | mycelium | stone | stone | ... and mycelium | A | stone | A | ... but nothing else | A | * | A | Everything else is left as it is - + msSpongePrint: Used for most generators, it allows carving out air pockets, too, and uses the Sponge as the NOP block | area block | | @@ -155,7 +155,7 @@ public: +----------+--------+--------+ | A | sponge | A | Sponge is the NOP block | * | B | B | Everything else overwrites anything - + msMask: Combines two areas, the blocks that are the same are kept, differing ones are reset to air | area block | | @@ -166,68 +166,68 @@ public: */ void Merge(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_RelZ, eMergeStrategy a_Strategy); - + /** Merges another block area into this one, using the specified block combinating strategy. See Merge() above for details. */ void Merge(const cBlockArea & a_Src, const Vector3i & a_RelMinCoords, eMergeStrategy a_Strategy); - + /** Fills the entire block area with the specified data */ void Fill(int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f); - + /** Fills a cuboid inside the block area with the specified data */ void FillRelCuboid(int a_MinRelX, int a_MaxRelX, int a_MinRelY, int a_MaxRelY, int a_MinRelZ, int a_MaxRelZ, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Fills a cuboid inside the block area with the specified data. a_Cuboid must be sorted. */ void FillRelCuboid(const cCuboid & a_RelCuboid, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Draws a line from between two points with the specified data */ void RelLine(int a_RelX1, int a_RelY1, int a_RelZ1, int a_RelX2, int a_RelY2, int a_RelZ2, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Draws a line from between two points with the specified data */ void RelLine(const Vector3i & a_Point1, const Vector3i & a_Point2, int a_DataTypes, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta = 0, NIBBLETYPE a_BlockLight = 0, NIBBLETYPE a_BlockSkyLight = 0x0f ); - + /** Rotates the entire area counter-clockwise around the Y axis */ void RotateCCW(void); - + /** Rotates the entire area clockwise around the Y axis */ void RotateCW(void); - + /** Mirrors the entire area around the XY plane */ void MirrorXY(void); - + /** Mirrors the entire area around the XZ plane */ void MirrorXZ(void); - + /** Mirrors the entire area around the YZ plane */ void MirrorYZ(void); - + /** Rotates the entire area counter-clockwise around the Y axis, doesn't use blockhandlers for block meta */ void RotateCCWNoMeta(void); - + /** Rotates the entire area clockwise around the Y axis, doesn't use blockhandlers for block meta */ void RotateCWNoMeta(void); - + /** Mirrors the entire area around the XY plane, doesn't use blockhandlers for block meta */ void MirrorXYNoMeta(void); - + /** Mirrors the entire area around the XZ plane, doesn't use blockhandlers for block meta */ void MirrorXZNoMeta(void); - + /** Mirrors the entire area around the YZ plane, doesn't use blockhandlers for block meta */ void MirrorYZNoMeta(void); - + // Setters: void SetRelBlockType (int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType); void SetBlockType (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType); @@ -253,80 +253,80 @@ public: void SetBlockTypeMeta (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); void SetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); - + // tolua_end - + // These need manual exporting, tolua generates the binding as requiring 2 extra input params void GetBlockTypeMeta (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const; void GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const; - + // GetSize() is already exported manually to return 3 numbers, can't auto-export const Vector3i & GetSize(void) const { return m_Size; } - + // GetOrigin() is already exported manually to return 3 numbers, can't auto-export const Vector3i & GetOrigin(void) const { return m_Origin; } - + // tolua_begin - + int GetSizeX(void) const { return m_Size.x; } int GetSizeY(void) const { return m_Size.y; } int GetSizeZ(void) const { return m_Size.z; } - + /** Returns the volume of the area, as number of blocks */ int GetVolume(void) const { return m_Size.x * m_Size.y * m_Size.z; } - + int GetOriginX(void) const { return m_Origin.x; } int GetOriginY(void) const { return m_Origin.y; } int GetOriginZ(void) const { return m_Origin.z; } - + /** Returns the datatypes that are stored in the object (bitmask of baXXX values) */ int GetDataTypes(void) const; - - bool HasBlockTypes (void) const { return (m_BlockTypes != NULL); } - bool HasBlockMetas (void) const { return (m_BlockMetas != NULL); } - bool HasBlockLights (void) const { return (m_BlockLight != NULL); } - bool HasBlockSkyLights(void) const { return (m_BlockSkyLight != NULL); } - + + bool HasBlockTypes (void) const { return (m_BlockTypes != nullptr); } + bool HasBlockMetas (void) const { return (m_BlockMetas != nullptr); } + bool HasBlockLights (void) const { return (m_BlockLight != nullptr); } + bool HasBlockSkyLights(void) const { return (m_BlockSkyLight != nullptr); } + // tolua_end - + // Clients can use these for faster access to all blocktypes. Be careful though! /** Returns the internal pointer to the block types */ BLOCKTYPE * GetBlockTypes (void) const { return m_BlockTypes; } 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 static_cast(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: friend class cChunkDesc; friend class cSchematicFileSerializer; - + class cChunkReader : public cChunkDataCallback { public: cChunkReader(cBlockArea & a_Area); - + protected: cBlockArea & m_Area; Vector3i m_Origin; int m_CurrentChunkX; int m_CurrentChunkZ; - + void CopyNibbles(NIBBLETYPE * a_AreaDst, const NIBBLETYPE * a_ChunkSrc); - + // cChunkDataCallback overrides: virtual bool Coords(int a_ChunkX, int a_ChunkZ) override; virtual void ChunkData(const cChunkData & a_BlockTypes) override; } ; - + typedef NIBBLETYPE * NIBBLEARRAY; - - + + Vector3i m_Origin; Vector3i m_Size; - + /** An extra data value sometimes stored in the .schematic file. Used mainly by the WorldEdit plugin. cBlockArea doesn't use this value in any way. */ Vector3i m_WEOffset; @@ -335,10 +335,10 @@ protected: NIBBLETYPE * m_BlockMetas; // Each meta is stored as a separate byte for faster access NIBBLETYPE * m_BlockLight; // Each light value is stored as a separate byte for faster access NIBBLETYPE * m_BlockSkyLight; // Each light value is stored as a separate byte for faster access - + /** Clears the data stored and prepares a fresh new block area with the specified dimensions */ bool SetSize(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes); - + // Basic Setters: void SetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Value, NIBBLETYPE * a_Array); void SetNibble (int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_Value, NIBBLETYPE * a_Array); @@ -346,11 +346,11 @@ protected: // Basic Getters: NIBBLETYPE GetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE * a_Array) const; NIBBLETYPE GetNibble (int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE * a_Array) const; - + // Crop helpers: void CropBlockTypes(int a_AddMinX, int a_SubMaxX, int a_AddMinY, int a_SubMaxY, int a_AddMinZ, int a_SubMaxZ); void CropNibbles (NIBBLEARRAY & a_Array, int a_AddMinX, int a_SubMaxX, int a_AddMinY, int a_SubMaxY, int a_AddMinZ, int a_SubMaxZ); - + // Expand helpers: void ExpandBlockTypes(int a_SubMinX, int a_AddMaxX, int a_SubMinY, int a_AddMaxY, int a_SubMinZ, int a_AddMaxZ); void ExpandNibbles (NIBBLEARRAY & a_Array, int a_SubMinX, int a_AddMaxX, int a_SubMinY, int a_AddMaxY, int a_SubMinZ, int a_AddMaxZ); @@ -361,9 +361,13 @@ 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/BlockEntities/BeaconEntity.cpp b/src/BlockEntities/BeaconEntity.cpp index fe5bcf143..85819446c 100644 --- a/src/BlockEntities/BeaconEntity.cpp +++ b/src/BlockEntities/BeaconEntity.cpp @@ -2,7 +2,6 @@ #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "BeaconEntity.h" -#include #include "../BlockArea.h" #include "../Entities/Player.h" @@ -98,7 +97,7 @@ bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect) m_PrimaryEffect = a_Effect; // Send window update: - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->SetProperty(1, m_PrimaryEffect); } @@ -120,7 +119,7 @@ bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect) m_SecondaryEffect = a_Effect; // Send window update: - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->SetProperty(2, m_SecondaryEffect); } @@ -185,7 +184,7 @@ void cBeaconEntity::UpdateBeacon(void) if (m_BeaconLevel != OldBeaconLevel) { // Send window update: - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->SetProperty(0, m_BeaconLevel); } @@ -228,7 +227,10 @@ void cBeaconEntity::GiveEffects(void) virtual bool Item(cPlayer * a_Player) { Vector3d PlayerPosition = Vector3d(a_Player->GetPosition()); - PlayerPosition.y = std::min(static_cast(m_PosY), PlayerPosition.y); + if (PlayerPosition.y > (double)m_PosY) + { + PlayerPosition.y = (double)m_PosY; + } // TODO: Vanilla minecraft uses an AABB check instead of a radius one Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ); @@ -253,7 +255,7 @@ void cBeaconEntity::GiveEffects(void) , m_PrimaryEffect(a_PrimaryEffect) , m_SecondaryEffect(a_SecondaryEffect) , m_EffectLevel(a_EffectLevel) - {} + {}; } PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel); GetWorld()->ForEachPlayer(PlayerCallback); @@ -281,13 +283,13 @@ bool cBeaconEntity::Tick(float a_Dt, cChunk & a_Chunk) void cBeaconEntity::UsedBy(cPlayer * a_Player) { cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this)); Window = GetWindow(); } - - if (Window != NULL) + + if (Window != nullptr) { // if (a_Player->GetWindow() != Window) // -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ... @@ -305,3 +307,7 @@ void cBeaconEntity::SendTo(cClientHandle & a_Client) { a_Client.SendUpdateBlockEntity(*this); } + + + + diff --git a/src/BlockEntities/BlockEntity.cpp b/src/BlockEntities/BlockEntity.cpp index 05ad03a3d..3d96e891e 100644 --- a/src/BlockEntities/BlockEntity.cpp +++ b/src/BlockEntities/BlockEntity.cpp @@ -48,7 +48,7 @@ cBlockEntity * cBlockEntity::CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE __FUNCTION__, a_BlockType, ItemTypeToString(a_BlockType).c_str() ); ASSERT(!"Requesting creation of an unknown block entity"); - return NULL; + return nullptr; } diff --git a/src/BlockEntities/BlockEntity.h b/src/BlockEntities/BlockEntity.h index b04d20340..ffd6ee856 100644 --- a/src/BlockEntities/BlockEntity.h +++ b/src/BlockEntities/BlockEntity.h @@ -70,8 +70,8 @@ public: /// Creates a new block entity for the specified block type /// If a_World is valid, then the entity is created bound to that world - /// Returns NULL for unknown block types - static cBlockEntity * CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World = NULL); + /// Returns nullptr for unknown block types + static cBlockEntity * CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World = nullptr); static const char * GetClassStatic(void) // Needed for ManualBindings's ForEach templates { diff --git a/src/BlockEntities/BlockEntityWithItems.h b/src/BlockEntities/BlockEntityWithItems.h index cb7bc2fb4..8c7d4749b 100644 --- a/src/BlockEntities/BlockEntityWithItems.h +++ b/src/BlockEntities/BlockEntityWithItems.h @@ -47,7 +47,7 @@ public: virtual void Destroy(void) override { // Drop the contents as pickups: - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); cItems Pickups; m_Contents.CopyToItems(Pickups); m_Contents.Clear(); @@ -78,9 +78,9 @@ protected: { UNUSED(a_SlotNum); ASSERT(a_Grid == &m_Contents); - if (m_World != NULL) + if (m_World != nullptr) { - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->BroadcastWholeWindow(); } diff --git a/src/BlockEntities/ChestEntity.cpp b/src/BlockEntities/ChestEntity.cpp index 19d88b646..0cd9c66e0 100644 --- a/src/BlockEntities/ChestEntity.cpp +++ b/src/BlockEntities/ChestEntity.cpp @@ -23,7 +23,7 @@ cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_ cChestEntity::~cChestEntity() { cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -49,14 +49,14 @@ void cChestEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { diff --git a/src/BlockEntities/CommandBlockEntity.cpp b/src/BlockEntities/CommandBlockEntity.cpp index 1a5a3f01e..b7f938ffd 100644 --- a/src/BlockEntities/CommandBlockEntity.cpp +++ b/src/BlockEntities/CommandBlockEntity.cpp @@ -154,7 +154,7 @@ void cCommandBlockEntity::SendTo(cClientHandle & a_Client) void cCommandBlockEntity::Execute() { - ASSERT(m_World != NULL); // Execute should not be called before the command block is attached to a world + ASSERT(m_World != nullptr); // Execute should not be called before the command block is attached to a world if (!m_World->AreCommandBlocksEnabled()) { diff --git a/src/BlockEntities/DispenserEntity.cpp b/src/BlockEntities/DispenserEntity.cpp index 157862bd1..42a0476b6 100644 --- a/src/BlockEntities/DispenserEntity.cpp +++ b/src/BlockEntities/DispenserEntity.cpp @@ -28,7 +28,7 @@ void cDispenserEntity::DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) NIBBLETYPE Meta = a_Chunk.GetMeta(m_RelX, m_PosY, m_RelZ); AddDropSpenserDir(DispX, DispY, DispZ, Meta); cChunk * DispChunk = a_Chunk.GetRelNeighborChunkAdjustCoords(DispX, DispZ); - if (DispChunk == NULL) + if (DispChunk == nullptr) { // Would dispense into / interact with a non-loaded chunk, ignore the tick return; @@ -190,7 +190,7 @@ void cDispenserEntity::DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) void cDispenserEntity::SpawnProjectileFromDispenser(int a_BlockX, int a_BlockY, int a_BlockZ, cProjectileEntity::eKind a_Kind, const Vector3d & a_ShootVector) { - m_World->CreateProjectile(static_cast(a_BlockX + 0.5), static_cast(a_BlockY + 0.5), static_cast(a_BlockZ + 0.5), a_Kind, NULL, NULL, &a_ShootVector); + m_World->CreateProjectile(static_cast(a_BlockX + 0.5), static_cast(a_BlockY + 0.5), static_cast(a_BlockZ + 0.5), a_Kind, nullptr, nullptr, &a_ShootVector); } diff --git a/src/BlockEntities/DropSpenserEntity.cpp b/src/BlockEntities/DropSpenserEntity.cpp index e39b938a0..3f98836e7 100644 --- a/src/BlockEntities/DropSpenserEntity.cpp +++ b/src/BlockEntities/DropSpenserEntity.cpp @@ -28,7 +28,7 @@ cDropSpenserEntity::~cDropSpenserEntity() { // Tell window its owner is destroyed cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -70,19 +70,19 @@ void cDropSpenserEntity::DropSpense(cChunk & a_Chunk) SlotsCnt++; } } // for i - m_Contents[] - + if (SlotsCnt == 0) { // Nothing in the dropspenser, play the click sound m_World->BroadcastSoundEffect("random.click", m_PosX * 8, m_PosY * 8, m_PosZ * 8, 1.0f, 1.2f); return; } - + int RandomSlot = m_World->GetTickRandomNumber(SlotsCnt - 1); - + // DropSpense the item, using the specialized behavior in the subclasses: DropSpenseFromSlot(a_Chunk, OccupiedSlots[RandomSlot]); - + // Broadcast a smoke and click effects: NIBBLETYPE Meta = a_Chunk.GetMeta(m_RelX, m_PosY, m_RelZ); int SmokeDir = 0; @@ -132,7 +132,7 @@ bool cDropSpenserEntity::Tick(float a_Dt, cChunk & a_Chunk) { return false; } - + m_ShouldDropSpense = false; DropSpense(a_Chunk); return true; @@ -155,13 +155,13 @@ void cDropSpenserEntity::SendTo(cClientHandle & a_Client) void cDropSpenserEntity::UsedBy(cPlayer * a_Player) { cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenWindow(new cDropSpenserWindow(m_PosX, m_PosY, m_PosZ, this)); Window = GetWindow(); } - - if (Window != NULL) + + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { @@ -205,3 +205,7 @@ void cDropSpenserEntity::DropFromSlot(cChunk & a_Chunk, int a_SlotNum) m_World->SpawnItemPickups(Pickups, MicroX, MicroY, MicroZ, PickupSpeedX, PickupSpeedY, PickupSpeedZ); } + + + + diff --git a/src/BlockEntities/EnderChestEntity.cpp b/src/BlockEntities/EnderChestEntity.cpp index 0654d97dd..e18490a1e 100644 --- a/src/BlockEntities/EnderChestEntity.cpp +++ b/src/BlockEntities/EnderChestEntity.cpp @@ -23,7 +23,7 @@ cEnderChestEntity::cEnderChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, c cEnderChestEntity::~cEnderChestEntity() { cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -37,14 +37,14 @@ void cEnderChestEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { diff --git a/src/BlockEntities/FlowerPotEntity.cpp b/src/BlockEntities/FlowerPotEntity.cpp index ad7b496cc..64b7edd02 100644 --- a/src/BlockEntities/FlowerPotEntity.cpp +++ b/src/BlockEntities/FlowerPotEntity.cpp @@ -59,7 +59,7 @@ void cFlowerPotEntity::Destroy(void) // Drop the contents as pickups: if (!m_Item.IsEmpty()) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); cItems Pickups; Pickups.Add(m_Item); m_World->SpawnItemPickups(Pickups, m_PosX + 0.5, m_PosY + 0.5, m_PosZ + 0.5); diff --git a/src/BlockEntities/FlowerPotEntity.h b/src/BlockEntities/FlowerPotEntity.h index 5b86621f5..fc886c51f 100644 --- a/src/BlockEntities/FlowerPotEntity.h +++ b/src/BlockEntities/FlowerPotEntity.h @@ -38,7 +38,7 @@ public: BLOCKENTITY_PROTODEF(cFlowerPotEntity); - /** Creates a new flowerpot entity at the specified block coords. a_World may be NULL */ + /** Creates a new flowerpot entity at the specified block coords. a_World may be nullptr */ cFlowerPotEntity(int a_BlocX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual void Destroy(void) override; diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index ac71f1541..d2ec2bd1e 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -26,7 +26,7 @@ enum cFurnaceEntity::cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cWorld * a_World) : super(a_BlockType, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), m_BlockMeta(a_BlockMeta), - m_CurrentRecipe(NULL), + m_CurrentRecipe(nullptr), m_IsDestroyed(false), m_IsCooking(a_BlockType == E_BLOCK_LIT_FURNACE), m_NeedCookTime(0), @@ -45,7 +45,7 @@ cFurnaceEntity::~cFurnaceEntity() { // Tell window its owner is destroyed cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -145,7 +145,7 @@ void cFurnaceEntity::SendTo(cClientHandle & a_Client) void cFurnaceEntity::BroadcastProgress(short a_ProgressbarID, short a_Value) { cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->SetProperty(a_ProgressbarID, a_Value); } @@ -306,7 +306,7 @@ void cFurnaceEntity::UpdateOutput(void) bool cFurnaceEntity::CanCookInputToOutput(void) const { - if (m_CurrentRecipe == NULL) + if (m_CurrentRecipe == nullptr) { // This input cannot be cooked return false; diff --git a/src/BlockEntities/HopperEntity.cpp b/src/BlockEntities/HopperEntity.cpp index 9f64ea148..fe3fb85c4 100644 --- a/src/BlockEntities/HopperEntity.cpp +++ b/src/BlockEntities/HopperEntity.cpp @@ -86,14 +86,14 @@ void cHopperEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { @@ -197,7 +197,7 @@ bool cHopperEntity::MovePickupsIn(cChunk & a_Chunk, Int64 a_CurrentTick) virtual bool Item(cEntity * a_Entity) override { - ASSERT(a_Entity != NULL); + ASSERT(a_Entity != nullptr); if (!a_Entity->IsPickup() || a_Entity->IsDestroyed()) { @@ -299,7 +299,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) int OutRelX = OutX - a_Chunk.GetPosX() * cChunkDef::Width; int OutRelZ = OutZ - a_Chunk.GetPosZ() * cChunkDef::Width; cChunk * DestChunk = a_Chunk.GetRelNeighborChunkAdjustCoords(OutRelX, OutRelZ); - if (DestChunk == NULL) + if (DestChunk == nullptr) { // The destination chunk has been unloaded, don't tick return false; @@ -328,7 +328,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) case E_BLOCK_HOPPER: { cBlockEntityWithItems * BlockEntity = static_cast(DestChunk->GetBlockEntity(OutX, OutY, OutZ)); - if (BlockEntity == NULL) + if (BlockEntity == nullptr) { LOGWARNING("%s: A block entity was not found where expected at {%d, %d, %d}", __FUNCTION__, OutX, OutY, OutZ); return false; @@ -355,7 +355,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) { cChestEntity * MainChest = static_cast(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); - if (MainChest == NULL) + if (MainChest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX, m_PosY + 1, m_PosZ); return false; @@ -383,7 +383,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) int x = m_RelX + Coords[i].x; int z = m_RelZ + Coords[i].z; cChunk * Neighbor = a_Chunk.GetRelNeighborChunkAdjustCoords(x, z); - if (Neighbor == NULL) + if (Neighbor == nullptr) { continue; } @@ -396,7 +396,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) } cChestEntity * SideChest = static_cast(Neighbor->GetBlockEntity(m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z)); - if (SideChest == NULL) + if (SideChest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z); } @@ -422,7 +422,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk) { cFurnaceEntity * Furnace = static_cast(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); - if (Furnace == NULL) + if (Furnace == nullptr) { LOGWARNING("%s: A furnace entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX, m_PosY + 1, m_PosZ); return false; @@ -536,7 +536,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block { // Try the chest directly connected to the hopper: cChestEntity * ConnectedChest = static_cast(a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ)); - if (ConnectedChest == NULL) + if (ConnectedChest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, a_BlockX, a_BlockY, a_BlockZ); return false; @@ -566,7 +566,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block int x = RelX + Coords[i].x; int z = RelZ + Coords[i].z; cChunk * Neighbor = a_Chunk.GetRelNeighborChunkAdjustCoords(x, z); - if (Neighbor == NULL) + if (Neighbor == nullptr) { continue; } @@ -579,7 +579,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block } cChestEntity * Chest = static_cast(Neighbor->GetBlockEntity(a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z)); - if (Chest == NULL) + if (Chest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d} (%d, %d)", __FUNCTION__, a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z, x, z); continue; diff --git a/src/BlockEntities/MobHeadEntity.h b/src/BlockEntities/MobHeadEntity.h index 7f69bc5ad..7132ef558 100644 --- a/src/BlockEntities/MobHeadEntity.h +++ b/src/BlockEntities/MobHeadEntity.h @@ -36,7 +36,7 @@ public: BLOCKENTITY_PROTODEF(cMobHeadEntity); - /** Creates a new mob head entity at the specified block coords. a_World may be NULL */ + /** Creates a new mob head entity at the specified block coords. a_World may be nullptr */ cMobHeadEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); // tolua_begin diff --git a/src/BlockEntities/NoteEntity.h b/src/BlockEntities/NoteEntity.h index 74dbde046..fc5f27d07 100644 --- a/src/BlockEntities/NoteEntity.h +++ b/src/BlockEntities/NoteEntity.h @@ -42,7 +42,7 @@ public: BLOCKENTITY_PROTODEF(cNoteEntity); - /// Creates a new note entity. a_World may be NULL + /// Creates a new note entity. a_World may be nullptr cNoteEntity(int a_X, int a_Y, int a_Z, cWorld * a_World); virtual ~cNoteEntity() {} diff --git a/src/BlockEntities/SignEntity.h b/src/BlockEntities/SignEntity.h index be13c7a32..52baa486d 100644 --- a/src/BlockEntities/SignEntity.h +++ b/src/BlockEntities/SignEntity.h @@ -36,7 +36,7 @@ public: BLOCKENTITY_PROTODEF(cSignEntity); - /// Creates a new empty sign entity at the specified block coords and block type (wall or standing). a_World may be NULL + /// Creates a new empty sign entity at the specified block coords and block type (wall or standing). a_World may be nullptr cSignEntity(BLOCKTYPE a_BlockType, int a_X, int a_Y, int a_Z, cWorld * a_World); // tolua_begin diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp index bdd3a9c26..bcab21e77 100644 --- a/src/BlockInfo.cpp +++ b/src/BlockInfo.cpp @@ -9,7 +9,7 @@ cBlockInfo::~cBlockInfo() { delete m_Handler; - m_Handler = NULL; + m_Handler = nullptr; } @@ -17,7 +17,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) { for (unsigned int i = 0; i < 256; ++i) { - if (a_Info[i].m_Handler == NULL) + if (a_Info[i].m_Handler == nullptr) { a_Info[i].m_Handler = cBlockHandler::CreateBlockHandler((BLOCKTYPE) i); } diff --git a/src/BlockInfo.h b/src/BlockInfo.h index 1e4cf2ca0..4709f2357 100644 --- a/src/BlockInfo.h +++ b/src/BlockInfo.h @@ -102,7 +102,7 @@ protected: , m_FullyOccupiesVoxel(false) , m_CanBeTerraformed(false) , m_PlaceSound("") - , m_Handler(NULL) + , m_Handler(nullptr) {} /** Cleans up the stored values */ diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h index 89dfc963d..aae6719e2 100644 --- a/src/Blocks/BlockDirt.h +++ b/src/Blocks/BlockDirt.h @@ -72,7 +72,7 @@ public: int BlockY = a_RelY + OfsY; int BlockZ = a_RelZ + OfsZ; cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(BlockX, BlockZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Unloaded chunk continue; diff --git a/src/Blocks/BlockHandler.cpp b/src/Blocks/BlockHandler.cpp index b6ef5dd6f..60f13a747 100644 --- a/src/Blocks/BlockHandler.cpp +++ b/src/Blocks/BlockHandler.cpp @@ -99,9 +99,9 @@ public: for (BLOCKTYPE Type = 0; Type < E_BLOCK_MAX_TYPE_ID; Type++) { cBlockHandler * Handler = cBlockInfo::GetHandler(Type); - if (Handler == NULL) + if (Handler == nullptr) { - printf("NULL handler for block type %d!\n", Type); + printf("nullptr handler for block type %d!\n", Type); continue; } AString BlockName = ItemTypeToString(Type); @@ -441,7 +441,7 @@ void cBlockHandler::DropBlock(cChunkInterface & a_ChunkInterface, cWorldInterfac if (a_CanDrop) { - if ((a_Digger != NULL) && (a_Digger->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchSilkTouch) > 0)) + if ((a_Digger != nullptr) && (a_Digger->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchSilkTouch) > 0)) { switch (m_BlockType) { @@ -562,7 +562,7 @@ void cBlockHandler::Check(cChunkInterface & a_ChunkInterface, cBlockPluginInterf { int BlockX = a_RelX + a_Chunk.GetPosX() * cChunkDef::Width; int BlockZ = a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width; - DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, NULL, BlockX, a_RelY, BlockZ); + DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, nullptr, BlockX, a_RelY, BlockZ); } a_Chunk.SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); diff --git a/src/Blocks/BlockHandler.h b/src/Blocks/BlockHandler.h index 83de836cb..f2298afb5 100644 --- a/src/Blocks/BlockHandler.h +++ b/src/Blocks/BlockHandler.h @@ -78,7 +78,7 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta); /** Handles the dropping, but not destruction, of a block based on what ConvertTo(Verbatim)Pickups() returns, including the spawning of pickups and alertion of plugins - @param a_Digger The entity causing the drop; it may be NULL + @param a_Digger The entity causing the drop; it may be nullptr @param a_CanDrop Informs the handler whether the block should be dropped at all. One example when this is false is when stone is destroyed by hand @param a_DropVerbatim Calls ConvertToVerbatimPickups() instead of its counterpart, meaning the block itself is dropped by default (due to a speical tool or enchantment) */ diff --git a/src/Blocks/BlockLeaves.h b/src/Blocks/BlockLeaves.h index add571675..bd9a7414e 100644 --- a/src/Blocks/BlockLeaves.h +++ b/src/Blocks/BlockLeaves.h @@ -109,7 +109,7 @@ public: } // Decay the leaves: - DropBlock(a_ChunkInterface, a_WorldInterface, a_PluginInterface, NULL, BlockX, a_RelY, BlockZ); + DropBlock(a_ChunkInterface, a_WorldInterface, a_PluginInterface, nullptr, BlockX, a_RelY, BlockZ); a_ChunkInterface.DigBlock(a_WorldInterface, BlockX, a_RelY, BlockZ); } } ; diff --git a/src/Blocks/BlockPiston.cpp b/src/Blocks/BlockPiston.cpp index 34d11f675..8d245cabe 100644 --- a/src/Blocks/BlockPiston.cpp +++ b/src/Blocks/BlockPiston.cpp @@ -139,7 +139,7 @@ void cBlockPistonHandler::ExtendPiston(int a_BlockX, int a_BlockY, int a_BlockZ, { cChunkInterface ChunkInterface(a_World->GetChunkMap()); cBlockInServerPluginInterface PluginInterface(*a_World); - Handler->DropBlock(ChunkInterface, *a_World, PluginInterface, NULL, a_BlockX, a_BlockY, a_BlockZ); + Handler->DropBlock(ChunkInterface, *a_World, PluginInterface, nullptr, a_BlockX, a_BlockY, a_BlockZ); } } diff --git a/src/Blocks/BlockVine.h b/src/Blocks/BlockVine.h index ff34cdf87..00d7a69b8 100644 --- a/src/Blocks/BlockVine.h +++ b/src/Blocks/BlockVine.h @@ -148,7 +148,7 @@ public: { int BlockX = a_RelX + a_Chunk.GetPosX() * cChunkDef::Width; int BlockZ = a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width; - DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, NULL, BlockX, a_RelY, BlockZ); + DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, nullptr, BlockX, a_RelY, BlockZ); } a_Chunk.SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); return; diff --git a/src/Blocks/BroadcastInterface.h b/src/Blocks/BroadcastInterface.h index cf332b153..bf464627d 100644 --- a/src/Blocks/BroadcastInterface.h +++ b/src/Blocks/BroadcastInterface.h @@ -7,6 +7,6 @@ public: virtual ~cBroadcastInterface() {} virtual void BroadcastUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) = 0; - virtual void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL) = 0; - virtual void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL) = 0; + virtual void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr) = 0; + virtual void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr) = 0; }; diff --git a/src/ByteBuffer.cpp b/src/ByteBuffer.cpp index dc6b32a44..012105ca1 100644 --- a/src/ByteBuffer.cpp +++ b/src/ByteBuffer.cpp @@ -165,7 +165,7 @@ cByteBuffer::~cByteBuffer() { CheckValid(); delete[] m_Buffer; - m_Buffer = NULL; + m_Buffer = nullptr; } diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 7d6d88b26..542b17255 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -95,19 +95,19 @@ cChunk::cChunk( m_RedstoneSimulatorData(a_World->GetRedstoneSimulator()->CreateChunkData()), m_AlwaysTicked(0) { - if (a_NeighborXM != NULL) + if (a_NeighborXM != nullptr) { a_NeighborXM->m_NeighborXP = this; } - if (a_NeighborXP != NULL) + if (a_NeighborXP != nullptr) { a_NeighborXP->m_NeighborXM = this; } - if (a_NeighborZM != NULL) + if (a_NeighborZM != nullptr) { a_NeighborZM->m_NeighborZP = this; } - if (a_NeighborZP != NULL) + if (a_NeighborZP != nullptr) { a_NeighborZP->m_NeighborZM = this; } @@ -141,28 +141,28 @@ cChunk::~cChunk() } } - if (m_NeighborXM != NULL) + if (m_NeighborXM != nullptr) { - m_NeighborXM->m_NeighborXP = NULL; + m_NeighborXM->m_NeighborXP = nullptr; } - if (m_NeighborXP != NULL) + if (m_NeighborXP != nullptr) { - m_NeighborXP->m_NeighborXM = NULL; + m_NeighborXP->m_NeighborXM = nullptr; } - if (m_NeighborZM != NULL) + if (m_NeighborZM != nullptr) { - m_NeighborZM->m_NeighborZP = NULL; + m_NeighborZM->m_NeighborZP = nullptr; } - if (m_NeighborZP != NULL) + if (m_NeighborZP != nullptr) { - m_NeighborZP->m_NeighborZM = NULL; + m_NeighborZP->m_NeighborZM = nullptr; } delete m_WaterSimulatorData; - m_WaterSimulatorData = NULL; + m_WaterSimulatorData = nullptr; delete m_LavaSimulatorData; - m_LavaSimulatorData = NULL; + m_LavaSimulatorData = nullptr; delete m_RedstoneSimulatorData; - m_RedstoneSimulatorData = NULL; + m_RedstoneSimulatorData = nullptr; } @@ -581,7 +581,7 @@ void cChunk::SpawnMobs(cMobSpawner& a_MobSpawner) } cEntity * newMob = a_MobSpawner.TryToSpawnHere(this, TryX, TryY, TryZ, Biome, MaxNbOfSuccess); - if (newMob == NULL) + if (newMob == nullptr) { continue; } @@ -639,7 +639,7 @@ void cChunk::Tick(float a_Dt) { // Remove all entities that are travelling to another world MarkDirty(); - (*itr)->SetWorldTravellingFrom(NULL); + (*itr)->SetWorldTravellingFrom(nullptr); itr = m_Entities.erase(itr); } else if ( @@ -668,7 +668,7 @@ void cChunk::Tick(float a_Dt) void cChunk::TickBlock(int a_RelX, int a_RelY, int a_RelZ) { cBlockHandler * Handler = BlockHandler(GetBlock(a_RelX, a_RelY, a_RelZ)); - ASSERT(Handler != NULL); // Happenned on server restart, FS #243 + ASSERT(Handler != nullptr); // Happenned on server restart, FS #243 cChunkInterface ChunkInterface(this->GetWorld()->GetChunkMap()); cBlockInServerPluginInterface PluginInterface(*this->GetWorld()); Handler->OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, a_RelX, a_RelY, a_RelZ); @@ -681,10 +681,10 @@ void cChunk::TickBlock(int a_RelX, int a_RelY, int a_RelZ) void cChunk::MoveEntityToNewChunk(cEntity * a_Entity) { cChunk * Neighbor = GetNeighborChunk(a_Entity->GetChunkX() * cChunkDef::Width, a_Entity->GetChunkZ() * cChunkDef::Width); - if (Neighbor == NULL) + if (Neighbor == nullptr) { Neighbor = m_ChunkMap->GetChunkNoLoad(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); - if (Neighbor == NULL) + if (Neighbor == nullptr) { // TODO: What to do with this? LOGWARNING("%s: Failed to move entity, destination chunk unreachable. Entity lost", __FUNCTION__); @@ -847,7 +847,7 @@ void cChunk::TickBlocks(void) } cBlockHandler * Handler = BlockHandler(GetBlock(m_BlockTickX, m_BlockTickY, m_BlockTickZ)); - ASSERT(Handler != NULL); // Happenned on server restart, FS #243 + ASSERT(Handler != nullptr); // Happenned on server restart, FS #243 Handler->OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, m_BlockTickX, m_BlockTickY, m_BlockTickZ); } // for i - tickblocks } @@ -1127,7 +1127,7 @@ bool cChunk::UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1148,7 +1148,7 @@ bool cChunk::UnboundedRelGetBlockType(int a_RelX, int a_RelY, int a_RelZ, BLOCKT return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1169,7 +1169,7 @@ bool cChunk::UnboundedRelGetBlockMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLE return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1190,7 +1190,7 @@ bool cChunk::UnboundedRelGetBlockBlockLight(int a_RelX, int a_RelY, int a_RelZ, return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1211,7 +1211,7 @@ bool cChunk::UnboundedRelGetBlockSkyLight(int a_RelX, int a_RelY, int a_RelZ, NI return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1232,7 +1232,7 @@ bool cChunk::UnboundedRelGetBlockLights(int a_RelX, int a_RelY, int a_RelZ, NIBB return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1254,7 +1254,7 @@ bool cChunk::UnboundedRelSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1275,7 +1275,7 @@ bool cChunk::UnboundedRelFastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKT return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1296,7 +1296,7 @@ void cChunk::UnboundedQueueTickBlock(int a_RelX, int a_RelY, int a_RelZ) return; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->QueueTickBlock(a_RelX, a_RelY, a_RelZ); } @@ -1452,12 +1452,12 @@ void cChunk::SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, // If there was a block entity, remove it: Vector3i WorldPos = PositionToWorldPosition(a_RelX, a_RelY, a_RelZ); cBlockEntity * BlockEntity = GetBlockEntity(WorldPos); - if (BlockEntity != NULL) + if (BlockEntity != nullptr) { BlockEntity->Destroy(); RemoveBlockEntity(BlockEntity); delete BlockEntity; - BlockEntity = NULL; + BlockEntity = nullptr; } // If the new block is a block entity, create the entity object: @@ -1619,7 +1619,7 @@ 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) { - if (a_Client == NULL) + if (a_Client == nullptr) { // 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(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ))); @@ -1673,7 +1673,7 @@ cBlockEntity * cChunk::GetBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ) } } // for itr - m_BlockEntities[] - return NULL; + return nullptr; } @@ -1708,7 +1708,7 @@ void cChunk::SetAlwaysTicked(bool a_AlwaysTicked) void cChunk::UseBlockEntity(cPlayer * a_Player, int a_X, int a_Y, int a_Z) { cBlockEntity * be = GetBlockEntity(a_X, a_Y, a_Z); - if (be != NULL) + if (be != nullptr) { be->UsedBy(a_Player); } @@ -2664,10 +2664,10 @@ cChunk * cChunk::GetRelNeighborChunk(int a_RelX, int a_RelZ) bool ReturnThis = true; if (a_RelX < 0) { - if (m_NeighborXM != NULL) + if (m_NeighborXM != nullptr) { cChunk * Candidate = m_NeighborXM->GetRelNeighborChunk(a_RelX + cChunkDef::Width, a_RelZ); - if (Candidate != NULL) + if (Candidate != nullptr) { return Candidate; } @@ -2677,10 +2677,10 @@ cChunk * cChunk::GetRelNeighborChunk(int a_RelX, int a_RelZ) } else if (a_RelX >= cChunkDef::Width) { - if (m_NeighborXP != NULL) + if (m_NeighborXP != nullptr) { cChunk * Candidate = m_NeighborXP->GetRelNeighborChunk(a_RelX - cChunkDef::Width, a_RelZ); - if (Candidate != NULL) + if (Candidate != nullptr) { return Candidate; } @@ -2691,24 +2691,24 @@ cChunk * cChunk::GetRelNeighborChunk(int a_RelX, int a_RelZ) if (a_RelZ < 0) { - if (m_NeighborZM != NULL) + if (m_NeighborZM != nullptr) { return m_NeighborZM->GetRelNeighborChunk(a_RelX, a_RelZ + cChunkDef::Width); // For requests crossing both X and Z, the X-first way has been already tried } - return NULL; + return nullptr; } else if (a_RelZ >= cChunkDef::Width) { - if (m_NeighborZP != NULL) + if (m_NeighborZP != nullptr) { return m_NeighborZP->GetRelNeighborChunk(a_RelX, a_RelZ - cChunkDef::Width); // For requests crossing both X and Z, the X-first way has been already tried } - return NULL; + return nullptr; } - return (ReturnThis ? this : NULL); + return (ReturnThis ? this : nullptr); } @@ -2731,27 +2731,27 @@ cChunk * cChunk::GetRelNeighborChunkAdjustCoords(int & a_RelX, int & a_RelZ) con // Request for a different chunk, calculate chunk offset: int RelX = a_RelX; // Make a local copy of the coords (faster access) int RelZ = a_RelZ; - while ((RelX >= Width) && (ToReturn != NULL)) + while ((RelX >= Width) && (ToReturn != nullptr)) { RelX -= Width; ToReturn = ToReturn->m_NeighborXP; } - while ((RelX < 0) && (ToReturn != NULL)) + while ((RelX < 0) && (ToReturn != nullptr)) { RelX += Width; ToReturn = ToReturn->m_NeighborXM; } - while ((RelZ >= Width) && (ToReturn != NULL)) + while ((RelZ >= Width) && (ToReturn != nullptr)) { RelZ -= Width; ToReturn = ToReturn->m_NeighborZP; } - while ((RelZ < 0) && (ToReturn != NULL)) + while ((RelZ < 0) && (ToReturn != nullptr)) { RelZ += Width; ToReturn = ToReturn->m_NeighborZM; } - if (ToReturn != NULL) + if (ToReturn != nullptr) { a_RelX = RelX; a_RelZ = RelZ; @@ -2821,7 +2821,7 @@ void cChunk::BroadcastBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cons { // We can operate on entity pointers, we're inside the ChunkMap's CS lock which guards the list cBlockEntity * Entity = GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); - if (Entity == NULL) + if (Entity == nullptr) { return; } @@ -3158,7 +3158,7 @@ void cChunk::BroadcastUseBed(const cEntity & a_Entity, int a_BlockX, int a_Block void cChunk::SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client) { cBlockEntity * Entity = GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); - if (Entity == NULL) + if (Entity == nullptr) { return; } diff --git a/src/Chunk.h b/src/Chunk.h index 5f8fcaf7b..6f4ac5cac 100644 --- a/src/Chunk.h +++ b/src/Chunk.h @@ -190,13 +190,13 @@ public: void GetBlockInfo (int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight); /** Returns the chunk into which the specified block belongs, by walking the neighbors. - Will return self if appropriate. Returns NULL if not reachable through neighbors. + Will return self if appropriate. Returns nullptr if not reachable through neighbors. */ cChunk * GetNeighborChunk(int a_BlockX, int a_BlockZ); /** Returns the chunk into which the relatively-specified block belongs, by walking the neighbors. - Will return self if appropriate. Returns NULL if not reachable through neighbors. + Will return self if appropriate. Returns nullptr if not reachable through neighbors. */ cChunk * GetRelNeighborChunk(int a_RelX, int a_RelZ); @@ -316,28 +316,28 @@ public: // Broadcast various packets to all clients of this chunk: // (Please keep these alpha-sorted) void BroadcastAttachEntity (const cEntity & a_Entity, const cEntity * a_Vehicle); - void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); - void BroadcastChunkData (cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectEntity (const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL); - void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = NULL); - void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL); - void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); + void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastChunkData (cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectEntity (const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr); + void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = nullptr); + void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = nullptr); + void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); void BroadcastUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ); void SendBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client); diff --git a/src/ChunkData.cpp b/src/ChunkData.cpp index 03b0224a6..57b27c5e0 100644 --- a/src/ChunkData.cpp +++ b/src/ChunkData.cpp @@ -36,7 +36,7 @@ cChunkData::cChunkData(cAllocationPool & a_Pool) : { for (size_t i = 0; i < NumSections; i++) { - m_Sections[i] = NULL; + m_Sections[i] = nullptr; } } @@ -56,7 +56,7 @@ cChunkData::~cChunkData() for (size_t i = 0; i < NumSections; i++) { Free(m_Sections[i]); - m_Sections[i] = NULL; + m_Sections[i] = nullptr; } } @@ -96,7 +96,7 @@ cChunkData::~cChunkData() for (size_t i = 0; i < NumSections; i++) { Free(m_Sections[i]); - m_Sections[i] = NULL; + m_Sections[i] = nullptr; } } @@ -120,7 +120,7 @@ cChunkData::~cChunkData() for (size_t i = 0; i < NumSections; i++) { m_Sections[i] = other.m_Sections[i]; - other.m_Sections[i] = NULL; + other.m_Sections[i] = nullptr; } } @@ -137,7 +137,7 @@ cChunkData::~cChunkData() { Free(m_Sections[i]); m_Sections[i] = other.m_Sections[i]; - other.m_Sections[i] = NULL; + other.m_Sections[i] = nullptr; } } return *this; @@ -154,7 +154,7 @@ BLOCKTYPE cChunkData::GetBlock(int a_X, int a_Y, int a_Z) const ASSERT((a_Y >= 0) && (a_Y < cChunkDef::Height)); ASSERT((a_Z >= 0) && (a_Z < cChunkDef::Width)); int Section = a_Y / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_X, a_Y - (Section * SectionHeight), a_Z); return m_Sections[Section]->m_BlockTypes[Index]; @@ -182,14 +182,14 @@ void cChunkData::SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_Block) } int Section = a_RelY / SectionHeight; - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { if (a_Block == 0x00) { return; } m_Sections[Section] = Allocate(); - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { ASSERT(!"Failed to allocate a new section in Chunkbuffer"); return; @@ -212,7 +212,7 @@ NIBBLETYPE cChunkData::GetMeta(int a_RelX, int a_RelY, int a_RelZ) const (a_RelZ < cChunkDef::Width) && (a_RelZ > -1)) { int Section = a_RelY / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * SectionHeight), a_RelZ); return (m_Sections[Section]->m_BlockMetas[Index / 2] >> ((Index & 1) * 4)) & 0x0f; @@ -243,14 +243,14 @@ bool cChunkData::SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Nibble } int Section = a_RelY / SectionHeight; - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { if ((a_Nibble & 0xf) == 0x00) { return false; } m_Sections[Section] = Allocate(); - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { ASSERT(!"Failed to allocate a new section in Chunkbuffer"); return false; @@ -279,7 +279,7 @@ NIBBLETYPE cChunkData::GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const ) { int Section = a_RelY / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * SectionHeight), a_RelZ); return (m_Sections[Section]->m_BlockLight[Index / 2] >> ((Index & 1) * 4)) & 0x0f; @@ -302,7 +302,7 @@ NIBBLETYPE cChunkData::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 / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * SectionHeight), a_RelZ); return (m_Sections[Section]->m_BlockSkyLight[Index / 2] >> ((Index & 1) * 4)) & 0x0f; @@ -325,7 +325,7 @@ cChunkData cChunkData::Copy(void) const cChunkData copy(m_Pool); for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { copy.m_Sections[i] = copy.Allocate(); *copy.m_Sections[i] = *m_Sections[i]; @@ -354,7 +354,7 @@ void cChunkData::CopyBlockTypes(BLOCKTYPE * a_Dest, size_t a_Idx, size_t a_Lengt { size_t ToCopy = std::min(+SectionBlockCount - StartPos, a_Length); a_Length -= ToCopy; - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { BLOCKTYPE * blockbuffer = m_Sections[i]->m_BlockTypes; memcpy(&a_Dest[(i * SectionBlockCount) + StartPos - a_Idx], blockbuffer + StartPos, sizeof(BLOCKTYPE) * ToCopy); @@ -375,7 +375,7 @@ void cChunkData::CopyMetas(NIBBLETYPE * a_Dest) const { for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(&a_Dest[i * SectionBlockCount / 2], &m_Sections[i]->m_BlockMetas, sizeof(m_Sections[i]->m_BlockMetas)); } @@ -394,7 +394,7 @@ void cChunkData::CopyBlockLight(NIBBLETYPE * a_Dest) const { for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(&a_Dest[i * SectionBlockCount / 2], &m_Sections[i]->m_BlockLight, sizeof(m_Sections[i]->m_BlockLight)); } @@ -413,7 +413,7 @@ void cChunkData::CopySkyLight(NIBBLETYPE * a_Dest) const { for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(&a_Dest[i * SectionBlockCount / 2], &m_Sections[i]->m_BlockSkyLight, sizeof(m_Sections[i]->m_BlockSkyLight)); } @@ -430,12 +430,12 @@ void cChunkData::CopySkyLight(NIBBLETYPE * a_Dest) const void cChunkData::SetBlockTypes(const BLOCKTYPE * a_Src) { - ASSERT(a_Src != NULL); + ASSERT(a_Src != nullptr); for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockTypes, &a_Src[i * SectionBlockCount], sizeof(m_Sections[i]->m_BlockTypes)); continue; @@ -462,12 +462,12 @@ void cChunkData::SetBlockTypes(const BLOCKTYPE * a_Src) void cChunkData::SetMetas(const NIBBLETYPE * a_Src) { - ASSERT(a_Src != NULL); + ASSERT(a_Src != nullptr); for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockMetas, &a_Src[i * SectionBlockCount / 2], sizeof(m_Sections[i]->m_BlockMetas)); continue; @@ -495,7 +495,7 @@ void cChunkData::SetMetas(const NIBBLETYPE * a_Src) void cChunkData::SetBlockLight(const NIBBLETYPE * a_Src) { - if (a_Src == NULL) + if (a_Src == nullptr) { return; } @@ -503,7 +503,7 @@ void cChunkData::SetBlockLight(const NIBBLETYPE * a_Src) for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockLight, &a_Src[i * SectionBlockCount / 2], sizeof(m_Sections[i]->m_BlockLight)); continue; @@ -530,7 +530,7 @@ void cChunkData::SetBlockLight(const NIBBLETYPE * a_Src) void cChunkData::SetSkyLight(const NIBBLETYPE * a_Src) { - if (a_Src == NULL) + if (a_Src == nullptr) { return; } @@ -538,7 +538,7 @@ void cChunkData::SetSkyLight(const NIBBLETYPE * a_Src) for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockSkyLight, &a_Src[i * SectionBlockCount / 2], sizeof(m_Sections[i]->m_BlockSkyLight)); continue; diff --git a/src/ChunkData.h b/src/ChunkData.h index fe8b068a2..2ab629b29 100644 --- a/src/ChunkData.h +++ b/src/ChunkData.h @@ -88,12 +88,12 @@ public: /** Copies the blocklight data from the specified flat array into the internal representation. Allocates sectios that are needed for the operation. - Allows a_Src to be NULL, in which case it doesn't do anything. */ + Allows a_Src to be nullptr, in which case it doesn't do anything. */ void SetBlockLight(const NIBBLETYPE * a_Src); /** Copies the skylight data from the specified flat array into the internal representation. Allocates sectios that are needed for the operation. - Allows a_Src to be NULL, in which case it doesn't do anything. */ + Allows a_Src to be nullptr, in which case it doesn't do anything. */ void SetSkyLight(const NIBBLETYPE * a_Src); struct sChunkSection @@ -118,7 +118,7 @@ private: sChunkSection * Allocate(void); /** Frees the specified section, previously allocated using Allocate(). - Note that a_Section may be NULL. */ + Note that a_Section may be nullptr. */ void Free(sChunkSection * a_Section); /** Sets the data in the specified section to their default values. */ diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index 6f56b23e0..595040a54 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -88,10 +88,10 @@ cChunkMap::cChunkLayer * cChunkMap::GetLayer(int a_LayerX, int a_LayerZ) // Not found, create new: cChunkLayer * Layer = new cChunkLayer(a_LayerX, a_LayerZ, this, *m_Pool); - if (Layer == NULL) + if (Layer == nullptr) { LOGERROR("cChunkMap: Cannot create new layer, server out of memory?"); - return NULL; + return nullptr; } m_Layers.push_back(Layer); return Layer; @@ -125,7 +125,7 @@ cChunkMap::cChunkLayer * cChunkMap::FindLayer(int a_LayerX, int a_LayerZ) } // for itr - m_Layers[] // Not found - return NULL; + return nullptr; } @@ -148,16 +148,16 @@ cChunkPtr cChunkMap::GetChunk(int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); // m_CSLayers should already be locked by the operation that called us cChunkLayer * Layer = GetLayerForChunk(a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { // An error must have occurred, since layers are automatically created if they don't exist - return NULL; + return nullptr; } cChunkPtr Chunk = Layer->GetChunk(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { - return NULL; + return nullptr; } if (!Chunk->IsValid() && !Chunk->IsQueued()) { @@ -177,16 +177,16 @@ cChunkPtr cChunkMap::GetChunkNoGen(int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); // m_CSLayers should already be locked by the operation that called us cChunkLayer * Layer = GetLayerForChunk(a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { // An error must have occurred, since layers are automatically created if they don't exist - return NULL; + return nullptr; } cChunkPtr Chunk = Layer->GetChunk(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { - return NULL; + return nullptr; } if (!Chunk->IsValid() && !Chunk->IsQueued()) { @@ -206,10 +206,10 @@ cChunkPtr cChunkMap::GetChunkNoLoad( int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); // m_CSLayers should already be locked by the operation that called us cChunkLayer * Layer = GetLayerForChunk( a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { // An error must have occurred, since layers are automatically created if they don't exist - return NULL; + return nullptr; } return Layer->GetChunk(a_ChunkX, a_ChunkZ); @@ -227,7 +227,7 @@ bool cChunkMap::LockedGetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -249,7 +249,7 @@ bool cChunkMap::LockedGetBlockType(int a_BlockX, int a_BlockY, int a_BlockZ, BLO int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -270,7 +270,7 @@ bool cChunkMap::LockedGetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ, NIB int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -289,7 +289,7 @@ bool cChunkMap::LockedSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -308,7 +308,7 @@ bool cChunkMap::LockedFastSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLO int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -326,9 +326,9 @@ cChunk * cChunkMap::FindChunk(int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); cChunkLayer * Layer = FindLayerForChunk(a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { - return NULL; + return nullptr; } return Layer->FindChunk(a_ChunkX, a_ChunkZ); } @@ -341,7 +341,7 @@ void cChunkMap::BroadcastAttachEntity(const cEntity & a_Entity, const cEntity * { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -361,7 +361,7 @@ void cChunkMap::BroadcastBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, c z = a_BlockZ; cChunkDef::BlockToChunk(x, z, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -380,7 +380,7 @@ void cChunkMap::BroadcastBlockBreakAnimation(int a_entityID, int a_blockX, int a cChunkDef::BlockToChunk(a_blockX, a_blockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -398,7 +398,7 @@ void cChunkMap::BroadcastBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, c int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -413,7 +413,7 @@ void cChunkMap::BroadcastChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSeriali { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -429,7 +429,7 @@ void cChunkMap::BroadcastCollectEntity(const cEntity & a_Entity, const cPlayer & { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -445,7 +445,7 @@ void cChunkMap::BroadcastDestroyEntity(const cEntity & a_Entity, const cClientHa { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -461,7 +461,7 @@ void cChunkMap::BroadcastEntityEffect(const cEntity & a_Entity, int a_EffectID, { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -477,7 +477,7 @@ void cChunkMap::BroadcastEntityEquipment(const cEntity & a_Entity, short a_SlotN { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -493,7 +493,7 @@ void cChunkMap::BroadcastEntityHeadLook(const cEntity & a_Entity, const cClientH { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -509,7 +509,7 @@ void cChunkMap::BroadcastEntityLook(const cEntity & a_Entity, const cClientHandl { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -525,7 +525,7 @@ void cChunkMap::BroadcastEntityMetadata(const cEntity & a_Entity, const cClientH { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -541,7 +541,7 @@ void cChunkMap::BroadcastEntityRelMove(const cEntity & a_Entity, char a_RelX, ch { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -557,7 +557,7 @@ void cChunkMap::BroadcastEntityRelMoveLook(const cEntity & a_Entity, char a_RelX { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -573,7 +573,7 @@ void cChunkMap::BroadcastEntityStatus(const cEntity & a_Entity, char a_Status, c { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -589,7 +589,7 @@ void cChunkMap::BroadcastEntityVelocity(const cEntity & a_Entity, const cClientH { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -605,7 +605,7 @@ void cChunkMap::BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animat { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -624,7 +624,7 @@ void cChunkMap::BroadcastParticleEffect(const AString & a_ParticleName, float a_ cChunkDef::BlockToChunk((int) a_SrcX, (int) a_SrcZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -641,7 +641,7 @@ void cChunkMap::BroadcastRemoveEntityEffect(const cEntity & a_Entity, int a_Effe cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -660,7 +660,7 @@ void cChunkMap::BroadcastSoundEffect(const AString & a_SoundName, double a_X, do cChunkDef::BlockToChunk((int)std::floor(a_X), (int)std::floor(a_Z), ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -679,7 +679,7 @@ void cChunkMap::BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_S cChunkDef::BlockToChunk(a_SrcX, a_SrcZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -695,7 +695,7 @@ void cChunkMap::BroadcastSpawnEntity(cEntity & a_Entity, const cClientHandle * a { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -713,7 +713,7 @@ void cChunkMap::BroadcastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ, c int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -732,7 +732,7 @@ void cChunkMap::BroadcastUseBed(const cEntity & a_Entity, int a_BlockX, int a_Bl cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -750,7 +750,7 @@ void cChunkMap::SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClien int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -768,7 +768,7 @@ void cChunkMap::UseBlockEntity(cPlayer * a_Player, int a_BlockX, int a_BlockY, i int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -783,7 +783,7 @@ bool cChunkMap::DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback & a_Callb { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -800,7 +800,7 @@ void cChunkMap::WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ) int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -829,7 +829,7 @@ void cChunkMap::WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_M for (int x = MinChunkX; x <= MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoGen(x, z); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -857,7 +857,7 @@ void cChunkMap::MarkRedstoneDirty(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -872,7 +872,7 @@ void cChunkMap::MarkChunkDirty(int a_ChunkX, int a_ChunkZ, bool a_MarkRedstoneDi { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -891,7 +891,7 @@ void cChunkMap::MarkChunkSaving(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -906,7 +906,7 @@ void cChunkMap::MarkChunkSaved (int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -924,7 +924,7 @@ void cChunkMap::SetChunkData(cSetChunkData & a_SetChunkData) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -969,7 +969,7 @@ void cChunkMap::ChunkLighted( { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -985,7 +985,7 @@ bool cChunkMap::GetChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataCallback & a_ { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1001,7 +1001,7 @@ bool cChunkMap::GetChunkBlockTypes(int a_ChunkX, int a_ChunkZ, BLOCKTYPE * a_Blo { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1017,7 +1017,7 @@ bool cChunkMap::IsChunkQueued(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - return (Chunk != NULL) && Chunk->IsQueued(); + return (Chunk != nullptr) && Chunk->IsQueued(); } @@ -1028,7 +1028,7 @@ bool cChunkMap::IsChunkValid(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - return (Chunk != NULL) && Chunk->IsValid(); + return (Chunk != nullptr) && Chunk->IsValid(); } @@ -1039,7 +1039,7 @@ bool cChunkMap::HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - return (Chunk != NULL) && Chunk->HasAnyClients(); + return (Chunk != nullptr) && Chunk->HasAnyClients(); } @@ -1054,7 +1054,7 @@ int cChunkMap::GetHeight(int a_BlockX, int a_BlockZ) int ChunkX, ChunkZ, BlockY = 0; cChunkDef::AbsoluteToRelative(a_BlockX, BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return 0; } @@ -1081,7 +1081,7 @@ bool cChunkMap::TryGetHeight(int a_BlockX, int a_BlockZ, int & a_Height) int ChunkX, ChunkZ, BlockY = 0; cChunkDef::AbsoluteToRelative(a_BlockX, BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1104,7 +1104,7 @@ void cChunkMap::FastSetBlocks(sSetBlockList & a_BlockList) int ChunkZ = a_BlockList.front().ChunkZ; cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { for (sSetBlockList::iterator itr = a_BlockList.begin(); itr != a_BlockList.end();) { @@ -1193,7 +1193,7 @@ BLOCKTYPE cChunkMap::GetBlock(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetBlock(a_BlockX, a_BlockY, a_BlockZ); } @@ -1222,7 +1222,7 @@ NIBBLETYPE cChunkMap::GetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetMeta(a_BlockX, a_BlockY, a_BlockZ); } @@ -1240,7 +1240,7 @@ NIBBLETYPE cChunkMap::GetBlockSkyLight(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetSkyLight(a_BlockX, a_BlockY, a_BlockZ); } @@ -1258,7 +1258,7 @@ NIBBLETYPE cChunkMap::GetBlockBlockLight(int a_BlockX, int a_BlockY, int a_Block cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetBlockLight(a_BlockX, a_BlockY, a_BlockZ); } @@ -1277,7 +1277,7 @@ void cChunkMap::SetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYP cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetMeta(a_BlockX, a_BlockY, a_BlockZ, a_BlockMeta); } @@ -1300,7 +1300,7 @@ void cChunkMap::SetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_B cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetBlock(X, Y, Z, a_BlockType, a_BlockMeta, a_SendToClients); m_World->GetSimulatorManager()->WakeUp(a_BlockX, a_BlockY, a_BlockZ, Chunk); @@ -1319,7 +1319,7 @@ void cChunkMap::QueueSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYP cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->QueueSetBlock(X, Y, Z, a_BlockType, a_BlockMeta, a_Tick, a_PreviousBlockType); } @@ -1336,7 +1336,7 @@ bool cChunkMap::GetBlockTypeMeta(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCK cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->GetBlockTypeMeta(X, Y, Z, a_BlockType, a_BlockMeta); return true; @@ -1355,7 +1355,7 @@ bool cChunkMap::GetBlockInfo(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->GetBlockInfo(X, Y, Z, a_BlockType, a_Meta, a_SkyLight, a_BlockLight); return true; @@ -1373,7 +1373,7 @@ void cChunkMap::ReplaceBlocks(const sSetBlockVector & a_Blocks, BLOCKTYPE a_Filt for (sSetBlockVector::const_iterator itr = a_Blocks.begin(); itr != a_Blocks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->ChunkX, itr->ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -1394,7 +1394,7 @@ void cChunkMap::ReplaceTreeBlocks(const sSetBlockVector & a_Blocks) for (sSetBlockVector::const_iterator itr = a_Blocks.begin(); itr != a_Blocks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->ChunkX, itr->ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -1429,7 +1429,7 @@ EMCSBiome cChunkMap::GetBiomeAt (int a_BlockX, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetBiomeAt(X, Z); } @@ -1450,7 +1450,7 @@ bool cChunkMap::SetBiomeAt(int a_BlockX, int a_BlockZ, EMCSBiome a_Biome) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetBiomeAt(X, Z, a_Biome); return true; @@ -1483,7 +1483,7 @@ bool cChunkMap::SetAreaBiome(int a_MinX, int a_MaxX, int a_MinZ, int a_MaxZ, EMC int MinRelZ = (z == MinChunkZ) ? MinZ : 0; int MaxRelZ = (z == MaxChunkZ) ? MaxZ : cChunkDef::Width - 1; cChunkPtr Chunk = GetChunkNoLoad(x, z); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetAreaBiome(MinRelX, MaxRelX, MinRelZ, MaxRelZ, a_Biome); } @@ -1507,7 +1507,7 @@ bool cChunkMap::GetBlocks(sSetBlockVector & a_Blocks, bool a_ContinueOnFailure) for (sSetBlockVector::iterator itr = a_Blocks.begin(); itr != a_Blocks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->ChunkX, itr->ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { if (!a_ContinueOnFailure) { @@ -1535,7 +1535,7 @@ bool cChunkMap::DigBlock(int a_X, int a_Y, int a_Z) { cCSLock Lock(m_CSLayers); cChunkPtr DestChunk = GetChunk( ChunkX, ChunkZ); - if ((DestChunk == NULL) || !DestChunk->IsValid()) + if ((DestChunk == nullptr) || !DestChunk->IsValid()) { return false; } @@ -1558,7 +1558,7 @@ void cChunkMap::SendBlockTo(int a_X, int a_Y, int a_Z, cPlayer * a_Player) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && (Chunk->IsValid())) + if ((Chunk != nullptr) && (Chunk->IsValid())) { Chunk->SendBlockTo(a_X, a_Y, a_Z, a_Player->GetClientHandle()); } @@ -1572,12 +1572,12 @@ void cChunkMap::CompareChunkClients(int a_ChunkX1, int a_ChunkZ1, int a_ChunkX2, { cCSLock Lock(m_CSLayers); cChunkPtr Chunk1 = GetChunkNoGen(a_ChunkX1, a_ChunkZ1); - if (Chunk1 == NULL) + if (Chunk1 == nullptr) { return; } cChunkPtr Chunk2 = GetChunkNoGen(a_ChunkX2, a_ChunkZ2); - if (Chunk2 == NULL) + if (Chunk2 == nullptr) { return; } @@ -1639,7 +1639,7 @@ bool cChunkMap::AddChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Cli { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -1654,7 +1654,7 @@ void cChunkMap::RemoveChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_ { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -1684,7 +1684,7 @@ void cChunkMap::AddEntity(cEntity * a_Entity) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); if ( - (Chunk == NULL) || // Chunk not present at all + (Chunk == nullptr) || // Chunk not present at all (!Chunk->IsValid() && !a_Entity->IsPlayer()) // Chunk present, but no valid data; players need to spawn in such chunks (#953) ) { @@ -1705,7 +1705,7 @@ void cChunkMap::AddEntityIfNotPresent(cEntity * a_Entity) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); if ( - (Chunk == NULL) || // Chunk not present at all + (Chunk == nullptr) || // Chunk not present at all (!Chunk->IsValid() && !a_Entity->IsPlayer()) // Chunk present, but no valid data; players need to spawn in such chunks (#953) ) { @@ -1747,7 +1747,7 @@ void cChunkMap::RemoveEntity(cEntity * a_Entity) cChunkPtr Chunk = GetChunkNoGen(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); // Even if a chunk is not valid, it may still contain entities such as players; make sure to remove them (#1190) - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -1779,7 +1779,7 @@ bool cChunkMap::ForEachEntityInChunk(int a_ChunkX, int a_ChunkZ, cEntityCallback { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1805,7 +1805,7 @@ bool cChunkMap::ForEachEntityInBox(const cBoundingBox & a_Box, cEntityCallback & for (int x = MinChunkX; x <= MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoGen(x, z); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -1980,7 +1980,7 @@ void cChunkMap::DoExplosionAt(double a_ExplosionSize, double a_BlockX, double a_ } // Ensure that the damage dealt is inversely proportional to the distance to the TNT centre - the closer a player is, the harder they are hit - a_Entity->TakeDamage(dtExplosion, NULL, (int)((1 / DistanceFromExplosion.Length()) * 6 * m_ExplosionSize), 0); + a_Entity->TakeDamage(dtExplosion, nullptr, (int)((1 / DistanceFromExplosion.Length()) * 6 * m_ExplosionSize), 0); } // Apply force to entities around the explosion - code modified from World.cpp DoExplosionAt() @@ -2038,7 +2038,7 @@ bool cChunkMap::ForEachBlockEntityInChunk(int a_ChunkX, int a_ChunkZ, cBlockEnti { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2053,7 +2053,7 @@ bool cChunkMap::ForEachChestInChunk(int a_ChunkX, int a_ChunkZ, cChestCallback & { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2068,7 +2068,7 @@ bool cChunkMap::ForEachDispenserInChunk(int a_ChunkX, int a_ChunkZ, cDispenserCa { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2083,7 +2083,7 @@ bool cChunkMap::ForEachDropperInChunk(int a_ChunkX, int a_ChunkZ, cDropperCallba { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2098,7 +2098,7 @@ bool cChunkMap::ForEachDropSpenserInChunk(int a_ChunkX, int a_ChunkZ, cDropSpens { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2113,7 +2113,7 @@ bool cChunkMap::ForEachFurnaceInChunk(int a_ChunkX, int a_ChunkZ, cFurnaceCallba { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2131,7 +2131,7 @@ bool cChunkMap::DoWithBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cB cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2149,7 +2149,7 @@ bool cChunkMap::DoWithBeaconAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBeacon cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2167,7 +2167,7 @@ bool cChunkMap::DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCa cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2185,7 +2185,7 @@ bool cChunkMap::DoWithDispenserAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDis cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2203,7 +2203,7 @@ bool cChunkMap::DoWithDropperAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDropp cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2221,7 +2221,7 @@ bool cChunkMap::DoWithDropSpenserAt(int a_BlockX, int a_BlockY, int a_BlockZ, cD cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2239,7 +2239,7 @@ bool cChunkMap::DoWithFurnaceAt(int a_BlockX, int a_BlockY, int a_BlockZ, cFurna cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2256,7 +2256,7 @@ bool cChunkMap::DoWithNoteBlockAt(int a_BlockX, int a_BlockY, int a_BlockZ, cNot cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2273,7 +2273,7 @@ bool cChunkMap::DoWithCommandBlockAt(int a_BlockX, int a_BlockY, int a_BlockZ, c cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2291,7 +2291,7 @@ bool cChunkMap::DoWithMobHeadAt(int a_BlockX, int a_BlockY, int a_BlockZ, cMobHe cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2309,7 +2309,7 @@ bool cChunkMap::DoWithFlowerPotAt(int a_BlockX, int a_BlockY, int a_BlockZ, cFlo cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2327,7 +2327,7 @@ bool cChunkMap::GetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, AString & cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2352,7 +2352,7 @@ void cChunkMap::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -2369,7 +2369,7 @@ bool cChunkMap::SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const ASt int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2384,7 +2384,7 @@ void cChunkMap::MarkChunkRegenerating(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Not present return; @@ -2400,7 +2400,7 @@ bool cChunkMap::IsChunkLighted(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Not present return false; @@ -2421,7 +2421,7 @@ bool cChunkMap::ForEachChunkInRect(int a_MinChunkX, int a_MaxChunkX, int a_MinCh for (int x = a_MinChunkX; x <= a_MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoLoad(x, z); - if ((Chunk == NULL) || (!Chunk->IsValid())) + if ((Chunk == nullptr) || (!Chunk->IsValid())) { // Not present / not valid Result = false; @@ -2463,7 +2463,7 @@ bool cChunkMap::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBl for (int x = MinChunkX; x <= MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoLoad(x, z); - if ((Chunk == NULL) || (!Chunk->IsValid())) + if ((Chunk == nullptr) || (!Chunk->IsValid())) { // Not present / not valid Result = false; @@ -2504,7 +2504,7 @@ void cChunkMap::GrowMelonPumpkin(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCK cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->GrowMelonPumpkin(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_Rand); } @@ -2521,7 +2521,7 @@ void cChunkMap::GrowSugarcane(int a_BlockX, int a_BlockY, int a_BlockZ, int a_Nu cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->GrowSugarcane(a_BlockX, a_BlockY, a_BlockZ, a_NumBlocksToGrow); } @@ -2538,7 +2538,7 @@ void cChunkMap::GrowCactus(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBl cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->GrowCactus(a_BlockX, a_BlockY, a_BlockZ, a_NumBlocksToGrow); } @@ -2555,7 +2555,7 @@ void cChunkMap::SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->SetNextBlockTick(a_BlockX, a_BlockY, a_BlockZ); } @@ -2610,7 +2610,7 @@ void cChunkMap::TickBlock(int a_BlockX, int a_BlockY, int a_BlockZ) int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -2679,7 +2679,7 @@ void cChunkMap::QueueTickBlock(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->QueueTickBlock(a_BlockX, a_BlockY, a_BlockZ); } @@ -2693,7 +2693,7 @@ void cChunkMap::SetChunkAlwaysTicked(int a_ChunkX, int a_ChunkZ, bool a_AlwaysTi { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->SetAlwaysTicked(a_AlwaysTicked); } @@ -2729,7 +2729,7 @@ cChunkMap::cChunkLayer::~cChunkLayer() for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { delete m_Chunks[i]; - m_Chunks[i] = NULL; // Must zero out, because further chunk deletions query the chunkmap for entities and that would touch deleted data + m_Chunks[i] = nullptr; // Must zero out, because further chunk deletions query the chunkmap for entities and that would touch deleted data } // for i - m_Chunks[] } @@ -2747,11 +2747,11 @@ cChunkPtr cChunkMap::cChunkLayer::GetChunk( int a_ChunkX, int a_ChunkZ) if (!((LocalX < LAYER_SIZE) && (LocalZ < LAYER_SIZE) && (LocalX > -1) && (LocalZ > -1))) { ASSERT(!"Asking a cChunkLayer for a chunk that doesn't belong to it!"); - return NULL; + return nullptr; } int Index = LocalX + LocalZ * LAYER_SIZE; - if (m_Chunks[Index] == NULL) + if (m_Chunks[Index] == nullptr) { cChunk * neixm = (LocalX > 0) ? m_Chunks[Index - 1] : m_Parent->FindChunk(a_ChunkX - 1, a_ChunkZ); cChunk * neixp = (LocalX < LAYER_SIZE - 1) ? m_Chunks[Index + 1] : m_Parent->FindChunk(a_ChunkX + 1, a_ChunkZ); @@ -2774,7 +2774,7 @@ cChunk * cChunkMap::cChunkLayer::FindChunk(int a_ChunkX, int a_ChunkZ) if (!((LocalX < LAYER_SIZE) && (LocalZ < LAYER_SIZE) && (LocalX > -1) && (LocalZ > -1))) { ASSERT(!"Asking a cChunkLayer for a chunk that doesn't belong to it!"); - return NULL; + return nullptr; } int Index = LocalX + LocalZ * LAYER_SIZE; @@ -2791,7 +2791,7 @@ void cChunkMap::cChunkLayer::CollectMobCensus(cMobCensus& a_ToFill) // We do count every Mobs in the world. But we are assuming that every chunk not loaded by any client // doesn't affect us. Normally they should not have mobs because every "too far" mobs despawn // If they have (f.i. when player disconnect) we assume we don't have to make them live or despawn - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) { m_Chunks[i]->CollectMobCensus(a_ToFill); } @@ -2808,7 +2808,7 @@ void cChunkMap::cChunkLayer::SpawnMobs(cMobSpawner& a_MobSpawner) for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { // We only spawn close to players - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) { m_Chunks[i]->SpawnMobs(a_MobSpawner); } @@ -2824,7 +2824,7 @@ void cChunkMap::cChunkLayer::Tick(float a_Dt) for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { // Only tick chunks that are valid and should be ticked: - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->ShouldBeTicked()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->ShouldBeTicked()) { m_Chunks[i]->Tick(a_Dt); } @@ -2839,7 +2839,7 @@ void cChunkMap::cChunkLayer::RemoveClient(cClientHandle * a_Client) { for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if (m_Chunks[i] != NULL) + if (m_Chunks[i] != nullptr) { m_Chunks[i]->RemoveClient(a_Client); } @@ -2855,7 +2855,7 @@ bool cChunkMap::cChunkLayer::ForEachEntity(cEntityCallback & a_Callback) // Calls the callback for each entity in the entire world; returns true if all entities processed, false if the callback aborted by returning true for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid()) { if (!m_Chunks[i]->ForEachEntity(a_Callback)) { @@ -2875,7 +2875,7 @@ bool cChunkMap::cChunkLayer::DoWithEntityByID(int a_EntityID, cEntityCallback & // Calls the callback if the entity with the specified ID is found, with the entity object as the callback param. Returns true if entity found. for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid()) { if (m_Chunks[i]->DoWithEntityByID(a_EntityID, a_Callback, a_CallbackReturn)) { @@ -2894,7 +2894,7 @@ bool cChunkMap::cChunkLayer::HasEntity(int a_EntityID) { for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid()) { if (m_Chunks[i]->HasEntity(a_EntityID)) { @@ -2914,7 +2914,7 @@ int cChunkMap::cChunkLayer::GetNumChunksLoaded(void) const int NumChunks = 0; for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { - if (m_Chunks[i] != NULL) + if (m_Chunks[i] != nullptr) { NumChunks++; } @@ -2932,7 +2932,7 @@ void cChunkMap::cChunkLayer::GetChunkStats(int & a_NumChunksValid, int & a_NumCh int NumDirty = 0; for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { - if (m_Chunks[i] == NULL) + if (m_Chunks[i] == nullptr) { continue; } @@ -2955,7 +2955,7 @@ void cChunkMap::cChunkLayer::Save(void) cWorld * World = m_Parent->GetWorld(); for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->IsDirty()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->IsDirty()) { World->GetStorage().QueueSaveChunk(m_Chunks[i]->GetPosX(), m_Chunks[i]->GetPosZ()); } @@ -2971,7 +2971,7 @@ void cChunkMap::cChunkLayer::UnloadUnusedChunks(void) for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { if ( - (m_Chunks[i] != NULL) && // Is valid + (m_Chunks[i] != nullptr) && // Is valid (m_Chunks[i]->CanUnload()) && // Can unload !cPluginManager::Get()->CallHookChunkUnloading(*(m_Parent->GetWorld()), m_Chunks[i]->GetPosX(), m_Chunks[i]->GetPosZ()) // Plugins agree ) @@ -2980,7 +2980,7 @@ void cChunkMap::cChunkLayer::UnloadUnusedChunks(void) // so we still need to be able to return the chunk. Therefore we first delete, then NULLify // Doing otherwise results in bug http://forum.mc-server.org/showthread.php?tid=355 delete m_Chunks[i]; - m_Chunks[i] = NULL; + m_Chunks[i] = nullptr; } } // for i - m_Chunks[] } @@ -3033,7 +3033,7 @@ void cChunkMap::AddChunkStay(cChunkStay & a_ChunkStay) for (cChunkCoordsVector::const_iterator itr = WantedChunks.begin(); itr != WantedChunks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->m_ChunkX, itr->m_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { continue; } @@ -3082,7 +3082,7 @@ void cChunkMap::DelChunkStay(cChunkStay & a_ChunkStay) for (cChunkCoordsVector::const_iterator itr = Chunks.begin(), end = Chunks.end(); itr != end; ++itr) { cChunkPtr Chunk = GetChunkNoLoad(itr->m_ChunkX, itr->m_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { continue; } diff --git a/src/ChunkMap.h b/src/ChunkMap.h index 38e7f4052..51be5cb3d 100644 --- a/src/ChunkMap.h +++ b/src/ChunkMap.h @@ -70,29 +70,29 @@ public: // Broadcast respective packets to all clients of the chunk where the event is taking place // (Please keep these alpha-sorted) void BroadcastAttachEntity(const cEntity & a_Entity, const cEntity * a_Vehicle); - void BroadcastBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockBreakAnimation(int a_entityID, int a_blockX, int a_blockY, int a_blockZ, char a_stage, const cClientHandle * a_Exclude = NULL); + void BroadcastBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockBreakAnimation(int a_entityID, int a_blockX, int a_blockY, int a_blockZ, char a_stage, const cClientHandle * a_Exclude = nullptr); void BroadcastBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude); - void BroadcastChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectPickup(const cPickup & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastDestroyEntity(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEffect(const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityHeadLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityMetadata(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMove(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMoveLook(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityStatus(const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityVelocity(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL); - void BroadcastParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = NULL); - void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL); - void BroadcastSpawnEntity(cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); + void BroadcastChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectPickup(const cPickup & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastDestroyEntity(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEffect(const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityHeadLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityMetadata(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMove(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMoveLook(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityStatus(const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityVelocity(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr); + void BroadcastParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = nullptr); + void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = nullptr); + void BroadcastSpawnEntity(cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); void BroadcastUseBed(const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ); /** Sends the block entity, if it is at the coords specified, to a_Client */ @@ -368,7 +368,7 @@ private: /** Always returns an assigned chunkptr, but the chunk needn't be valid (loaded / generated) - callers must check */ cChunkPtr GetChunk( int a_ChunkX, int a_ChunkZ); - /** Returns the specified chunk, or NULL if not created yet */ + /** Returns the specified chunk, or nullptr if not created yet */ cChunk * FindChunk(int a_ChunkX, int a_ChunkZ); int GetX(void) const {return m_LayerX; } @@ -431,10 +431,10 @@ private: typedef std::list cChunkStays; - /** Finds the cChunkLayer object responsible for the specified chunk; returns NULL if not found. Assumes m_CSLayers is locked. */ + /** Finds the cChunkLayer object responsible for the specified chunk; returns nullptr if not found. Assumes m_CSLayers is locked. */ cChunkLayer * FindLayerForChunk(int a_ChunkX, int a_ChunkZ); - /** Returns the specified cChunkLayer object; returns NULL if not found. Assumes m_CSLayers is locked. */ + /** Returns the specified cChunkLayer object; returns nullptr if not found. Assumes m_CSLayers is locked. */ cChunkLayer * FindLayer(int a_LayerX, int a_LayerZ); /** Returns the cChunkLayer object responsible for the specified chunk; creates it if not found. */ diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index a3151eb3f..c94004780 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -35,9 +35,9 @@ void cNotifyChunkSender::Call(int a_ChunkX, int a_ChunkZ) cChunkSender::cChunkSender(void) : super("ChunkSender"), - m_World(NULL), + m_World(nullptr), m_RemoveCount(0), - m_Notify(NULL) + m_Notify(nullptr) { m_Notify.SetChunkSender(this); } @@ -93,7 +93,7 @@ void cChunkSender::ChunkReady(int a_ChunkX, int a_ChunkZ) void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) { - ASSERT(a_Client != NULL); + ASSERT(a_Client != nullptr); { cCSLock Lock(m_CS); if (std::find(m_SendChunks.begin(), m_SendChunks.end(), sSendChunk(a_ChunkX, a_ChunkZ, a_Client)) != m_SendChunks.end()) @@ -161,7 +161,7 @@ void cChunkSender::Execute(void) m_ChunksReady.pop_front(); Lock.Unlock(); - SendChunk(Coords.m_ChunkX, Coords.m_ChunkZ, NULL); + SendChunk(Coords.m_ChunkX, Coords.m_ChunkZ, nullptr); } else { @@ -189,10 +189,10 @@ void cChunkSender::Execute(void) void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); // Ask the client if it still wants the chunk: - if (a_Client != NULL) + if (a_Client != nullptr) { if (!a_Client->WantsSendChunk(a_ChunkX, a_ChunkZ)) { @@ -227,7 +227,7 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien cChunkDataSerializer Data(m_BlockTypes, m_BlockMetas, m_BlockLight, m_BlockSkyLight, m_BiomeMap); // Send: - if (a_Client == NULL) + if (a_Client == nullptr) { m_World->BroadcastChunkData(a_ChunkX, a_ChunkZ, Data); } @@ -239,7 +239,7 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien // Send block-entity packets: for (sBlockCoords::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr) { - if (a_Client == NULL) + if (a_Client == nullptr) { m_World->BroadcastBlockEntity(itr->m_BlockX, itr->m_BlockY, itr->m_BlockZ); } diff --git a/src/ChunkSender.h b/src/ChunkSender.h index a0e9087a9..f17029aea 100644 --- a/src/ChunkSender.h +++ b/src/ChunkSender.h @@ -158,7 +158,7 @@ protected: virtual void Entity (cEntity * a_Entity) override; virtual void BlockEntity (cBlockEntity * a_Entity) override; - /// Sends the specified chunk to a_Client, or to all chunk clients if a_Client == NULL + /// Sends the specified chunk to a_Client, or to all chunk clients if a_Client == nullptr void SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); } ; diff --git a/src/ChunkStay.cpp b/src/ChunkStay.cpp index 38aa89a37..0772787de 100644 --- a/src/ChunkStay.cpp +++ b/src/ChunkStay.cpp @@ -12,7 +12,7 @@ cChunkStay::cChunkStay(void) : - m_ChunkMap(NULL) + m_ChunkMap(nullptr) { } @@ -31,7 +31,7 @@ cChunkStay::~cChunkStay() void cChunkStay::Clear(void) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); m_Chunks.clear(); } @@ -41,7 +41,7 @@ void cChunkStay::Clear(void) void cChunkStay::Add(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); for (cChunkCoordsVector::const_iterator itr = m_Chunks.begin(); itr != m_Chunks.end(); ++itr) { @@ -60,7 +60,7 @@ void cChunkStay::Add(int a_ChunkX, int a_ChunkZ) void cChunkStay::Remove(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); for (cChunkCoordsVector::iterator itr = m_Chunks.begin(); itr != m_Chunks.end(); ++itr) { @@ -79,7 +79,7 @@ void cChunkStay::Remove(int a_ChunkX, int a_ChunkZ) void cChunkStay::Enable(cChunkMap & a_ChunkMap) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); m_OutstandingChunks = m_Chunks; m_ChunkMap = &a_ChunkMap; @@ -92,10 +92,10 @@ void cChunkStay::Enable(cChunkMap & a_ChunkMap) void cChunkStay::Disable(void) { - ASSERT(m_ChunkMap != NULL); + ASSERT(m_ChunkMap != nullptr); cChunkMap * ChunkMap = m_ChunkMap; - m_ChunkMap = NULL; + m_ChunkMap = nullptr; ChunkMap->DelChunkStay(*this); } diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index f15d845ef..a83561838 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -68,7 +68,7 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_ViewDistance(a_ViewDistance), m_IPString(a_Socket->GetIPString()), m_OutgoingData(64 KiB), - m_Player(NULL), + m_Player(nullptr), m_HasSentDC(false), m_LastStreamedChunkX(0x7fffffff), // bogus chunk coords to force streaming upon login m_LastStreamedChunkZ(0x7fffffff), @@ -122,10 +122,10 @@ cClientHandle::~cClientHandle() m_ChunksToSend.clear(); } - if (m_Player != NULL) + if (m_Player != nullptr) { cWorld * World = m_Player->GetWorld(); - if (World != NULL) + if (World != nullptr) { if (!m_Username.empty()) { @@ -137,7 +137,7 @@ cClientHandle::~cClientHandle() m_Player->Destroy(); } delete m_Player; - m_Player = NULL; + m_Player = nullptr; } if (!m_HasSentDC) @@ -149,7 +149,7 @@ cClientHandle::~cClientHandle() cRoot::Get()->GetServer()->RemoveClient(this); delete m_Protocol; - m_Protocol = NULL; + m_Protocol = nullptr; LOGD("ClientHandle at %p deleted", this); } @@ -173,7 +173,7 @@ void cClientHandle::Destroy(void) // DEBUG: LOGD("%s: client %p, \"%s\"", __FUNCTION__, this, m_Username.c_str()); - if ((m_Player != NULL) && (m_Player->GetWorld() != NULL)) + if ((m_Player != nullptr) && (m_Player->GetWorld() != nullptr)) { RemoveFromAllChunks(); m_Player->GetWorld()->RemoveClientFromChunkSender(this); @@ -314,7 +314,7 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID, return; } - ASSERT(m_Player == NULL); + ASSERT(m_Player == nullptr); m_Username = a_Name; @@ -335,7 +335,7 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID, m_Player = new cPlayer(this, GetUsername()); cWorld * World = cRoot::Get()->GetWorld(m_Player->GetLoadedWorldName()); - if (World == NULL) + if (World == nullptr) { World = cRoot::Get()->GetDefaultWorld(); } @@ -412,7 +412,7 @@ void cClientHandle::StreamChunks(void) return; } - ASSERT(m_Player != NULL); + ASSERT(m_Player != nullptr); int ChunkPosX = FAST_FLOOR_DIV((int)m_Player->GetPosX(), cChunkDef::Width); int ChunkPosZ = FAST_FLOOR_DIV((int)m_Player->GetPosZ(), cChunkDef::Width); @@ -427,7 +427,7 @@ void cClientHandle::StreamChunks(void) LOGD("Streaming chunks centered on [%d, %d], view distance %d", ChunkPosX, ChunkPosZ, m_ViewDistance); cWorld * World = m_Player->GetWorld(); - ASSERT(World != NULL); + ASSERT(World != nullptr); // Remove all loaded chunks that are no longer in range; deferred to out-of-CS: cChunkCoordsList RemoveChunks; @@ -513,7 +513,7 @@ void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) } cWorld * World = m_Player->GetWorld(); - ASSERT(World != NULL); + ASSERT(World != nullptr); if (World->AddChunkClient(a_ChunkX, a_ChunkZ, this)) { @@ -534,7 +534,7 @@ void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) void cClientHandle::RemoveFromAllChunks() { cWorld * World = m_Player->GetWorld(); - if (World != NULL) + if (World != nullptr) { World->RemoveClientFromChunks(this); } @@ -650,7 +650,7 @@ void cClientHandle::HandlePlayerAbilities(bool a_CanFly, bool a_IsFlying, float void cClientHandle::HandlePlayerPos(double a_PosX, double a_PosY, double a_PosZ, double a_Stance, bool a_IsOnGround) { - if ((m_Player == NULL) || (m_State != csPlaying)) + if ((m_Player == nullptr) || (m_State != csPlaying)) { // The client hasn't been spawned yet and sends nonsense, we know better return; @@ -784,7 +784,7 @@ void cClientHandle::UnregisterPluginChannels(const AStringVector & a_ChannelList void cClientHandle::HandleBeaconSelection(int a_PrimaryEffect, int a_SecondaryEffect) { cWindow * Window = m_Player->GetWindow(); - if ((Window == NULL) || (Window->GetWindowType() != cWindow::wtBeacon)) + if ((Window == nullptr) || (Window->GetWindowType() != cWindow::wtBeacon)) { return; } @@ -860,7 +860,7 @@ void cClientHandle::HandleCommandBlockEntityChange(int a_EntityID, const AString void cClientHandle::HandleAnvilItemName(const AString & a_ItemName) { - if ((m_Player->GetWindow() == NULL) || (m_Player->GetWindow()->GetWindowType() != cWindow::wtAnvil)) + if ((m_Player->GetWindow() == nullptr) || (m_Player->GetWindow()->GetWindowType() != cWindow::wtAnvil)) { return; } @@ -1497,7 +1497,7 @@ void cClientHandle::HandleChat(const AString & a_Message) void cClientHandle::HandlePlayerLook(float a_Rotation, float a_Pitch, bool a_IsOnGround) { - if ((m_Player == NULL) || (m_State != csPlaying)) + if ((m_Player == nullptr) || (m_State != csPlaying)) { return; } @@ -1597,7 +1597,7 @@ void cClientHandle::HandleWindowClick(char a_WindowID, short a_SlotNum, eClickAc ); cWindow * Window = m_Player->GetWindow(); - if (Window == NULL) + if (Window == nullptr) { LOGWARNING("Player \"%s\" clicked in a non-existent window. Ignoring", m_Username.c_str()); return; @@ -1689,7 +1689,7 @@ void cClientHandle::HandleUseEntity(int a_TargetEntityID, bool a_IsLeftClick) void cClientHandle::HandleRespawn(void) { - if (m_Player == NULL) + if (m_Player == nullptr) { Destroy(); return; @@ -1779,7 +1779,7 @@ void cClientHandle::HandleEntitySprinting(int a_EntityID, bool a_IsSprinting) void cClientHandle::HandleUnmount(void) { - if (m_Player == NULL) + if (m_Player == nullptr) { return; } @@ -1884,8 +1884,8 @@ void cClientHandle::RemoveFromWorld(void) bool cClientHandle::CheckBlockInteractionsRate(void) { - ASSERT(m_Player != NULL); - ASSERT(m_Player->GetWorld() != NULL); + ASSERT(m_Player != nullptr); + ASSERT(m_Player->GetWorld() != nullptr); if (m_NumBlockChangeInteractionsThisTick > MAX_BLOCK_CHANGE_INTERACTIONS) { @@ -1916,7 +1916,7 @@ void cClientHandle::Tick(float a_Dt) Destroy(); } - if (m_Player == NULL) + if (m_Player == nullptr) { return; } @@ -2067,10 +2067,10 @@ void cClientHandle::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSetBlock void cClientHandle::SendChat(const AString & a_Message, eMessageType a_ChatPrefix, const AString & a_AdditionalData) { cWorld * World = GetPlayer()->GetWorld(); - if (World == NULL) + if (World == nullptr) { World = cRoot::Get()->GetWorld(GetPlayer()->GetLoadedWorldName()); - if (World == NULL) + if (World == nullptr) { World = cRoot::Get()->GetDefaultWorld(); } @@ -2095,7 +2095,7 @@ void cClientHandle::SendChat(const cCompositeChat & a_Message) void cClientHandle::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) { - ASSERT(m_Player != NULL); + ASSERT(m_Player != nullptr); // Check chunks being sent, erase them from m_ChunksToSend: bool Found = false; @@ -2926,7 +2926,7 @@ void cClientHandle::HandleEnchantItem(Byte & a_WindowID, Byte & a_Enchantment) } if ( - (m_Player->GetWindow() == NULL) || + (m_Player->GetWindow() == nullptr) || (m_Player->GetWindow()->GetWindowID() != a_WindowID) || (m_Player->GetWindow()->GetWindowType() != cWindow::wtEnchantment) ) diff --git a/src/CraftingRecipes.cpp b/src/CraftingRecipes.cpp index 0828a6c74..64fb21181 100644 --- a/src/CraftingRecipes.cpp +++ b/src/CraftingRecipes.cpp @@ -59,7 +59,7 @@ cCraftingGrid::cCraftingGrid(const cCraftingGrid & a_Original) : cCraftingGrid::~cCraftingGrid() { delete[] m_Items; - m_Items = NULL; + m_Items = nullptr; } @@ -291,7 +291,7 @@ void cCraftingRecipes::GetRecipe(cPlayer & a_Player, cCraftingGrid & a_CraftingG // Built-in recipes: std::auto_ptr Recipe(FindRecipe(a_CraftingGrid.GetItems(), a_CraftingGrid.GetWidth(), a_CraftingGrid.GetHeight())); a_Recipe.Clear(); - if (Recipe.get() == NULL) + if (Recipe.get() == nullptr) { // Allow plugins to intercept a no-recipe-found situation: cRoot::Get()->GetPluginManager()->CallHookCraftingNoRecipe(a_Player, a_CraftingGrid, &a_Recipe); @@ -603,9 +603,9 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipe(const cItem * a_Craftin // Search in the possibly minimized grid, but keep the stride: const cItem * Grid = a_CraftingGrid + GridLeft + (a_GridWidth * GridTop); cRecipe * Recipe = FindRecipeCropped(Grid, GridWidth, GridHeight, a_GridWidth); - if (Recipe == NULL) + if (Recipe == nullptr) { - return NULL; + return nullptr; } // A recipe has been found, move it to correspond to the original crafting grid: @@ -637,7 +637,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipeCropped(const cItem * a_ for (int x = 0; x <= MaxOfsX; x++) for (int y = 0; y <= MaxOfsY; y++) { cRecipe * Recipe = MatchRecipe(a_CraftingGrid, a_GridWidth, a_GridHeight, a_GridStride, *itr, x, y); - if (Recipe != NULL) + if (Recipe != nullptr) { return Recipe; } @@ -645,7 +645,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipeCropped(const cItem * a_ } // for itr - m_Recipes[] // No matching recipe found - return NULL; + return nullptr; } @@ -681,7 +681,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_Crafti ) { // Doesn't match - return NULL; + return nullptr; } HasMatched[itrS->x + a_OffsetX][itrS->y + a_OffsetY] = true; } // for itrS - Recipe->m_Ingredients[] @@ -743,7 +743,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_Crafti } // for x if (!Found) { - return NULL; + return nullptr; } } // for itrS - a_Recipe->m_Ingredients[] @@ -753,7 +753,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_Crafti if (!HasMatched[x][y] && !a_CraftingGrid[x + a_GridStride * y].IsEmpty()) { // There's an unmatched item in the grid - return NULL; + return nullptr; } } // for y, for x diff --git a/src/CraftingRecipes.h b/src/CraftingRecipes.h index 5ebabe098..44444d42e 100644 --- a/src/CraftingRecipes.h +++ b/src/CraftingRecipes.h @@ -157,13 +157,13 @@ protected: /// Moves the recipe to top-left corner, sets its MinWidth / MinHeight void NormalizeIngredients(cRecipe * a_Recipe); - /// Finds a recipe matching the crafting grid. Returns a newly allocated recipe (with all its coords set) or NULL if not found. Caller must delete return value! + /// Finds a recipe matching the crafting grid. Returns a newly allocated recipe (with all its coords set) or nullptr if not found. Caller must delete return value! cRecipe * FindRecipe(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight); /// Same as FindRecipe, but the grid is guaranteed to be of minimal dimensions needed cRecipe * FindRecipeCropped(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight, int a_GridStride); - /// Checks if the grid matches the specified recipe, offset by the specified offsets. Returns a matched cRecipe * if so, or NULL if not matching. Caller must delete the return value! + /// Checks if the grid matches the specified recipe, offset by the specified offsets. Returns a matched cRecipe * if so, or nullptr if not matching. Caller must delete the return value! cRecipe * MatchRecipe(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight, int a_GridStride, const cRecipe * a_Recipe, int a_OffsetX, int a_OffsetY); /** Searches for anything firework related, and does the data setting if appropriate */ diff --git a/src/Defines.h b/src/Defines.h index f1ff911e7..c2f46c241 100644 --- a/src/Defines.h +++ b/src/Defines.h @@ -477,16 +477,16 @@ inline void AddFaceDirection(int & a_BlockX, unsigned char & a_BlockY, int & a_B -#define PI 3.14159265358979323846264338327950288419716939937510582097494459072381640628620899862803482534211706798f + inline void EulerToVector(double a_Pan, double a_Pitch, double & a_X, double & a_Y, double & a_Z) { // a_X = sinf ( a_Pan / 180 * PI) * cosf ( a_Pitch / 180 * PI); // a_Y = -sinf ( a_Pitch / 180 * PI); // a_Z = -cosf ( a_Pan / 180 * PI) * cosf ( a_Pitch / 180 * PI); - a_X = cos(a_Pan / 180 * PI) * cos(a_Pitch / 180 * PI); - a_Y = sin(a_Pan / 180 * PI) * cos(a_Pitch / 180 * PI); - a_Z = sin(a_Pitch / 180 * PI); + a_X = cos(a_Pan / 180 * M_PI) * cos(a_Pitch / 180 * M_PI); + a_Y = sin(a_Pan / 180 * M_PI) * cos(a_Pitch / 180 * M_PI); + a_Z = sin(a_Pitch / 180 * M_PI); } @@ -502,10 +502,10 @@ inline void VectorToEuler(double a_X, double a_Y, double a_Z, double & a_Pan, do } else { - a_Pan = atan2(a_Z, a_X) * 180 / PI - 90; + a_Pan = atan2(a_Z, a_X) * 180 / M_PI - 90; } - a_Pitch = atan2(a_Y, r) * 180 / PI; + a_Pitch = atan2(a_Y, r) * 180 / M_PI; } diff --git a/src/Entities/ArrowEntity.cpp b/src/Entities/ArrowEntity.cpp index 7e429c62e..30f18f677 100644 --- a/src/Entities/ArrowEntity.cpp +++ b/src/Entities/ArrowEntity.cpp @@ -217,7 +217,7 @@ void cArrowEntity::Tick(float a_Dt, cChunk & a_Chunk) int RelPosZ = m_HitBlockPos.z - a_Chunk.GetPosZ() * cChunkDef::Width; cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(RelPosX, RelPosZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Inside an unloaded chunk, abort return; diff --git a/src/Entities/Boat.cpp b/src/Entities/Boat.cpp index 328a70846..953213bca 100644 --- a/src/Entities/Boat.cpp +++ b/src/Entities/Boat.cpp @@ -42,7 +42,7 @@ bool cBoat::DoTakeDamage(TakeDamageInfo & TDI) if (GetHealth() == 0) { - if (TDI.Attacker != NULL) + if (TDI.Attacker != nullptr) { if (TDI.Attacker->IsPlayer()) { @@ -64,7 +64,7 @@ void cBoat::OnRightClicked(cPlayer & a_Player) { super::OnRightClicked(a_Player); - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp index da85dec50..afc61c73f 100644 --- a/src/Entities/Entity.cpp +++ b/src/Entities/Entity.cpp @@ -29,8 +29,8 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d : m_UniqueID(0) , m_Health(1) , m_MaxHealth(1) - , m_AttachedTo(NULL) - , m_Attachee(NULL) + , m_AttachedTo(nullptr) + , m_Attachee(nullptr) , m_bDirtyHead(true) , m_bDirtyOrientation(true) , m_bHasSentNoSpeed(true) @@ -38,9 +38,9 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d , m_Gravity(-9.81f) , m_LastPos(a_X, a_Y, a_Z) , m_IsInitialized(false) - , m_WorldTravellingFrom(NULL) + , m_WorldTravellingFrom(nullptr) , m_EntityType(a_EntityType) - , m_World(NULL) + , m_World(nullptr) , m_IsFireproof(false) , m_TicksSinceLastBurnDamage(0) , m_TicksSinceLastLavaDamage(0) @@ -73,7 +73,7 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d cEntity::~cEntity() { // Before deleting, the entity needs to have been removed from the world, if ever added - ASSERT((m_World == NULL) || !m_World->HasEntity(m_UniqueID)); + ASSERT((m_World == nullptr) || !m_World->HasEntity(m_UniqueID)); /* // DEBUG: @@ -85,11 +85,11 @@ cEntity::~cEntity() ); */ - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { Detach(); } - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { m_Attachee->Detach(); } @@ -242,7 +242,7 @@ void cEntity::TakeDamage(eDamageType a_DamageType, cEntity * a_Attacker, int a_R TDI.FinalDamage = a_FinalDamage; Vector3d Heading(0, 0, 0); - if (a_Attacker != NULL) + if (a_Attacker != nullptr) { Heading = a_Attacker->GetLookVector() * (a_Attacker->IsSprinting() ? 16 : 11); Heading.y = 1.6; @@ -265,7 +265,7 @@ void cEntity::SetYawFromSpeed(void) SetYaw(0); return; } - SetYaw(atan2(m_Speed.x, m_Speed.z) * 180 / PI); + SetYaw(atan2(m_Speed.x, m_Speed.z) * 180 / M_PI); } @@ -282,7 +282,7 @@ void cEntity::SetPitchFromSpeed(void) SetPitch(0); return; } - SetPitch(atan2(m_Speed.y, xz) * 180 / PI); + SetPitch(atan2(m_Speed.y, xz) * 180 / M_PI); } @@ -308,7 +308,7 @@ bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI) return false; } - if ((a_TDI.Attacker != NULL) && (a_TDI.Attacker->IsPlayer())) + if ((a_TDI.Attacker != nullptr) && (a_TDI.Attacker->IsPlayer())) { cPlayer * Player = (cPlayer *)a_TDI.Attacker; @@ -544,7 +544,7 @@ bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI) m_Health = std::max(m_Health, 0); // Add knockback: - if ((IsMob() || IsPlayer()) && (a_TDI.Attacker != NULL)) + if ((IsMob() || IsPlayer()) && (a_TDI.Attacker != nullptr)) { int KnockbackLevel = a_TDI.Attacker->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchKnockback); // More common enchantment if (KnockbackLevel < 1) @@ -571,7 +571,7 @@ bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI) { KilledBy(a_TDI); - if (a_TDI.Attacker != NULL) + if (a_TDI.Attacker != nullptr) { a_TDI.Attacker->Killed(this); } @@ -778,7 +778,7 @@ void cEntity::Tick(float a_Dt, cChunk & a_Chunk) m_InvulnerableTicks--; } - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { Vector3d DeltaPos = m_Pos - m_AttachedTo->GetPosition(); if (DeltaPos.Length() > 0.5) @@ -1092,7 +1092,7 @@ void cEntity::TickBurning(cChunk & a_Chunk) { if (!m_IsFireproof) { - TakeDamage(dtOnFire, NULL, BURN_DAMAGE, 0); + TakeDamage(dtOnFire, nullptr, BURN_DAMAGE, 0); } m_TicksSinceLastBurnDamage = 0; } @@ -1163,7 +1163,7 @@ void cEntity::TickBurning(cChunk & a_Chunk) { if (!m_IsFireproof) { - TakeDamage(dtLavaContact, NULL, LAVA_DAMAGE, 0); + TakeDamage(dtLavaContact, nullptr, LAVA_DAMAGE, 0); } m_TicksSinceLastLavaDamage = 0; } @@ -1184,7 +1184,7 @@ void cEntity::TickBurning(cChunk & a_Chunk) { if (!m_IsFireproof) { - TakeDamage(dtFireContact, NULL, FIRE_DAMAGE, 0); + TakeDamage(dtFireContact, nullptr, FIRE_DAMAGE, 0); } m_TicksSinceLastFireDamage = 0; } @@ -1213,7 +1213,7 @@ void cEntity::TickInVoid(cChunk & a_Chunk) { if (m_TicksSinceLastVoidDamage == 20) { - TakeDamage(dtInVoid, NULL, 2, 0); + TakeDamage(dtInVoid, nullptr, 2, 0); m_TicksSinceLastVoidDamage = 0; } else @@ -1239,7 +1239,7 @@ void cEntity::DetectCacti(void) (((GetPosY() - Y < 1) && (GetWorld()->GetBlock(X, Y, Z) == E_BLOCK_CACTUS)))) ) { - TakeDamage(dtCactusContact, NULL, 1, 0); + TakeDamage(dtCactusContact, nullptr, 1, 0); } } @@ -1380,7 +1380,7 @@ bool cEntity::DetectPortal() bool cEntity::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) { UNUSED(a_ShouldSendRespawn); - ASSERT(a_World != NULL); + ASSERT(a_World != nullptr); if (GetWorld() == a_World) { @@ -1406,7 +1406,7 @@ bool cEntity::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) bool cEntity::MoveToWorld(const AString & a_WorldName, bool a_ShouldSendRespawn) { cWorld * World = cRoot::Get()->GetWorld(a_WorldName); - if (World == NULL) + if (World == nullptr) { LOG("%s: Couldn't find world \"%s\".", __FUNCTION__, a_WorldName.c_str()); return false; @@ -1493,7 +1493,7 @@ void cEntity::HandleAir(void) if (m_AirTickTimer <= 0) { // Damage player - TakeDamage(dtDrowning, NULL, 1, 1, 0); + TakeDamage(dtDrowning, nullptr, 1, 1, 0); // Reset timer m_AirTickTimer = DROWNING_TICKS; } @@ -1708,7 +1708,7 @@ void cEntity::AttachTo(cEntity * a_AttachTo) // Already attached to that entity, nothing to do here return; } - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { // Detach from any previous entity: Detach(); @@ -1726,14 +1726,14 @@ void cEntity::AttachTo(cEntity * a_AttachTo) void cEntity::Detach(void) { - if (m_AttachedTo == NULL) + if (m_AttachedTo == nullptr) { // Attached to no entity, our work is done return; } - m_AttachedTo->m_Attachee = NULL; - m_AttachedTo = NULL; - m_World->BroadcastAttachEntity(*this, NULL); + m_AttachedTo->m_Attachee = nullptr; + m_AttachedTo = nullptr; + m_World->BroadcastAttachEntity(*this, nullptr); } @@ -1956,7 +1956,7 @@ void cEntity::HandleSpeedFromAttachee(float a_Forward, float a_Sideways) void cEntity::SteerVehicle(float a_Forward, float a_Sideways) { - if (m_AttachedTo == NULL) + if (m_AttachedTo == nullptr) { return; } diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h index 451ac3711..af545fe4a 100644 --- a/src/Entities/Entity.h +++ b/src/Entities/Entity.h @@ -32,7 +32,7 @@ #define POSZ_TOINT FloorC(GetPosZ()) #define POS_TOINT Vector3i(POSXTOINT, POSYTOINT, POSZTOINT) -#define GET_AND_VERIFY_CURRENT_CHUNK(ChunkVarName, X, Z) cChunk * ChunkVarName = a_Chunk.GetNeighborChunk(X, Z); if ((ChunkVarName == NULL) || !ChunkVarName->IsValid()) { return; } +#define GET_AND_VERIFY_CURRENT_CHUNK(ChunkVarName, X, Z) cChunk * ChunkVarName = a_Chunk.GetNeighborChunk(X, Z); if ((ChunkVarName == nullptr) || !ChunkVarName->IsValid()) { return; } @@ -84,13 +84,13 @@ public: etFloater, etItemFrame, etPainting, - + // Common variations etMob = etMonster, // DEPRECATED, use etMonster instead! } ; - + // tolua_end - + enum eEntityStatus { // TODO: Investiagate 0, 1, and 5 as Wiki.vg is not certain @@ -127,22 +127,22 @@ public: // Informs client to explode a firework based on its metadata esFireworkExploding = 17, } ; - + static const int FIRE_TICKS_PER_DAMAGE = 10; ///< Ticks to wait between damaging an entity when it stands in fire static const int FIRE_DAMAGE = 1; ///< Damage to deal when standing in fire static const int LAVA_TICKS_PER_DAMAGE = 10; ///< Ticks to wait between damaging an entity when it stands in lava static const int LAVA_DAMAGE = 5; ///< Damage to deal when standing in lava static const int BURN_TICKS_PER_DAMAGE = 20; ///< Ticks to wait between damaging an entity when it is burning static const int BURN_DAMAGE = 1; ///< Damage to deal when the entity is burning - + static const int BURN_TICKS = 200; ///< Ticks to keep an entity burning after it has stood in lava / fire - + static const int MAX_AIR_LEVEL = 300; ///< Maximum air an entity can have static const int DROWNING_TICKS = 20; ///< Number of ticks per heart of damage - + static const int VOID_BOUNDARY = -46; ///< Y position to begin applying void damage static const int FALL_DAMAGE_HEIGHT = 4; ///< Y difference after which fall damage is applied - + cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, double a_Width, double a_Height); virtual ~cEntity(); @@ -151,9 +151,9 @@ public: virtual bool Initialize(cWorld & a_World); // tolua_begin - + eEntityType GetEntityType(void) const { return m_EntityType; } - + bool IsEnderCrystal(void) const { return (m_EntityType == etEnderCrystal); } bool IsPlayer (void) const { return (m_EntityType == etPlayer); } bool IsPickup (void) const { return (m_EntityType == etPickup); } @@ -168,16 +168,16 @@ public: bool IsFloater (void) const { return (m_EntityType == etFloater); } bool IsItemFrame (void) const { return (m_EntityType == etItemFrame); } bool IsPainting (void) const { return (m_EntityType == etPainting); } - + /// Returns true if the entity is of the specified class or a subclass (cPawn's IsA("cEntity") returns true) virtual bool IsA(const char * a_ClassName) const; - + /** Returns the class name of this class */ static const char * GetClassStatic(void); /** Returns the topmost class name for the object */ virtual const char * GetClass(void) const; - + /** Returns the topmost class's parent class name for the object. cEntity returns an empty string (no parent). */ virtual const char * GetParentClass(void) const; @@ -200,9 +200,9 @@ public: double GetSpeedY (void) const { return m_Speed.y; } double GetSpeedZ (void) const { return m_Speed.z; } double GetWidth (void) const { return m_Width; } - - int GetChunkX(void) const {return static_cast(floor(m_Pos.x / cChunkDef::Width)); } - int GetChunkZ(void) const {return static_cast(floor(m_Pos.z / cChunkDef::Width)); } + + int GetChunkX(void) const {return (int)floor(m_Pos.x / cChunkDef::Width); } + int GetChunkZ(void) const {return (int)floor(m_Pos.z / cChunkDef::Width); } void SetHeadYaw (double a_HeadYaw); void SetHeight (double a_Height); @@ -219,21 +219,21 @@ public: /** Sets the speed of the entity, measured in m / sec */ void SetSpeed(double a_SpeedX, double a_SpeedY, double a_SpeedZ); - + /** Sets the speed of the entity, measured in m / sec */ void SetSpeed(const Vector3d & a_Speed) { SetSpeed(a_Speed.x, a_Speed.y, a_Speed.z); } - + /** Sets the speed in the X axis, leaving the other speed components intact. Measured in m / sec. */ void SetSpeedX(double a_SpeedX); - + /** Sets the speed in the Y axis, leaving the other speed components intact. Measured in m / sec. */ void SetSpeedY(double a_SpeedY); - + /** Sets the speed in the Z axis, leaving the other speed components intact. Measured in m / sec. */ void SetSpeedZ(double a_SpeedZ); - + void SetWidth (double a_Width); - + void AddPosX (double a_AddPosX); void AddPosY (double a_AddPosY); void AddPosZ (double a_AddPosZ); @@ -244,7 +244,7 @@ public: void AddSpeedX (double a_AddSpeedX); void AddSpeedY (double a_AddSpeedY); void AddSpeedZ (double a_AddSpeedZ); - + virtual void HandleSpeedFromAttachee(float a_Forward, float a_Sideways); void SteerVehicle(float a_Forward, float a_Sideways); @@ -256,60 +256,60 @@ public: /// Makes this pawn take damage from an attack by a_Attacker. Damage values are calculated automatically and DoTakeDamage() called void TakeDamage(cEntity & a_Attacker); - + /// Makes this entity take the specified damage. The final damage is calculated using current armor, then DoTakeDamage() called void TakeDamage(eDamageType a_DamageType, cEntity * a_Attacker, int a_RawDamage, double a_KnockbackAmount); /// Makes this entity take the specified damage. The values are packed into a TDI, knockback calculated, then sent through DoTakeDamage() void TakeDamage(eDamageType a_DamageType, cEntity * a_Attacker, int a_RawDamage, int a_FinalDamage, double a_KnockbackAmount); - + float GetGravity(void) const { return m_Gravity; } - + void SetGravity(float a_Gravity) { m_Gravity = a_Gravity; } - + /// Sets the rotation to match the speed vector (entity goes "face-forward") void SetYawFromSpeed(void); - + /// Sets the pitch to match the speed vector (entity gies "face-forward") void SetPitchFromSpeed(void); - + // 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 receive any damage. */ virtual bool DoTakeDamage(TakeDamageInfo & a_TDI); - + // tolua_begin /// Returns the hitpoints that this pawn can deal to a_Receiver using its equipped items virtual int GetRawDamageAgainst(const cEntity & a_Receiver); - + /** Returns whether armor will protect against the passed damage type **/ virtual bool ArmorCoversAgainst(eDamageType a_DamageType); - + /// Returns the hitpoints out of a_RawDamage that the currently equipped armor would cover virtual int GetArmorCoverAgainst(const cEntity * a_Attacker, eDamageType a_DamageType, int a_RawDamage); - + /// Returns the knockback amount that the currently equipped items would cause to a_Receiver on a hit virtual double GetKnockbackAmountAgainst(const cEntity & a_Receiver); - + /// Returns the curently equipped weapon; empty item if none virtual cItem GetEquippedWeapon(void) const { return cItem(); } - + /// Returns the currently equipped helmet; empty item if none virtual cItem GetEquippedHelmet(void) const { return cItem(); } - + /// Returns the currently equipped chestplate; empty item if none virtual cItem GetEquippedChestplate(void) const { return cItem(); } /// Returns the currently equipped leggings; empty item if none virtual cItem GetEquippedLeggings(void) const { return cItem(); } - + /// Returns the currently equipped boots; empty item if none virtual cItem GetEquippedBoots(void) const { return cItem(); } - /// Called when the health drops below zero. a_Killer may be NULL (environmental damage) + /// Called when the health drops below zero. a_Killer may be nullptr (environmental damage) virtual void KilledBy(TakeDamageInfo & a_TDI); /// Called when the entity kills another entity @@ -317,20 +317,20 @@ public: /// Heals the specified amount of HPs virtual void Heal(int a_HitPoints); - + /// Returns the health of this entity int GetHealth(void) const { return m_Health; } - + /// Sets the health of this entity; doesn't broadcast any hurt animation void SetHealth(int a_Health); - + // tolua_end virtual void Tick(float a_Dt, cChunk & a_Chunk); - + /// Handles the physics of the entity - updates position based on speed, updates speed based on environment virtual void HandlePhysics(float a_Dt, cChunk & a_Chunk); - + /// Updates the state related to this entity being on fire virtual void TickBurning(cChunk & a_Chunk); @@ -341,34 +341,34 @@ public: Returns true if MoveToWorld() was called, false if not */ virtual bool DetectPortal(void); - + /// Handles when the entity is in the void virtual void TickInVoid(cChunk & a_Chunk); /// Called when the entity starts burning virtual void OnStartedBurning(void); - + /// Called when the entity finishes burning virtual void OnFinishedBurning(void); - + // tolua_begin - + /// Sets the maximum value for the health void SetMaxHealth(int a_MaxHealth); int GetMaxHealth(void) const { return m_MaxHealth; } - + /// Sets whether the entity is fireproof void SetIsFireproof(bool a_IsFireproof); - + bool IsFireproof(void) const { return m_IsFireproof; } - + /// Puts the entity on fire for the specified amount of ticks void StartBurning(int a_TicksLeftBurning); - + /// Stops the entity from burning, resets all burning timers void StopBurning(void); - + // tolua_end /** Descendants override this function to send a command to the specified client to spawn the entity on the client. @@ -377,10 +377,10 @@ public: virtual void SpawnOn(cClientHandle & a_Client) = 0; // tolua_begin - + /// Teleports to the entity specified virtual void TeleportToEntity(cEntity & a_Entity); - + /// Teleports to the coordinates specified virtual void TeleportToCoords(double a_PosX, double a_PosY, double a_PosZ); @@ -389,7 +389,7 @@ public: /** Moves entity to specified world, taking a world name */ bool MoveToWorld(const AString & a_WorldName, bool a_ShouldSendRespawn = true); - + // tolua_end virtual bool DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn); @@ -399,16 +399,16 @@ public: /** Sets the world the entity will be leaving */ void SetWorldTravellingFrom(cWorld * a_World) { m_WorldTravellingFrom = a_World; } - + /// Updates clients of changes in the entity. - virtual void BroadcastMovementUpdate(const cClientHandle * a_Exclude = NULL); - + virtual void BroadcastMovementUpdate(const cClientHandle * a_Exclude = nullptr); + /// Attaches to the specified entity; detaches from any previous one first void AttachTo(cEntity * a_AttachTo); - + /// Detaches from the currently attached entity, if any virtual void Detach(void); - + /// Makes sure head yaw is not over the specified range. void WrapHeadYaw(); @@ -417,9 +417,9 @@ public: /// Makes speed is not over 20. Max speed is 20 blocks / second void WrapSpeed(); - + // tolua_begin - + // COMMON metadata flags; descendants may override the defaults: virtual bool IsOnFire (void) const {return (m_TicksLeftBurning > 0); } virtual bool IsCrouched (void) const {return false; } @@ -437,20 +437,20 @@ public: /** Gets number of ticks this entity has existed for */ long int GetTicksAlive(void) const { return m_TicksAlive; } - + /** 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 - + /// Called when the specified player right-clicks this entity virtual void OnRightClicked(cPlayer & a_Player) {} /// Returns the list of drops for this pawn when it is killed. May check a_Killer for special handling (sword of looting etc.). Called from KilledBy(). - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) { UNUSED(a_Drops); UNUSED(a_Killer); @@ -462,38 +462,38 @@ public: protected: static cCriticalSection m_CSCount; static int m_EntityCount; - + /** Measured in meter/second (m/s) */ Vector3d m_Speed; int m_UniqueID; - + int m_Health; int m_MaxHealth; - - /// The entity to which this entity is attached (vehicle), NULL if none + + /// The entity to which this entity is attached (vehicle), nullptr if none cEntity * m_AttachedTo; - - /// The entity which is attached to this entity (rider), NULL if none + + /// The entity which is attached to this entity (rider), nullptr if none cEntity * m_Attachee; /** 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; @@ -502,37 +502,37 @@ protected: bool m_IsInitialized; /** World entity is travelling from - Set to a valid world pointer by MoveToWorld; reset to NULL when the entity is removed from the old world + Set to a valid world pointer by MoveToWorld; reset to nullptr when the entity is removed from the old world Can't be a simple boolean as context switches between worlds may leave the new chunk processing (and therefore immediately removing) the entity before the old chunk could remove it */ cWorld * m_WorldTravellingFrom; eEntityType m_EntityType; - + cWorld * m_World; - + /// Whether the entity is capable of taking fire or lava damage. bool m_IsFireproof; /// Time, in ticks, since the last damage dealt by being on fire. Valid only if on fire (IsOnFire()) int m_TicksSinceLastBurnDamage; - + /// Time, in ticks, since the last damage dealt by standing in lava. Reset to zero when moving out of lava. int m_TicksSinceLastLavaDamage; - + /// Time, in ticks, since the last damage dealt by standing in fire. Reset to zero when moving out of fire. int m_TicksSinceLastFireDamage; - + /// Time, in ticks, until the entity extinguishes its fire int m_TicksLeftBurning; - + /// Time, in ticks, since the last damage dealt by the void. Reset to zero when moving out of the void. int m_TicksSinceLastVoidDamage; - + /** Does the actual speed-setting. The default implementation just sets the member variable value; overrides can provide further processing, such as forcing players to move at the given speed. */ virtual void DoSetSpeed(double a_SpeedX, double a_SpeedY, double a_SpeedZ); - + virtual void Destroyed(void) {} // Called after the entity has been destroyed /** Applies friction to an entity @@ -543,7 +543,7 @@ protected: /** Called in each tick to handle air-related processing i.e. drowning */ virtual void HandleAir(void); - + /** Called once per tick to set IsSwimming and IsSubmerged */ virtual void SetSwimState(cChunk & a_Chunk); @@ -568,29 +568,29 @@ protected: /** Portal delay timer and cooldown boolean data */ sPortalCooldownData m_PortalCooldownData; - + /** The number of ticks this entity has been alive for */ long int m_TicksAlive; - + private: /** Measured in degrees, [-180, +180) */ double m_HeadYaw; - + /** Measured in degrees, [-180, +180) */ Vector3d m_Rot; - + /** Position of the entity's XZ center and Y bottom */ Vector3d m_Pos; - + /** Measured in meter / second */ Vector3d m_WaterSpeed; - + /** 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. */ double m_Width; - + /** Height of the entity (Y axis) */ double m_Height; @@ -600,3 +600,7 @@ private: } ; // tolua_export typedef std::list cEntityList; + + + + diff --git a/src/Entities/EntityEffect.cpp b/src/Entities/EntityEffect.cpp index b1ddaa30e..bae686b77 100644 --- a/src/Entities/EntityEffect.cpp +++ b/src/Entities/EntityEffect.cpp @@ -216,7 +216,7 @@ cEntityEffect * cEntityEffect::CreateEntityEffect(cEntityEffect::eType a_EffectT } ASSERT(!"Unhandled entity effect type!"); - return NULL; + return nullptr; } @@ -329,7 +329,7 @@ void cEntityEffectInstantHealth::OnActivate(cPawn & a_Target) if (a_Target.IsMob() && ((cMonster &) a_Target).IsUndead()) { - a_Target.TakeDamage(dtPotionOfHarming, NULL, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage + a_Target.TakeDamage(dtPotionOfHarming, nullptr, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage return; } a_Target.Heal(amount); @@ -352,7 +352,7 @@ void cEntityEffectInstantDamage::OnActivate(cPawn & a_Target) a_Target.Heal(amount); return; } - a_Target.TakeDamage(dtPotionOfHarming, NULL, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage + a_Target.TakeDamage(dtPotionOfHarming, nullptr, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage } @@ -452,7 +452,7 @@ void cEntityEffectPoison::OnTick(cPawn & a_Target) // Cannot take poison damage when health is at 1 if (a_Target.GetHealth() > 1) { - a_Target.TakeDamage(dtPoisoning, NULL, 1, 0); + a_Target.TakeDamage(dtPoisoning, nullptr, 1, 0); } } } @@ -473,7 +473,7 @@ void cEntityEffectWither::OnTick(cPawn & a_Target) if ((m_Ticks % frequency) == 0) { - a_Target.TakeDamage(dtWither, NULL, 1, 0); + a_Target.TakeDamage(dtWither, nullptr, 1, 0); } } diff --git a/src/Entities/ExpOrb.cpp b/src/Entities/ExpOrb.cpp index 73d5cbfed..751308661 100644 --- a/src/Entities/ExpOrb.cpp +++ b/src/Entities/ExpOrb.cpp @@ -45,7 +45,7 @@ void cExpOrb::SpawnOn(cClientHandle & a_Client) void cExpOrb::Tick(float a_Dt, cChunk & a_Chunk) { cPlayer * a_ClosestPlayer(m_World->FindClosestPlayer(Vector3f(GetPosition()), 5)); - if (a_ClosestPlayer != NULL) + if (a_ClosestPlayer != nullptr) { Vector3f a_PlayerPos(a_ClosestPlayer->GetPosition()); a_PlayerPos.y++; diff --git a/src/Entities/Floater.cpp b/src/Entities/Floater.cpp index 159429147..5fe6a1238 100644 --- a/src/Entities/Floater.cpp +++ b/src/Entities/Floater.cpp @@ -22,7 +22,7 @@ public: m_Pos(a_Pos), m_NextPos(a_NextPos), m_MinCoeff(1), - m_HitEntity(NULL) + m_HitEntity(nullptr) { } virtual bool Item(cEntity * a_Entity) override diff --git a/src/Entities/ItemFrame.cpp b/src/Entities/ItemFrame.cpp index 6704c05b4..dfffcd3ed 100644 --- a/src/Entities/ItemFrame.cpp +++ b/src/Entities/ItemFrame.cpp @@ -62,7 +62,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI) return; } - if ((a_TDI.Attacker != NULL) && a_TDI.Attacker->IsPlayer() && !((cPlayer *)a_TDI.Attacker)->IsGameModeCreative()) + if ((a_TDI.Attacker != nullptr) && a_TDI.Attacker->IsPlayer() && !((cPlayer *)a_TDI.Attacker)->IsGameModeCreative()) { cItems Item; Item.push_back(m_Item); @@ -83,7 +83,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI) void cItemFrame::GetDrops(cItems & a_Items, cEntity * a_Killer) { - if ((a_Killer != NULL) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) + if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) { a_Items.push_back(cItem(E_ITEM_ITEM_FRAME)); } diff --git a/src/Entities/Minecart.cpp b/src/Entities/Minecart.cpp index f45e7bb69..22e046800 100644 --- a/src/Entities/Minecart.cpp +++ b/src/Entities/Minecart.cpp @@ -36,7 +36,7 @@ public: virtual bool Item(cEntity * a_Entity) override { - ASSERT(a_Entity != NULL); + ASSERT(a_Entity != nullptr); if (!a_Entity->IsPlayer() && !a_Entity->IsMob() && !a_Entity->IsMinecart() && !a_Entity->IsBoat()) { @@ -130,7 +130,7 @@ void cMinecart::HandlePhysics(float a_Dt, cChunk & a_Chunk) int RelPosX = POSX_TOINT - a_Chunk.GetPosX() * cChunkDef::Width; int RelPosZ = POSZ_TOINT - a_Chunk.GetPosZ() * cChunkDef::Width; cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(RelPosX, RelPosZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Inside an unloaded chunk, bail out all processing return; @@ -806,7 +806,7 @@ bool cMinecart::TestBlockCollision(NIBBLETYPE a_RailMeta) bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta) { - cMinecartCollisionCallback MinecartCollisionCallback(GetPosition(), GetHeight(), GetWidth(), GetUniqueID(), ((m_Attachee == NULL) ? -1 : m_Attachee->GetUniqueID())); + cMinecartCollisionCallback MinecartCollisionCallback(GetPosition(), GetHeight(), GetWidth(), GetUniqueID(), ((m_Attachee == nullptr) ? -1 : m_Attachee->GetUniqueID())); int ChunkX, ChunkZ; cChunkDef::BlockToChunk(POSX_TOINT, POSZ_TOINT, ChunkX, ChunkZ); m_World->ForEachEntityInChunk(ChunkX, ChunkZ, MinecartCollisionCallback); @@ -980,7 +980,7 @@ bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta) bool cMinecart::DoTakeDamage(TakeDamageInfo & TDI) { - if ((TDI.Attacker != NULL) && TDI.Attacker->IsPlayer() && ((cPlayer *)TDI.Attacker)->IsGameModeCreative()) + if ((TDI.Attacker != nullptr) && TDI.Attacker->IsPlayer() && ((cPlayer *)TDI.Attacker)->IsGameModeCreative()) { Destroy(); TDI.FinalDamage = GetMaxHealth(); // Instant hit for creative @@ -1074,7 +1074,7 @@ void cRideableMinecart::OnRightClicked(cPlayer & a_Player) { super::OnRightClicked(a_Player); - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { @@ -1120,14 +1120,14 @@ void cMinecartWithChest::OnRightClicked(cPlayer & a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player.GetWindow() != Window) { diff --git a/src/Entities/Minecart.h b/src/Entities/Minecart.h index ab906fd06..40e22c641 100644 --- a/src/Entities/Minecart.h +++ b/src/Entities/Minecart.h @@ -140,9 +140,9 @@ protected: { UNUSED(a_SlotNum); ASSERT(a_Grid == &m_Contents); - if (m_World != NULL) + if (m_World != nullptr) { - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->BroadcastWholeWindow(); } diff --git a/src/Entities/Painting.cpp b/src/Entities/Painting.cpp index e217556c7..1aa6da0a1 100644 --- a/src/Entities/Painting.cpp +++ b/src/Entities/Painting.cpp @@ -43,7 +43,7 @@ void cPainting::Tick(float a_Dt, cChunk & a_Chunk) void cPainting::GetDrops(cItems & a_Items, cEntity * a_Killer) { - if ((a_Killer != NULL) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) + if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) { a_Items.push_back(cItem(E_ITEM_PAINTING)); } diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index 6bd0a3d20..790147fd3 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -56,8 +56,8 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName) : m_Stance(0.0), m_Inventory(*this), m_EnderChestContents(9, 3), - m_CurrentWindow(NULL), - m_InventoryWindow(NULL), + m_CurrentWindow(nullptr), + m_InventoryWindow(nullptr), m_GameMode(eGameMode_NotSet), m_IP(""), m_ClientHandle(a_Client), @@ -78,10 +78,10 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName) : m_IsChargingBow(false), m_BowCharge(0), m_FloaterID(-1), - m_Team(NULL), + m_Team(nullptr), m_TicksUntilNextSave(PLAYER_INVENTORY_SAVE_INTERVAL), m_bIsTeleporting(false), - m_UUID((a_Client != NULL) ? a_Client->GetUUID() : ""), + m_UUID((a_Client != nullptr) ? a_Client->GetUUID() : ""), m_CustomName("") { m_InventoryWindow = new cInventoryWindow(*this); @@ -96,7 +96,7 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName) : m_PlayerName = a_PlayerName; - cWorld * World = NULL; + cWorld * World = nullptr; if (!LoadFromDisk(World)) { m_Inventory.Clear(); @@ -144,10 +144,10 @@ cPlayer::~cPlayer(void) SaveToDisk(); - m_ClientHandle = NULL; + m_ClientHandle = nullptr; delete m_InventoryWindow; - m_InventoryWindow = NULL; + m_InventoryWindow = nullptr; LOGD("Player %p deleted", this); } @@ -186,12 +186,12 @@ void cPlayer::SpawnOn(cClientHandle & a_Client) void cPlayer::Tick(float a_Dt, cChunk & a_Chunk) { - if (m_ClientHandle != NULL) + if (m_ClientHandle != nullptr) { if (m_ClientHandle->IsDestroyed()) { // This should not happen, because destroying a client will remove it from the world, but just in case - m_ClientHandle = NULL; + m_ClientHandle = nullptr; return; } @@ -504,7 +504,7 @@ void cPlayer::SetTouchGround(bool a_bTouchGround) if (Damage > 0) { // cPlayer makes sure damage isn't applied in creative, no need to check here - TakeDamage(dtFalling, NULL, Damage, Damage, 0); + TakeDamage(dtFalling, nullptr, Damage, Damage, 0); // Fall particles GetWorld()->BroadcastSoundParticleEffect(2006, POSX_TOINT, (int)GetPosY() - 1, POSZ_TOINT, Damage /* Used as particle effect speed modifier */); @@ -651,7 +651,7 @@ void cPlayer::AbortEating(void) void cPlayer::SendHealth(void) { - if (m_ClientHandle != NULL) + if (m_ClientHandle != nullptr) { m_ClientHandle->SendHealth(); } @@ -663,7 +663,7 @@ void cPlayer::SendHealth(void) void cPlayer::SendExperience(void) { - if (m_ClientHandle != NULL) + if (m_ClientHandle != nullptr) { m_ClientHandle->SendExperience(); m_bDirtyExperience = false; @@ -859,11 +859,11 @@ bool cPlayer::DoTakeDamage(TakeDamageInfo & a_TDI) } } - if ((a_TDI.Attacker != NULL) && (a_TDI.Attacker->IsPlayer())) + if ((a_TDI.Attacker != nullptr) && (a_TDI.Attacker->IsPlayer())) { cPlayer * Attacker = (cPlayer *)a_TDI.Attacker; - if ((m_Team != NULL) && (m_Team == Attacker->m_Team)) + if ((m_Team != nullptr) && (m_Team == Attacker->m_Team)) { if (!m_Team->AllowsFriendlyFire()) { @@ -915,7 +915,7 @@ void cPlayer::KilledBy(TakeDamageInfo & a_TDI) m_World->SpawnItemPickups(Pickups, GetPosX(), GetPosY(), GetPosZ(), 10); SaveToDisk(); // Save it, yeah the world is a tough place ! - if ((a_TDI.Attacker == NULL) && m_World->ShouldBroadcastDeathMessages()) + if ((a_TDI.Attacker == nullptr) && m_World->ShouldBroadcastDeathMessages()) { AString DamageText; switch (a_TDI.DamageType) @@ -941,7 +941,7 @@ void cPlayer::KilledBy(TakeDamageInfo & a_TDI) } GetWorld()->BroadcastChatDeath(Printf("%s %s", GetName().c_str(), DamageText.c_str())); } - else if (a_TDI.Attacker == NULL) // && !m_World->ShouldBroadcastDeathMessages() by fallthrough + else if (a_TDI.Attacker == nullptr) // && !m_World->ShouldBroadcastDeathMessages() by fallthrough { // no-op } @@ -997,7 +997,7 @@ void cPlayer::Killed(cEntity * a_Victim) void cPlayer::Respawn(void) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_Health = GetMaxHealth(); SetInvulnerableTicks(20); @@ -1107,9 +1107,9 @@ void cPlayer::SetTeam(cTeam * a_Team) cTeam * cPlayer::UpdateTeam(void) { - if (m_World == NULL) + if (m_World == nullptr) { - SetTeam(NULL); + SetTeam(nullptr); } else { @@ -1142,7 +1142,7 @@ void cPlayer::OpenWindow(cWindow * a_Window) void cPlayer::CloseWindow(bool a_CanRefuse) { - if (m_CurrentWindow == NULL) + if (m_CurrentWindow == nullptr) { m_CurrentWindow = m_InventoryWindow; return; @@ -1167,7 +1167,7 @@ void cPlayer::CloseWindow(bool a_CanRefuse) void cPlayer::CloseWindowIfID(char a_WindowID, bool a_CanRefuse) { - if ((m_CurrentWindow == NULL) || (m_CurrentWindow->GetWindowID() != a_WindowID)) + if ((m_CurrentWindow == nullptr) || (m_CurrentWindow->GetWindowID() != a_WindowID)) { return; } @@ -1354,7 +1354,7 @@ void cPlayer::MoveTo( const Vector3d & a_NewPos) // Y = -999 and X, Z = attempting to create speed, usually up to 0.03 // We cannot test m_AttachedTo, because when deattaching, the server thinks the client is already deattached while // the client may still send more of these nonsensical packets. - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { Vector3d AddSpeed(a_NewPos); AddSpeed.y = 0; @@ -1581,7 +1581,7 @@ void cPlayer::TossItems(const cItems & a_Items) bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) { - ASSERT(a_World != NULL); + ASSERT(a_World != nullptr); if (GetWorld() == a_World) { @@ -1590,7 +1590,7 @@ bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) } // Send the respawn packet: - if (a_ShouldSendRespawn && (m_ClientHandle != NULL)) + if (a_ShouldSendRespawn && (m_ClientHandle != nullptr)) { m_ClientHandle->SendRespawn(a_World->GetDimension()); } @@ -1652,7 +1652,7 @@ bool cPlayer::LoadFromDisk(cWorldPtr & a_World) GetName().c_str(), m_UUID.c_str(), OfflineUUID.c_str(), OfflineUsage ); - if (a_World == NULL) + if (a_World == nullptr) { a_World = cRoot::Get()->GetDefaultWorld(); } @@ -1729,7 +1729,7 @@ bool cPlayer::LoadFromFile(const AString & a_FileName, cWorldPtr & a_World) m_LoadedWorldName = root.get("world", "world").asString(); a_World = cRoot::Get()->GetWorld(GetLoadedWorldName(), false); - if (a_World == NULL) + if (a_World == nullptr) { a_World = cRoot::Get()->GetDefaultWorld(); } @@ -1795,7 +1795,7 @@ bool cPlayer::SaveToDisk() root["SpawnY"] = GetLastBedPos().y; root["SpawnZ"] = GetLastBedPos().z; - if (m_World != NULL) + if (m_World != nullptr) { root["world"] = m_World->GetName(); if (m_GameMode == m_World->GetGameMode()) @@ -1949,7 +1949,7 @@ void cPlayer::HandleFood(void) else if ((m_FoodLevel <= 0) && (m_Health > 1)) { // Damage from starving - TakeDamage(dtStarving, NULL, 1, 1, 0); + TakeDamage(dtStarving, nullptr, 1, 1, 0); } } } @@ -2018,7 +2018,7 @@ void cPlayer::UpdateMovementStats(const Vector3d & a_DeltaPos) { StatValue Value = (StatValue)floor(a_DeltaPos.Length() * 100 + 0.5); - if (m_AttachedTo == NULL) + if (m_AttachedTo == nullptr) { if (IsClimbing()) { @@ -2091,7 +2091,7 @@ void cPlayer::ApplyFoodExhaustionFromMovement() } // If riding anything, apply no food exhaustion - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { return; } diff --git a/src/Entities/Player.h b/src/Entities/Player.h index 22d6a2ae2..4bb51b556 100644 --- a/src/Entities/Player.h +++ b/src/Entities/Player.h @@ -176,10 +176,10 @@ public: AString GetIP(void) const { return m_IP; } // tolua_export - /** Returns the associated team, NULL if none */ + /** Returns the associated team, nullptr if none */ cTeam * GetTeam(void) { return m_Team; } // tolua_export - /** Sets the player team, NULL if none */ + /** Sets the player team, nullptr if none */ void SetTeam(cTeam * a_Team); // tolua_end diff --git a/src/Entities/ProjectileEntity.cpp b/src/Entities/ProjectileEntity.cpp index ab25ac30c..1768714f8 100644 --- a/src/Entities/ProjectileEntity.cpp +++ b/src/Entities/ProjectileEntity.cpp @@ -135,7 +135,7 @@ public: m_Pos(a_Pos), m_NextPos(a_NextPos), m_MinCoeff(1), - m_HitEntity(NULL) + m_HitEntity(nullptr) { } @@ -221,9 +221,9 @@ cProjectileEntity::cProjectileEntity(eKind a_Kind, cEntity * a_Creator, double a super(etProjectile, a_X, a_Y, a_Z, a_Width, a_Height), m_ProjectileKind(a_Kind), m_CreatorData( - ((a_Creator != NULL) ? a_Creator->GetUniqueID() : -1), - ((a_Creator != NULL) ? (a_Creator->IsPlayer() ? ((cPlayer *)a_Creator)->GetName() : "") : ""), - ((a_Creator != NULL) ? a_Creator->GetEquippedWeapon().m_Enchantments : cEnchantments()) + ((a_Creator != nullptr) ? a_Creator->GetUniqueID() : -1), + ((a_Creator != nullptr) ? (a_Creator->IsPlayer() ? ((cPlayer *)a_Creator)->GetName() : "") : ""), + ((a_Creator != nullptr) ? a_Creator->GetEquippedWeapon().m_Enchantments : cEnchantments()) ), m_IsInGround(false) { @@ -251,7 +251,7 @@ cProjectileEntity::cProjectileEntity(eKind a_Kind, cEntity * a_Creator, const Ve cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem * a_Item, const Vector3d * a_Speed) { Vector3d Speed; - if (a_Speed != NULL) + if (a_Speed != nullptr) { Speed = *a_Speed; } @@ -269,10 +269,10 @@ cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator, case pkWitherSkull: return new cWitherSkullEntity (a_Creator, a_X, a_Y, a_Z, Speed); case pkFirework: { - ASSERT(a_Item != NULL); + ASSERT(a_Item != nullptr); if (a_Item->m_FireworkItem.m_Colours.empty()) { - return NULL; + return nullptr; } return new cFireworkEntity(a_Creator, a_X, a_Y, a_Z, *a_Item); @@ -280,7 +280,7 @@ cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator, } LOGWARNING("%s: Unknown projectile kind: %d", __FUNCTION__, a_Kind); - return NULL; + return nullptr; } diff --git a/src/Entities/ProjectileEntity.h b/src/Entities/ProjectileEntity.h index b9d2dfa63..2a98e31c7 100644 --- a/src/Entities/ProjectileEntity.h +++ b/src/Entities/ProjectileEntity.h @@ -46,7 +46,7 @@ public: cProjectileEntity(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, double a_Width, double a_Height); cProjectileEntity(eKind a_Kind, cEntity * a_Creator, const Vector3d & a_Pos, const Vector3d & a_Speed, double a_Width, double a_Height); - static cProjectileEntity * Create(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem * a_Item, const Vector3d * a_Speed = NULL); + static cProjectileEntity * Create(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem * a_Item, const Vector3d * a_Speed = nullptr); /** Called by the physics blocktracer when the entity hits a solid block, the hit position and the face hit (BLOCK_FACE_) is given */ virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace); @@ -110,7 +110,7 @@ protected: eKind m_ProjectileKind; /** The structure for containing the entity ID and name who has created this projectile - The ID and/or name may be NULL (e.g. for dispensers/mobs) + The ID and/or name may be nullptr (e.g. for dispensers/mobs) */ CreatorData m_CreatorData; diff --git a/src/FurnaceRecipe.cpp b/src/FurnaceRecipe.cpp index d200ef3d7..9b3b2ecbe 100644 --- a/src/FurnaceRecipe.cpp +++ b/src/FurnaceRecipe.cpp @@ -43,7 +43,7 @@ cFurnaceRecipe::~cFurnaceRecipe() { ClearRecipes(); delete m_pState; - m_pState = NULL; + m_pState = nullptr; } @@ -247,9 +247,9 @@ void cFurnaceRecipe::ClearRecipes(void) { cRecipe Recipe = *itr; delete Recipe.In; - Recipe.In = NULL; + Recipe.In = nullptr; delete Recipe.Out; - Recipe.Out = NULL; + Recipe.Out = nullptr; } m_pState->Recipes.clear(); @@ -257,7 +257,7 @@ void cFurnaceRecipe::ClearRecipes(void) { cFuel Fuel = *itr; delete Fuel.In; - Fuel.In = NULL; + Fuel.In = nullptr; } m_pState->Fuel.clear(); } diff --git a/src/FurnaceRecipe.h b/src/FurnaceRecipe.h index 6a1650695..936ef706d 100644 --- a/src/FurnaceRecipe.h +++ b/src/FurnaceRecipe.h @@ -32,7 +32,7 @@ public: int CookTime; ///< How long this recipe takes to smelt, in ticks }; - /** Returns a recipe for the specified input, NULL if no recipe found */ + /** Returns a recipe for the specified input, nullptr if no recipe found */ const cRecipe * GetRecipeFrom(const cItem & a_Ingredient) const; /** Returns the amount of time that the specified fuel burns, in ticks */ diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index b9face1f8..d86d44bbc 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -69,9 +69,9 @@ cBioGenCache::cBioGenCache(cBiomeGenPtr a_BioGenToCache, int a_CacheSize) : cBioGenCache::~cBioGenCache() { delete[] m_CacheData; - m_CacheData = NULL; + m_CacheData = nullptr; delete[] m_CacheOrder; - m_CacheOrder = NULL; + m_CacheOrder = nullptr; } @@ -928,7 +928,7 @@ cBiomeGenPtr cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & BiomeGenName = "MultiStepMap"; } - cBiomeGen * res = NULL; + cBiomeGen * res = nullptr; a_CacheOffByDefault = false; if (NoCaseCompare(BiomeGenName, "constant") == 0) { diff --git a/src/Generating/ChunkDesc.cpp b/src/Generating/ChunkDesc.cpp index 566332b1f..020d3bd0f 100644 --- a/src/Generating/ChunkDesc.cpp +++ b/src/Generating/ChunkDesc.cpp @@ -530,10 +530,10 @@ cBlockEntity * cChunkDesc::GetBlockEntity(int a_RelX, int a_RelY, int a_RelZ) // The block entity is not created yet, try to create it and add to list: cBlockEntity * be = cBlockEntity::CreateByBlockType(GetBlockType(a_RelX, a_RelY, a_RelZ), GetBlockMeta(a_RelX, a_RelY, a_RelZ), AbsX, a_RelY, AbsZ); - if (be == NULL) + if (be == nullptr) { // No block entity for this block type - return NULL; + return nullptr; } m_BlockEntities.push_back(be); return be; diff --git a/src/Generating/ChunkDesc.h b/src/Generating/ChunkDesc.h index eeea0c957..570132790 100644 --- a/src/Generating/ChunkDesc.h +++ b/src/Generating/ChunkDesc.h @@ -172,7 +172,7 @@ public: /** Returns the block entity at the specified coords. If there is no block entity at those coords, tries to create one, based on the block type - If the blocktype doesn't support a block entity, returns NULL. */ + If the blocktype doesn't support a block entity, returns nullptr. */ cBlockEntity * GetBlockEntity(int a_RelX, int a_RelY, int a_RelZ); /** Updates the heightmap to match the current contents. diff --git a/src/Generating/ChunkGenerator.cpp b/src/Generating/ChunkGenerator.cpp index d615456c1..1eecd6e51 100644 --- a/src/Generating/ChunkGenerator.cpp +++ b/src/Generating/ChunkGenerator.cpp @@ -28,9 +28,9 @@ const unsigned int QUEUE_SKIP_LIMIT = 500; cChunkGenerator::cChunkGenerator(void) : super("cChunkGenerator"), m_Seed(0), // Will be overwritten by the actual generator - m_Generator(NULL), - m_PluginInterface(NULL), - m_ChunkSink(NULL) + m_Generator(nullptr), + m_PluginInterface(nullptr), + m_ChunkSink(nullptr) { } @@ -80,7 +80,7 @@ bool cChunkGenerator::Start(cPluginInterface & a_PluginInterface, cChunkSink & a m_Generator = new cComposableGenerator(*this); } - if (m_Generator == NULL) + if (m_Generator == nullptr) { LOGERROR("Generator could not start, aborting the server"); return false; @@ -103,7 +103,7 @@ void cChunkGenerator::Stop(void) Wait(); delete m_Generator; - m_Generator = NULL; + m_Generator = nullptr; } @@ -144,7 +144,7 @@ void cChunkGenerator::QueueGenerateChunk(int a_ChunkX, int a_ChunkZ, bool a_Forc void cChunkGenerator::GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) { - if (m_Generator != NULL) + if (m_Generator != nullptr) { m_Generator->GenerateBiomes(a_ChunkX, a_ChunkZ, a_BiomeMap); } @@ -180,7 +180,7 @@ int cChunkGenerator::GetQueueLength(void) EMCSBiome cChunkGenerator::GetBiomeAt(int a_BlockX, int a_BlockZ) { - ASSERT(m_Generator != NULL); + ASSERT(m_Generator != nullptr); return m_Generator->GetBiomeAt(a_BlockX, a_BlockZ); } @@ -283,8 +283,8 @@ void cChunkGenerator::Execute(void) void cChunkGenerator::DoGenerate(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_PluginInterface != NULL); - ASSERT(m_ChunkSink != NULL); + ASSERT(m_PluginInterface != nullptr); + ASSERT(m_ChunkSink != nullptr); ASSERT(m_ChunkSink->IsChunkQueued(a_ChunkX, a_ChunkZ)); cChunkDesc ChunkDesc(a_ChunkX, a_ChunkZ); diff --git a/src/Generating/CompoGen.cpp b/src/Generating/CompoGen.cpp index 0105fdb70..2c88f23f1 100644 --- a/src/Generating/CompoGen.cpp +++ b/src/Generating/CompoGen.cpp @@ -687,9 +687,9 @@ cCompoGenCache::cCompoGenCache(cTerrainCompositionGenPtr a_Underlying, int a_Cac cCompoGenCache::~cCompoGenCache() { delete[] m_CacheData; - m_CacheData = NULL; + m_CacheData = nullptr; delete[] m_CacheOrder; - m_CacheOrder = NULL; + m_CacheOrder = nullptr; } diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index b5af4e96a..9a52588d5 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -48,7 +48,7 @@ cTerrainCompositionGenPtr cTerrainCompositionGen::CreateCompositionGen(cIniFile CompoGenName = "Biomal"; } - cTerrainCompositionGen * res = NULL; + cTerrainCompositionGen * res = nullptr; if (NoCaseCompare(CompoGenName, "sameblock") == 0) { res = new cCompoGenSameBlock; @@ -102,7 +102,7 @@ cTerrainCompositionGenPtr cTerrainCompositionGen::CreateCompositionGen(cIniFile a_IniFile.SetValue("Generator", "CompositionGen", "Biomal"); return CreateCompositionGen(a_IniFile, a_BiomeGen, a_HeightGen, a_Seed); } - ASSERT(res != NULL); + ASSERT(res != nullptr); // Read the settings from the ini file: res->InitializeCompoGen(a_IniFile); @@ -145,7 +145,7 @@ void cComposableGenerator::Initialize(cIniFile & a_IniFile) void cComposableGenerator::GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) { - if (m_BiomeGen != NULL) // Quick fix for generator deinitializing before the world storage finishes loading + if (m_BiomeGen != nullptr) // Quick fix for generator deinitializing before the world storage finishes loading { m_BiomeGen->GenBiomes(a_ChunkX, a_ChunkZ, a_BiomeMap); } diff --git a/src/Generating/DungeonRoomsFinisher.cpp b/src/Generating/DungeonRoomsFinisher.cpp index 93fe8b472..3f328868d 100644 --- a/src/Generating/DungeonRoomsFinisher.cpp +++ b/src/Generating/DungeonRoomsFinisher.cpp @@ -198,7 +198,7 @@ protected: } ; cChestEntity * ChestEntity = (cChestEntity *)a_ChunkDesc.GetBlockEntity(RelX, m_FloorHeight + 1, RelZ); - ASSERT((ChestEntity != NULL) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); + ASSERT((ChestEntity != nullptr) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); cNoise Noise(a_ChunkDesc.GetChunkX() ^ a_ChunkDesc.GetChunkZ()); int NumSlots = 3 + ((Noise.IntNoise3DInt(a_Chest.x, a_Chest.y, a_Chest.z) / 11) % 4); int Seed = Noise.IntNoise2DInt(RelX, RelZ); diff --git a/src/Generating/GridStructGen.cpp b/src/Generating/GridStructGen.cpp index 7090f14b1..3c08c1a39 100644 --- a/src/Generating/GridStructGen.cpp +++ b/src/Generating/GridStructGen.cpp @@ -135,7 +135,7 @@ void cGridStructGen::GetStructuresForChunk(int a_ChunkX, int a_ChunkZ, cStructur int OriginX = GridX + ((m_Noise.IntNoise2DInt(GridX + 3, GridZ + 5) / 7) % (m_MaxOffsetX * 2)) - m_MaxOffsetX; int OriginZ = GridZ + ((m_Noise.IntNoise2DInt(GridX + 5, GridZ + 3) / 7) % (m_MaxOffsetZ * 2)) - m_MaxOffsetZ; cStructurePtr Structure = CreateStructure(GridX, GridZ, OriginX, OriginZ); - if (Structure.get() == NULL) + if (Structure.get() == nullptr) { Structure.reset(new cEmptyStructure(GridX, GridZ, OriginX, OriginZ)); } diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index b7d4b337c..acfefaefc 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -29,7 +29,7 @@ cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cB } a_CacheOffByDefault = false; - cTerrainHeightGen * res = NULL; + cTerrainHeightGen * res = nullptr; if (NoCaseCompare(HeightGenName, "flat") == 0) { res = new cHeiGenFlat; @@ -142,9 +142,9 @@ cHeiGenCache::cHeiGenCache(cTerrainHeightGenPtr a_HeiGenToCache, int a_CacheSize cHeiGenCache::~cHeiGenCache() { delete[] m_CacheData; - m_CacheData = NULL; + m_CacheData = nullptr; delete[] m_CacheOrder; - m_CacheOrder = NULL; + m_CacheOrder = nullptr; } diff --git a/src/Generating/MineShafts.cpp b/src/Generating/MineShafts.cpp index 0532aff39..55b3b64dd 100644 --- a/src/Generating/MineShafts.cpp +++ b/src/Generating/MineShafts.cpp @@ -112,7 +112,7 @@ class cMineShaftCorridor : public: /** Creates a new Corridor attached to the specified pivot point and direction. Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit. - May return NULL if cannot fit. + May return nullptr if cannot fit. */ static cMineShaft * CreateAndFit( cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, @@ -165,7 +165,7 @@ class cMineShaftCrossing : public: /** Creates a new Crossing attached to the specified pivot point and direction. Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit. - May return NULL if cannot fit. + May return nullptr if cannot fit. */ static cMineShaft * CreateAndFit( cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, @@ -199,7 +199,7 @@ public: /** Creates a new Staircase attached to the specified pivot point and direction. Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit. - May return NULL if cannot fit. + May return nullptr if cannot fit. */ static cMineShaft * CreateAndFit( cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, @@ -351,7 +351,7 @@ void cStructGenMineShafts::cMineShaftSystem::AppendBranch( return; } - cMineShaft * Next = NULL; + cMineShaft * Next = nullptr; int rnd = (a_Noise.IntNoise3DInt(a_PivotX, a_PivotY + a_RecursionLevel * 16, a_PivotZ) / 13) % m_ProbLevelStaircase; if (rnd < m_ProbLevelCorridor) { @@ -365,7 +365,7 @@ void cStructGenMineShafts::cMineShaftSystem::AppendBranch( { Next = cMineShaftStaircase::CreateAndFit(*this, a_PivotX, a_PivotY, a_PivotZ, a_Direction, a_Noise); } - if (Next == NULL) + if (Next == nullptr) { return; } @@ -552,7 +552,7 @@ cMineShaft * cMineShaftCorridor::CreateAndFit( } if (!a_ParentSystem.CanAppend(BoundingBox)) { - return NULL; + return nullptr; } return new cMineShaftCorridor(a_ParentSystem, BoundingBox, NumSegments, a_Direction, a_Noise); } @@ -796,7 +796,7 @@ void cMineShaftCorridor::PlaceChest(cChunkDesc & a_ChunkDesc) { a_ChunkDesc.SetBlockTypeMeta(x, m_BoundingBox.p1.y + 1, z, E_BLOCK_CHEST, Meta); cChestEntity * ChestEntity = (cChestEntity *)a_ChunkDesc.GetBlockEntity(x, m_BoundingBox.p1.y + 1, z); - ASSERT((ChestEntity != NULL) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); + ASSERT((ChestEntity != nullptr) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); cNoise Noise(a_ChunkDesc.GetChunkX() ^ a_ChunkDesc.GetChunkZ()); int NumSlots = 3 + ((Noise.IntNoise3DInt(x, m_BoundingBox.p1.y, z) / 11) % 4); int Seed = Noise.IntNoise2DInt(x, z); @@ -1006,7 +1006,7 @@ cMineShaft * cMineShaftCrossing::CreateAndFit( } if (!a_ParentSystem.CanAppend(BoundingBox)) { - return NULL; + return nullptr; } return new cMineShaftCrossing(a_ParentSystem, BoundingBox); } @@ -1157,7 +1157,7 @@ cMineShaft * cMineShaftStaircase::CreateAndFit( } if (!a_ParentSystem.CanAppend(Box)) { - return NULL; + return nullptr; } return new cMineShaftStaircase(a_ParentSystem, Box, a_Direction, Slope); } diff --git a/src/Generating/PieceGenerator.cpp b/src/Generating/PieceGenerator.cpp index ae4b6e36c..97aa646fc 100644 --- a/src/Generating/PieceGenerator.cpp +++ b/src/Generating/PieceGenerator.cpp @@ -289,7 +289,7 @@ cPlacedPiece::cPlacedPiece(const cPlacedPiece * a_Parent, const cPiece & a_Piece m_NumCCWRotations(a_NumCCWRotations), m_HasBeenMovedToGround(false) { - m_Depth = (m_Parent == NULL) ? 0 : (m_Parent->GetDepth() + 1); + m_Depth = (m_Parent == nullptr) ? 0 : (m_Parent->GetDepth() + 1); m_HitBox = a_Piece.RotateMoveHitBox(a_NumCCWRotations, a_Coords.x, a_Coords.y, a_Coords.z); m_HitBox.Sort(); } @@ -402,7 +402,7 @@ cPlacedPiece * cPieceGenerator::PlaceStartingPiece(int a_BlockX, int a_BlockY, i } int Rotation = Rotations[rnd % NumRotations]; - cPlacedPiece * res = new cPlacedPiece(NULL, *StartingPiece, Vector3i(a_BlockX, a_BlockY, a_BlockZ), Rotation); + cPlacedPiece * res = new cPlacedPiece(nullptr, *StartingPiece, Vector3i(a_BlockX, a_BlockY, a_BlockZ), Rotation); // Place the piece's connectors into a_OutConnectors: const cPiece::cConnectors & Conn = StartingPiece->GetConnectors(); diff --git a/src/Generating/Prefab.cpp b/src/Generating/Prefab.cpp index 6da3c3d10..761986690 100644 --- a/src/Generating/Prefab.cpp +++ b/src/Generating/Prefab.cpp @@ -328,7 +328,7 @@ void cPrefab::AddConnector(int a_RelX, int a_RelY, int a_RelZ, eBlockFace a_Dire void cPrefab::ParseCharMap(CharMap & a_CharMapOut, const char * a_CharMapDef) { - ASSERT(a_CharMapDef != NULL); + ASSERT(a_CharMapDef != nullptr); // Initialize the charmap to all-invalid values: for (size_t i = 0; i < ARRAYCOUNT(a_CharMapOut); i++) @@ -389,7 +389,7 @@ void cPrefab::ParseBlockImage(const CharMap & a_CharMap, const char * a_BlockIma void cPrefab::ParseConnectors(const char * a_ConnectorsDef) { - ASSERT(a_ConnectorsDef != NULL); + ASSERT(a_ConnectorsDef != nullptr); AStringVector Lines = StringSplitAndTrim(a_ConnectorsDef, "\n"); for (AStringVector::const_iterator itr = Lines.begin(), end = Lines.end(); itr != end; ++itr) @@ -436,7 +436,7 @@ void cPrefab::ParseConnectors(const char * a_ConnectorsDef) void cPrefab::ParseDepthWeight(const char * a_DepthWeightDef) { // The member needn't be defined at all, if so, skip: - if (a_DepthWeightDef == NULL) + if (a_DepthWeightDef == nullptr) { return; } diff --git a/src/Generating/PrefabPiecePool.cpp b/src/Generating/PrefabPiecePool.cpp index 122b9d2af..895555ef8 100644 --- a/src/Generating/PrefabPiecePool.cpp +++ b/src/Generating/PrefabPiecePool.cpp @@ -16,7 +16,7 @@ cPrefabPiecePool::cPrefabPiecePool( ) { AddPieceDefs(a_PieceDefs, a_NumPieceDefs); - if (a_StartingPieceDefs != NULL) + if (a_StartingPieceDefs != nullptr) { AddStartingPieceDefs(a_StartingPieceDefs, a_NumStartingPieceDefs); } @@ -56,7 +56,7 @@ void cPrefabPiecePool::Clear(void) void cPrefabPiecePool::AddPieceDefs(const cPrefab::sDef * a_PieceDefs, size_t a_NumPieceDefs) { - ASSERT(a_PieceDefs != NULL); + ASSERT(a_PieceDefs != nullptr); for (size_t i = 0; i < a_NumPieceDefs; i++) { cPrefab * Prefab = new cPrefab(a_PieceDefs[i]); @@ -71,7 +71,7 @@ void cPrefabPiecePool::AddPieceDefs(const cPrefab::sDef * a_PieceDefs, size_t a_ void cPrefabPiecePool::AddStartingPieceDefs(const cPrefab::sDef * a_StartingPieceDefs, size_t a_NumStartingPieceDefs) { - ASSERT(a_StartingPieceDefs != NULL); + ASSERT(a_StartingPieceDefs != nullptr); for (size_t i = 0; i < a_NumStartingPieceDefs; i++) { cPrefab * Prefab = new cPrefab(a_StartingPieceDefs[i]); diff --git a/src/Generating/VillageGen.cpp b/src/Generating/VillageGen.cpp index 1806fd427..a9b359b6a 100644 --- a/src/Generating/VillageGen.cpp +++ b/src/Generating/VillageGen.cpp @@ -385,7 +385,7 @@ cGridStructGen::cStructurePtr cVillageGen::CreateStructure(int a_GridX, int a_Gr // Check if all the biomes are village-friendly: // If just one is not, no village is created, because it's likely that an unfriendly biome is too close - cVillagePiecePool * VillagePrefabs = NULL; + cVillagePiecePool * VillagePrefabs = nullptr; BLOCKTYPE RoadBlock = E_BLOCK_GRAVEL; BLOCKTYPE WaterRoadBlock = E_BLOCK_PLANKS; int rnd = m_Noise.IntNoise2DInt(a_OriginX, a_OriginZ) / 11; @@ -432,7 +432,7 @@ cGridStructGen::cStructurePtr cVillageGen::CreateStructure(int a_GridX, int a_Gr } // Create a village based on the chosen prefabs: - if (VillagePrefabs == NULL) + if (VillagePrefabs == nullptr) { return cStructurePtr(); } diff --git a/src/HTTPServer/HTTPConnection.cpp b/src/HTTPServer/HTTPConnection.cpp index bf46bb241..d5dbf0199 100644 --- a/src/HTTPServer/HTTPConnection.cpp +++ b/src/HTTPServer/HTTPConnection.cpp @@ -15,7 +15,7 @@ cHTTPConnection::cHTTPConnection(cHTTPServer & a_HTTPServer) : m_HTTPServer(a_HTTPServer), m_State(wcsRecvHeaders), - m_CurrentRequest(NULL), + m_CurrentRequest(nullptr), m_CurrentRequestBodyRemaining(0) { // LOGD("HTTP: New connection at %p", this); @@ -29,7 +29,7 @@ cHTTPConnection::~cHTTPConnection() { // LOGD("HTTP: Connection deleting: %p", this); delete m_CurrentRequest; - m_CurrentRequest = NULL; + m_CurrentRequest = nullptr; } @@ -136,7 +136,7 @@ void cHTTPConnection::AwaitNextRequest(void) void cHTTPConnection::Terminate(void) { - if (m_CurrentRequest != NULL) + if (m_CurrentRequest != nullptr) { m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); } @@ -153,7 +153,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) { case wcsRecvHeaders: { - if (m_CurrentRequest == NULL) + if (m_CurrentRequest == nullptr) { m_CurrentRequest = new cHTTPRequest; } @@ -162,7 +162,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) if (BytesConsumed == AString::npos) { delete m_CurrentRequest; - m_CurrentRequest = NULL; + m_CurrentRequest = nullptr; m_State = wcsInvalid; m_HTTPServer.CloseConnection(*this); return true; @@ -196,7 +196,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) case wcsRecvBody: { - ASSERT(m_CurrentRequest != NULL); + ASSERT(m_CurrentRequest != nullptr); if (m_CurrentRequestBodyRemaining > 0) { size_t BytesToConsume = std::min(m_CurrentRequestBodyRemaining, (size_t)a_Size); @@ -214,7 +214,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) return true; } delete m_CurrentRequest; - m_CurrentRequest = NULL; + m_CurrentRequest = nullptr; } break; } @@ -243,7 +243,7 @@ void cHTTPConnection::GetOutgoingData(AString & a_Data) void cHTTPConnection::SocketClosed(void) { - if (m_CurrentRequest != NULL) + if (m_CurrentRequest != nullptr) { m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); } diff --git a/src/HTTPServer/HTTPConnection.h b/src/HTTPServer/HTTPConnection.h index 6ea8a1ae8..ccbf26466 100644 --- a/src/HTTPServer/HTTPConnection.h +++ b/src/HTTPServer/HTTPConnection.h @@ -31,10 +31,10 @@ public: enum eState { - wcsRecvHeaders, ///< Receiving request headers (m_CurrentRequest is created if NULL) + wcsRecvHeaders, ///< Receiving request headers (m_CurrentRequest is created if nullptr) wcsRecvBody, ///< Receiving request body (m_CurrentRequest is valid) - wcsRecvIdle, ///< Has received the entire body, waiting to send the response (m_CurrentRequest == NULL) - wcsSendingResp, ///< Sending response body (m_CurrentRequest == NULL) + wcsRecvIdle, ///< Has received the entire body, waiting to send the response (m_CurrentRequest == nullptr) + wcsSendingResp, ///< Sending response body (m_CurrentRequest == nullptr) wcsInvalid, ///< The request was malformed, the connection is closing } ; diff --git a/src/HTTPServer/HTTPFormParser.cpp b/src/HTTPServer/HTTPFormParser.cpp index c50c6dcf2..72872078b 100644 --- a/src/HTTPServer/HTTPFormParser.cpp +++ b/src/HTTPServer/HTTPFormParser.cpp @@ -86,7 +86,7 @@ void cHTTPFormParser::Parse(const char * a_Data, size_t a_Size) } case fpkMultipart: { - ASSERT(m_MultipartParser.get() != NULL); + ASSERT(m_MultipartParser.get() != nullptr); m_MultipartParser->Parse(a_Data, a_Size); break; } @@ -145,7 +145,7 @@ bool cHTTPFormParser::HasFormData(const cHTTPRequest & a_Request) void cHTTPFormParser::BeginMultipart(const cHTTPRequest & a_Request) { - ASSERT(m_MultipartParser.get() == NULL); + ASSERT(m_MultipartParser.get() == nullptr); m_MultipartParser.reset(new cMultipartParser(a_Request.GetContentType(), *this)); } diff --git a/src/HTTPServer/HTTPMessage.cpp b/src/HTTPServer/HTTPMessage.cpp index 65d73fd87..f6c0204ae 100644 --- a/src/HTTPServer/HTTPMessage.cpp +++ b/src/HTTPServer/HTTPMessage.cpp @@ -70,7 +70,7 @@ cHTTPRequest::cHTTPRequest(void) : super(mkRequest), m_EnvelopeParser(*this), m_IsValid(true), - m_UserData(NULL), + m_UserData(nullptr), m_HasAuth(false), m_AllowKeepAlive(false) { diff --git a/src/HTTPServer/HTTPServer.cpp b/src/HTTPServer/HTTPServer.cpp index 0c41b54b2..9ab030a1f 100644 --- a/src/HTTPServer/HTTPServer.cpp +++ b/src/HTTPServer/HTTPServer.cpp @@ -44,7 +44,7 @@ class cDebugCallbacks : UNUSED(a_Connection); cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData()); - if (FormParser != NULL) + if (FormParser != nullptr) { FormParser->Parse(a_Data, a_Size); } @@ -54,7 +54,7 @@ class cDebugCallbacks : virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override { cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData()); - if (FormParser != NULL) + if (FormParser != nullptr) { if (FormParser->Finish()) { @@ -124,7 +124,7 @@ class cDebugCallbacks : cHTTPServer::cHTTPServer(void) : m_ListenThreadIPv4(*this, cSocket::IPv4, "WebServer"), m_ListenThreadIPv6(*this, cSocket::IPv6, "WebServer"), - m_Callbacks(NULL) + m_Callbacks(nullptr) { } @@ -168,7 +168,7 @@ bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_Port } // Notify the admin about the HTTPS / HTTP status - if (m_Cert.get() == NULL) + if (m_Cert.get() == nullptr) { LOGWARNING("WebServer: The server is running in unsecured HTTP mode."); LOGINFO("Put a valid HTTPS certificate in file 'webadmin/httpscert.crt' and its corresponding private key to 'webadmin/httpskey.pem' (without any password) to enable HTTPS support"); @@ -235,7 +235,7 @@ void cHTTPServer::Stop(void) void cHTTPServer::OnConnectionAccepted(cSocket & a_Socket) { cHTTPConnection * Connection; - if (m_Cert.get() != NULL) + if (m_Cert.get() != nullptr) { Connection = new cSslHTTPConnection(*this, m_Cert, m_CertPrivKey); } diff --git a/src/Inventory.cpp b/src/Inventory.cpp index 832a079bc..51ac32da9 100644 --- a/src/Inventory.cpp +++ b/src/Inventory.cpp @@ -220,7 +220,7 @@ void cInventory::SetSlot(int a_SlotNum, const cItem & a_Item) int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { LOGWARNING("%s(%d): requesting an invalid itemgrid. Ignoring.", __FUNCTION__, a_SlotNum); return; @@ -278,7 +278,7 @@ const cItem & cInventory::GetSlot(int a_SlotNum) const } int GridSlotNum = 0; const cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { // Something went wrong, but we don't know what. We must return a value, so return the first inventory slot LOGWARNING("%s(%d): requesting an invalid ItemGrid, returning the first inventory slot instead.", __FUNCTION__, a_SlotNum); @@ -372,7 +372,7 @@ int cInventory::ChangeSlotCount(int a_SlotNum, int a_AddToCount) { int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { LOGWARNING("%s: invalid slot number, expected 0 .. %d, got %d; ignoring", __FUNCTION__, invNumSlots, a_SlotNum); return -1; @@ -398,7 +398,7 @@ bool cInventory::DamageItem(int a_SlotNum, short a_Amount) int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { LOGWARNING("%s(%d, %d): requesting an invalid grid, ignoring.", __FUNCTION__, a_SlotNum, a_Amount); return false; @@ -640,7 +640,7 @@ bool cInventory::LoadFromJson(Json::Value & a_Value) int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(SlotIdx - 5, GridSlotNum); - ASSERT(Grid != NULL); + ASSERT(Grid != nullptr); Grid->SetSlot(GridSlotNum, Item); } // for itr - a_Value[] return true; @@ -708,7 +708,7 @@ void cInventory::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) // Armor update needs broadcast to other players: cWorld * World = m_Owner.GetWorld(); - if ((a_ItemGrid == &m_ArmorSlots) && (World != NULL)) + if ((a_ItemGrid == &m_ArmorSlots) && (World != nullptr)) { World->BroadcastEntityEquipment( m_Owner, ArmorSlotNumToEntityEquipmentID(a_SlotNum), diff --git a/src/Inventory.h b/src/Inventory.h index 5628fb0da..4e76bc0d3 100644 --- a/src/Inventory.h +++ b/src/Inventory.h @@ -179,10 +179,10 @@ protected: cPlayer & m_Owner; - /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return NULL for invalid SlotNum */ + /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return nullptr for invalid SlotNum */ const cItemGrid * GetGridForSlotNum(int a_SlotNum, int & a_GridSlotNum) const; - /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return NULL for invalid SlotNum */ + /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return nullptr for invalid SlotNum */ cItemGrid * GetGridForSlotNum(int a_SlotNum, int & a_GridSlotNum); // cItemGrid::cListener override: diff --git a/src/Item.cpp b/src/Item.cpp index ebdf99ca5..36c444328 100644 --- a/src/Item.cpp +++ b/src/Item.cpp @@ -391,7 +391,7 @@ cItem * cItems::Get(int a_Idx) if ((a_Idx < 0) || (a_Idx >= (int)size())) { LOGWARNING("cItems: Attempt to get an out-of-bounds item at index %d; there are currently " SIZE_T_FMT " items. Returning a nil.", a_Idx, size()); - return NULL; + return nullptr; } return &at(a_Idx); } diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 1977216d8..55fb36a17 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -28,7 +28,7 @@ cItemGrid::cItemGrid(int a_Width, int a_Height) : cItemGrid::~cItemGrid() { delete[] m_Slots; - m_Slots = NULL; + m_Slots = nullptr; } diff --git a/src/Items/ItemBow.h b/src/Items/ItemBow.h index f29cc5d59..cf2fe9ad2 100644 --- a/src/Items/ItemBow.h +++ b/src/Items/ItemBow.h @@ -29,7 +29,7 @@ public: virtual bool OnItemUse(cWorld * a_World, cPlayer * a_Player, const cItem & a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Dir) override { - ASSERT(a_Player != NULL); + ASSERT(a_Player != nullptr); // Check if the player has an arrow in the inventory, or is in Creative: if (!(a_Player->IsGameModeCreative() || a_Player->GetInventory().HasItems(cItem(E_ITEM_ARROW)))) @@ -45,7 +45,7 @@ public: virtual void OnItemShoot(cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace) override { // Actual shot - produce the arrow with speed based on the ticks that the bow was charged - ASSERT(a_Player != NULL); + ASSERT(a_Player != nullptr); int BowCharge = a_Player->FinishChargingBow(); double Force = (double)BowCharge / 20.0; @@ -65,14 +65,14 @@ public: // Create the arrow entity: cArrowEntity * Arrow = new cArrowEntity(*a_Player, Force * 2); - if (Arrow == NULL) + if (Arrow == nullptr) { return; } if (!Arrow->Initialize(*a_Player->GetWorld())) { delete Arrow; - Arrow = NULL; + Arrow = nullptr; return; } a_Player->GetWorld()->BroadcastSoundEffect("random.bow", a_Player->GetPosX(), a_Player->GetPosY(), a_Player->GetPosZ(), 0.5, (float)Force); diff --git a/src/Items/ItemEmptyMap.h b/src/Items/ItemEmptyMap.h index 953673382..9238d771b 100644 --- a/src/Items/ItemEmptyMap.h +++ b/src/Items/ItemEmptyMap.h @@ -50,7 +50,7 @@ public: return true; } - if (NewMap == NULL) + if (NewMap == nullptr) { return true; } diff --git a/src/Items/ItemHandler.cpp b/src/Items/ItemHandler.cpp index f1f1ddcc5..9272a723d 100644 --- a/src/Items/ItemHandler.cpp +++ b/src/Items/ItemHandler.cpp @@ -83,7 +83,7 @@ cItemHandler * cItemHandler::GetItemHandler(int a_ItemType) memset(m_ItemHandler, 0, sizeof(m_ItemHandler)); m_HandlerInitialized = true; } - if (m_ItemHandler[a_ItemType] == NULL) + if (m_ItemHandler[a_ItemType] == nullptr) { m_ItemHandler[a_ItemType] = CreateItemHandler(a_ItemType); } @@ -278,7 +278,7 @@ void cItemHandler::Deinit() for (int i = 0; i < 2267; i++) { delete m_ItemHandler[i]; - m_ItemHandler[i] = NULL; + m_ItemHandler[i] = nullptr; } memset(m_ItemHandler, 0, sizeof(m_ItemHandler)); // Don't leave any dangling pointers around, just in case m_HandlerInitialized = false; diff --git a/src/Items/ItemItemFrame.h b/src/Items/ItemItemFrame.h index 87e20ecf0..5d22c1cb8 100644 --- a/src/Items/ItemItemFrame.h +++ b/src/Items/ItemItemFrame.h @@ -37,7 +37,7 @@ public: if (!ItemFrame->Initialize(*a_World)) { delete ItemFrame; - ItemFrame = NULL; + ItemFrame = nullptr; return false; } diff --git a/src/Items/ItemMap.h b/src/Items/ItemMap.h index 056fe0fe7..2dbbb3dc0 100644 --- a/src/Items/ItemMap.h +++ b/src/Items/ItemMap.h @@ -31,7 +31,7 @@ public: { cMap * Map = a_World->GetMapManager().GetMapData((unsigned)a_Item.m_ItemDamage); - if (Map == NULL) + if (Map == nullptr) { return; } diff --git a/src/Items/ItemMinecart.h b/src/Items/ItemMinecart.h index 63038de51..ed0a4711c 100644 --- a/src/Items/ItemMinecart.h +++ b/src/Items/ItemMinecart.h @@ -56,7 +56,7 @@ public: double x = (double)a_BlockX + 0.5; double y = (double)a_BlockY + 0.5; double z = (double)a_BlockZ + 0.5; - cMinecart * Minecart = NULL; + cMinecart * Minecart = nullptr; switch (m_ItemType) { case E_ITEM_MINECART: Minecart = new cRideableMinecart (x, y, z, cItem(), 1); break; diff --git a/src/LeakFinder.h b/src/LeakFinder.h index e63b9ec5d..ceaa53782 100644 --- a/src/LeakFinder.h +++ b/src/LeakFinder.h @@ -68,7 +68,7 @@ public: LeakFinderShowCompleteCallstack = 0x1000 } LeakFinderOptions; - LeakFinderOutput(int options = OptionsAll, LPCSTR szSymPath = NULL); + LeakFinderOutput(int options = OptionsAll, LPCSTR szSymPath = nullptr); virtual void OnLeakSearchStart(LPCSTR sszLeakFinderName); virtual void OnLeakStartEntry(LPCSTR szKeyName, SIZE_T nDataSize); protected: @@ -110,7 +110,7 @@ class ZZZ_LeakFinder public: ZZZ_LeakFinder() { - m_pXml = NULL; + m_pXml = nullptr; #ifdef XML_LEAK_FINDER m_pXml = new LeakFinderXmlOutput(); #endif @@ -119,7 +119,7 @@ public: ~ZZZ_LeakFinder() { DeinitLeakFinder(m_pXml); - if (m_pXml != NULL) delete m_pXml; + if (m_pXml != nullptr) delete m_pXml; } protected: LeakFinderXmlOutput *m_pXml; @@ -148,7 +148,7 @@ ZZZ_LeakFinder zzz_LeakFinder; -extern void DumpUsedMemory(LeakFinderOutput * output = NULL); +extern void DumpUsedMemory(LeakFinderOutput * output = nullptr); diff --git a/src/LightingThread.cpp b/src/LightingThread.cpp index 652b03e46..ae5e746e7 100644 --- a/src/LightingThread.cpp +++ b/src/LightingThread.cpp @@ -91,7 +91,7 @@ public: cLightingThread::cLightingThread(void) : super("cLightingThread"), - m_World(NULL), + m_World(nullptr), m_MaxHeight(0), m_NumSeeds(0) { @@ -112,7 +112,7 @@ cLightingThread::~cLightingThread() bool cLightingThread::Start(cWorld * a_World) { - ASSERT(m_World == NULL); // Not started yet + ASSERT(m_World == nullptr); // Not started yet m_World = a_World; return super::Start(); @@ -151,7 +151,7 @@ void cLightingThread::Stop(void) void cLightingThread::QueueChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_CallbackAfter) { - ASSERT(m_World != NULL); // Did you call Start() properly? + ASSERT(m_World != nullptr); // Did you call Start() properly? cChunkStay * ChunkStay = new cLightingChunkStay(*this, a_ChunkX, a_ChunkZ, a_CallbackAfter); { @@ -310,7 +310,7 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item) m_World->ChunkLighted(a_Item.m_ChunkX, a_Item.m_ChunkZ, BlockLight, SkyLight); - if (a_Item.m_CallbackAfter != NULL) + if (a_Item.m_CallbackAfter != nullptr) { a_Item.m_CallbackAfter->Call(a_Item.m_ChunkX, a_Item.m_ChunkZ); } diff --git a/src/LightingThread.h b/src/LightingThread.h index f71d2cf1a..87eb9c6d8 100644 --- a/src/LightingThread.h +++ b/src/LightingThread.h @@ -61,7 +61,7 @@ public: void Stop(void); /** Queues the entire chunk for lighting */ - void QueueChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_CallbackAfter = NULL); + void QueueChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_CallbackAfter = nullptr); /** Blocks until the queue is empty or the thread is terminated */ void WaitForQueueEmpty(void); diff --git a/src/LineBlockTracer.cpp b/src/LineBlockTracer.cpp index 1b42081c2..90f97cd23 100644 --- a/src/LineBlockTracer.cpp +++ b/src/LineBlockTracer.cpp @@ -198,7 +198,7 @@ bool cLineBlockTracer::Item(cChunk * a_Chunk) for (;;) { // Report the current block through the callbacks: - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { m_Callbacks->OnNoChunk(); return false; @@ -228,7 +228,7 @@ bool cLineBlockTracer::Item(cChunk * a_Chunk) // Update the current chunk a_Chunk = a_Chunk->GetNeighborChunk(m_CurrentX, m_CurrentZ); - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { m_Callbacks->OnNoChunk(); return false; diff --git a/src/LinearUpscale.h b/src/LinearUpscale.h index a49f4bdf9..1b0fbd89a 100644 --- a/src/LinearUpscale.h +++ b/src/LinearUpscale.h @@ -95,8 +95,8 @@ template void LinearUpscale2DArray( const int MAX_UPSCALE_X = 128; const int MAX_UPSCALE_Y = 128; - ASSERT(a_Src != NULL); - ASSERT(a_Dst != NULL); + ASSERT(a_Src != nullptr); + ASSERT(a_Dst != nullptr); ASSERT(a_SrcSizeX > 0); ASSERT(a_SrcSizeY > 0); ASSERT(a_UpscaleX > 0); @@ -166,8 +166,8 @@ template void LinearUpscale3DArray( const int MAX_UPSCALE_Y = 128; const int MAX_UPSCALE_Z = 128; - ASSERT(a_Src != NULL); - ASSERT(a_Dst != NULL); + ASSERT(a_Src != nullptr); + ASSERT(a_Dst != nullptr); ASSERT(a_SrcSizeX > 0); ASSERT(a_SrcSizeY > 0); ASSERT(a_SrcSizeZ > 0); diff --git a/src/LoggerListeners.cpp b/src/LoggerListeners.cpp index 77e2aaf67..5c7097956 100644 --- a/src/LoggerListeners.cpp +++ b/src/LoggerListeners.cpp @@ -280,7 +280,7 @@ cFileListener::cFileListener(void) { cFile::CreateFolder(FILE_IO_PREFIX + AString("logs")); AString FileName; - FileName = Printf("%s%sLOG_%d.txt", FILE_IO_PREFIX, "logs/", (int)time(NULL)); + FileName = Printf("%s%sLOG_%d.txt", FILE_IO_PREFIX, "logs/", (int)time(nullptr)); m_File.Open(FileName, cFile::fmAppend); } diff --git a/src/Map.cpp b/src/Map.cpp index c106ccd83..fbde00cf7 100644 --- a/src/Map.cpp +++ b/src/Map.cpp @@ -21,7 +21,7 @@ cMapDecorator::cMapDecorator(cMap * a_Map, eType a_Type, int a_X, int a_Z, int a , m_PixelX(a_X) , m_PixelZ(a_Z) , m_Rot(a_Rot) - , m_Player(NULL) + , m_Player(nullptr) { } @@ -43,9 +43,9 @@ cMapDecorator::cMapDecorator(cMap * a_Map, cPlayer * a_Player) void cMapDecorator::Update(void) { - if (m_Player != NULL) + if (m_Player != nullptr) { - ASSERT(m_Map != NULL); + ASSERT(m_Map != nullptr); unsigned int PixelWidth = m_Map->GetPixelWidth(); int InsideWidth = (m_Map->GetWidth() / 2) - 1; @@ -221,7 +221,7 @@ bool cMap::UpdatePixel(unsigned int a_X, unsigned int a_Z) virtual bool Item(cChunk * a_Chunk) override { - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { return false; } @@ -322,7 +322,7 @@ bool cMap::UpdatePixel(unsigned int a_X, unsigned int a_Z) } } CalculatePixelCb(this, RelX, RelZ); - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->DoWithChunk(ChunkX, ChunkZ, CalculatePixelCb); SetPixel(a_X, a_Z, CalculatePixelCb.GetPixelData()); @@ -349,7 +349,7 @@ void cMap::UpdateDecorators(void) void cMap::AddPlayer(cPlayer * a_Player, Int64 a_WorldAge) { cClientHandle * Handle = a_Player->GetClientHandle(); - if (Handle == NULL) + if (Handle == nullptr) { return; } @@ -454,10 +454,10 @@ void cMap::StreamNext(cMapClient & a_Client) void cMap::UpdateClient(cPlayer * a_Player) { - ASSERT(a_Player != NULL); + ASSERT(a_Player != nullptr); cClientHandle * Handle = a_Player->GetClientHandle(); - if (Handle == NULL) + if (Handle == nullptr) { return; } @@ -498,7 +498,7 @@ void cMap::EraseData(void) eDimension cMap::GetDimension(void) const { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); return m_World->GetDimension(); } diff --git a/src/MapManager.cpp b/src/MapManager.cpp index e7df75118..2a3ab192b 100644 --- a/src/MapManager.cpp +++ b/src/MapManager.cpp @@ -15,7 +15,7 @@ cMapManager::cMapManager(cWorld * a_World) : m_World(a_World) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); } @@ -27,7 +27,7 @@ bool cMapManager::DoWithMap(int a_ID, cMapCallback & a_Callback) cCSLock Lock(m_CS); cMap * Map = GetMapData(a_ID); - if (Map == NULL) + if (Map == nullptr) { return false; } @@ -68,7 +68,7 @@ cMap * cMapManager::GetMapData(unsigned int a_ID) } else { - return NULL; + return nullptr; } } @@ -83,7 +83,7 @@ cMap * cMapManager::CreateMap(int a_CenterX, int a_CenterY, int a_Scale) if (m_MapData.size() >= 65536) { LOGWARN("Could not craft map - Too many maps in use"); - return NULL; + return nullptr; } cMap Map((unsigned)m_MapData.size(), a_CenterX, a_CenterY, m_World, a_Scale); diff --git a/src/MapManager.h b/src/MapManager.h index a40ec2630..2cc6a7bce 100644 --- a/src/MapManager.h +++ b/src/MapManager.h @@ -31,12 +31,12 @@ public: cMapManager(cWorld * a_World); - /** Returns the map with the specified ID, NULL if out of range. + /** Returns the map with the specified ID, nullptr if out of range. WARNING: The returned map object is not thread safe. */ cMap * GetMapData(unsigned int a_ID); - /** Creates a new map. Returns NULL on error */ + /** Creates a new map. Returns nullptr on error */ cMap * CreateMap(int a_CenterX, int a_CenterY, int a_Scale = 3); /** Calls the callback for the map with the specified ID. diff --git a/src/MobSpawner.cpp b/src/MobSpawner.cpp index ea3fe8c72..e461fae4c 100644 --- a/src/MobSpawner.cpp +++ b/src/MobSpawner.cpp @@ -301,7 +301,7 @@ bool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_R cMonster* cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int& a_MaxPackSize) { - cMonster* toReturn = NULL; + cMonster* toReturn = nullptr; if (m_NewPack) { m_MobType = ChooseMobType(a_Biome); diff --git a/src/Mobs/AggressiveMonster.cpp b/src/Mobs/AggressiveMonster.cpp index be2f71f7a..41ef26e2a 100644 --- a/src/Mobs/AggressiveMonster.cpp +++ b/src/Mobs/AggressiveMonster.cpp @@ -26,7 +26,7 @@ void cAggressiveMonster::InStateChasing(float a_Dt) { super::InStateChasing(a_Dt); - if (m_Target != NULL) + if (m_Target != nullptr) { if (m_Target->IsPlayer()) { @@ -74,7 +74,7 @@ void cAggressiveMonster::Tick(float a_Dt, cChunk & a_Chunk) CheckEventSeePlayer(); } - if (m_Target == NULL) + if (m_Target == nullptr) return; cTracer LineOfSight(GetWorld()); @@ -95,7 +95,7 @@ void cAggressiveMonster::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if ((m_Target == NULL) || (m_AttackInterval < 3.0)) + if ((m_Target == nullptr) || (m_AttackInterval < 3.0)) { return; } diff --git a/src/Mobs/Blaze.cpp b/src/Mobs/Blaze.cpp index b4104d530..16869c79d 100644 --- a/src/Mobs/Blaze.cpp +++ b/src/Mobs/Blaze.cpp @@ -19,7 +19,7 @@ cBlaze::cBlaze(void) : void cBlaze::GetDrops(cItems & a_Drops, cEntity * a_Killer) { - if ((a_Killer != NULL) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) + if ((a_Killer != nullptr) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) { int LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); AddRandomDropItem(a_Drops, 0, 1 + LootingLevel, E_ITEM_BLAZE_ROD); @@ -34,20 +34,20 @@ void cBlaze::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if (m_Target != NULL && m_AttackInterval > 3.0) + if (m_Target != nullptr && m_AttackInterval > 3.0) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cFireChargeEntity * FireCharge = new cFireChargeEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); - if (FireCharge == NULL) + if (FireCharge == nullptr) { return; } if (!FireCharge->Initialize(*m_World)) { delete FireCharge; - FireCharge = NULL; + FireCharge = nullptr; return; } m_World->BroadcastSpawnEntity(*FireCharge); diff --git a/src/Mobs/Blaze.h b/src/Mobs/Blaze.h index f283b1070..e2a4ad9f1 100644 --- a/src/Mobs/Blaze.h +++ b/src/Mobs/Blaze.h @@ -17,6 +17,6 @@ public: CLASS_PROTODEF(cBlaze) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Attack(float a_Dt) override; } ; diff --git a/src/Mobs/CaveSpider.cpp b/src/Mobs/CaveSpider.cpp index 118a6e93b..045b47e73 100644 --- a/src/Mobs/CaveSpider.cpp +++ b/src/Mobs/CaveSpider.cpp @@ -45,12 +45,12 @@ void cCaveSpider::Attack(float a_Dt) void cCaveSpider::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } AddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_STRING); - if ((a_Killer != NULL) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) + if ((a_Killer != nullptr) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) { AddRandomUncommonDropItem(a_Drops, 33.0f, E_ITEM_SPIDER_EYE); } diff --git a/src/Mobs/CaveSpider.h b/src/Mobs/CaveSpider.h index f9ed10e1b..494ba1360 100644 --- a/src/Mobs/CaveSpider.h +++ b/src/Mobs/CaveSpider.h @@ -18,7 +18,7 @@ public: virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual void Attack(float a_Dt) override; - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Chicken.cpp b/src/Mobs/Chicken.cpp index f7e44238f..634867cfa 100644 --- a/src/Mobs/Chicken.cpp +++ b/src/Mobs/Chicken.cpp @@ -49,7 +49,7 @@ void cChicken::Tick(float a_Dt, cChunk & a_Chunk) void cChicken::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Chicken.h b/src/Mobs/Chicken.h index b1a50b61c..07b921884 100644 --- a/src/Mobs/Chicken.h +++ b/src/Mobs/Chicken.h @@ -16,7 +16,7 @@ public: CLASS_PROTODEF(cChicken) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual const cItem GetFollowedItem(void) const override { return cItem(E_ITEM_SEEDS); } diff --git a/src/Mobs/Cow.cpp b/src/Mobs/Cow.cpp index 9914df6b5..7dc6f3f37 100644 --- a/src/Mobs/Cow.cpp +++ b/src/Mobs/Cow.cpp @@ -22,7 +22,7 @@ cCow::cCow(void) : void cCow::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Cow.h b/src/Mobs/Cow.h index 8814b7e09..ee1a4fafe 100644 --- a/src/Mobs/Cow.h +++ b/src/Mobs/Cow.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cCow) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual const cItem GetFollowedItem(void) const override { return cItem(E_ITEM_WHEAT); } diff --git a/src/Mobs/Creeper.cpp b/src/Mobs/Creeper.cpp index 02718edf8..a073224cf 100644 --- a/src/Mobs/Creeper.cpp +++ b/src/Mobs/Creeper.cpp @@ -61,13 +61,13 @@ void cCreeper::GetDrops(cItems & a_Drops, cEntity * a_Killer) } int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } AddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_GUNPOWDER); - if ((a_Killer != NULL) && a_Killer->IsProjectile() && (((cProjectileEntity *)a_Killer)->GetCreatorUniqueID() >= 0)) + if ((a_Killer != nullptr) && a_Killer->IsProjectile() && (((cProjectileEntity *)a_Killer)->GetCreatorUniqueID() >= 0)) { class cProjectileCreatorCallback : public cEntityCallback { diff --git a/src/Mobs/Creeper.h b/src/Mobs/Creeper.h index 747daca09..bf3272e22 100644 --- a/src/Mobs/Creeper.h +++ b/src/Mobs/Creeper.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cCreeper) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) 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; diff --git a/src/Mobs/EnderDragon.h b/src/Mobs/EnderDragon.h index 1d4cd657c..e4ca9dcf9 100644 --- a/src/Mobs/EnderDragon.h +++ b/src/Mobs/EnderDragon.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cEnderDragon) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Enderman.cpp b/src/Mobs/Enderman.cpp index 567714382..56ea10245 100644 --- a/src/Mobs/Enderman.cpp +++ b/src/Mobs/Enderman.cpp @@ -15,7 +15,7 @@ class cPlayerLookCheck : { public: cPlayerLookCheck(Vector3d a_EndermanPos, int a_SightDistance) : - m_Player(NULL), + m_Player(nullptr), m_EndermanPos(a_EndermanPos), m_SightDistance(a_SightDistance) { @@ -92,7 +92,7 @@ cEnderman::cEnderman(void) : void cEnderman::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -104,7 +104,7 @@ void cEnderman::GetDrops(cItems & a_Drops, cEntity * a_Killer) void cEnderman::CheckEventSeePlayer() { - if (m_Target != NULL) + if (m_Target != nullptr) { return; } @@ -115,7 +115,7 @@ void cEnderman::CheckEventSeePlayer() return; } - ASSERT(Callback.GetPlayer() != NULL); + ASSERT(Callback.GetPlayer() != nullptr); if (!CheckLight()) { @@ -196,7 +196,7 @@ void cEnderman::Tick(float a_Dt, cChunk & a_Chunk) if (IsSwimming()) { EventLosePlayer(); - TakeDamage(dtDrowning, NULL, 1, 0); + TakeDamage(dtDrowning, nullptr, 1, 0); // TODO teleport to a safe location } diff --git a/src/Mobs/Enderman.h b/src/Mobs/Enderman.h index 947c32b96..28bbceb84 100644 --- a/src/Mobs/Enderman.h +++ b/src/Mobs/Enderman.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cEnderman) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void CheckEventSeePlayer(void) override; virtual void CheckEventLostPlayer(void) override; virtual void EventLosePlayer(void) override; diff --git a/src/Mobs/Ghast.cpp b/src/Mobs/Ghast.cpp index 6aac14779..c65c0d29a 100644 --- a/src/Mobs/Ghast.cpp +++ b/src/Mobs/Ghast.cpp @@ -20,7 +20,7 @@ cGhast::cGhast(void) : void cGhast::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -36,20 +36,20 @@ void cGhast::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if (m_Target != NULL && m_AttackInterval > 3.0) + if (m_Target != nullptr && m_AttackInterval > 3.0) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cGhastFireballEntity * GhastBall = new cGhastFireballEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); - if (GhastBall == NULL) + if (GhastBall == nullptr) { return; } if (!GhastBall->Initialize(*m_World)) { delete GhastBall; - GhastBall = NULL; + GhastBall = nullptr; return; } m_World->BroadcastSpawnEntity(*GhastBall); diff --git a/src/Mobs/Ghast.h b/src/Mobs/Ghast.h index 1d4e6b94a..a28940a01 100644 --- a/src/Mobs/Ghast.h +++ b/src/Mobs/Ghast.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cGhast) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Attack(float a_Dt) override; bool IsCharging(void) const {return false; } diff --git a/src/Mobs/Giant.h b/src/Mobs/Giant.h index 7c04c9b4f..8d3060940 100644 --- a/src/Mobs/Giant.h +++ b/src/Mobs/Giant.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cGiant) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Horse.cpp b/src/Mobs/Horse.cpp index 67a09d4ab..d92f0d023 100644 --- a/src/Mobs/Horse.cpp +++ b/src/Mobs/Horse.cpp @@ -49,7 +49,7 @@ void cHorse::Tick(float a_Dt, cChunk & a_Chunk) } } - if ((m_Attachee != NULL) && (!m_bIsTame)) + if ((m_Attachee != nullptr) && (!m_bIsTame)) { if (m_TameAttemptTimes < m_TimesToTame) { @@ -113,7 +113,7 @@ void cHorse::OnRightClicked(cPlayer & a_Player) } else { - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { @@ -141,7 +141,7 @@ void cHorse::OnRightClicked(cPlayer & a_Player) void cHorse::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Horse.h b/src/Mobs/Horse.h index 47189b3b0..4c644e512 100644 --- a/src/Mobs/Horse.h +++ b/src/Mobs/Horse.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cHorse) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual void OnRightClicked(cPlayer & a_Player) override; diff --git a/src/Mobs/IronGolem.h b/src/Mobs/IronGolem.h index c5341ed76..721ca2701 100644 --- a/src/Mobs/IronGolem.h +++ b/src/Mobs/IronGolem.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cIronGolem) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; // Iron golems do not drown nor float virtual void HandleAir(void) override {} diff --git a/src/Mobs/MagmaCube.h b/src/Mobs/MagmaCube.h index bfe63fa2e..d66ea423a 100644 --- a/src/Mobs/MagmaCube.h +++ b/src/Mobs/MagmaCube.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cMagmaCube) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; int GetSize(void) const { return m_Size; } protected: diff --git a/src/Mobs/Monster.cpp b/src/Mobs/Monster.cpp index 73dbcb3c3..23b4d9f45 100644 --- a/src/Mobs/Monster.cpp +++ b/src/Mobs/Monster.cpp @@ -79,7 +79,7 @@ cMonster::cMonster(const AString & a_ConfigName, eMonsterType a_MobType, const A : super(etMonster, a_Width, a_Height) , m_EMState(IDLE) , m_EMPersonality(AGGRESSIVE) - , m_Target(NULL) + , m_Target(nullptr) , m_bMovingToDestination(false) , m_LastGroundHeight(POSY_TOINT) , m_IdleInterval(0) @@ -274,8 +274,8 @@ void cMonster::Tick(float a_Dt, cChunk & a_Chunk) return; } - if ((m_Target != NULL) && m_Target->IsDestroyed()) - m_Target = NULL; + if ((m_Target != nullptr) && m_Target->IsDestroyed()) + m_Target = nullptr; // Burning in daylight HandleDaylightBurning(a_Chunk); @@ -379,7 +379,7 @@ void cMonster::Tick(float a_Dt, cChunk & a_Chunk) void cMonster::SetPitchAndYawFromDestination() { Vector3d FinalDestination = m_FinalDestination; - if (m_Target != NULL) + if (m_Target != nullptr) { if (m_Target->IsPlayer()) { @@ -423,7 +423,7 @@ void cMonster::HandleFalling() if (Damage > 0) { - TakeDamage(dtFalling, NULL, Damage, Damage, 0); + TakeDamage(dtFalling, nullptr, Damage, Damage, 0); // Fall particles GetWorld()->BroadcastSoundParticleEffect(2006, POSX_TOINT, POSY_TOINT - 1, POSZ_TOINT, Damage /* Used as particle effect speed modifier */); @@ -479,7 +479,7 @@ bool cMonster::DoTakeDamage(TakeDamageInfo & a_TDI) m_World->BroadcastSoundEffect(m_SoundHurt, GetPosX(), GetPosY(), GetPosZ(), 1.0f, 0.8f); } - if (a_TDI.Attacker != NULL) + if (a_TDI.Attacker != nullptr) { m_Target = a_TDI.Attacker; } @@ -556,7 +556,7 @@ void cMonster::KilledBy(TakeDamageInfo & a_TDI) break; } } - if ((a_TDI.Attacker != NULL) && (!IsBaby())) + if ((a_TDI.Attacker != nullptr) && (!IsBaby())) { m_World->SpawnExperienceOrb(GetPosX(), GetPosY(), GetPosZ(), Reward); } @@ -593,7 +593,7 @@ void cMonster::CheckEventSeePlayer(void) // TODO: Rewrite this to use cWorld's DoWithPlayers() cPlayer * Closest = m_World->FindClosestPlayer(GetPosition(), (float)m_SightDistance, false); - if (Closest != NULL) + if (Closest != nullptr) { EventSeePlayer(Closest); } @@ -605,7 +605,7 @@ void cMonster::CheckEventSeePlayer(void) void cMonster::CheckEventLostPlayer(void) { - if (m_Target != NULL) + if (m_Target != nullptr) { if ((m_Target->GetPosition() - GetPosition()).Length() > m_SightDistance) { @@ -635,7 +635,7 @@ void cMonster::EventSeePlayer(cEntity * a_SeenPlayer) void cMonster::EventLosePlayer(void) { - m_Target = NULL; + m_Target = nullptr; m_EMState = IDLE; } @@ -697,7 +697,7 @@ void cMonster::InStateEscaping(float a_Dt) { UNUSED(a_Dt); - if (m_Target != NULL) + if (m_Target != nullptr) { Vector3d newloc = GetPosition(); newloc.x = (m_Target->GetPosition().x < newloc.x)? (newloc.x + m_SightDistance): (newloc.x - m_SightDistance); @@ -724,7 +724,7 @@ void cMonster::SetCustomName(const AString & a_CustomName) m_CustomName = a_CustomName.substr(0, 64); } - if (m_World != NULL) + if (m_World != nullptr) { m_World->BroadcastEntityMetadata(*this); } @@ -737,7 +737,7 @@ void cMonster::SetCustomName(const AString & a_CustomName) void cMonster::SetCustomNameAlwaysVisible(bool a_CustomNameAlwaysVisible) { m_CustomNameAlwaysVisible = a_CustomNameAlwaysVisible; - if (m_World != NULL) + if (m_World != nullptr) { m_World->BroadcastEntityMetadata(*this); } @@ -893,7 +893,7 @@ int cMonster::GetSpawnDelay(cMonster::eFamily a_MobFamily) cMonster * cMonster::NewMonsterFromType(eMonsterType a_MobType) { cFastRandom Random; - cMonster * toReturn = NULL; + cMonster * toReturn = nullptr; // Create the mob entity switch (a_MobType) diff --git a/src/Mobs/Mooshroom.cpp b/src/Mobs/Mooshroom.cpp index 99958720f..ec533cfca 100644 --- a/src/Mobs/Mooshroom.cpp +++ b/src/Mobs/Mooshroom.cpp @@ -25,7 +25,7 @@ cMooshroom::cMooshroom(void) : void cMooshroom::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Mooshroom.h b/src/Mobs/Mooshroom.h index fb002c2bf..754725c92 100644 --- a/src/Mobs/Mooshroom.h +++ b/src/Mobs/Mooshroom.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cMooshroom) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual const cItem GetFollowedItem(void) const override { return cItem(E_ITEM_WHEAT); } diff --git a/src/Mobs/PassiveAggressiveMonster.cpp b/src/Mobs/PassiveAggressiveMonster.cpp index e0cc2fd21..cb8650cb9 100644 --- a/src/Mobs/PassiveAggressiveMonster.cpp +++ b/src/Mobs/PassiveAggressiveMonster.cpp @@ -26,7 +26,7 @@ bool cPassiveAggressiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI) return false; } - if ((m_Target != NULL) && (m_Target->IsPlayer())) + if ((m_Target != nullptr) && (m_Target->IsPlayer())) { if (!((cPlayer *)m_Target)->IsGameModeCreative()) { diff --git a/src/Mobs/PassiveMonster.cpp b/src/Mobs/PassiveMonster.cpp index be3043e3d..1048616d0 100644 --- a/src/Mobs/PassiveMonster.cpp +++ b/src/Mobs/PassiveMonster.cpp @@ -24,7 +24,7 @@ bool cPassiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI) { return false; } - if ((a_TDI.Attacker != this) && (a_TDI.Attacker != NULL)) + if ((a_TDI.Attacker != this) && (a_TDI.Attacker != nullptr)) { m_EMState = ESCAPING; } @@ -49,7 +49,7 @@ void cPassiveMonster::Tick(float a_Dt, cChunk & a_Chunk) return; } cPlayer * a_Closest_Player = m_World->FindClosestPlayer(GetPosition(), (float)m_SightDistance); - if (a_Closest_Player != NULL) + if (a_Closest_Player != nullptr) { if (a_Closest_Player->GetEquippedItem().IsEqual(FollowedItem)) { diff --git a/src/Mobs/Pig.cpp b/src/Mobs/Pig.cpp index 1f77cf613..55a4412ca 100644 --- a/src/Mobs/Pig.cpp +++ b/src/Mobs/Pig.cpp @@ -22,7 +22,7 @@ cPig::cPig(void) : void cPig::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -41,7 +41,7 @@ void cPig::OnRightClicked(cPlayer & a_Player) { if (m_bIsSaddled) { - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { @@ -85,7 +85,7 @@ void cPig::Tick(float a_Dt, cChunk & a_Chunk) super::Tick(a_Dt, a_Chunk); // If the attachee player is holding a carrot-on-stick, let them drive this pig: - if (m_bIsSaddled && (m_Attachee != NULL)) + if (m_bIsSaddled && (m_Attachee != nullptr)) { if (m_Attachee->IsPlayer() && (m_Attachee->GetEquippedWeapon().m_ItemType == E_ITEM_CARROT_ON_STICK)) { diff --git a/src/Mobs/Pig.h b/src/Mobs/Pig.h index 534a0ca6f..953850b3a 100644 --- a/src/Mobs/Pig.h +++ b/src/Mobs/Pig.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cPig) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; diff --git a/src/Mobs/Sheep.cpp b/src/Mobs/Sheep.cpp index cbb33cb90..c46404391 100644 --- a/src/Mobs/Sheep.cpp +++ b/src/Mobs/Sheep.cpp @@ -41,7 +41,7 @@ void cSheep::GetDrops(cItems & a_Drops, cEntity * a_Killer) } int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Sheep.h b/src/Mobs/Sheep.h index 28e1c7254..16d5fddd3 100644 --- a/src/Mobs/Sheep.h +++ b/src/Mobs/Sheep.h @@ -22,7 +22,7 @@ public: CLASS_PROTODEF(cSheep) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; diff --git a/src/Mobs/Skeleton.cpp b/src/Mobs/Skeleton.cpp index cd707f4bb..f17bc307c 100644 --- a/src/Mobs/Skeleton.cpp +++ b/src/Mobs/Skeleton.cpp @@ -23,7 +23,7 @@ cSkeleton::cSkeleton(bool IsWither) : void cSkeleton::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -71,20 +71,20 @@ void cSkeleton::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if (m_Target != NULL && m_AttackInterval > 3.0) + if (m_Target != nullptr && m_AttackInterval > 3.0) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cArrowEntity * Arrow = new cArrowEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); - if (Arrow == NULL) + if (Arrow == nullptr) { return; } if (!Arrow->Initialize(*m_World)) { delete Arrow; - Arrow = NULL; + Arrow = nullptr; return; } m_World->BroadcastSpawnEntity(*Arrow); diff --git a/src/Mobs/Skeleton.h b/src/Mobs/Skeleton.h index 577588b32..cd1c6c3f0 100644 --- a/src/Mobs/Skeleton.h +++ b/src/Mobs/Skeleton.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cSkeleton) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void MoveToPosition(const Vector3d & a_Position) override; virtual void Attack(float a_Dt) override; virtual void SpawnOn(cClientHandle & a_ClientHandle) override; diff --git a/src/Mobs/Slime.cpp b/src/Mobs/Slime.cpp index b709ec664..1c68c5189 100644 --- a/src/Mobs/Slime.cpp +++ b/src/Mobs/Slime.cpp @@ -30,7 +30,7 @@ cSlime::cSlime(int a_Size) : void cSlime::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Slime.h b/src/Mobs/Slime.h index f0b800f94..a177a279c 100644 --- a/src/Mobs/Slime.h +++ b/src/Mobs/Slime.h @@ -19,7 +19,7 @@ public: CLASS_PROTODEF(cSlime) // cAggressiveMonster overrides: - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Attack(float a_Dt) override; virtual void KilledBy(TakeDamageInfo & a_TDI) override; diff --git a/src/Mobs/SnowGolem.h b/src/Mobs/SnowGolem.h index aba89e52d..f036b1867 100644 --- a/src/Mobs/SnowGolem.h +++ b/src/Mobs/SnowGolem.h @@ -18,7 +18,7 @@ public: CLASS_PROTODEF(cSnowGolem) virtual void Tick(float a_Dt, cChunk & a_Chunk) override; - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Spider.cpp b/src/Mobs/Spider.cpp index 8b978ff6b..deb263c41 100644 --- a/src/Mobs/Spider.cpp +++ b/src/Mobs/Spider.cpp @@ -19,12 +19,12 @@ cSpider::cSpider(void) : void cSpider::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } AddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_STRING); - if ((a_Killer != NULL) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) + if ((a_Killer != nullptr) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) { AddRandomUncommonDropItem(a_Drops, 33.0f, E_ITEM_SPIDER_EYE); } diff --git a/src/Mobs/Spider.h b/src/Mobs/Spider.h index 813d2e266..24134c00f 100644 --- a/src/Mobs/Spider.h +++ b/src/Mobs/Spider.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cSpider) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Squid.cpp b/src/Mobs/Squid.cpp index bd0e141a0..59ee963ae 100644 --- a/src/Mobs/Squid.cpp +++ b/src/Mobs/Squid.cpp @@ -22,7 +22,7 @@ void cSquid::GetDrops(cItems & a_Drops, cEntity * a_Killer) { // Drops 0-3 Ink Sacs int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Squid.h b/src/Mobs/Squid.h index b57340427..a46d738c6 100644 --- a/src/Mobs/Squid.h +++ b/src/Mobs/Squid.h @@ -19,7 +19,7 @@ public: CLASS_PROTODEF(cSquid) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; // Squids do not drown (or float) virtual void HandleAir(void) override {} diff --git a/src/Mobs/Villager.cpp b/src/Mobs/Villager.cpp index 0efd5501e..5c9999a59 100644 --- a/src/Mobs/Villager.cpp +++ b/src/Mobs/Villager.cpp @@ -30,7 +30,7 @@ bool cVillager::DoTakeDamage(TakeDamageInfo & a_TDI) return false; } - if ((a_TDI.Attacker != NULL) && a_TDI.Attacker->IsPlayer()) + if ((a_TDI.Attacker != nullptr) && a_TDI.Attacker->IsPlayer()) { if (m_World->GetTickRandomNumber(5) == 3) { diff --git a/src/Mobs/Witch.cpp b/src/Mobs/Witch.cpp index 6956f7b7a..747a11f97 100644 --- a/src/Mobs/Witch.cpp +++ b/src/Mobs/Witch.cpp @@ -19,7 +19,7 @@ cWitch::cWitch(void) : void cWitch::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Witch.h b/src/Mobs/Witch.h index bd059f61d..03691fef1 100644 --- a/src/Mobs/Witch.h +++ b/src/Mobs/Witch.h @@ -18,7 +18,7 @@ public: CLASS_PROTODEF(cWitch) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; bool IsAngry(void) const {return ((m_EMState == ATTACKING) || (m_EMState == CHASING)); } } ; diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h index 2403823ed..a20fed3d3 100644 --- a/src/Mobs/Wither.h +++ b/src/Mobs/Wither.h @@ -26,7 +26,7 @@ public: // cEntity overrides virtual bool Initialize(cWorld & a_World) override; - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual void KilledBy(TakeDamageInfo & a_TDI) override; diff --git a/src/Mobs/Wolf.cpp b/src/Mobs/Wolf.cpp index 4fe1ff1d6..4711d5a7a 100644 --- a/src/Mobs/Wolf.cpp +++ b/src/Mobs/Wolf.cpp @@ -47,7 +47,7 @@ void cWolf::Attack(float a_Dt) { UNUSED(a_Dt); - if ((m_Target != NULL) && (m_Target->IsPlayer())) + if ((m_Target != nullptr) && (m_Target->IsPlayer())) { if (((cPlayer *)m_Target)->GetName() != m_OwnerName) { @@ -157,7 +157,7 @@ void cWolf::Tick(float a_Dt, cChunk & a_Chunk) } cPlayer * a_Closest_Player = m_World->FindClosestPlayer(GetPosition(), (float)m_SightDistance); - if (a_Closest_Player != NULL) + if (a_Closest_Player != nullptr) { switch (a_Closest_Player->GetEquippedItem().m_ItemType) { diff --git a/src/Mobs/Zombie.cpp b/src/Mobs/Zombie.cpp index 30225c32d..63042e252 100644 --- a/src/Mobs/Zombie.cpp +++ b/src/Mobs/Zombie.cpp @@ -24,7 +24,7 @@ cZombie::cZombie(bool a_IsVillagerZombie) : void cZombie::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Zombie.h b/src/Mobs/Zombie.h index 118b6e6e7..809c2a6fe 100644 --- a/src/Mobs/Zombie.h +++ b/src/Mobs/Zombie.h @@ -16,7 +16,7 @@ public: CLASS_PROTODEF(cZombie) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void MoveToPosition(const Vector3d & a_Position) override; virtual bool IsUndead(void) override { return true; } diff --git a/src/Mobs/ZombiePigman.cpp b/src/Mobs/ZombiePigman.cpp index 05350f877..8b415b0af 100644 --- a/src/Mobs/ZombiePigman.cpp +++ b/src/Mobs/ZombiePigman.cpp @@ -19,7 +19,7 @@ cZombiePigman::cZombiePigman(void) : void cZombiePigman::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -41,7 +41,7 @@ void cZombiePigman::KilledBy(TakeDamageInfo & a_TDI) { super::KilledBy(a_TDI); - if ((a_TDI.Attacker != NULL) && (a_TDI.Attacker->IsPlayer())) + if ((a_TDI.Attacker != nullptr) && (a_TDI.Attacker->IsPlayer())) { // TODO: Anger all nearby zombie pigmen // TODO: In vanilla, if one player angers ZPs, do they attack any nearby player, or only that one attacker? diff --git a/src/Mobs/ZombiePigman.h b/src/Mobs/ZombiePigman.h index bae0115eb..d8b886ca4 100644 --- a/src/Mobs/ZombiePigman.h +++ b/src/Mobs/ZombiePigman.h @@ -16,7 +16,7 @@ public: CLASS_PROTODEF(cZombiePigman) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void KilledBy(TakeDamageInfo & a_TDI) override; virtual bool IsUndead(void) override { return true; } diff --git a/src/MonsterConfig.cpp b/src/MonsterConfig.cpp index f5e078213..a15e413ba 100644 --- a/src/MonsterConfig.cpp +++ b/src/MonsterConfig.cpp @@ -47,7 +47,7 @@ cMonsterConfig::cMonsterConfig(void) cMonsterConfig::~cMonsterConfig() { delete m_pState; - m_pState = NULL; + m_pState = nullptr; } diff --git a/src/Noise.cpp b/src/Noise.cpp index 71e801f30..8fcfe2920 100644 --- a/src/Noise.cpp +++ b/src/Noise.cpp @@ -845,7 +845,7 @@ void cPerlinNoise::Generate2D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY; if (ShouldFreeWorkspace) { @@ -886,7 +886,7 @@ void cPerlinNoise::Generate2D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } @@ -910,7 +910,7 @@ void cPerlinNoise::Generate3D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY * a_SizeZ; if (ShouldFreeWorkspace) { @@ -953,7 +953,7 @@ void cPerlinNoise::Generate3D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } @@ -1015,7 +1015,7 @@ void cRidgedMultiNoise::Generate2D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY; if (ShouldFreeWorkspace) { @@ -1056,7 +1056,7 @@ void cRidgedMultiNoise::Generate2D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } @@ -1080,7 +1080,7 @@ void cRidgedMultiNoise::Generate3D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY * a_SizeZ; if (ShouldFreeWorkspace) { @@ -1123,7 +1123,7 @@ void cRidgedMultiNoise::Generate3D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } diff --git a/src/Noise.h b/src/Noise.h index 4cf8d4ad8..b7a90d5b7 100644 --- a/src/Noise.h +++ b/src/Noise.h @@ -155,7 +155,7 @@ public: NOISE_DATATYPE * a_Array, ///< Array to generate into int a_SizeX, ///< Count of the array NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -164,7 +164,7 @@ public: int a_SizeX, int a_SizeY, ///< Count of the array, in each direction NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -174,7 +174,7 @@ public: NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction NOISE_DATATYPE a_StartZ, NOISE_DATATYPE a_EndZ, ///< Noise-space coords of the array in the Z direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; protected: @@ -219,7 +219,7 @@ public: NOISE_DATATYPE * a_Array, ///< Array to generate into int a_SizeX, ///< Count of the array NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -228,7 +228,7 @@ public: int a_SizeX, int a_SizeY, ///< Count of the array, in each direction NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -238,7 +238,7 @@ public: NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction NOISE_DATATYPE a_StartZ, NOISE_DATATYPE a_EndZ, ///< Noise-space coords of the array in the Z direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; protected: diff --git a/src/OSSupport/Errors.cpp b/src/OSSupport/Errors.cpp index 9401ec257..a5361e1a6 100644 --- a/src/OSSupport/Errors.cpp +++ b/src/OSSupport/Errors.cpp @@ -10,7 +10,7 @@ AString GetOSErrorString( int a_ErrNo) #ifdef _WIN32 - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, a_ErrNo, 0, buffer, ARRAYCOUNT(buffer), NULL); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, a_ErrNo, 0, buffer, ARRAYCOUNT(buffer), nullptr); Printf(Out, "%d: %s", a_ErrNo, buffer); if (!Out.empty() && (Out[Out.length() - 1] == '\n')) { @@ -25,7 +25,7 @@ AString GetOSErrorString( int a_ErrNo) #if !defined(__APPLE__) && ( _GNU_SOURCE) && !defined(ANDROID_NDK) // GNU version of strerror_r() char * res = strerror_r( errno, buffer, ARRAYCOUNT(buffer)); - if (res != NULL) + if (res != nullptr) { Printf(Out, "%d: %s", a_ErrNo, res); return Out; diff --git a/src/OSSupport/Event.cpp b/src/OSSupport/Event.cpp index 7cf8a826c..87bc110ce 100644 --- a/src/OSSupport/Event.cpp +++ b/src/OSSupport/Event.cpp @@ -15,8 +15,8 @@ cEvent::cEvent(void) { #ifdef _WIN32 - m_Event = CreateEvent(NULL, FALSE, FALSE, NULL); - if (m_Event == NULL) + m_Event = CreateEvent(nullptr, FALSE, FALSE, nullptr); + if (m_Event == nullptr) { LOGERROR("cEvent: cannot create event, GLE = %u. Aborting server.", (unsigned)GetLastError()); abort(); @@ -71,7 +71,7 @@ cEvent::~cEvent() { sem_destroy(m_Event); delete m_Event; - m_Event = NULL; + m_Event = nullptr; } #endif } diff --git a/src/OSSupport/File.cpp b/src/OSSupport/File.cpp index cb6031da6..8957dfaef 100644 --- a/src/OSSupport/File.cpp +++ b/src/OSSupport/File.cpp @@ -17,7 +17,7 @@ cFile::cFile(void) : #ifdef USE_STDIO_FILE - m_File(NULL) + m_File(nullptr) #else m_File(INVALID_HANDLE_VALUE) #endif // USE_STDIO_FILE @@ -31,7 +31,7 @@ cFile::cFile(void) : cFile::cFile(const AString & iFileName, eMode iMode) : #ifdef USE_STDIO_FILE - m_File(NULL) + m_File(nullptr) #else m_File(INVALID_HANDLE_VALUE) #endif // USE_STDIO_FILE @@ -64,7 +64,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) Close(); } - const char * Mode = NULL; + const char * Mode = nullptr; switch (iMode) { case fmRead: Mode = "rb"; break; @@ -72,7 +72,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) case fmReadWrite: Mode = "rb+"; break; case fmAppend: Mode = "a+"; break; } - if (Mode == NULL) + if (Mode == nullptr) { ASSERT(!"Unhandled file mode"); return false; @@ -84,7 +84,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) m_File = fopen((FILE_IO_PREFIX + iFileName).c_str(), Mode); #endif // _WIN32 - if ((m_File == NULL) && (iMode == fmReadWrite)) + if ((m_File == nullptr) && (iMode == fmReadWrite)) { // Fix for MS not following C spec, opening "a" mode files for writing at the end only // The file open operation has been tried with "read update", fails if file not found @@ -98,7 +98,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) #endif // _WIN32 } - return (m_File != NULL); + return (m_File != nullptr); } @@ -114,7 +114,7 @@ void cFile::Close(void) } fclose(m_File); - m_File = NULL; + m_File = nullptr; } @@ -123,7 +123,7 @@ void cFile::Close(void) bool cFile::IsOpen(void) const { - return (m_File != NULL); + return (m_File != nullptr); } @@ -366,7 +366,7 @@ int cFile::GetSize(const AString & a_FileName) bool cFile::CreateFolder(const AString & a_FolderPath) { #ifdef _WIN32 - return (CreateDirectoryA(a_FolderPath.c_str(), NULL) != 0); + return (CreateDirectoryA(a_FolderPath.c_str(), nullptr) != 0); #else return (mkdir(a_FolderPath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0); #endif @@ -415,13 +415,13 @@ AStringVector cFile::GetFolderContents(const AString & a_Folder) { Folder = "."; } - if ((dp = opendir(Folder.c_str())) == NULL) + if ((dp = opendir(Folder.c_str())) == nullptr) { LOGERROR("Error (%i) opening directory \"%s\"\n", errno, Folder.c_str()); } else { - while ((dirp = readdir(dp)) != NULL) + while ((dirp = readdir(dp)) != nullptr) { AllFiles.push_back(dirp->d_name); } diff --git a/src/OSSupport/GZipFile.cpp b/src/OSSupport/GZipFile.cpp index 22d887783..32d84a0d5 100644 --- a/src/OSSupport/GZipFile.cpp +++ b/src/OSSupport/GZipFile.cpp @@ -11,7 +11,7 @@ cGZipFile::cGZipFile(void) : - m_File(NULL), m_Mode(fmRead) + m_File(nullptr), m_Mode(fmRead) { } @@ -30,14 +30,14 @@ cGZipFile::~cGZipFile() bool cGZipFile::Open(const AString & a_FileName, eMode a_Mode) { - if (m_File != NULL) + if (m_File != nullptr) { ASSERT(!"A file is already open in this object"); return false; } m_File = gzopen(a_FileName.c_str(), (a_Mode == fmRead) ? "r" : "w"); m_Mode = a_Mode; - return (m_File != NULL); + return (m_File != nullptr); } @@ -46,10 +46,10 @@ bool cGZipFile::Open(const AString & a_FileName, eMode a_Mode) void cGZipFile::Close(void) { - if (m_File != NULL) + if (m_File != nullptr) { gzclose(m_File); - m_File = NULL; + m_File = nullptr; } } @@ -59,7 +59,7 @@ void cGZipFile::Close(void) int cGZipFile::ReadRestOfFile(AString & a_Contents) { - if (m_File == NULL) + if (m_File == nullptr) { ASSERT(!"No file has been opened"); return -1; @@ -90,7 +90,7 @@ int cGZipFile::ReadRestOfFile(AString & a_Contents) bool cGZipFile::Write(const char * a_Contents, int a_Size) { - if (m_File == NULL) + if (m_File == nullptr) { ASSERT(!"No file has been opened"); return false; diff --git a/src/OSSupport/ListenThread.cpp b/src/OSSupport/ListenThread.cpp index 02e98acfc..b029634e9 100644 --- a/src/OSSupport/ListenThread.cpp +++ b/src/OSSupport/ListenThread.cpp @@ -214,7 +214,7 @@ void cListenThread::Execute(void) timeval tv; // On Linux select() doesn't seem to wake up when socket is closed, so let's kinda busy-wait: tv.tv_sec = 1; tv.tv_usec = 0; - if (select((int)Highest + 1, &fdRead, NULL, NULL, &tv) == -1) + if (select((int)Highest + 1, &fdRead, nullptr, nullptr, &tv) == -1) { LOG("select(R) call failed in cListenThread: \"%s\"", cSocket::GetLastErrorString().c_str()); continue; diff --git a/src/OSSupport/Semaphore.cpp b/src/OSSupport/Semaphore.cpp index c1fc7d9c7..6a2d57901 100644 --- a/src/OSSupport/Semaphore.cpp +++ b/src/OSSupport/Semaphore.cpp @@ -36,7 +36,7 @@ cSemaphore::cSemaphore( unsigned int a_MaxCount, unsigned int a_InitialCount /* } #else m_Handle = CreateSemaphore( - NULL, // security attribute + nullptr, // security attribute a_InitialCount, // initial count a_MaxCount, // maximum count 0 // name (optional) @@ -98,7 +98,7 @@ void cSemaphore::Signal() LOG("ERROR: Could not signal cSemaphore. (%i)", errno); } #else - ReleaseSemaphore( m_Handle, 1, NULL); + ReleaseSemaphore( m_Handle, 1, nullptr); #endif } diff --git a/src/OSSupport/Socket.cpp b/src/OSSupport/Socket.cpp index c07d31c8b..5025a09ad 100644 --- a/src/OSSupport/Socket.cpp +++ b/src/OSSupport/Socket.cpp @@ -292,7 +292,7 @@ bool cSocket::ConnectIPv4(const AString & a_HostNameOrAddr, unsigned short a_Por { // It is not an IP Address string, but rather a regular hostname, resolve: hostent * hp = gethostbyname(a_HostNameOrAddr.c_str()); - if (hp == NULL) + if (hp == nullptr) { LOGWARNING("%s: Could not resolve hostname \"%s\"", __FUNCTION__, a_HostNameOrAddr.c_str()); CloseSocket(); diff --git a/src/OSSupport/SocketThreads.cpp b/src/OSSupport/SocketThreads.cpp index f436318a5..7a3ef4274 100644 --- a/src/OSSupport/SocketThreads.cpp +++ b/src/OSSupport/SocketThreads.cpp @@ -61,7 +61,7 @@ bool cSocketThreads::AddClient(const cSocket & a_Socket, cCallback * a_Client) // There was an error launching the thread (but it was already logged along with the reason) LOGERROR("A new cSocketThread failed to start"); delete Thread; - Thread = NULL; + Thread = nullptr; return false; } Thread->AddClient(a_Socket, a_Client); @@ -233,7 +233,7 @@ bool cSocketThreads::cSocketThread::RemoveClient(const cCallback * a_Client) // More data to send, shut down reading and wait for the rest to get sent: m_Slots[i].m_State = sSlot::ssWritingRestOut; } - m_Slots[i].m_Client = NULL; + m_Slots[i].m_Client = nullptr; } // Notify the thread of the change: @@ -407,7 +407,7 @@ void cSocketThreads::cSocketThread::Execute(void) timeval Timeout; Timeout.tv_sec = 5; Timeout.tv_usec = 0; - if (select((int)Highest + 1, &fdRead, &fdWrite, NULL, &Timeout) == -1) + if (select((int)Highest + 1, &fdRead, &fdWrite, nullptr, &Timeout) == -1) { LOG("select() call failed in cSocketThread: \"%s\"", cSocket::GetLastErrorString().c_str()); continue; @@ -519,7 +519,7 @@ void cSocketThreads::cSocketThread::ReadFromSockets(fd_set * a_Read) } else { - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { m_Slots[i].m_Client->DataReceived(Buffer, Received); } @@ -545,7 +545,7 @@ void cSocketThreads::cSocketThread::WriteToSockets(fd_set * a_Write) if (m_Slots[i].m_Outgoing.empty()) { // Request another chunk of outgoing data: - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { AString Data; m_Slots[i].m_Client->GetOutgoingData(Data); @@ -573,7 +573,7 @@ void cSocketThreads::cSocketThread::WriteToSockets(fd_set * a_Write) int Err = cSocket::GetLastError(); LOGWARNING("Error %d while writing to client \"%s\", disconnecting. \"%s\"", Err, m_Slots[i].m_Socket.GetIPString().c_str(), GetOSErrorString(Err).c_str()); m_Slots[i].m_Socket.CloseSocket(); - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { m_Slots[i].m_Client->SocketClosed(); } @@ -668,7 +668,7 @@ void cSocketThreads::cSocketThread::QueueOutgoingData(void) cCSLock Lock(m_Parent->m_CS); for (int i = 0; i < m_NumSlots; i++) { - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { AString Data; m_Slots[i].m_Client->GetOutgoingData(Data); diff --git a/src/OSSupport/SocketThreads.h b/src/OSSupport/SocketThreads.h index 944f5f3bc..df819468d 100644 --- a/src/OSSupport/SocketThreads.h +++ b/src/OSSupport/SocketThreads.h @@ -137,7 +137,7 @@ private: /** The socket is primarily owned by this object */ cSocket m_Socket; - /** The callback to call for events. May be NULL */ + /** The callback to call for events. May be nullptr */ cCallback * m_Client; /** If sending writes only partial data, the rest is stored here for another send. diff --git a/src/PolarSSL++/BlockingSslClientSocket.cpp b/src/PolarSSL++/BlockingSslClientSocket.cpp index 699bc57ee..59e1281ac 100644 --- a/src/PolarSSL++/BlockingSslClientSocket.cpp +++ b/src/PolarSSL++/BlockingSslClientSocket.cpp @@ -48,7 +48,7 @@ bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Po } // If we have been assigned a trusted CA root cert store, push it into the SSL context: - if (m_CACerts.get() != NULL) + if (m_CACerts.get() != nullptr) { m_Ssl.SetCACerts(m_CACerts, m_ExpectedPeerName); } @@ -72,7 +72,7 @@ bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Po 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) + if (m_CACerts.get() != nullptr) { LOGWARNING( "SSL: Trying to set multiple trusted CA root cert stores, only the last one will be used. Name: %s", diff --git a/src/PolarSSL++/CallbackSslContext.cpp b/src/PolarSSL++/CallbackSslContext.cpp index c4d19b2a0..e061e3f03 100644 --- a/src/PolarSSL++/CallbackSslContext.cpp +++ b/src/PolarSSL++/CallbackSslContext.cpp @@ -12,7 +12,7 @@ cCallbackSslContext::cCallbackSslContext(void) : - m_Callbacks(NULL) + m_Callbacks(nullptr) { // Nothing needed, but the constructor needs to exist so } @@ -32,7 +32,7 @@ cCallbackSslContext::cCallbackSslContext(cCallbackSslContext::cDataCallbacks & a int cCallbackSslContext::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes) { - if (m_Callbacks == NULL) + if (m_Callbacks == nullptr) { LOGWARNING("SSL: Trying to receive data with no callbacks, aborting."); return POLARSSL_ERR_NET_RECV_FAILED; @@ -46,7 +46,7 @@ int cCallbackSslContext::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_Num int cCallbackSslContext::SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes) { - if (m_Callbacks == NULL) + if (m_Callbacks == nullptr) { LOGWARNING("SSL: Trying to send data with no callbacks, aborting."); return POLARSSL_ERR_NET_SEND_FAILED; diff --git a/src/PolarSSL++/CryptoKey.cpp b/src/PolarSSL++/CryptoKey.cpp index 0763c387b..7c4f021b3 100644 --- a/src/PolarSSL++/CryptoKey.cpp +++ b/src/PolarSSL++/CryptoKey.cpp @@ -123,7 +123,7 @@ int cCryptoKey::ParsePrivate(const void * a_Data, size_t a_NumBytes, const AStri if (a_Password.empty()) { - return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, NULL, 0); + return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, nullptr, 0); } else { diff --git a/src/PolarSSL++/SslContext.cpp b/src/PolarSSL++/SslContext.cpp index 482470c3a..902267f90 100644 --- a/src/PolarSSL++/SslContext.cpp +++ b/src/PolarSSL++/SslContext.cpp @@ -46,7 +46,7 @@ int cSslContext::Initialize(bool a_IsClient, const SharedPtr & // Set the CtrDrbg context, create a new one if needed: m_CtrDrbg = a_CtrDrbg; - if (m_CtrDrbg.get() == NULL) + if (m_CtrDrbg.get() == nullptr) { m_CtrDrbg.reset(new cCtrDrbgContext); m_CtrDrbg->Initialize("MCServer", 8); @@ -98,7 +98,7 @@ void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cRsaPrivateKe 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)) + if ((a_OwnCert.get() == nullptr) || (a_OwnCertPrivKey.get() == nullptr)) { LOGWARNING("SSL: Own certificate is not valid, skipping the set."); return; @@ -121,7 +121,7 @@ void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cCryptoKeyPtr 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)) + if ((a_OwnCert.get() == nullptr) || (a_OwnCertPrivKey.get() == nullptr)) { LOGWARNING("SSL: Own certificate is not valid, skipping the set."); return; @@ -150,7 +150,7 @@ void cSslContext::SetCACerts(const cX509CertPtr & a_CACert, const AString & a_Ex // 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()); + ssl_set_ca_chain(&m_Ssl, m_CACerts->GetInternal(), nullptr, m_ExpectedPeerName.empty() ? nullptr : m_ExpectedPeerName.c_str()); } diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp index a4b4dbd3b..dd0d62af5 100644 --- a/src/Protocol/MojangAPI.cpp +++ b/src/Protocol/MojangAPI.cpp @@ -196,7 +196,7 @@ cMojangAPI::cMojangAPI(void) : m_NameToUUIDAddress(DEFAULT_NAME_TO_UUID_ADDRESS), m_UUIDToProfileServer(DEFAULT_UUID_TO_PROFILE_SERVER), m_UUIDToProfileAddress(DEFAULT_UUID_TO_PROFILE_ADDRESS), - m_RankMgr(NULL), + m_RankMgr(nullptr), m_UpdateThread(new cUpdateThread()) { } @@ -335,7 +335,7 @@ AStringVector cMojangAPI::GetUUIDsFromPlayerNames(const AStringVector & a_Player void cMojangAPI::AddPlayerNameToUUIDMapping(const AString & a_PlayerName, const AString & a_UUID) { AString UUID = MakeUUIDShort(a_UUID); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSNameToUUID); m_NameToUUID[StrToLower(a_PlayerName)] = sProfile(a_PlayerName, UUID, "", "", Now); @@ -354,7 +354,7 @@ void cMojangAPI::AddPlayerNameToUUIDMapping(const AString & a_PlayerName, const void cMojangAPI::AddPlayerProfile(const AString & a_PlayerName, const AString & a_UUID, const Json::Value & a_Properties) { AString UUID = MakeUUIDShort(a_UUID); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSNameToUUID); m_NameToUUID[StrToLower(a_PlayerName)] = sProfile(a_PlayerName, UUID, "", "", Now); @@ -558,7 +558,7 @@ void cMojangAPI::SaveCachesToDisk(void) db.exec("DELETE FROM UUIDToProfile"); // Save all cache entries - m_PlayerNameToUUID: - Int64 LimitDateTime = time(NULL) - MAX_AGE; + Int64 LimitDateTime = time(nullptr) - MAX_AGE; { SQLite::Statement stmt(db, "INSERT INTO PlayerNameToUUID(PlayerName, UUID, DateTime) VALUES (?, ?, ?)"); cCSLock Lock(m_CSNameToUUID); @@ -697,7 +697,7 @@ void cMojangAPI::QueryNamesToUUIDs(AStringVector & a_NamesToQuery) // Store the returned results into cache: Json::Value::UInt JsonCount = root.size(); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSNameToUUID); for (Json::Value::UInt idx = 0; idx < JsonCount; ++idx) @@ -831,7 +831,7 @@ void cMojangAPI::QueryUUIDToProfile(const AString & a_UUID) return; } Json::Value Properties = root.get("properties", ""); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSUUIDToProfile); m_UUIDToProfile[a_UUID] = sProfile(PlayerName, a_UUID, Properties, Now); @@ -855,7 +855,7 @@ void cMojangAPI::NotifyNameUUID(const AString & a_PlayerName, const AString & a_ { // Notify the rank manager: cCSLock Lock(m_CSRankMgr); - if (m_RankMgr != NULL) + if (m_RankMgr != nullptr) { m_RankMgr->NotifyNameUUID(a_PlayerName, a_UUID); } @@ -867,7 +867,7 @@ void cMojangAPI::NotifyNameUUID(const AString & a_PlayerName, const AString & a_ void cMojangAPI::Update(void) { - Int64 LimitDateTime = time(NULL) - MAX_AGE; + Int64 LimitDateTime = time(nullptr) - MAX_AGE; // Re-query all playernames that are stale: AStringVector PlayerNames; diff --git a/src/Protocol/MojangAPI.h b/src/Protocol/MojangAPI.h index 393fd4baa..0dc2617b6 100644 --- a/src/Protocol/MojangAPI.h +++ b/src/Protocol/MojangAPI.h @@ -89,7 +89,7 @@ public: the profile to the respective mapping caches and updtes their datetime stamp to now. */ void AddPlayerProfile(const AString & a_PlayerName, const AString & a_UUID, const Json::Value & a_Properties); - /** Sets the m_RankMgr that is used for name-uuid notifications. Accepts NULL to remove the binding. */ + /** Sets the m_RankMgr that is used for name-uuid notifications. Accepts nullptr to remove the binding. */ void SetRankManager(cRankManager * a_RankManager) { m_RankMgr = a_RankManager; } protected: @@ -112,7 +112,7 @@ protected: m_UUID(), m_Textures(), m_TexturesSignature(), - m_DateTime(time(NULL)) + m_DateTime(time(nullptr)) { } @@ -176,7 +176,7 @@ protected: /** Protects m_UUIDToProfile against simultaneous multi-threaded access. */ cCriticalSection m_CSUUIDToProfile; - /** The rank manager that is notified of the name-uuid pairings. May be NULL. Protected by m_CSRankMgr. */ + /** The rank manager that is notified of the name-uuid pairings. May be nullptr. Protected by m_CSRankMgr. */ cRankManager * m_RankMgr; /** Protects m_RankMgr agains simultaneous multi-threaded access. */ diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index f4779d83b..f33d37b30 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -120,7 +120,7 @@ cProtocol172::cProtocol172(cClientHandle * a_Client, const AString & a_ServerAdd { static int sCounter = 0; cFile::CreateFolder("CommLogs"); - AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(NULL), sCounter++, a_Client->GetIPString().c_str()); + AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(nullptr), sCounter++, a_Client->GetIPString().c_str()); m_CommLogFile.Open(FileName, cFile::fmWrite); } } @@ -159,7 +159,7 @@ void cProtocol172::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_ cPacketizer Pkt(*this, 0x1b); // Attach Entity packet Pkt.WriteInt(a_Entity.GetUniqueID()); - Pkt.WriteInt((a_Vehicle != NULL) ? a_Vehicle->GetUniqueID() : 0); + Pkt.WriteInt((a_Vehicle != nullptr) ? a_Vehicle->GetUniqueID() : 0); Pkt.WriteBool(false); } @@ -254,7 +254,7 @@ void cProtocol172::SendChat(const cCompositeChat & a_Message) ASSERT(m_State == 3); // In game mode? cWorld * World = m_Client->GetPlayer()->GetWorld(); - bool ShouldUseChatPrefixes = (World == NULL) ? false : World->ShouldUseChatPrefixes(); + bool ShouldUseChatPrefixes = (World == nullptr) ? false : World->ShouldUseChatPrefixes(); // Send the message to the client: cPacketizer Pkt(*this, 0x02); diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index 39046e2ed..8445e8f26 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -107,7 +107,7 @@ cProtocol180::cProtocol180(cClientHandle * a_Client, const AString & a_ServerAdd { static int sCounter = 0; cFile::CreateFolder("CommLogs"); - AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(NULL), sCounter++, a_Client->GetIPString().c_str()); + AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(nullptr), sCounter++, a_Client->GetIPString().c_str()); m_CommLogFile.Open(FileName, cFile::fmWrite); } } @@ -146,7 +146,7 @@ void cProtocol180::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_ cPacketizer Pkt(*this, 0x1b); // Attach Entity packet Pkt.WriteInt(a_Entity.GetUniqueID()); - Pkt.WriteInt((a_Vehicle != NULL) ? a_Vehicle->GetUniqueID() : 0); + Pkt.WriteInt((a_Vehicle != nullptr) ? a_Vehicle->GetUniqueID() : 0); Pkt.WriteBool(false); } @@ -234,7 +234,7 @@ void cProtocol180::SendChat(const cCompositeChat & a_Message) ASSERT(m_State == 3); // In game mode? cWorld * World = m_Client->GetPlayer()->GetWorld(); - bool ShouldUseChatPrefixes = (World == NULL) ? false : World->ShouldUseChatPrefixes(); + bool ShouldUseChatPrefixes = (World == nullptr) ? false : World->ShouldUseChatPrefixes(); // Send the message to the client: cPacketizer Pkt(*this, 0x02); diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index 0c1e83b67..af9e0d1bc 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -22,7 +22,7 @@ cProtocolRecognizer::cProtocolRecognizer(cClientHandle * a_Client) : super(a_Client), - m_Protocol(NULL), + m_Protocol(nullptr), m_Buffer(8192) // We need a larger buffer to support BungeeCord - it sends one huge packet at the start { } @@ -34,7 +34,7 @@ cProtocolRecognizer::cProtocolRecognizer(cClientHandle * a_Client) : cProtocolRecognizer::~cProtocolRecognizer() { delete m_Protocol; - m_Protocol = NULL; + m_Protocol = nullptr; } @@ -59,7 +59,7 @@ AString cProtocolRecognizer::GetVersionTextFromInt(int a_ProtocolVersion) void cProtocolRecognizer::DataReceived(const char * a_Data, size_t a_Size) { - if (m_Protocol == NULL) + if (m_Protocol == nullptr) { if (!m_Buffer.Write(a_Data, a_Size)) { @@ -90,7 +90,7 @@ void cProtocolRecognizer::DataReceived(const char * a_Data, size_t a_Size) void cProtocolRecognizer::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_Vehicle) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendAttachEntity(a_Entity, a_Vehicle); } @@ -100,7 +100,7 @@ void cProtocolRecognizer::SendAttachEntity(const cEntity & a_Entity, const cEnti void cProtocolRecognizer::SendBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockAction(a_BlockX, a_BlockY, a_BlockZ, a_Byte1, a_Byte2, a_BlockType); } @@ -110,7 +110,7 @@ void cProtocolRecognizer::SendBlockAction(int a_BlockX, int a_BlockY, int a_Bloc void cProtocolRecognizer::SendBlockBreakAnim(int a_entityID, int a_BlockX, int a_BlockY, int a_BlockZ, char stage) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockBreakAnim(a_entityID, a_BlockX, a_BlockY, a_BlockZ, stage); } @@ -120,7 +120,7 @@ void cProtocolRecognizer::SendBlockBreakAnim(int a_entityID, int a_BlockX, int a void cProtocolRecognizer::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockChange(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); } @@ -130,7 +130,7 @@ void cProtocolRecognizer::SendBlockChange(int a_BlockX, int a_BlockY, int a_Bloc void cProtocolRecognizer::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSetBlockVector & a_Changes) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockChanges(a_ChunkX, a_ChunkZ, a_Changes); } @@ -140,7 +140,7 @@ void cProtocolRecognizer::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSe void cProtocolRecognizer::SendChat(const AString & a_Message) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendChat(a_Message); } @@ -150,7 +150,7 @@ void cProtocolRecognizer::SendChat(const AString & a_Message) void cProtocolRecognizer::SendChat(const cCompositeChat & a_Message) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendChat(a_Message); } @@ -160,7 +160,7 @@ void cProtocolRecognizer::SendChat(const cCompositeChat & a_Message) void cProtocolRecognizer::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendChunkData(a_ChunkX, a_ChunkZ, a_Serializer); } @@ -170,7 +170,7 @@ void cProtocolRecognizer::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSe void cProtocolRecognizer::SendCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendCollectEntity(a_Entity, a_Player); } @@ -180,7 +180,7 @@ void cProtocolRecognizer::SendCollectEntity(const cEntity & a_Entity, const cPla void cProtocolRecognizer::SendDestroyEntity(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendDestroyEntity(a_Entity); } @@ -190,7 +190,7 @@ void cProtocolRecognizer::SendDestroyEntity(const cEntity & a_Entity) void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) { - if (m_Protocol != NULL) + if (m_Protocol != nullptr) { m_Protocol->SendDisconnect(a_Reason); } @@ -212,7 +212,7 @@ void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) void cProtocolRecognizer::SendEditSign(int a_BlockX, int a_BlockY, int a_BlockZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEditSign(a_BlockX, a_BlockY, a_BlockZ); } @@ -222,7 +222,7 @@ void cProtocolRecognizer::SendEditSign(int a_BlockX, int a_BlockY, int a_BlockZ) void cProtocolRecognizer::SendEntityEffect(const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityEffect(a_Entity, a_EffectID, a_Amplifier, a_Duration); } @@ -232,7 +232,7 @@ void cProtocolRecognizer::SendEntityEffect(const cEntity & a_Entity, int a_Effec void cProtocolRecognizer::SendEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityEquipment(a_Entity, a_SlotNum, a_Item); } @@ -242,7 +242,7 @@ void cProtocolRecognizer::SendEntityEquipment(const cEntity & a_Entity, short a_ void cProtocolRecognizer::SendEntityHeadLook(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityHeadLook(a_Entity); } @@ -252,7 +252,7 @@ void cProtocolRecognizer::SendEntityHeadLook(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityLook(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityLook(a_Entity); } @@ -262,7 +262,7 @@ void cProtocolRecognizer::SendEntityLook(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityMetadata(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityMetadata(a_Entity); } @@ -272,7 +272,7 @@ void cProtocolRecognizer::SendEntityMetadata(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityProperties(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityProperties(a_Entity); } @@ -282,7 +282,7 @@ void cProtocolRecognizer::SendEntityProperties(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityRelMove(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityRelMove(a_Entity, a_RelX, a_RelY, a_RelZ); } @@ -292,7 +292,7 @@ void cProtocolRecognizer::SendEntityRelMove(const cEntity & a_Entity, char a_Rel void cProtocolRecognizer::SendEntityRelMoveLook(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityRelMoveLook(a_Entity, a_RelX, a_RelY, a_RelZ); } @@ -302,7 +302,7 @@ void cProtocolRecognizer::SendEntityRelMoveLook(const cEntity & a_Entity, char a void cProtocolRecognizer::SendEntityStatus(const cEntity & a_Entity, char a_Status) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityStatus(a_Entity, a_Status); } @@ -312,7 +312,7 @@ void cProtocolRecognizer::SendEntityStatus(const cEntity & a_Entity, char a_Stat void cProtocolRecognizer::SendEntityVelocity(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityVelocity(a_Entity); } @@ -322,7 +322,7 @@ void cProtocolRecognizer::SendEntityVelocity(const cEntity & a_Entity) void cProtocolRecognizer::SendExplosion(double a_BlockX, double a_BlockY, double a_BlockZ, float a_Radius, const cVector3iArray & a_BlocksAffected, const Vector3d & a_PlayerMotion) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendExplosion(a_BlockX, a_BlockY, a_BlockZ, a_Radius, a_BlocksAffected, a_PlayerMotion); } @@ -332,7 +332,7 @@ void cProtocolRecognizer::SendExplosion(double a_BlockX, double a_BlockY, double void cProtocolRecognizer::SendGameMode(eGameMode a_GameMode) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendGameMode(a_GameMode); } @@ -342,7 +342,7 @@ void cProtocolRecognizer::SendGameMode(eGameMode a_GameMode) void cProtocolRecognizer::SendHealth(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendHealth(); } @@ -352,7 +352,7 @@ void cProtocolRecognizer::SendHealth(void) void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWindowProperty(a_Window, a_Property, a_Value); } @@ -362,7 +362,7 @@ void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, short a_P void cProtocolRecognizer::SendInventorySlot(char a_WindowID, short a_SlotNum, const cItem & a_Item) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendInventorySlot(a_WindowID, a_SlotNum, a_Item); } @@ -372,7 +372,7 @@ void cProtocolRecognizer::SendInventorySlot(char a_WindowID, short a_SlotNum, co void cProtocolRecognizer::SendKeepAlive(int a_PingID) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendKeepAlive(a_PingID); } @@ -382,7 +382,7 @@ void cProtocolRecognizer::SendKeepAlive(int a_PingID) void cProtocolRecognizer::SendLogin(const cPlayer & a_Player, const cWorld & a_World) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendLogin(a_Player, a_World); } @@ -392,7 +392,7 @@ void cProtocolRecognizer::SendLogin(const cPlayer & a_Player, const cWorld & a_W void cProtocolRecognizer::SendLoginSuccess(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendLoginSuccess(); } @@ -402,7 +402,7 @@ void cProtocolRecognizer::SendLoginSuccess(void) void cProtocolRecognizer::SendMapColumn(int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length, unsigned int m_Scale) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendMapColumn(a_ID, a_X, a_Y, a_Colors, a_Length, m_Scale); } @@ -412,7 +412,7 @@ void cProtocolRecognizer::SendMapColumn(int a_ID, int a_X, int a_Y, const Byte * void cProtocolRecognizer::SendMapDecorators(int a_ID, const cMapDecoratorList & a_Decorators, unsigned int m_Scale) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendMapDecorators(a_ID, a_Decorators, m_Scale); } @@ -422,7 +422,7 @@ void cProtocolRecognizer::SendMapDecorators(int a_ID, const cMapDecoratorList & void cProtocolRecognizer::SendMapInfo(int a_ID, unsigned int a_Scale) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendMapInfo(a_ID, a_Scale); } @@ -432,7 +432,7 @@ void cProtocolRecognizer::SendMapInfo(int a_ID, unsigned int a_Scale) void cProtocolRecognizer::SendParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendParticleEffect(a_ParticleName, a_SrcX, a_SrcY, a_SrcZ, a_OffsetX, a_OffsetY, a_OffsetZ, a_ParticleData, a_ParticleAmount); } @@ -450,7 +450,7 @@ void cProtocolRecognizer::SendPaintingSpawn(const cPainting & a_Painting) void cProtocolRecognizer::SendPickupSpawn(const cPickup & a_Pickup) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPickupSpawn(a_Pickup); } @@ -460,7 +460,7 @@ void cProtocolRecognizer::SendPickupSpawn(const cPickup & a_Pickup) void cProtocolRecognizer::SendPlayerAbilities(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerAbilities(); } @@ -470,7 +470,7 @@ void cProtocolRecognizer::SendPlayerAbilities(void) void cProtocolRecognizer::SendEntityAnimation(const cEntity & a_Entity, char a_Animation) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityAnimation(a_Entity, a_Animation); } @@ -480,7 +480,7 @@ void cProtocolRecognizer::SendEntityAnimation(const cEntity & a_Entity, char a_A void cProtocolRecognizer::SendPlayerListAddPlayer(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListAddPlayer(a_Player); } @@ -490,7 +490,7 @@ void cProtocolRecognizer::SendPlayerListAddPlayer(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListRemovePlayer(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListRemovePlayer(a_Player); } @@ -500,7 +500,7 @@ void cProtocolRecognizer::SendPlayerListRemovePlayer(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListUpdateGameMode(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListUpdateGameMode(a_Player); } @@ -510,7 +510,7 @@ void cProtocolRecognizer::SendPlayerListUpdateGameMode(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListUpdatePing(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListUpdatePing(a_Player); } @@ -520,7 +520,7 @@ void cProtocolRecognizer::SendPlayerListUpdatePing(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListUpdateDisplayName(a_Player, a_CustomName); } @@ -530,7 +530,7 @@ void cProtocolRecognizer::SendPlayerListUpdateDisplayName(const cPlayer & a_Play void cProtocolRecognizer::SendPlayerMaxSpeed(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerMaxSpeed(); } @@ -540,7 +540,7 @@ void cProtocolRecognizer::SendPlayerMaxSpeed(void) void cProtocolRecognizer::SendPlayerMoveLook(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerMoveLook(); } @@ -550,7 +550,7 @@ void cProtocolRecognizer::SendPlayerMoveLook(void) void cProtocolRecognizer::SendPlayerPosition(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerPosition(); } @@ -560,7 +560,7 @@ void cProtocolRecognizer::SendPlayerPosition(void) void cProtocolRecognizer::SendPlayerSpawn(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerSpawn(a_Player); } @@ -570,7 +570,7 @@ void cProtocolRecognizer::SendPlayerSpawn(const cPlayer & a_Player) void cProtocolRecognizer::SendPluginMessage(const AString & a_Channel, const AString & a_Message) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPluginMessage(a_Channel, a_Message); } @@ -580,7 +580,7 @@ void cProtocolRecognizer::SendPluginMessage(const AString & a_Channel, const ASt void cProtocolRecognizer::SendRemoveEntityEffect(const cEntity & a_Entity, int a_EffectID) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendRemoveEntityEffect(a_Entity, a_EffectID); } @@ -590,7 +590,7 @@ void cProtocolRecognizer::SendRemoveEntityEffect(const cEntity & a_Entity, int a void cProtocolRecognizer::SendRespawn(eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendRespawn(a_Dimension, a_ShouldIgnoreDimensionChecks); } @@ -600,7 +600,7 @@ void cProtocolRecognizer::SendRespawn(eDimension a_Dimension, bool a_ShouldIgnor void cProtocolRecognizer::SendExperience(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendExperience(); } @@ -610,7 +610,7 @@ void cProtocolRecognizer::SendExperience(void) void cProtocolRecognizer::SendExperienceOrb(const cExpOrb & a_ExpOrb) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendExperienceOrb(a_ExpOrb); } @@ -620,7 +620,7 @@ void cProtocolRecognizer::SendExperienceOrb(const cExpOrb & a_ExpOrb) void cProtocolRecognizer::SendScoreboardObjective(const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendScoreboardObjective(a_Name, a_DisplayName, a_Mode); } @@ -630,7 +630,7 @@ void cProtocolRecognizer::SendScoreboardObjective(const AString & a_Name, const void cProtocolRecognizer::SendScoreUpdate(const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendScoreUpdate(a_Objective, a_Player, a_Score, a_Mode); } @@ -640,7 +640,7 @@ void cProtocolRecognizer::SendScoreUpdate(const AString & a_Objective, const ASt void cProtocolRecognizer::SendDisplayObjective(const AString & a_Objective, cScoreboard::eDisplaySlot a_Display) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendDisplayObjective(a_Objective, a_Display); } @@ -650,7 +650,7 @@ void cProtocolRecognizer::SendDisplayObjective(const AString & a_Objective, cSco void cProtocolRecognizer::SendSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSoundEffect(a_SoundName, a_X, a_Y, a_Z, a_Volume, a_Pitch); } @@ -660,7 +660,7 @@ void cProtocolRecognizer::SendSoundEffect(const AString & a_SoundName, double a_ void cProtocolRecognizer::SendSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSoundParticleEffect(a_EffectID, a_SrcX, a_SrcY, a_SrcZ, a_Data); } @@ -670,7 +670,7 @@ void cProtocolRecognizer::SendSoundParticleEffect(int a_EffectID, int a_SrcX, in void cProtocolRecognizer::SendSpawnFallingBlock(const cFallingBlock & a_FallingBlock) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnFallingBlock(a_FallingBlock); } @@ -680,7 +680,7 @@ void cProtocolRecognizer::SendSpawnFallingBlock(const cFallingBlock & a_FallingB void cProtocolRecognizer::SendSpawnMob(const cMonster & a_Mob) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnMob(a_Mob); } @@ -690,7 +690,7 @@ void cProtocolRecognizer::SendSpawnMob(const cMonster & a_Mob) void cProtocolRecognizer::SendSpawnObject(const cEntity & a_Entity, char a_ObjectType, int a_ObjectData, Byte a_Yaw, Byte a_Pitch) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnObject(a_Entity, a_ObjectType, a_ObjectData, a_Yaw, a_Pitch); } @@ -700,7 +700,7 @@ void cProtocolRecognizer::SendSpawnObject(const cEntity & a_Entity, char a_Objec void cProtocolRecognizer::SendSpawnVehicle(const cEntity & a_Vehicle, char a_VehicleType, char a_VehicleSubType) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnVehicle(a_Vehicle, a_VehicleType, a_VehicleSubType); } @@ -710,7 +710,7 @@ void cProtocolRecognizer::SendSpawnVehicle(const cEntity & a_Vehicle, char a_Veh void cProtocolRecognizer::SendStatistics(const cStatManager & a_Manager) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendStatistics(a_Manager); } @@ -720,7 +720,7 @@ void cProtocolRecognizer::SendStatistics(const cStatManager & a_Manager) void cProtocolRecognizer::SendTabCompletionResults(const AStringVector & a_Results) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendTabCompletionResults(a_Results); } @@ -730,7 +730,7 @@ void cProtocolRecognizer::SendTabCompletionResults(const AStringVector & a_Resul void cProtocolRecognizer::SendTeleportEntity(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendTeleportEntity(a_Entity); } @@ -740,7 +740,7 @@ void cProtocolRecognizer::SendTeleportEntity(const cEntity & a_Entity) void cProtocolRecognizer::SendThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendThunderbolt(a_BlockX, a_BlockY, a_BlockZ); } @@ -750,7 +750,7 @@ void cProtocolRecognizer::SendThunderbolt(int a_BlockX, int a_BlockY, int a_Bloc void cProtocolRecognizer::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendTimeUpdate(a_WorldAge, a_TimeOfDay, a_DoDaylightCycle); } @@ -760,7 +760,7 @@ void cProtocolRecognizer::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bo void cProtocolRecognizer::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUnloadChunk(a_ChunkX, a_ChunkZ); } @@ -770,7 +770,7 @@ void cProtocolRecognizer::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) void cProtocolRecognizer::SendUpdateBlockEntity(cBlockEntity & a_BlockEntity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUpdateBlockEntity(a_BlockEntity); } @@ -780,7 +780,7 @@ void cProtocolRecognizer::SendUpdateBlockEntity(cBlockEntity & a_BlockEntity) void cProtocolRecognizer::SendUpdateSign(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUpdateSign(a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4); } @@ -790,7 +790,7 @@ void cProtocolRecognizer::SendUpdateSign(int a_BlockX, int a_BlockY, int a_Block void cProtocolRecognizer::SendUseBed(const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUseBed(a_Entity, a_BlockX, a_BlockY, a_BlockZ); } @@ -800,7 +800,7 @@ void cProtocolRecognizer::SendUseBed(const cEntity & a_Entity, int a_BlockX, int void cProtocolRecognizer::SendWeather(eWeather a_Weather) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWeather(a_Weather); } @@ -810,7 +810,7 @@ void cProtocolRecognizer::SendWeather(eWeather a_Weather) void cProtocolRecognizer::SendWholeInventory(const cWindow & a_Window) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWholeInventory(a_Window); } @@ -820,7 +820,7 @@ void cProtocolRecognizer::SendWholeInventory(const cWindow & a_Window) void cProtocolRecognizer::SendWindowClose(const cWindow & a_Window) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWindowClose(a_Window); } @@ -830,7 +830,7 @@ void cProtocolRecognizer::SendWindowClose(const cWindow & a_Window) void cProtocolRecognizer::SendWindowOpen(const cWindow & a_Window) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWindowOpen(a_Window); } @@ -840,7 +840,7 @@ void cProtocolRecognizer::SendWindowOpen(const cWindow & a_Window) AString cProtocolRecognizer::GetAuthServerID(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); return m_Protocol->GetAuthServerID(); } diff --git a/src/RCONServer.cpp b/src/RCONServer.cpp index 141c67d1b..df027c91f 100644 --- a/src/RCONServer.cpp +++ b/src/RCONServer.cpp @@ -242,7 +242,7 @@ bool cRCONServer::cConnection::ProcessPacket(int a_RequestID, int a_PacketType, if (strncmp(a_Payload, m_RCONServer.m_Password.c_str(), a_PayloadLength) != 0) { LOGINFO("RCON: Invalid password from client %s, dropping connection.", m_IPAddress.c_str()); - SendResponse(-1, RCON_PACKET_RESPONSE, 0, NULL); + SendResponse(-1, RCON_PACKET_RESPONSE, 0, nullptr); return false; } m_IsAuthenticated = true; @@ -250,7 +250,7 @@ bool cRCONServer::cConnection::ProcessPacket(int a_RequestID, int a_PacketType, LOGD("RCON: Client at %s has successfully authenticated", m_IPAddress.c_str()); // Send OK response: - SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, NULL); + SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } @@ -268,7 +268,7 @@ bool cRCONServer::cConnection::ProcessPacket(int a_RequestID, int a_PacketType, cRoot::Get()->ExecuteConsoleCommand(cmd, *(new cRCONCommandOutput(*this, a_RequestID))); // Send an empty response: - SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, NULL); + SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } } @@ -310,7 +310,7 @@ void cRCONServer::cConnection::IntToBuffer(int a_Value, char * a_Buffer) /// Sends a RCON packet back to the client void cRCONServer::cConnection::SendResponse(int a_RequestID, int a_PacketType, int a_PayloadLength, const char * a_Payload) { - ASSERT((a_PayloadLength == 0) || (a_Payload != NULL)); // Either zero data to send, or a valid payload ptr + ASSERT((a_PayloadLength == 0) || (a_Payload != nullptr)); // Either zero data to send, or a valid payload ptr char Buffer[4]; int Length = a_PayloadLength + 10; diff --git a/src/RankManager.cpp b/src/RankManager.cpp index f5342ed3d..3778f5d64 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -384,7 +384,7 @@ protected: cRankManager::cRankManager(void) : m_DB("Ranks.sqlite", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE), m_IsInitialized(false), - m_MojangAPI(NULL) + m_MojangAPI(nullptr) { } @@ -394,9 +394,9 @@ cRankManager::cRankManager(void) : cRankManager::~cRankManager() { - if (m_MojangAPI != NULL) + if (m_MojangAPI != nullptr) { - m_MojangAPI->SetRankManager(NULL); + m_MojangAPI->SetRankManager(nullptr); } } diff --git a/src/RankManager.h b/src/RankManager.h index 61c52fda6..5dff634b5 100644 --- a/src/RankManager.h +++ b/src/RankManager.h @@ -240,7 +240,7 @@ protected: bool m_IsInitialized; /** The MojangAPI instance that is used for translating playernames to UUIDs. - Set in Initialize(), may be NULL. */ + Set in Initialize(), may be nullptr. */ cMojangAPI * m_MojangAPI; diff --git a/src/Root.cpp b/src/Root.cpp index 02455518c..6a91ec238 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -35,21 +35,21 @@ -cRoot* cRoot::s_Root = NULL; +cRoot* cRoot::s_Root = nullptr; cRoot::cRoot(void) : - m_pDefaultWorld(NULL), - m_InputThread(NULL), - m_Server(NULL), - m_MonsterConfig(NULL), - m_CraftingRecipes(NULL), - m_FurnaceRecipe(NULL), - m_WebAdmin(NULL), - m_PluginManager(NULL), + m_pDefaultWorld(nullptr), + m_InputThread(nullptr), + m_Server(nullptr), + m_MonsterConfig(nullptr), + m_CraftingRecipes(nullptr), + m_FurnaceRecipe(nullptr), + m_WebAdmin(nullptr), + m_PluginManager(nullptr), m_bStop(false), m_bRestart(false) { @@ -215,7 +215,7 @@ void cRoot::Start(void) } #if !defined(ANDROID_NDK) - delete m_InputThread; m_InputThread = NULL; + delete m_InputThread; m_InputThread = nullptr; #endif // Stop the server: @@ -230,21 +230,21 @@ void cRoot::Start(void) m_Authenticator.Stop(); LOGD("Freeing MonsterConfig..."); - delete m_MonsterConfig; m_MonsterConfig = NULL; - delete m_WebAdmin; m_WebAdmin = NULL; + delete m_MonsterConfig; m_MonsterConfig = nullptr; + delete m_WebAdmin; m_WebAdmin = nullptr; LOGD("Unloading recipes..."); - delete m_FurnaceRecipe; m_FurnaceRecipe = NULL; - delete m_CraftingRecipes; m_CraftingRecipes = NULL; + delete m_FurnaceRecipe; m_FurnaceRecipe = nullptr; + delete m_CraftingRecipes; m_CraftingRecipes = nullptr; LOGD("Unloading worlds..."); UnloadWorlds(); LOGD("Stopping plugin manager..."); - delete m_PluginManager; m_PluginManager = NULL; + delete m_PluginManager; m_PluginManager = nullptr; cItemHandler::Deinit(); LOG("Cleaning up..."); - delete m_Server; m_Server = NULL; + delete m_Server; m_Server = nullptr; LOG("Shutdown successful!"); } @@ -319,7 +319,7 @@ void cRoot::LoadWorlds(cIniFile & IniFile) cWorld * cRoot::CreateAndInitializeWorld(const AString & a_WorldName, eDimension a_Dimension, const AString & a_OverworldName) { cWorld * World = m_WorldsByName[a_WorldName]; - if (World != NULL) + if (World != nullptr) { return World; } @@ -364,7 +364,7 @@ void cRoot::StopWorlds(void) void cRoot::UnloadWorlds(void) { - m_pDefaultWorld = NULL; + m_pDefaultWorld = nullptr; for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr) { delete itr->second; @@ -397,7 +397,7 @@ cWorld * cRoot::GetWorld(const AString & a_WorldName, bool a_SearchForFolder) { return CreateAndInitializeWorld(a_WorldName); } - return NULL; + return nullptr; } @@ -409,7 +409,7 @@ bool cRoot::ForEachWorld(cWorldListCallback & a_Callback) for (WorldMap::iterator itr = m_WorldsByName.begin(), itr2 = itr; itr != m_WorldsByName.end(); itr = itr2) { ++itr2; - if (itr->second != NULL) + if (itr->second != nullptr) { if (a_Callback.Item(itr->second)) { @@ -544,7 +544,7 @@ void cRoot::BroadcastChat(const AString & a_Message, eMessageType a_ChatPrefix) { for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr) { - itr->second->BroadcastChat(a_Message, NULL, a_ChatPrefix); + itr->second->BroadcastChat(a_Message, nullptr, a_ChatPrefix); } // for itr - m_WorldsByName[] } @@ -614,7 +614,7 @@ bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallbac m_BestRating(0), m_NameLength(a_PlayerName.length()), m_PlayerName(a_PlayerName), - m_BestMatch(NULL), + m_BestMatch(nullptr), m_NumMatches(0) {} diff --git a/src/Scoreboard.cpp b/src/Scoreboard.cpp index def952029..adce8b549 100644 --- a/src/Scoreboard.cpp +++ b/src/Scoreboard.cpp @@ -278,7 +278,7 @@ cScoreboard::cScoreboard(cWorld * a_World) : m_World(a_World) { for (int i = 0; i < (int) dsCount; ++i) { - m_Display[i] = NULL; + m_Display[i] = nullptr; } } @@ -294,14 +294,14 @@ cObjective* cScoreboard::RegisterObjective(const AString & a_Name, const AString if (Status.second) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->BroadcastScoreboardObjective(a_Name, a_DisplayName, 0); return &Status.first->second; } else { - return NULL; + return nullptr; } } @@ -320,14 +320,14 @@ bool cScoreboard::RemoveObjective(const AString & a_Name) return false; } - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->BroadcastScoreboardObjective(it->second.GetName(), it->second.GetDisplayName(), 1); for (unsigned int i = 0; i < (unsigned int) dsCount; ++i) { if (m_Display[i] == &it->second) { - SetDisplay(NULL, (eDisplaySlot) i); + SetDisplay(nullptr, (eDisplaySlot) i); } } @@ -348,7 +348,7 @@ cObjective * cScoreboard::GetObjective(const AString & a_Name) if (it == m_Objectives.end()) { - return NULL; + return nullptr; } else { @@ -369,7 +369,7 @@ cTeam * cScoreboard::RegisterTeam( std::pair Status = m_Teams.insert(cNamedTeam(a_Name, Team)); - return Status.second ? &Status.first->second : NULL; + return Status.second ? &Status.first->second : nullptr; } @@ -404,7 +404,7 @@ cTeam * cScoreboard::GetTeam(const AString & a_Name) if (it == m_Teams.end()) { - return NULL; + return nullptr; } else { @@ -428,7 +428,7 @@ cTeam * cScoreboard::QueryPlayerTeam(const AString & a_Name) } } - return NULL; + return nullptr; } @@ -452,7 +452,7 @@ void cScoreboard::SetDisplay(cObjective * a_Objective, eDisplaySlot a_Slot) { m_Display[a_Slot] = a_Objective; - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->BroadcastDisplayObjective(a_Objective ? a_Objective->GetName() : "", a_Slot); } diff --git a/src/Scoreboard.h b/src/Scoreboard.h index f53b8c803..dd4073c89 100644 --- a/src/Scoreboard.h +++ b/src/Scoreboard.h @@ -226,22 +226,22 @@ public: // tolua_begin - /** Registers a new scoreboard objective, returns the cObjective instance, NULL on name collision */ + /** Registers a new scoreboard objective, returns the cObjective instance, nullptr on name collision */ cObjective * RegisterObjective(const AString & a_Name, const AString & a_DisplayName, cObjective::eType a_Type); /** Removes a registered objective, returns true if operation was successful */ bool RemoveObjective(const AString & a_Name); - /** Retrieves the objective with the specified name, NULL if not found */ + /** Retrieves the objective with the specified name, nullptr if not found */ cObjective * GetObjective(const AString & a_Name); - /** Registers a new team, returns the cTeam instance, NULL on name collision */ + /** Registers a new team, returns the cTeam instance, nullptr on name collision */ cTeam * RegisterTeam(const AString & a_Name, const AString & a_DisplayName, const AString & a_Prefix, const AString & a_Suffix); /** Removes a registered team, returns true if operation was successful */ bool RemoveTeam(const AString & a_Name); - /** Retrieves the team with the specified name, NULL if not found */ + /** Retrieves the team with the specified name, nullptr if not found */ cTeam * GetTeam(const AString & a_Name); void SetDisplay(const AString & a_Objective, eDisplaySlot a_Slot); diff --git a/src/Server.cpp b/src/Server.cpp index db3ab2ed4..5085d4c94 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -338,7 +338,7 @@ void cServer::OnConnectionAccepted(cSocket & a_Socket) LOGERROR("Client \"%s\" cannot be handled, server probably unstable", ClientIP.c_str()); a_Socket.CloseSocket(); delete NewHandle; - NewHandle = NULL; + NewHandle = nullptr; return; } @@ -637,17 +637,17 @@ void cServer::PrintHelp(const AStringVector & a_Split, cCommandOutputCallback & void cServer::BindBuiltInConsoleCommands(void) { cPluginManager * PlgMgr = cPluginManager::Get(); - PlgMgr->BindConsoleCommand("help", NULL, " - Shows the available commands"); - PlgMgr->BindConsoleCommand("reload", NULL, " - Reloads all plugins"); - PlgMgr->BindConsoleCommand("restart", NULL, " - Restarts the server cleanly"); - PlgMgr->BindConsoleCommand("stop", NULL, " - Stops the server cleanly"); - PlgMgr->BindConsoleCommand("chunkstats", NULL, " - Displays detailed chunk memory statistics"); - PlgMgr->BindConsoleCommand("load ", NULL, " - Adds and enables the specified plugin"); - PlgMgr->BindConsoleCommand("unload ", NULL, " - Disables the specified plugin"); - PlgMgr->BindConsoleCommand("destroyentities", NULL, " - Destroys all entities in all worlds"); + PlgMgr->BindConsoleCommand("help", nullptr, " - Shows the available commands"); + PlgMgr->BindConsoleCommand("reload", nullptr, " - Reloads all plugins"); + PlgMgr->BindConsoleCommand("restart", nullptr, " - Restarts the server cleanly"); + PlgMgr->BindConsoleCommand("stop", nullptr, " - Stops the server cleanly"); + PlgMgr->BindConsoleCommand("chunkstats", nullptr, " - Displays detailed chunk memory statistics"); + PlgMgr->BindConsoleCommand("load ", nullptr, " - Adds and enables the specified plugin"); + PlgMgr->BindConsoleCommand("unload ", nullptr, " - Disables the specified plugin"); + PlgMgr->BindConsoleCommand("destroyentities", nullptr, " - Destroys all entities in all worlds"); #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) - PlgMgr->BindConsoleCommand("dumpmem", NULL, " - Dumps all used memory blocks together with their callstacks into memdump.xml"); + PlgMgr->BindConsoleCommand("dumpmem", nullptr, " - Dumps all used memory blocks together with their callstacks into memdump.xml"); #endif } @@ -716,7 +716,7 @@ void cServer::AuthenticateUser(int a_ClientID, const AString & a_Name, const ASt cServer::cNotifyWriteThread::cNotifyWriteThread(void) : super("ClientPacketThread"), - m_Server(NULL) + m_Server(nullptr) { } diff --git a/src/SetChunkData.cpp b/src/SetChunkData.cpp index 707dfb9e8..e335176a8 100644 --- a/src/SetChunkData.cpp +++ b/src/SetChunkData.cpp @@ -42,15 +42,15 @@ cSetChunkData::cSetChunkData( m_ShouldMarkDirty(a_ShouldMarkDirty) { // Check the params' validity: - ASSERT(a_BlockTypes != NULL); - ASSERT(a_BlockMetas != NULL); + ASSERT(a_BlockTypes != nullptr); + ASSERT(a_BlockMetas != nullptr); // Copy block types and metas: memcpy(m_BlockTypes, a_BlockTypes, sizeof(cChunkDef::BlockTypes)); memcpy(m_BlockMetas, a_BlockMetas, sizeof(cChunkDef::BlockNibbles)); // Copy lights, if both given: - if ((a_BlockLight != NULL) && (a_SkyLight != NULL)) + if ((a_BlockLight != nullptr) && (a_SkyLight != nullptr)) { memcpy(m_BlockLight, a_BlockLight, sizeof(m_BlockLight)); memcpy(m_SkyLight, a_SkyLight, sizeof(m_SkyLight)); @@ -62,7 +62,7 @@ cSetChunkData::cSetChunkData( } // Copy the heightmap, if available: - if (a_HeightMap != NULL) + if (a_HeightMap != nullptr) { memcpy(m_HeightMap, a_HeightMap, sizeof(m_HeightMap)); m_IsHeightMapValid = true; @@ -73,7 +73,7 @@ cSetChunkData::cSetChunkData( } // Copy biomes, if available: - if (a_Biomes != NULL) + if (a_Biomes != nullptr) { memcpy(m_Biomes, a_Biomes, sizeof(m_Biomes)); m_AreBiomesValid = true; diff --git a/src/SetChunkData.h b/src/SetChunkData.h index 03e9ef4d9..1eeb75ca9 100644 --- a/src/SetChunkData.h +++ b/src/SetChunkData.h @@ -27,7 +27,7 @@ public: Will move the entity and blockentity lists into the internal storage, and empty the a_Entities and a_BlockEntities lists. a_BlockTypes and a_BlockMetas must always be valid. - If either of the light arrays are NULL, the chunk data will be marked as not having any light at all and + If either of the light arrays are nullptr, the chunk data will be marked as not having any light at all and will be scheduled for re-lighting once it is set into the chunkmap. If a_Biomes is not valid, the internal flag is set and the world will calculate the biomes using the chunk generator when setting the chunk data. diff --git a/src/Simulator/DelayedFluidSimulator.cpp b/src/Simulator/DelayedFluidSimulator.cpp index 59ea51aa0..dc8dffe2d 100644 --- a/src/Simulator/DelayedFluidSimulator.cpp +++ b/src/Simulator/DelayedFluidSimulator.cpp @@ -55,7 +55,7 @@ cDelayedFluidSimulatorChunkData::cDelayedFluidSimulatorChunkData(int a_TickDelay cDelayedFluidSimulatorChunkData::~cDelayedFluidSimulatorChunkData() { delete[] m_Slots; - m_Slots = NULL; + m_Slots = nullptr; } @@ -86,7 +86,7 @@ void cDelayedFluidSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, return; } - if ((a_Chunk == NULL) || !a_Chunk->IsValid()) + if ((a_Chunk == nullptr) || !a_Chunk->IsValid()) { return; } diff --git a/src/Simulator/FireSimulator.cpp b/src/Simulator/FireSimulator.cpp index d3deee74a..75ebefcf7 100644 --- a/src/Simulator/FireSimulator.cpp +++ b/src/Simulator/FireSimulator.cpp @@ -220,7 +220,7 @@ bool cFireSimulator::DoesBurnForever(BLOCKTYPE a_BlockType) void cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { - if ((a_Chunk == NULL) || !a_Chunk->IsValid()) + if ((a_Chunk == nullptr) || !a_Chunk->IsValid()) { return; } @@ -359,7 +359,7 @@ void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_Rel int Z = a_RelZ + gNeighborCoords[i].z; cChunkPtr Neighbour = a_Chunk->GetRelNeighborChunkAdjustCoords(X, Z); - if (Neighbour == NULL) + if (Neighbour == nullptr) { continue; } diff --git a/src/Simulator/FloodyFluidSimulator.cpp b/src/Simulator/FloodyFluidSimulator.cpp index b839aa746..e95ef216d 100644 --- a/src/Simulator/FloodyFluidSimulator.cpp +++ b/src/Simulator/FloodyFluidSimulator.cpp @@ -220,7 +220,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i ASSERT(a_NewMeta > 0); // Source blocks aren't spread a_NearChunk = a_NearChunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((a_NearChunk == NULL) || (!a_NearChunk->IsValid())) + if ((a_NearChunk == nullptr) || (!a_NearChunk->IsValid())) { // Chunk not available return; @@ -297,7 +297,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i ChunkInterface, m_World, PluginInterface, - NULL, + nullptr, BlockX, a_RelY, BlockZ diff --git a/src/Simulator/FluidSimulator.cpp b/src/Simulator/FluidSimulator.cpp index 58501326f..9c8453d04 100644 --- a/src/Simulator/FluidSimulator.cpp +++ b/src/Simulator/FluidSimulator.cpp @@ -178,7 +178,7 @@ Direction cFluidSimulator::GetFlowingDirection(int a_X, int a_Y, int a_Z, bool a } delete Pos; - Pos = NULL; + Pos = nullptr; } if (LowestPoint == m_World.GetBlockMeta(a_X, a_Y, a_Z)) diff --git a/src/Simulator/FluidSimulator.h b/src/Simulator/FluidSimulator.h index 0877a7bf1..d65a8e78b 100644 --- a/src/Simulator/FluidSimulator.h +++ b/src/Simulator/FluidSimulator.h @@ -51,7 +51,7 @@ public: virtual Direction GetFlowingDirection(int a_X, int a_Y, int a_Z, bool a_Over = true); /// Creates a ChunkData object for the simulator to use. The simulator returns the correct object type. - virtual cFluidSimulatorData * CreateChunkData(void) { return NULL; } + virtual cFluidSimulatorData * CreateChunkData(void) { return nullptr; } bool IsFluidBlock (BLOCKTYPE a_BlockType) const { return (a_BlockType == m_FluidBlock); } bool IsStationaryFluidBlock(BLOCKTYPE a_BlockType) const { return (a_BlockType == m_StationaryFluidBlock); } diff --git a/src/Simulator/NoopRedstoneSimulator.h b/src/Simulator/NoopRedstoneSimulator.h index 7c961f32b..832b26dfc 100644 --- a/src/Simulator/NoopRedstoneSimulator.h +++ b/src/Simulator/NoopRedstoneSimulator.h @@ -39,7 +39,7 @@ public: virtual cRedstoneSimulatorChunkData * CreateChunkData() override { - return NULL; + return nullptr; } } ; diff --git a/src/Simulator/SandSimulator.cpp b/src/Simulator/SandSimulator.cpp index aad41e463..073518b31 100644 --- a/src/Simulator/SandSimulator.cpp +++ b/src/Simulator/SandSimulator.cpp @@ -94,7 +94,7 @@ bool cSandSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType) void cSandSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { - if ((a_Chunk == NULL) || !a_Chunk->IsValid()) + if ((a_Chunk == nullptr) || !a_Chunk->IsValid()) { return; } diff --git a/src/Simulator/VaporizeFluidSimulator.cpp b/src/Simulator/VaporizeFluidSimulator.cpp index 484cac334..119742346 100644 --- a/src/Simulator/VaporizeFluidSimulator.cpp +++ b/src/Simulator/VaporizeFluidSimulator.cpp @@ -22,7 +22,7 @@ cVaporizeFluidSimulator::cVaporizeFluidSimulator(cWorld & a_World, BLOCKTYPE a_F void cVaporizeFluidSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { return; } diff --git a/src/StackWalker.h b/src/StackWalker.h index bf47d3726..a609f6840 100644 --- a/src/StackWalker.h +++ b/src/StackWalker.h @@ -88,7 +88,7 @@ public: StackWalker( int options = OptionsAll, // 'int' is by design, to combine the enum-flags - LPCSTR szSymPath = NULL, + LPCSTR szSymPath = nullptr, DWORD dwProcessId = GetCurrentProcessId(), HANDLE hProcess = GetCurrentProcess() ); @@ -108,9 +108,9 @@ public: BOOL ShowCallstack( HANDLE hThread = GetCurrentThread(), - const CONTEXT *context = NULL, - PReadProcessMemoryRoutine readMemoryFunction = NULL, - LPVOID pUserData = NULL // optional to identify some data in the 'readMemoryFunction'-callback + const CONTEXT *context = nullptr, + PReadProcessMemoryRoutine readMemoryFunction = nullptr, + LPVOID pUserData = nullptr // optional to identify some data in the 'readMemoryFunction'-callback ); #if _MSC_VER >= 1300 @@ -180,11 +180,11 @@ protected: #define GET_CURRENT_CONTEXT(c, contextFlags) \ do { \ memset(&c, 0, sizeof(CONTEXT)); \ - EXCEPTION_POINTERS *pExp = NULL; \ + EXCEPTION_POINTERS *pExp = nullptr; \ __try { \ throw 0; \ } __except( ( (pExp = GetExceptionInformation()) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_EXECUTE_HANDLER)) {} \ - if (pExp != NULL) \ + if (pExp != nullptr) \ memcpy(&c, pExp->ContextRecord, sizeof(CONTEXT)); \ c.ContextFlags = contextFlags; \ } while(0); diff --git a/src/StringUtils.cpp b/src/StringUtils.cpp index 21962f832..34f2da682 100644 --- a/src/StringUtils.cpp +++ b/src/StringUtils.cpp @@ -20,7 +20,7 @@ AString & AppendVPrintf(AString & str, const char * format, va_list args) { - ASSERT(format != NULL); + ASSERT(format != nullptr); char buffer[2048]; size_t len; @@ -562,7 +562,7 @@ AString & CreateHexDump(AString & a_Out, const void * a_Data, size_t a_Size, siz #else int Count = sprintf(line, "%08x:", (unsigned)i); #endif - // Remove the terminating NULL / leftover garbage in line, after the sprintf-ed value + // Remove the terminating nullptr / leftover garbage in line, after the sprintf-ed value memset(line + Count, 32, sizeof(line) - Count); p = line + 10; q = p + 2 + a_BytesPerLine * 3 + 1; diff --git a/src/UI/SlotArea.cpp b/src/UI/SlotArea.cpp index 88d9f44fc..9113ec343 100644 --- a/src/UI/SlotArea.cpp +++ b/src/UI/SlotArea.cpp @@ -48,9 +48,9 @@ void cSlotArea::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickA ASSERT((a_SlotNum >= 0) && (a_SlotNum < GetNumSlots())); bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -791,9 +791,9 @@ void cSlotAreaAnvil::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_C } bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -980,7 +980,7 @@ void cSlotAreaAnvil::OnTakeResult(cPlayer & a_Player) m_ParentWindow.SetProperty(0, m_MaximumCost, a_Player); m_MaximumCost = 0; - ((cAnvilWindow*)&m_ParentWindow)->SetRepairedItemName("", NULL); + ((cAnvilWindow*)&m_ParentWindow)->SetRepairedItemName("", nullptr); int PosX, PosY, PosZ; ((cAnvilWindow*)&m_ParentWindow)->GetBlockPos(PosX, PosY, PosZ); @@ -1238,9 +1238,9 @@ void cSlotAreaBeacon::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ ASSERT((a_SlotNum >= 0) && (a_SlotNum < GetNumSlots())); bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -1408,9 +1408,9 @@ void cSlotAreaEnchanting::Clicked(cPlayer & a_Player, int a_SlotNum, eClickActio ASSERT((a_SlotNum >= 0) && (a_SlotNum < GetNumSlots())); bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -1709,19 +1709,19 @@ cSlotAreaFurnace::~cSlotAreaFurnace() void cSlotAreaFurnace::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) { - if (m_Furnace == NULL) + if (m_Furnace == nullptr) { - LOGERROR("cSlotAreaFurnace::Clicked(): m_Furnace == NULL"); - ASSERT(!"cSlotAreaFurnace::Clicked(): m_Furnace == NULL"); + LOGERROR("cSlotAreaFurnace::Clicked(): m_Furnace == nullptr"); + ASSERT(!"cSlotAreaFurnace::Clicked(): m_Furnace == nullptr"); return; } if (a_SlotNum == 2) { bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -2071,9 +2071,9 @@ void cSlotAreaArmor::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_C } bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -2223,15 +2223,15 @@ const cItem * cSlotAreaTemporary::GetSlot(int a_SlotNum, cPlayer & a_Player) con LOGERROR("cSlotAreaTemporary: player \"%s\" not found for slot %d!", a_Player.GetName().c_str(), a_SlotNum); ASSERT(!"cSlotAreaTemporary: player not found!"); - // Player not found, this should not happen, ever! Return NULL, but things may break by this. - return NULL; + // Player not found, this should not happen, ever! Return nullptr, but things may break by this. + return nullptr; } if (a_SlotNum >= (int)(itr->second.size())) { LOGERROR("cSlotAreaTemporary: asking for more slots than actually stored!"); ASSERT(!"cSlotAreaTemporary: asking for more slots than actually stored!"); - return NULL; + return nullptr; } return &(itr->second[a_SlotNum]); @@ -2320,7 +2320,7 @@ cItem * cSlotAreaTemporary::GetPlayerSlots(cPlayer & a_Player) cItemMap::iterator itr = m_Items.find(a_Player.GetUniqueID()); if (itr == m_Items.end()) { - return NULL; + return nullptr; } return &(itr->second[0]); } diff --git a/src/UI/Window.cpp b/src/UI/Window.cpp index 802d0d219..1598dd3e7 100644 --- a/src/UI/Window.cpp +++ b/src/UI/Window.cpp @@ -33,7 +33,7 @@ cWindow::cWindow(WindowType a_WindowType, const AString & a_WindowTitle) : m_WindowTitle(a_WindowTitle), m_IsDestroyed(false), m_ShouldDistributeToHotbarFirst(true), - m_Owner(NULL) + m_Owner(nullptr) { if (a_WindowType == wtInventory) { @@ -105,10 +105,10 @@ const cItem * cWindow::GetSlot(cPlayer & a_Player, int a_SlotNum) const // Return the item at the specified slot for the specified player int LocalSlotNum = 0; const cSlotArea * Area = GetSlotArea(a_SlotNum, LocalSlotNum); - if (Area == NULL) + if (Area == nullptr) { - LOGWARNING("%s: requesting item from an invalid SlotArea (SlotNum %d), returning NULL.", __FUNCTION__, a_SlotNum); - return NULL; + LOGWARNING("%s: requesting item from an invalid SlotArea (SlotNum %d), returning nullptr.", __FUNCTION__, a_SlotNum); + return nullptr; } return Area->GetSlot(LocalSlotNum, a_Player); } @@ -122,7 +122,7 @@ void cWindow::SetSlot(cPlayer & a_Player, int a_SlotNum, const cItem & a_Item) // Set the item to the specified slot for the specified player int LocalSlotNum = 0; cSlotArea * Area = GetSlotArea(a_SlotNum, LocalSlotNum); - if (Area == NULL) + if (Area == nullptr) { LOGWARNING("%s: requesting write to an invalid SlotArea (SlotNum %d), ignoring.", __FUNCTION__, a_SlotNum); return; @@ -177,7 +177,7 @@ void cWindow::GetSlots(cPlayer & a_Player, cItems & a_Slots) const for (int i = 0; i < NumSlots; i++) { const cItem * Item = (*itr)->GetSlot(i, a_Player); - if (Item == NULL) + if (Item == nullptr) { a_Slots.push_back(cItem()); } @@ -311,7 +311,7 @@ bool cWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) } cClientHandle * ClientHandle = a_Player.GetClientHandle(); - if (ClientHandle != NULL) + if (ClientHandle != nullptr) { ClientHandle->SendWindowClose(*this); } @@ -345,7 +345,7 @@ bool cWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) void cWindow::OwnerDestroyed() { - m_Owner = NULL; + m_Owner = nullptr; // Close window for each player. Note that the last one needs special handling while (m_OpenedBy.size() > 1) { @@ -511,10 +511,10 @@ void cWindow::SendSlot(cPlayer & a_Player, cSlotArea * a_SlotArea, int a_Relativ void cWindow::Destroy(void) { - if (m_Owner != NULL) + if (m_Owner != nullptr) { m_Owner->CloseWindow(); - m_Owner = NULL; + m_Owner = nullptr; } m_IsDestroyed = true; } @@ -529,7 +529,7 @@ cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum) { LOGWARNING("%s: requesting an invalid SlotNum: %d out of %d slots", __FUNCTION__, a_GlobalSlotNum, GetNumSlots() - 1); ASSERT(!"Invalid SlotNum"); - return NULL; + return nullptr; } // Iterate through all the SlotAreas, find the correct one @@ -547,7 +547,7 @@ cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum) // We shouldn't be here - the check at the beginnning should prevent this. Log and assert LOGWARNING("%s: GetNumSlots() is out of sync: %d; LocalSlotNum = %d", __FUNCTION__, GetNumSlots(), LocalSlotNum); ASSERT(!"Invalid GetNumSlots"); - return NULL; + return nullptr; } @@ -560,7 +560,7 @@ const cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum { LOGWARNING("%s: requesting an invalid SlotNum: %d out of %d slots", __FUNCTION__, a_GlobalSlotNum, GetNumSlots() - 1); ASSERT(!"Invalid SlotNum"); - return NULL; + return nullptr; } // Iterate through all the SlotAreas, find the correct one @@ -578,7 +578,7 @@ const cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum // We shouldn't be here - the check at the beginnning should prevent this. Log and assert LOGWARNING("%s: GetNumSlots() is out of sync: %d; LocalSlotNum = %d", __FUNCTION__, GetNumSlots(), LocalSlotNum); ASSERT(!"Invalid GetNumSlots"); - return NULL; + return nullptr; } @@ -669,7 +669,7 @@ int cWindow::DistributeItemToSlots(cPlayer & a_Player, const cItem & a_Item, int { int LocalSlotNum = 0; cSlotArea * Area = GetSlotArea(*itr, LocalSlotNum); - if (Area == NULL) + if (Area == nullptr) { LOGWARNING("%s: Bad SlotArea for slot %d", __FUNCTION__, *itr); continue; @@ -836,7 +836,7 @@ void cAnvilWindow::SetRepairedItemName(const AString & a_Name, cPlayer * a_Playe { m_RepairedItemName = a_Name; - if (a_Player != NULL) + if (a_Player != nullptr) { m_AnvilSlotArea->UpdateResult(*a_Player); } @@ -963,7 +963,7 @@ cChestWindow::cChestWindow(cChestEntity * a_Chest) : m_BlockY(a_Chest->GetPosY()), m_BlockZ(a_Chest->GetPosZ()), m_PrimaryChest(a_Chest), - m_SecondaryChest(NULL) + m_SecondaryChest(nullptr) { m_SlotAreas.push_back(new cSlotAreaChest(a_Chest, *this)); m_SlotAreas.push_back(new cSlotAreaInventory(*this)); @@ -1014,7 +1014,7 @@ void cChestWindow::OpenedByPlayer(cPlayer & a_Player) cChunkDef::BlockToChunk(m_PrimaryChest->GetPosX(), m_PrimaryChest->GetPosZ(), ChunkX, ChunkZ); m_PrimaryChest->GetWorld()->MarkRedstoneDirty(ChunkX, ChunkZ); - if (m_SecondaryChest != NULL) + if (m_SecondaryChest != nullptr) { m_SecondaryChest->SetNumberOfPlayers(m_SecondaryChest->GetNumberOfPlayers() + 1); cChunkDef::BlockToChunk(m_SecondaryChest->GetPosX(), m_SecondaryChest->GetPosZ(), ChunkX, ChunkZ); @@ -1036,7 +1036,7 @@ bool cChestWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) cChunkDef::BlockToChunk(m_PrimaryChest->GetPosX(), m_PrimaryChest->GetPosZ(), ChunkX, ChunkZ); m_PrimaryChest->GetWorld()->MarkRedstoneDirty(ChunkX, ChunkZ); - if (m_SecondaryChest != NULL) + if (m_SecondaryChest != nullptr) { m_SecondaryChest->SetNumberOfPlayers(m_SecondaryChest->GetNumberOfPlayers() - 1); cChunkDef::BlockToChunk(m_SecondaryChest->GetPosX(), m_SecondaryChest->GetPosZ(), ChunkX, ChunkZ); diff --git a/src/UI/Window.h b/src/UI/Window.h index 26dd7f125..e62176d50 100644 --- a/src/UI/Window.h +++ b/src/UI/Window.h @@ -90,7 +90,7 @@ public: // tolua_begin - /// Returns the item at the specified slot for the specified player. Returns NULL if invalid SlotNum requested + /// Returns the item at the specified slot for the specified player. Returns nullptr if invalid SlotNum requested const cItem * GetSlot(cPlayer & a_Player, int a_SlotNum) const; /// Sets the item to the specified slot for the specified player @@ -189,13 +189,13 @@ protected: /** Returns the correct slot area for the specified window-global SlotNum Also returns the area-local SlotNum corresponding to the GlobalSlotNum - If the global SlotNum is out of range, returns NULL + If the global SlotNum is out of range, returns nullptr */ cSlotArea * GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum); /** Returns the correct slot area for the specified window-global SlotNum Also returns the area-local SlotNum corresponding to the GlobalSlotNum - If the global SlotNum is out of range, returns NULL. + If the global SlotNum is out of range, returns nullptr. Const version. */ const cSlotArea * GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum) const; diff --git a/src/UI/WindowOwner.h b/src/UI/WindowOwner.h index 6845a161b..4dc3cf080 100644 --- a/src/UI/WindowOwner.h +++ b/src/UI/WindowOwner.h @@ -22,7 +22,7 @@ class cWindowOwner { public: cWindowOwner() : - m_Window(NULL) + m_Window(nullptr) { } @@ -32,7 +32,7 @@ public: void CloseWindow(void) { - m_Window = NULL; + m_Window = nullptr; } void OpenWindow(cWindow * a_Window) diff --git a/src/WebAdmin.cpp b/src/WebAdmin.cpp index db2ace386..dbf600c25 100644 --- a/src/WebAdmin.cpp +++ b/src/WebAdmin.cpp @@ -224,7 +224,7 @@ void cWebAdmin::HandleWebadminRequest(cHTTPConnection & a_Connection, cHTTPReque // Retrieve the request data: cWebadminRequestData * Data = (cWebadminRequestData *)(a_Request.GetUserData()); - if (Data == NULL) + if (Data == nullptr) { a_Connection.SendStatusAndReason(500, "Bad UserData"); return; @@ -483,7 +483,7 @@ AString cWebAdmin::GetDefaultPage(void) const cPluginManager::PluginMap & List = PM->GetAllPlugins(); for (cPluginManager::PluginMap::const_iterator itr = List.begin(); itr != List.end(); ++itr) { - if (itr->second == NULL) + if (itr->second == nullptr) { continue; } @@ -494,7 +494,7 @@ AString cWebAdmin::GetDefaultPage(void) cPlayerAccum PlayerAccum; cWorld * World = cRoot::Get()->GetDefaultWorld(); // TODO - Create a list of worlds and players - if (World != NULL) + if (World != nullptr) { World->ForEachPlayer(PlayerAccum); Content.append(PlayerAccum.m_Contents); @@ -625,7 +625,7 @@ void cWebAdmin::OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_R { UNUSED(a_Connection); cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); - if (Data == NULL) + if (Data == nullptr) { return; } @@ -659,7 +659,7 @@ void cWebAdmin::OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & // Delete any request data assigned to the request: cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); delete Data; - Data = NULL; + Data = nullptr; } diff --git a/src/World.cpp b/src/World.cpp index 1f9361386..ff333ad2a 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -258,10 +258,10 @@ cWorld::cWorld(const AString & a_WorldName, eDimension a_Dimension, const AStrin m_VillagersShouldHarvestCrops(true), m_SimulatorManager(), m_SandSimulator(), - m_WaterSimulator(NULL), + m_WaterSimulator(nullptr), m_LavaSimulator(nullptr), m_FireSimulator(), - m_RedstoneSimulator(NULL), + m_RedstoneSimulator(nullptr), m_MaxPlayers(10), m_ChunkMap(), m_bAnimals(true), @@ -303,9 +303,9 @@ cWorld::cWorld(const AString & a_WorldName, eDimension a_Dimension, const AStrin cWorld::~cWorld() { - delete m_WaterSimulator; m_WaterSimulator = NULL; - delete m_LavaSimulator; m_LavaSimulator = NULL; - delete m_RedstoneSimulator; m_RedstoneSimulator = NULL; + delete m_WaterSimulator; m_WaterSimulator = nullptr; + delete m_LavaSimulator; m_LavaSimulator = nullptr; + delete m_RedstoneSimulator; m_RedstoneSimulator = nullptr; UnloadUnusedChunks(); @@ -1261,7 +1261,7 @@ void cWorld::DoExplosionAt(double a_ExplosionSize, double a_BlockX, double a_Blo for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if (ch == NULL) + if (ch == nullptr) { continue; } @@ -2016,7 +2016,7 @@ void cWorld::BroadcastChat(const AString & a_Message, const cClientHandle * a_Ex for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2034,7 +2034,7 @@ void cWorld::BroadcastChat(const cCompositeChat & a_Message, const cClientHandle for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2177,7 +2177,7 @@ void cWorld::BroadcastPlayerListAddPlayer(const cPlayer & a_Player, const cClien for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2195,7 +2195,7 @@ void cWorld::BroadcastPlayerListRemovePlayer(const cPlayer & a_Player, const cCl for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2213,7 +2213,7 @@ void cWorld::BroadcastPlayerListUpdateGameMode(const cPlayer & a_Player, const c for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2231,7 +2231,7 @@ void cWorld::BroadcastPlayerListUpdatePing(const cPlayer & a_Player, const cClie for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2249,7 +2249,7 @@ void cWorld::BroadcastPlayerListUpdateDisplayName(const cPlayer & a_Player, cons for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2276,7 +2276,7 @@ void cWorld::BroadcastScoreboardObjective(const AString & a_Name, const AString for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2294,7 +2294,7 @@ void cWorld::BroadcastScoreUpdate(const AString & a_Objective, const AString & a for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2312,7 +2312,7 @@ void cWorld::BroadcastDisplayObjective(const AString & a_Objective, cScoreboard: for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2357,7 +2357,7 @@ void cWorld::BroadcastTeleportEntity(const cEntity & a_Entity, const cClientHand for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2384,7 +2384,7 @@ void cWorld::BroadcastTimeUpdate(const cClientHandle * a_Exclude) for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2411,7 +2411,7 @@ void cWorld::BroadcastWeather(eWeather a_Weather, const cClientHandle * a_Exclud for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2646,7 +2646,7 @@ void cWorld::RemovePlayer(cPlayer * a_Player, bool a_RemoveFromChunk) // Remove the player's client from the list of clients to be ticked: cClientHandle * Client = a_Player->GetClientHandle(); - if (Client != NULL) + if (Client != nullptr) { Client->RemoveFromWorld(); m_ChunkMap->RemoveClientFromChunks(Client); @@ -2699,7 +2699,7 @@ bool cWorld::DoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_ bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCallback & a_Callback) { - cPlayer * BestMatch = NULL; + cPlayer * BestMatch = nullptr; size_t BestRating = 0; size_t NameLength = a_PlayerNameHint.length(); @@ -2718,7 +2718,7 @@ bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCa } } // for itr - m_Players[] - if (BestMatch != NULL) + if (BestMatch != nullptr) { return a_Callback.Item (BestMatch); } @@ -2735,7 +2735,7 @@ cPlayer * cWorld::FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, cTracer LineOfSight(this); double ClosestDistance = a_SightLimit; - cPlayer * ClosestPlayer = NULL; + cPlayer * ClosestPlayer = nullptr; cCSLock Lock(m_CSPlayers); for (cPlayerList::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) @@ -2774,7 +2774,7 @@ void cWorld::SendPlayerList(cPlayer * a_DestPlayer) for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch != NULL) && !ch->IsDestroyed()) + if ((ch != nullptr) && !ch->IsDestroyed()) { a_DestPlayer->GetClientHandle()->SendPlayerListAddPlayer(*(*itr)); } @@ -3218,10 +3218,10 @@ bool cWorld::IsBlockDirectlyWatered(int a_BlockX, int a_BlockY, int a_BlockZ) int cWorld::SpawnMob(double a_PosX, double a_PosY, double a_PosZ, eMonsterType a_MonsterType) { - cMonster * Monster = NULL; + cMonster * Monster = nullptr; Monster = cMonster::NewMonsterFromType(a_MonsterType); - if (Monster != NULL) + if (Monster != nullptr) { Monster->SetPosition(a_PosX, a_PosY, a_PosZ); } @@ -3247,7 +3247,7 @@ int cWorld::SpawnMobFinalize(cMonster * a_Monster) if (cPluginManager::Get()->CallHookSpawningMonster(*this, *a_Monster)) { delete a_Monster; - a_Monster = NULL; + a_Monster = nullptr; return -1; } @@ -3255,7 +3255,7 @@ int cWorld::SpawnMobFinalize(cMonster * a_Monster) if (!a_Monster->Initialize(*this)) { delete a_Monster; - a_Monster = NULL; + a_Monster = nullptr; return -1; } @@ -3272,14 +3272,14 @@ int cWorld::SpawnMobFinalize(cMonster * a_Monster) int cWorld::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) { cProjectileEntity * Projectile = cProjectileEntity::Create(a_Kind, a_Creator, a_PosX, a_PosY, a_PosZ, a_Item, a_Speed); - if (Projectile == NULL) + if (Projectile == nullptr) { return -1; } if (!Projectile->Initialize(*this)) { delete Projectile; - Projectile = NULL; + Projectile = nullptr; return -1; } return Projectile->GetUniqueID(); @@ -3362,7 +3362,7 @@ cRedstoneSimulator * cWorld::InitializeRedstoneSimulator(cIniFil SimulatorName = "Incremental"; } - cRedstoneSimulator * res = NULL; + cRedstoneSimulator * res = nullptr; if (NoCaseCompare(SimulatorName, "Incremental") == 0) { @@ -3395,7 +3395,7 @@ cFluidSimulator * cWorld::InitializeFluidSimulator(cIniFile & a_IniFile, const c SimulatorName = "Vanilla"; } - cFluidSimulator * res = NULL; + cFluidSimulator * res = nullptr; bool IsWater = (strcmp(a_FluidName, "Water") == 0); // Used for defaults int Rate = 1; if ( @@ -3485,7 +3485,7 @@ void cWorld::AddQueuedPlayers(void) for (cPlayerList::iterator itr = PlayersToAdd.begin(), end = PlayersToAdd.end(); itr != end; ++itr) { cClientHandle * Client = (*itr)->GetClientHandle(); - if (Client != NULL) + if (Client != nullptr) { m_Clients.push_back(Client); } @@ -3496,7 +3496,7 @@ void cWorld::AddQueuedPlayers(void) for (cPlayerList::iterator itr = PlayersToAdd.begin(), end = PlayersToAdd.end(); itr != end; ++itr) { cClientHandle * Client = (*itr)->GetClientHandle(); - if (Client != NULL) + if (Client != nullptr) { Client->StreamChunks(); Client->SendPlayerMoveLook(); @@ -3597,7 +3597,7 @@ void cWorld::cChunkGeneratorCallbacks::OnChunkGenerated(cChunkDesc & a_ChunkDesc cSetChunkDataPtr SetChunkData(new cSetChunkData( a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), a_ChunkDesc.GetBlockTypes(), BlockMetas, - NULL, NULL, // We don't have lighting, chunk will be lighted when needed + nullptr, nullptr, // We don't have lighting, chunk will be lighted when needed &a_ChunkDesc.GetHeightMap(), &a_ChunkDesc.GetBiomeMap(), a_ChunkDesc.GetEntities(), a_ChunkDesc.GetBlockEntities(), true diff --git a/src/World.h b/src/World.h index 0ced90562..d5f1994a5 100644 --- a/src/World.h +++ b/src/World.h @@ -84,7 +84,7 @@ class cWorld : public: // tolua_end - + /** A simple RAII locker for the chunkmap - locks the chunkmap in its constructor, unlocks it in the destructor */ class cLock : public cCSLock @@ -94,7 +94,7 @@ public: cLock(cWorld & a_World); } ; - + /** A common ancestor for all tasks queued onto the tick thread */ class cTask { @@ -102,10 +102,10 @@ public: virtual ~cTask() {} virtual void Run(cWorld & a_World) = 0; } ; - + typedef std::vector> cTasks; - + class cTaskSaveAllChunks : public cTask { @@ -113,7 +113,7 @@ public: // cTask overrides: virtual void Run(cWorld & a_World) override; } ; - + class cTaskUnloadUnusedChunks : public cTask @@ -142,7 +142,7 @@ public: { return "cWorld"; } - + // tolua_begin int GetTicksUntilWeatherChange(void) const { return m_WeatherInterval; } @@ -159,7 +159,7 @@ public: virtual Int64 GetWorldAge (void) const override { return m_WorldAge; } virtual int GetTimeOfDay(void) const override { return m_TimeOfDay; } - + void SetTicksUntilWeatherChange(int a_WeatherInterval) { m_WeatherInterval = a_WeatherInterval; @@ -168,42 +168,42 @@ public: virtual void SetTimeOfDay(int a_TimeOfDay) override { m_TimeOfDay = a_TimeOfDay; - m_TimeOfDaySecs = static_cast(a_TimeOfDay) / 20.0; + m_TimeOfDaySecs = (double)a_TimeOfDay / 20.0; UpdateSkyDarkness(); BroadcastTimeUpdate(); } - + /** Returns the default weather interval for the specific weather type. Returns -1 for any unknown weather. */ int GetDefaultWeatherInterval(eWeather a_Weather); - + /** Returns the current game mode. Partly OBSOLETE, you should use IsGameModeXXX() functions wherever applicable */ eGameMode GetGameMode(void) const { return m_GameMode; } /** Returns true if the world is in Creative mode */ bool IsGameModeCreative(void) const { return (m_GameMode == gmCreative); } - + /** Returns true if the world is in Survival mode */ bool IsGameModeSurvival(void) const { return (m_GameMode == gmSurvival); } - + /** Returns true if the world is in Adventure mode */ bool IsGameModeAdventure(void) const { return (m_GameMode == gmAdventure); } - + /** Returns true if the world is in Spectator mode */ bool IsGameModeSpectator(void) const { return (m_GameMode == gmSpectator); } - + bool IsPVPEnabled(void) const { return m_bEnabledPVP; } bool IsDeepSnowEnabled(void) const { return m_IsDeepSnowEnabled; } - + bool ShouldLavaSpawnFire(void) const { return m_ShouldLavaSpawnFire; } - + bool VillagersShouldHarvestCrops(void) const { return m_VillagersShouldHarvestCrops; } virtual eDimension GetDimension(void) const { return m_Dimension; } /** Returns the world height at the specified coords; waits for the chunk to get loaded / generated */ virtual int GetHeight(int a_BlockX, int a_BlockZ); - + // tolua_end /** Retrieves the world height at the specified coords; returns false if chunk not loaded / generated */ @@ -212,81 +212,81 @@ public: // Broadcast respective packets to all clients of the chunk where the event is taking place // (Please keep these alpha-sorted) void BroadcastAttachEntity (const cEntity & a_Entity, const cEntity * a_Vehicle); - void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); ///< If there is a block entity at the specified coods, sends it to all clients except a_Exclude + void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); ///< If there is a block entity at the specified coods, sends it to all clients except a_Exclude // tolua_begin - void BroadcastChat (const AString & a_Message, const cClientHandle * a_Exclude = NULL, eMessageType a_ChatPrefix = mtCustom); - void BroadcastChatInfo (const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtInformation); } - void BroadcastChatFailure(const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtFailure); } - void BroadcastChatSuccess(const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtSuccess); } - void BroadcastChatWarning(const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtWarning); } - void BroadcastChatFatal (const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtFailure); } - void BroadcastChatDeath (const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtDeath); } - void BroadcastChat (const cCompositeChat & a_Message, const cClientHandle * a_Exclude = NULL); + void BroadcastChat (const AString & a_Message, const cClientHandle * a_Exclude = nullptr, eMessageType a_ChatPrefix = mtCustom); + void BroadcastChatInfo (const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtInformation); } + void BroadcastChatFailure(const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtFailure); } + void BroadcastChatSuccess(const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtSuccess); } + void BroadcastChatWarning(const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtWarning); } + void BroadcastChatFatal (const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtFailure); } + void BroadcastChatDeath (const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtDeath); } + void BroadcastChat (const cCompositeChat & a_Message, const cClientHandle * a_Exclude = nullptr); // tolua_end - void BroadcastChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectEntity (const cEntity & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - virtual void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL) override; // tolua_export - void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastPlayerListAddPlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListRemovePlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListUpdateGameMode (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListUpdatePing (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName, const cClientHandle * a_Exclude = NULL); - void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = NULL); + void BroadcastChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectEntity (const cEntity & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + virtual void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr) override; // tolua_export + void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastPlayerListAddPlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListRemovePlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListUpdateGameMode (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListUpdatePing (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName, const cClientHandle * a_Exclude = nullptr); + void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = nullptr); void BroadcastScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode); void BroadcastScoreUpdate (const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode); void BroadcastDisplayObjective (const AString & a_Objective, cScoreboard::eDisplaySlot a_Display); - void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastTeleportEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); - void BroadcastTimeUpdate (const cClientHandle * a_Exclude = NULL); + void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastTeleportEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastTimeUpdate (const cClientHandle * a_Exclude = nullptr); virtual void BroadcastUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) override; - void BroadcastWeather (eWeather a_Weather, const cClientHandle * a_Exclude = NULL); - + void BroadcastWeather (eWeather a_Weather, const cClientHandle * a_Exclude = nullptr); + virtual cBroadcastInterface & GetBroadcastManager(void) override { return *this; } - + /** If there is a block entity at the specified coords, sends it to the client specified */ void SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client); - + void MarkRedstoneDirty(int a_ChunkX, int a_ChunkZ); void MarkChunkDirty (int a_ChunkX, int a_ChunkZ, bool a_MarkRedstoneDirty = false); void MarkChunkSaving(int a_ChunkX, int a_ChunkZ); void MarkChunkSaved (int a_ChunkX, int a_ChunkZ); - + /** Puts the chunk data into a queue to be set into the chunkmap in the tick thread. If the chunk data doesn't contain valid biomes, the biomes are calculated before adding the data into the queue. */ void QueueSetChunkData(const cSetChunkDataPtr & a_SetChunkData); - + void ChunkLighted( int a_ChunkX, int a_ChunkZ, const cChunkDef::BlockNibbles & a_BlockLight, const cChunkDef::BlockNibbles & a_SkyLight ); - + bool GetChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataCallback & a_Callback); - + /** Gets the chunk's blocks, only the block types */ bool GetChunkBlockTypes(int a_ChunkX, int a_ChunkZ, BLOCKTYPE * a_BlockTypes); - + /** Returns true iff the chunk is in the loader / generator queue. */ bool IsChunkQueued(int a_ChunkX, int a_ChunkZ) const; @@ -294,10 +294,10 @@ public: bool IsChunkValid(int a_ChunkX, int a_ChunkZ) const; bool HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) const; - + /** Queues a task to unload unused chunks onto the tick thread. The prefferred way of unloading*/ void QueueUnloadUnusedChunks(void); // tolua_export - + void CollectPickupsByPlayer(cPlayer & a_Player); /** Adds the player to the world. @@ -319,21 +319,21 @@ public: /** Finds a player from a partial or complete player name and calls the callback - case-insensitive */ bool FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << - + // TODO: This interface is dangerous - rewrite to DoWithClosestPlayer(pos, sight, action) cPlayer * FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, bool a_CheckLineOfSight = true); - + void SendPlayerList(cPlayer * a_DestPlayer); // Sends playerlist to the player /** Adds the entity into its appropriate chunk; takes ownership of the entity ptr. The entity is added lazily - this function only puts it in a queue that is then processed by the Tick thread. */ void AddEntity(cEntity * a_Entity); - + bool HasEntity(int a_UniqueID); - + /** Calls the callback for each entity in the entire world; returns true if all entities processed, false if the callback aborted by returning true */ bool ForEachEntity(cEntityCallback & a_Callback); // Exported in ManualBindings.cpp - + /** Calls the callback for each entity in the specified chunk; returns true if all entities processed, false if the callback aborted by returning true */ bool ForEachEntityInChunk(int a_ChunkX, int a_ChunkZ, cEntityCallback & a_Callback); // Exported in ManualBindings.cpp @@ -347,38 +347,38 @@ public: /** Compares clients of two chunks, calls the callback accordingly */ void CompareChunkClients(int a_ChunkX1, int a_ChunkZ1, int a_ChunkX2, int a_ChunkZ2, cClientDiffCallback & a_Callback); - + /** Adds client to a chunk, if not already present; returns true if added, false if present */ bool AddChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Removes client from the chunk specified */ void RemoveChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Removes the client from all chunks it is present in */ void RemoveClientFromChunks(cClientHandle * a_Client); - + /** Sends the chunk to the client specified, if the client doesn't have the chunk yet. If chunk not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ void SendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Sends the chunk to the client specified, even if the client already has the chunk. If the chunk's not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ void ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + /** Removes client from ChunkSender's queue of chunks to be sent */ void RemoveClientFromChunkSender(cClientHandle * a_Client); - + /** Touches the chunk, causing it to be loaded or generated */ void TouchChunk(int a_ChunkX, int a_ChunkZ); - + /** Marks the chunk as failed-to-load: */ void ChunkLoadFailed(int a_ChunkX, int a_ChunkZ); - - /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be NULL. Returns true if sign text changed. Same as UpdateSign() */ - bool SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = NULL); // Exported in ManualBindings.cpp - - /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be NULL. Returns true if sign text changed. Same as SetSignLines() */ - bool UpdateSign(int a_X, int a_Y, int a_Z, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = NULL); // Exported in ManualBindings.cpp + + /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be nullptr. Returns true if sign text changed. Same as UpdateSign() */ + bool SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = nullptr); // Exported in ManualBindings.cpp + + /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be nullptr. Returns true if sign text changed. Same as SetSignLines() */ + bool UpdateSign(int a_X, int a_Y, int a_Z, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = nullptr); // Exported in ManualBindings.cpp /** Sets the command block command. Returns true if command changed. */ bool SetCommandBlockCommand(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Command); // tolua_export @@ -391,25 +391,25 @@ public: /** Regenerate the given chunk: */ void RegenerateChunk(int a_ChunkX, int a_ChunkZ); // tolua_export - + /** Generates the given chunk */ void GenerateChunk(int a_ChunkX, int a_ChunkZ); // tolua_export - + /** Queues a chunk for lighting; a_Callback is called after the chunk is lighted */ - void QueueLightChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback = NULL); - + void QueueLightChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback = nullptr); + bool IsChunkLighted(int a_ChunkX, int a_ChunkZ); - + /** Calls the callback for each chunk in the coords specified (all cords are inclusive). Returns true if all chunks have been processed successfully */ virtual bool ForEachChunkInRect(int a_MinChunkX, int a_MaxChunkX, int a_MinChunkZ, int a_MaxChunkZ, cChunkDataCallback & a_Callback) override; // tolua_begin - + /** Sets the block at the specified coords to the specified value. Full processing, incl. updating neighbors, is performed. */ void SetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, bool a_SendToClients = true); - + /** Sets the block at the specified coords to the specified value. The replacement doesn't trigger block updates. The replaced blocks aren't checked for block entities (block entity is leaked if it exists at this block) @@ -418,7 +418,7 @@ public: { m_ChunkMap->FastSetBlock(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); } - + /** Queues a SetBlock() with the specified parameters after the specified number of ticks. Calls SetBlock(), so performs full processing of the replaced block. */ @@ -426,12 +426,12 @@ public: { m_ChunkMap->QueueSetBlock(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, GetWorldAge() + a_TickDelay, a_PreviousBlockType); } - + BLOCKTYPE GetBlock (int a_BlockX, int a_BlockY, int a_BlockZ) { return m_ChunkMap->GetBlock(a_BlockX, a_BlockY, a_BlockZ); } - + NIBBLETYPE GetBlockMeta (int a_BlockX, int a_BlockY, int a_BlockZ) { return m_ChunkMap->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); @@ -439,37 +439,37 @@ public: void SetBlockMeta (int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_MetaData); NIBBLETYPE GetBlockSkyLight (int a_BlockX, int a_BlockY, int a_BlockZ); NIBBLETYPE GetBlockBlockLight(int a_BlockX, int a_BlockY, int a_BlockZ); - + // tolua_end - + bool GetBlockTypeMeta (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta); // TODO: Exported in ManualBindings.cpp bool GetBlockInfo (int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight); // TODO: Exported in ManualBindings.cpp // TODO: NIBBLETYPE GetBlockActualLight(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_begin - + // Vector3i variants: void FastSetBlock(const Vector3i & a_Pos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { FastSetBlock( a_Pos.x, a_Pos.y, a_Pos.z, a_BlockType, a_BlockMeta); } BLOCKTYPE GetBlock (const Vector3i & a_Pos) { return GetBlock( a_Pos.x, a_Pos.y, a_Pos.z); } NIBBLETYPE GetBlockMeta(const Vector3i & a_Pos) { return GetBlockMeta( a_Pos.x, a_Pos.y, a_Pos.z); } void SetBlockMeta(const Vector3i & a_Pos, NIBBLETYPE a_MetaData) { SetBlockMeta( a_Pos.x, a_Pos.y, a_Pos.z, a_MetaData); } // tolua_end - + /** Writes the block area into the specified coords. Returns true if all chunks have been processed. Prefer cBlockArea::Write() instead, this is the internal implementation; cBlockArea does error checking, too. a_DataTypes is a bitmask of cBlockArea::baXXX constants ORed together. */ virtual bool WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes) override; - + // tolua_begin /** Spawns item pickups for each item in the list. May compress pickups if too many entities: */ virtual void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_FlyAwaySpeed = 1.0, bool IsPlayerCreated = false) override; - + /** Spawns item pickups for each item in the list. May compress pickups if too many entities. All pickups get the speed specified: */ virtual void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_SpeedX, double a_SpeedY, double a_SpeedZ, bool IsPlayerCreated = false) override; - + /** Spawns an falling block entity at the given position. It returns the UniqueID of the spawned falling block. */ int SpawnFallingBlock(int a_X, int a_Y, int a_Z, BLOCKTYPE BlockType, NIBBLETYPE BlockMeta); @@ -486,10 +486,10 @@ public: /** Replaces world blocks with a_Blocks, if they are of type a_FilterBlockType */ void ReplaceBlocks(const sSetBlockVector & a_Blocks, BLOCKTYPE a_FilterBlockType); - + /** Retrieves block types of the specified blocks. If a chunk is not loaded, doesn't modify the block. Returns true if all blocks were read. */ bool GetBlocks(sSetBlockVector & a_Blocks, bool a_ContinueOnFailure); - + // tolua_begin bool DigBlock (int a_X, int a_Y, int a_Z); virtual void SendBlockTo(int a_X, int a_Y, int a_Z, cPlayer * a_Player) override; @@ -500,21 +500,21 @@ public: /** Wakes up the simulators for the specified block */ virtual void WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ) override; - + /** Wakes up the simulators for the specified area of blocks */ void WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_MinBlockY, int a_MaxBlockY, int a_MinBlockZ, int a_MaxBlockZ); // tolua_end inline cSimulatorManager * GetSimulatorManager(void) { return m_SimulatorManager.get(); } - + inline cFluidSimulator * GetWaterSimulator(void) { return m_WaterSimulator; } inline cFluidSimulator * GetLavaSimulator (void) { return m_LavaSimulator; } inline cRedstoneSimulator * GetRedstoneSimulator(void) { return m_RedstoneSimulator; } - + /** Calls the callback for each block entity in the specified chunk; returns true if all block entities processed, false if the callback aborted by returning true */ bool ForEachBlockEntityInChunk(int a_ChunkX, int a_ChunkZ, cBlockEntityCallback & a_Callback); // Exported in ManualBindings.cpp - + /** Calls the callback for each chest in the specified chunk; returns true if all chests processed, false if the callback aborted by returning true */ bool ForEachChestInChunk(int a_ChunkX, int a_ChunkZ, cChestCallback & a_Callback); // Exported in ManualBindings.cpp @@ -529,7 +529,7 @@ public: /** Calls the callback for each furnace in the specified chunk; returns true if all furnaces processed, false if the callback aborted by returning true */ bool ForEachFurnaceInChunk(int a_ChunkX, int a_ChunkZ, cFurnaceCallback & a_Callback); // Exported in ManualBindings.cpp - + /** Does an explosion with the specified strength at the specified coordinate a_SourceData exact type depends on the a_Source: | esOther | void * | @@ -580,29 +580,29 @@ public: /** Retrieves the test on the sign at the specified coords; returns false if there's no sign at those coords, true if found */ bool GetSignLines (int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4); // Exported in ManualBindings.cpp - + /** a_Player is using block entity at [x, y, z], handle that: */ void UseBlockEntity(cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ) {m_ChunkMap->UseBlockEntity(a_Player, a_BlockX, a_BlockY, a_BlockZ); } // tolua_export - + /** Calls the callback for the chunk specified, with ChunkMapCS locked; returns false if the chunk doesn't exist, otherwise returns the same value as the callback */ bool DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback & a_Callback); void GrowTreeImage(const sSetBlockVector & a_Blocks); - + // tolua_begin /** Grows a tree at the specified coords, either from a sapling there, or based on the biome */ void GrowTree (int a_BlockX, int a_BlockY, int a_BlockZ); - + /** Grows a tree at the specified coords, based on the sapling meta provided */ void GrowTreeFromSapling(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_SaplingMeta); - + /** Grows a tree at the specified coords, based on the biome in the place */ void GrowTreeByBiome (int a_BlockX, int a_BlockY, int a_BlockZ); - + /** Grows the plant at the specified block to its ripe stage (bonemeal used); returns false if the block is not growable. If a_IsBonemeal is true, block is not grown if not allowed in world.ini */ bool GrowRipePlant(int a_BlockX, int a_BlockY, int a_BlockZ, bool a_IsByBonemeal = false); - + /** Grows a cactus present at the block specified by the amount of blocks specified, up to the max height specified in the config */ void GrowCactus(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBlocksToGrow); @@ -611,18 +611,18 @@ public: /** Grows a sugarcane present at the block specified by the amount of blocks specified, up to the max height specified in the config */ void GrowSugarcane(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBlocksToGrow); - + /** Returns the biome at the specified coords. Reads the biome from the chunk, if loaded, otherwise uses the world generator to provide the biome value */ EMCSBiome GetBiomeAt(int a_BlockX, int a_BlockZ); - + /** Sets the biome at the specified coords. Returns true if successful, false if not (chunk not loaded). Doesn't resend the chunk to clients, use ForceSendChunkTo() for that. */ bool SetBiomeAt(int a_BlockX, int a_BlockZ, EMCSBiome a_Biome); - + /** Sets the biome at the area. Returns true if successful, false if any subarea failed (chunk not loaded). (Re)sends the chunks to their relevant clients if successful. */ bool SetAreaBiome(int a_MinX, int a_MaxX, int a_MinZ, int a_MaxZ, EMCSBiome a_Biome); - + /** Sets the biome at the area. Returns true if successful, false if any subarea failed (chunk not loaded). (Re)sends the chunks to their relevant clients if successful. The cuboid needn't be sorted. */ @@ -630,7 +630,7 @@ public: /** Returns the name of the world */ const AString & GetName(void) const { return m_WorldName; } - + /** Returns the name of the world.ini file used by this world */ const AString & GetIniFileName(void) const {return m_IniFileName; } @@ -661,18 +661,18 @@ public: AString GetLinkedOverworldName(void) const { return m_OverworldName; } void SetLinkedOverworldName(const AString & a_Name) { m_OverworldName = a_Name; } - + // tolua_end - + /** Saves all chunks immediately. Dangerous interface, may deadlock, use QueueSaveAllChunks() instead */ void SaveAllChunks(void); - + /** Queues a task to save all chunks onto the tick thread. The prefferred way of saving chunks from external sources */ void QueueSaveAllChunks(void); // tolua_export - + /** Queues a task onto the tick thread. The task object will be deleted once the task is finished */ void QueueTask(std::unique_ptr a_Task); // Exported in ManualBindings.cpp - + /** Queues a task onto the tick thread, with the specified delay. The task object will be deleted once the task is finished */ void ScheduleTask(int a_DelayTicks, cTask * a_Task); @@ -690,13 +690,13 @@ public: inline size_t GetStorageSaveQueueLength(void) { return m_Storage.GetSaveQueueLength(); } // tolua_export void InitializeSpawn(void); - + /** Starts threads that belong to this world */ void Start(void); - + /** Stops threads that belong to this world (part of deinit) */ void Stop(void); - + /** Processes the blocks queued for ticking with a delay (m_BlockTickQueue[]) */ void TickQueuedBlocks(void); @@ -714,34 +714,34 @@ public: // tolua_begin /** Casts a thunderbolt at the specified coords */ void CastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ); - + /** Sets the specified weather; resets weather interval; asks and notifies plugins of the change */ void SetWeather(eWeather a_NewWeather); - + /** Forces a weather change in the next game tick */ void ChangeWeather(void); - + /** Returns the current weather. Instead of comparing values directly to the weather constants, use IsWeatherXXX() functions, if possible */ eWeather GetWeather(void) const { return m_Weather; } - + /** Returns true if the current weather is sun */ bool IsWeatherSunny(void) const { return (m_Weather == wSunny); } - + /** Returns true if it is sunny at the specified location. This takes into account biomes. */ bool IsWeatherSunnyAt(int a_BlockX, int a_BlockZ) { return (IsWeatherSunny() || IsBiomeNoDownfall(GetBiomeAt(a_BlockX, a_BlockZ))); } - + /** Returns true if the current weather is rain */ bool IsWeatherRain(void) const { return (m_Weather == wRain); } - + /** Returns true if it is raining at the specified location. This takes into account biomes. */ bool IsWeatherRainAt(int a_BlockX, int a_BlockZ) { return (IsWeatherRain() && !IsBiomeNoDownfall(GetBiomeAt(a_BlockX, a_BlockZ))); } - + /** Returns true if the current weather is stormy */ bool IsWeatherStorm(void) const { return (m_Weather == wStorm); } @@ -750,10 +750,10 @@ public: { return (IsWeatherStorm() && !IsBiomeNoDownfall(GetBiomeAt(a_BlockX, a_BlockZ))); } - + /** Returns true if the current weather has any precipitation - rain, storm or snow */ bool IsWeatherWet(void) const { return !IsWeatherSunny(); } - + /** Returns true if it is raining, stormy or snowing at the specified location. This takes into account biomes. */ virtual bool IsWeatherWetAt(int a_BlockX, int a_BlockZ) { @@ -765,33 +765,33 @@ public: cChunkGenerator & GetGenerator(void) { return m_Generator; } cWorldStorage & GetStorage (void) { return m_Storage; } cChunkMap * GetChunkMap (void) { return m_ChunkMap.get(); } - + /** Sets the blockticking to start at the specified block. Only one blocktick per chunk may be set, second call overwrites the first call */ void SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_export - + int GetMaxSugarcaneHeight(void) const { return m_MaxSugarcaneHeight; } // tolua_export int GetMaxCactusHeight (void) const { return m_MaxCactusHeight; } // tolua_export bool IsBlockDirectlyWatered(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_export - + /** Spawns a mob of the specified type. Returns the mob's EntityID if recognized and spawned, <0 otherwise */ virtual int SpawnMob(double a_PosX, double a_PosY, double a_PosZ, eMonsterType 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 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 - + 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 = nullptr); // tolua_export + /** Returns a random number from the m_TickRand in range [0 .. a_Range]. To be used only in the tick thread! */ - int GetTickRandomNumber(unsigned a_Range) { return static_cast(m_TickRand.randInt(a_Range)); } - + int GetTickRandomNumber(unsigned a_Range) { return (int)(m_TickRand.randInt(a_Range)); } + /** Appends all usernames starting with a_Text (case-insensitive) into Results */ void TabCompleteUserName(const AString & a_Text, AStringVector & a_Results); /** Get the current darkness level based on the time */ NIBBLETYPE GetSkyDarkness() { return m_SkyDarkness; } - + /** Increments (a_AlwaysTicked == true) or decrements (false) the m_AlwaysTicked counter for the specified chunk. If the m_AlwaysTicked counter is greater than zero, the chunk is ticked in the tick-thread regardless of whether it has any clients or not. @@ -802,43 +802,43 @@ public: private: friend class cRoot; - + class cTickThread : public cIsThread { typedef cIsThread super; public: cTickThread(cWorld & a_World); - + protected: cWorld & m_World; - + // cIsThread overrides: virtual void Execute(void) override; } ; - - + + /** Implementation of the callbacks that the ChunkGenerator uses to store new chunks and interface to plugins */ class cChunkGeneratorCallbacks : public cChunkGenerator::cChunkSink, public cChunkGenerator::cPluginInterface { cWorld * m_World; - + // cChunkSink overrides: virtual void OnChunkGenerated (cChunkDesc & a_ChunkDesc) override; virtual bool IsChunkValid (int a_ChunkX, int a_ChunkZ) override; virtual bool HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) override; virtual bool IsChunkQueued (int a_ChunkX, int a_ChunkZ) override; - + // cPluginInterface overrides: virtual void CallHookChunkGenerating(cChunkDesc & a_ChunkDesc) override; virtual void CallHookChunkGenerated (cChunkDesc & a_ChunkDesc) override; - + public: cChunkGeneratorCallbacks(cWorld & a_World); } ; - + /** A container for tasks that have been scheduled for a specific game tick */ class cScheduledTask @@ -846,18 +846,18 @@ private: public: Int64 m_TargetTick; cTask * m_Task; - + /** Creates a new scheduled task; takes ownership of the task object passed to it. */ cScheduledTask(Int64 a_TargetTick, cTask * a_Task) : m_TargetTick(a_TargetTick), m_Task(a_Task) { } - + virtual ~cScheduledTask() { delete m_Task; - m_Task = NULL; + m_Task = nullptr; } }; @@ -873,15 +873,15 @@ private: AString m_OverworldName; AString m_IniFileName; - + /** Name of the storage schema used to load and save chunks */ AString m_StorageSchema; - + int m_StorageCompressionFactor; - + /** The dimension of the world, used by the client to provide correct lighting scheme */ eDimension m_Dimension; - + /** This random generator is to be used only in the Tick() method, and thus only in the World-Tick-thread (MTRand is not exactly thread-safe) */ MTRand m_TickRand; @@ -910,7 +910,7 @@ private: bool m_IsDeepSnowEnabled; bool m_ShouldLavaSpawnFire; bool m_VillagersShouldHarvestCrops; - + std::vector m_BlockTickQueue; std::vector m_BlockTickQueueCopy; // Second is for safely removing the objects from the queue @@ -920,12 +920,12 @@ private: cFluidSimulator * m_LavaSimulator; std::unique_ptr m_FireSimulator; cRedstoneSimulator * m_RedstoneSimulator; - + cCriticalSection m_CSPlayers; cPlayerList m_Players; cWorldStorage m_Storage; - + unsigned int m_MaxPlayers; std::unique_ptr m_ChunkMap; @@ -935,7 +935,7 @@ private: eWeather m_Weather; int m_WeatherInterval; - + int m_MaxCactusHeight; int m_MaxSugarcaneHeight; bool m_IsCactusBonemealable; @@ -952,7 +952,7 @@ private: /** Whether command blocks are enabled or not */ bool m_bCommandBlocksEnabled; - + /** Whether prefixes such as [INFO] are prepended to SendMessageXXX() / BroadcastChatXXX() functions */ bool m_bUseChatPrefixes; @@ -966,43 +966,43 @@ private: /** Name of the end world */ AString m_EndWorldName; - + cChunkGenerator m_Generator; cScoreboard m_Scoreboard; cMapManager m_MapManager; - + /** The callbacks that the ChunkGenerator uses to store new chunks and interface to plugins */ cChunkGeneratorCallbacks m_GeneratorCallbacks; - + cChunkSender m_ChunkSender; cLightingThread m_Lighting; cTickThread m_TickThread; - + /** Guards the m_Tasks */ cCriticalSection m_CSTasks; - + /** Tasks that have been queued onto the tick thread; guarded by m_CSTasks */ cTasks m_Tasks; - + /** Guards the m_ScheduledTasks */ cCriticalSection m_CSScheduledTasks; - + /** Tasks that have been queued to be executed on the tick thread at target tick in the future. Ordered by increasing m_TargetTick. Guarded by m_CSScheduledTasks */ cScheduledTasks m_ScheduledTasks; - + /** Guards m_Clients */ cCriticalSection m_CSClients; - + /** List of clients in this world, these will be ticked by this world */ cClientHandleList m_Clients; - + /** Clients that are scheduled for removal (ticked in another world), waiting for TickClients() to remove them */ cClientHandleList m_ClientsToRemove; - + /** Clients that are scheduled for adding, waiting for TickClients to add them */ cClientHandleList m_ClientsToAdd; @@ -1017,10 +1017,10 @@ private: /** List of players that are scheduled for adding, waiting for the Tick thread to add them. */ cPlayerList m_PlayersToAdd; - + /** CS protecting m_SetChunkDataQueue. */ cCriticalSection m_CSSetChunkDataQueue; - + /** Queue for the chunk data to be set into m_ChunkMap by the tick thread. Protected by m_CSSetChunkDataQueue */ cSetChunkDataPtrs m_SetChunkDataQueue; @@ -1032,16 +1032,16 @@ private: /** Handles the weather in each tick */ void TickWeather(float a_Dt); - + /** Handles the mob spawning/moving/destroying each tick */ void TickMobs(float a_Dt); - + /** Executes all tasks queued onto the tick thread */ void TickQueuedTasks(void); - + /** Executes all tasks queued onto the tick thread */ void TickScheduledTasks(void); - + /** Ticks all clients that are in this world */ void TickClients(float a_Dt); @@ -1077,3 +1077,7 @@ private: void SetChunkData(cSetChunkData & a_SetChunkData); }; // tolua_export + + + + diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp index 80d9ab6d2..d85a5c329 100644 --- a/src/WorldStorage/NBTChunkSerializer.cpp +++ b/src/WorldStorage/NBTChunkSerializer.cpp @@ -467,7 +467,7 @@ void cNBTChunkSerializer::AddMinecartEntity(cMinecart * a_Minecart) void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster) { - const char * EntityClass = NULL; + const char * EntityClass = nullptr; switch (a_Monster->GetMobType()) { case mtBat: EntityClass = "Bat"; break; diff --git a/src/WorldStorage/ScoreboardSerializer.cpp b/src/WorldStorage/ScoreboardSerializer.cpp index e30eecf67..404604382 100644 --- a/src/WorldStorage/ScoreboardSerializer.cpp +++ b/src/WorldStorage/ScoreboardSerializer.cpp @@ -174,13 +174,13 @@ void cScoreboardSerializer::SaveScoreboardToNBT(cFastNBTWriter & a_Writer) a_Writer.BeginCompound("DisplaySlots"); cObjective * Objective = m_ScoreBoard->GetObjectiveIn(cScoreboard::dsList); - a_Writer.AddString("slot_0", (Objective == NULL) ? "" : Objective->GetName()); + a_Writer.AddString("slot_0", (Objective == nullptr) ? "" : Objective->GetName()); Objective = m_ScoreBoard->GetObjectiveIn(cScoreboard::dsSidebar); - a_Writer.AddString("slot_1", (Objective == NULL) ? "" : Objective->GetName()); + a_Writer.AddString("slot_1", (Objective == nullptr) ? "" : Objective->GetName()); Objective = m_ScoreBoard->GetObjectiveIn(cScoreboard::dsName); - a_Writer.AddString("slot_2", (Objective == NULL) ? "" : Objective->GetName()); + a_Writer.AddString("slot_2", (Objective == nullptr) ? "" : Objective->GetName()); a_Writer.EndCompound(); // DisplaySlots diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp index 8ebcff936..af7551ee4 100644 --- a/src/WorldStorage/WSSAnvil.cpp +++ b/src/WorldStorage/WSSAnvil.cpp @@ -126,7 +126,7 @@ cWSSAnvil::cWSSAnvil(cWorld * a_World, int a_CompressionFactor) : #endif // _DEBUG gzFile gz = gzopen((FILE_IO_PREFIX + fnam).c_str(), "wb"); - if (gz != NULL) + if (gz != nullptr) { gzwrite(gz, Writer.GetResult().data(), (unsigned)Writer.GetResult().size()); } @@ -193,7 +193,7 @@ bool cWSSAnvil::GetChunkData(const cChunkCoords & a_Chunk, AString & a_Data) { cCSLock Lock(m_CS); cMCAFile * File = LoadMCAFile(a_Chunk); - if (File == NULL) + if (File == nullptr) { return false; } @@ -208,7 +208,7 @@ bool cWSSAnvil::SetChunkData(const cChunkCoords & a_Chunk, const AString & a_Dat { cCSLock Lock(m_CS); cMCAFile * File = LoadMCAFile(a_Chunk); - if (File == NULL) + if (File == nullptr) { return false; } @@ -234,7 +234,7 @@ cWSSAnvil::cMCAFile * cWSSAnvil::LoadMCAFile(const cChunkCoords & a_Chunk) // Is it already cached? for (cMCAFiles::iterator itr = m_Files.begin(); itr != m_Files.end(); ++itr) { - if (((*itr) != NULL) && ((*itr)->GetRegionX() == RegionX) && ((*itr)->GetRegionZ() == RegionZ)) + if (((*itr) != nullptr) && ((*itr)->GetRegionX() == RegionX) && ((*itr)->GetRegionZ() == RegionZ)) { // Move the file to front and return it: cMCAFile * f = *itr; @@ -253,9 +253,9 @@ cWSSAnvil::cMCAFile * cWSSAnvil::LoadMCAFile(const cChunkCoords & a_Chunk) cFile::CreateFolder(FILE_IO_PREFIX + FileName); AppendPrintf(FileName, "/r.%d.%d.mca", RegionX, RegionZ); cMCAFile * f = new cMCAFile(FileName, RegionX, RegionZ); - if (f == NULL) + if (f == nullptr) { - return NULL; + return nullptr; } m_Files.push_front(f); @@ -373,7 +373,7 @@ bool cWSSAnvil::LoadChunkFromNBT(const cChunkCoords & a_Chunk, const cParsedNBT // Load the biomes from NBT, if present and valid. First try MCS-style, then Vanilla-style: cChunkDef::BiomeMap BiomeMap; cChunkDef::BiomeMap * Biomes = LoadBiomeMapFromNBT(&BiomeMap, a_NBT, a_NBT.FindChildByName(Level, "MCSBiomes")); - if (Biomes == NULL) + if (Biomes == nullptr) { // MCS-style biomes not available, load vanilla-style: Biomes = LoadVanillaBiomeMapFromNBT(&BiomeMap, a_NBT, a_NBT.FindChildByName(Level, "Biomes")); @@ -426,9 +426,9 @@ bool cWSSAnvil::LoadChunkFromNBT(const cChunkCoords & a_Chunk, const cParsedNBT cSetChunkDataPtr SetChunkData(new cSetChunkData( a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ, BlockTypes, MetaData, - IsLightValid ? BlockLight : NULL, - IsLightValid ? SkyLight : NULL, - NULL, Biomes, + IsLightValid ? BlockLight : nullptr, + IsLightValid ? SkyLight : nullptr, + nullptr, Biomes, Entities, BlockEntities, false )); @@ -525,12 +525,12 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadVanillaBiomeMapFromNBT(cChunkDef::BiomeMap { if ((a_TagIdx < 0) || (a_NBT.GetType(a_TagIdx) != TAG_ByteArray)) { - return NULL; + return nullptr; } if (a_NBT.GetDataLength(a_TagIdx) != 16 * 16) { // The biomes stored don't match in size - return NULL; + return nullptr; } const unsigned char * VanillaBiomeData = (const unsigned char *)(a_NBT.GetData(a_TagIdx)); for (size_t i = 0; i < ARRAYCOUNT(*a_BiomeMap); i++) @@ -538,7 +538,7 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadVanillaBiomeMapFromNBT(cChunkDef::BiomeMap if ((VanillaBiomeData)[i] == 0xff) { // Unassigned biomes - return NULL; + return nullptr; } (*a_BiomeMap)[i] = (EMCSBiome)(VanillaBiomeData[i]); } @@ -553,12 +553,12 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadBiomeMapFromNBT(cChunkDef::BiomeMap * a_Bio { if ((a_TagIdx < 0) || (a_NBT.GetType(a_TagIdx) != TAG_IntArray)) { - return NULL; + return nullptr; } if (a_NBT.GetDataLength(a_TagIdx) != sizeof(*a_BiomeMap)) { // The biomes stored don't match in size - return NULL; + return nullptr; } const char * BiomeData = (a_NBT.GetData(a_TagIdx)); for (size_t i = 0; i < ARRAYCOUNT(*a_BiomeMap); i++) @@ -567,7 +567,7 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadBiomeMapFromNBT(cChunkDef::BiomeMap * a_Bio if ((*a_BiomeMap)[i] == 0xff) { // Unassigned biomes - return NULL; + return nullptr; } } return a_BiomeMap; @@ -631,7 +631,7 @@ void cWSSAnvil::LoadBlockEntitiesFromNBT(cBlockEntityList & a_BlockEntities, con BLOCKTYPE BlockType = cChunkDef::GetBlock(a_BlockTypes, RelX, RelY, RelZ); NIBBLETYPE BlockMeta = cChunkDef::GetNibble(a_BlockMetas, RelX, RelY, RelZ); std::auto_ptr be(LoadBlockEntityFromNBT(a_NBT, Child, x, y, z, BlockType, BlockMeta)); - if (be.get() == NULL) + if (be.get() == nullptr) { continue; } @@ -670,7 +670,7 @@ cBlockEntity * cWSSAnvil::LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a case E_BLOCK_WALLSIGN: return LoadSignFromNBT (a_NBT, a_Tag, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_WALLSIGN); // Blocktypes that have block entities but don't load their contents from disk: - case E_BLOCK_ENDER_CHEST: return NULL; + case E_BLOCK_ENDER_CHEST: return nullptr; } // All the other blocktypes should have no entities assigned to them. Report an error: @@ -686,7 +686,7 @@ cBlockEntity * cWSSAnvil::LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a ItemTypeToString(a_BlockType).c_str(), a_BlockType, TypeName.c_str(), a_BlockX, a_BlockY, a_BlockZ ); - return NULL; + return nullptr; } @@ -836,7 +836,7 @@ cBlockEntity * cWSSAnvil::LoadBeaconFromNBT(const cParsedNBT & a_NBT, int a_TagI // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Beacon")) { - return NULL; + return nullptr; } std::auto_ptr Beacon(new cBeaconEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -881,13 +881,13 @@ cBlockEntity * cWSSAnvil::LoadChestFromNBT(const cParsedNBT & a_NBT, int a_TagId // https://github.com/mc-server/MCServer/blob/d0551e2e0a98a28f31a88d489d17b408e4a7d38d/src/WorldStorage/WSSAnvil.cpp#L637 if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Chest") && !CheckBlockEntityType(a_NBT, a_TagIdx, "TrappedChest")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty chest - the chunk loader will provide an empty cChestEntity for this + return nullptr; // Make it an empty chest - the chunk loader will provide an empty cChestEntity for this } std::auto_ptr Chest(new cChestEntity(a_BlockX, a_BlockY, a_BlockZ, m_World, a_ChestBlockType)); LoadItemGridFromNBT(Chest->GetContents(), a_NBT, Items); @@ -903,7 +903,7 @@ cBlockEntity * cWSSAnvil::LoadCommandBlockFromNBT(const cParsedNBT & a_NBT, int // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Control")) { - return NULL; + return nullptr; } std::auto_ptr CmdBlock(new cCommandBlockEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -940,13 +940,13 @@ cBlockEntity * cWSSAnvil::LoadDispenserFromNBT(const cParsedNBT & a_NBT, int a_T // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Trap")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty dispenser - the chunk loader will provide an empty cDispenserEntity for this + return nullptr; // Make it an empty dispenser - the chunk loader will provide an empty cDispenserEntity for this } std::auto_ptr Dispenser(new cDispenserEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); LoadItemGridFromNBT(Dispenser->GetContents(), a_NBT, Items); @@ -962,13 +962,13 @@ cBlockEntity * cWSSAnvil::LoadDropperFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Dropper")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty dropper - the chunk loader will provide an empty cDropperEntity for this + return nullptr; // Make it an empty dropper - the chunk loader will provide an empty cDropperEntity for this } std::auto_ptr Dropper(new cDropperEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); LoadItemGridFromNBT(Dropper->GetContents(), a_NBT, Items); @@ -984,7 +984,7 @@ cBlockEntity * cWSSAnvil::LoadFlowerPotFromNBT(const cParsedNBT & a_NBT, int a_T // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "FlowerPot")) { - return NULL; + return nullptr; } std::auto_ptr FlowerPot(new cFlowerPotEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1015,13 +1015,13 @@ cBlockEntity * cWSSAnvil::LoadFurnaceFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Furnace")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty furnace - the chunk loader will provide an empty cFurnaceEntity for this + return nullptr; // Make it an empty furnace - the chunk loader will provide an empty cFurnaceEntity for this } std::auto_ptr Furnace(new cFurnaceEntity(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, m_World)); @@ -1073,13 +1073,13 @@ cBlockEntity * cWSSAnvil::LoadHopperFromNBT(const cParsedNBT & a_NBT, int a_TagI // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Hopper")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty hopper - the chunk loader will provide an empty cHopperEntity for this + return nullptr; // Make it an empty hopper - the chunk loader will provide an empty cHopperEntity for this } std::auto_ptr Hopper(new cHopperEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); LoadItemGridFromNBT(Hopper->GetContents(), a_NBT, Items); @@ -1095,7 +1095,7 @@ cBlockEntity * cWSSAnvil::LoadJukeboxFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "RecordPlayer")) { - return NULL; + return nullptr; } std::auto_ptr Jukebox(new cJukeboxEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1116,7 +1116,7 @@ cBlockEntity * cWSSAnvil::LoadMobHeadFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Skull")) { - return NULL; + return nullptr; } std::auto_ptr MobHead(new cMobHeadEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1151,7 +1151,7 @@ cBlockEntity * cWSSAnvil::LoadNoteBlockFromNBT(const cParsedNBT & a_NBT, int a_T // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Music")) { - return NULL; + return nullptr; } std::auto_ptr NoteBlock(new cNoteEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1172,7 +1172,7 @@ cBlockEntity * cWSSAnvil::LoadSignFromNBT(const cParsedNBT & a_NBT, int a_TagIdx // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Sign")) { - return NULL; + return nullptr; } std::auto_ptr Sign(new cSignEntity(a_BlockType, a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1755,7 +1755,7 @@ void cWSSAnvil::LoadItemFrameFromNBT(cEntityList & a_Entities, const cParsedNBT void cWSSAnvil::LoadArrowFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr Arrow(new cArrowEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr Arrow(new cArrowEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Arrow.get(), a_NBT, a_TagIdx)) { return; @@ -1819,7 +1819,7 @@ void cWSSAnvil::LoadArrowFromNBT(cEntityList & a_Entities, const cParsedNBT & a_ void cWSSAnvil::LoadSplashPotionFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr SplashPotion(new cSplashPotionEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0), cItem())); + std::auto_ptr SplashPotion(new cSplashPotionEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0), cItem())); if (!LoadProjectileBaseFromNBT(*SplashPotion.get(), a_NBT, a_TagIdx)) { return; @@ -1843,7 +1843,7 @@ void cWSSAnvil::LoadSplashPotionFromNBT(cEntityList & a_Entities, const cParsedN void cWSSAnvil::LoadSnowballFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr Snowball(new cThrownSnowballEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr Snowball(new cThrownSnowballEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Snowball.get(), a_NBT, a_TagIdx)) { return; @@ -1859,7 +1859,7 @@ void cWSSAnvil::LoadSnowballFromNBT(cEntityList & a_Entities, const cParsedNBT & void cWSSAnvil::LoadEggFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr Egg(new cThrownEggEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr Egg(new cThrownEggEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Egg.get(), a_NBT, a_TagIdx)) { return; @@ -1875,7 +1875,7 @@ void cWSSAnvil::LoadEggFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NB void cWSSAnvil::LoadFireballFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr Fireball(new cGhastFireballEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr Fireball(new cGhastFireballEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Fireball.get(), a_NBT, a_TagIdx)) { return; @@ -1891,7 +1891,7 @@ void cWSSAnvil::LoadFireballFromNBT(cEntityList & a_Entities, const cParsedNBT & void cWSSAnvil::LoadFireChargeFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr FireCharge(new cFireChargeEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr FireCharge(new cFireChargeEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*FireCharge.get(), a_NBT, a_TagIdx)) { return; @@ -1907,7 +1907,7 @@ void cWSSAnvil::LoadFireChargeFromNBT(cEntityList & a_Entities, const cParsedNBT void cWSSAnvil::LoadThrownEnderpearlFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr Enderpearl(new cThrownEnderPearlEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr Enderpearl(new cThrownEnderPearlEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Enderpearl.get(), a_NBT, a_TagIdx)) { return; @@ -2864,7 +2864,7 @@ bool cWSSAnvil::cMCAFile::OpenFile(bool a_IsForReading) if (m_File.Read(m_Header, sizeof(m_Header)) != sizeof(m_Header)) { // Cannot read the header - perhaps the file has just been created? - // Try writing a NULL header (both chunk offsets and timestamps): + // Try writing a nullptr header (both chunk offsets and timestamps): memset(m_Header, 0, sizeof(m_Header)); if ( (m_File.Write(m_Header, sizeof(m_Header)) != sizeof(m_Header)) || // Real header - chunk offsets diff --git a/src/WorldStorage/WSSAnvil.h b/src/WorldStorage/WSSAnvil.h index 591ec6757..9c579a617 100644 --- a/src/WorldStorage/WSSAnvil.h +++ b/src/WorldStorage/WSSAnvil.h @@ -113,10 +113,10 @@ protected: /// Saves the chunk into NBT data using a_Writer; returns true on success bool SaveChunkToNBT(const cChunkCoords & a_Chunk, cFastNBTWriter & a_Writer); - /// Loads the chunk's biome map from vanilla-format; returns a_BiomeMap if biomes present and valid, NULL otherwise + /// Loads the chunk's biome map from vanilla-format; returns a_BiomeMap if biomes present and valid, nullptr otherwise cChunkDef::BiomeMap * LoadVanillaBiomeMapFromNBT(cChunkDef::BiomeMap * a_BiomeMap, const cParsedNBT & a_NBT, int a_TagIdx); - /// Loads the chunk's biome map from MCS format; returns a_BiomeMap if biomes present and valid, NULL otherwise + /// Loads the chunk's biome map from MCS format; returns a_BiomeMap if biomes present and valid, nullptr otherwise cChunkDef::BiomeMap * LoadBiomeMapFromNBT(cChunkDef::BiomeMap * a_BiomeMap, const cParsedNBT & a_NBT, int a_TagIdx); /// Loads the chunk's entities from NBT data (a_Tag is the Level\\Entities list tag; may be -1) @@ -126,7 +126,7 @@ protected: void LoadBlockEntitiesFromNBT(cBlockEntityList & a_BlockEntitites, const cParsedNBT & a_NBT, int a_Tag, BLOCKTYPE * a_BlockTypes, NIBBLETYPE * a_BlockMetas); /** Loads the data for a block entity from the specified NBT tag. - Returns the loaded block entity, or NULL upon failure. */ + Returns the loaded block entity, or nullptr upon failure. */ cBlockEntity * LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a_Tag, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); /// Loads a cItem contents from the specified NBT tag; returns true if successful. Doesn't load the Slot tag diff --git a/src/WorldStorage/WorldStorage.cpp b/src/WorldStorage/WorldStorage.cpp index c611bfd90..31318ee67 100644 --- a/src/WorldStorage/WorldStorage.cpp +++ b/src/WorldStorage/WorldStorage.cpp @@ -39,8 +39,8 @@ protected: cWorldStorage::cWorldStorage(void) : super("cWorldStorage"), - m_World(NULL), - m_SaveSchema(NULL) + m_World(nullptr), + m_SaveSchema(nullptr) { } diff --git a/src/XMLParser.h b/src/XMLParser.h index e39405529..5b53e55cf 100644 --- a/src/XMLParser.h +++ b/src/XMLParser.h @@ -68,7 +68,7 @@ protected: 3, Create an instance of your class: CMyParser Parser; 4, Call Create(): - Parser.Create(NULL, NULL); + Parser.Create(nullptr, nullptr); 4, Call Parse(), repeatedly: Parser.Parse(Buffer, Length); */ @@ -84,7 +84,7 @@ public: CExpatImpl () { - m_p = NULL; + m_p = nullptr; } // @cmember Destructor @@ -99,24 +99,24 @@ public: // @cmember Create a parser - bool Create (const XML_Char * pszEncoding = NULL, const XML_Char * pszSep = NULL) + bool Create (const XML_Char * pszEncoding = nullptr, const XML_Char * pszSep = nullptr) { // Destroy the old parser Destroy (); - // If the encoding or seperator are empty, then NULL - if (pszEncoding != NULL && pszEncoding [0] == 0) + // If the encoding or seperator are empty, then nullptr + if (pszEncoding != nullptr && pszEncoding [0] == 0) { - pszEncoding = NULL; + pszEncoding = nullptr; } - if (pszSep != NULL && pszSep [0] == 0) + if (pszSep != nullptr && pszSep [0] == 0) { - pszSep = NULL; + pszSep = nullptr; } // Create the new parser - m_p = XML_ParserCreate_MM (pszEncoding, NULL, pszSep); - if (m_p == NULL) + m_p = XML_ParserCreate_MM (pszEncoding, nullptr, pszSep); + if (m_p == nullptr) { return false; } @@ -134,11 +134,11 @@ public: void Destroy (void) { - if (m_p != NULL) + if (m_p != nullptr) { XML_ParserFree (m_p); } - m_p = NULL; + m_p = nullptr; } @@ -146,7 +146,7 @@ public: bool Parse (const char *pszBuffer, int nLength, bool fIsFinal = true) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_Parse (m_p, pszBuffer, nLength, fIsFinal) != 0; } @@ -154,7 +154,7 @@ public: bool ParseBuffer (int nLength, bool fIsFinal = true) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_ParseBuffer (m_p, nLength, fIsFinal) != 0; } @@ -162,7 +162,7 @@ public: void *GetBuffer (int nLength) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetBuffer (m_p, nLength); } @@ -174,23 +174,23 @@ protected: void EnableStartElementHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartElementHandler (m_p, fEnable ? StartElementHandler : NULL); + assert (m_p != nullptr); + XML_SetStartElementHandler (m_p, fEnable ? StartElementHandler : nullptr); } // @cmember Enable/Disable the end element handler void EnableEndElementHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetEndElementHandler (m_p, fEnable ? EndElementHandler : NULL); + assert (m_p != nullptr); + XML_SetEndElementHandler (m_p, fEnable ? EndElementHandler : nullptr); } // @cmember Enable/Disable the element handlers void EnableElementHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); EnableStartElementHandler (fEnable); EnableEndElementHandler (fEnable); } @@ -199,47 +199,47 @@ protected: void EnableCharacterDataHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetCharacterDataHandler (m_p, fEnable ? CharacterDataHandler : NULL); + assert (m_p != nullptr); + XML_SetCharacterDataHandler (m_p, fEnable ? CharacterDataHandler : nullptr); } // @cmember Enable/Disable the processing instruction handler void EnableProcessingInstructionHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetProcessingInstructionHandler (m_p, fEnable ? ProcessingInstructionHandler : NULL); + assert (m_p != nullptr); + XML_SetProcessingInstructionHandler (m_p, fEnable ? ProcessingInstructionHandler : nullptr); } // @cmember Enable/Disable the comment handler void EnableCommentHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetCommentHandler (m_p, fEnable ? CommentHandler : NULL); + assert (m_p != nullptr); + XML_SetCommentHandler (m_p, fEnable ? CommentHandler : nullptr); } // @cmember Enable/Disable the start CDATA section handler void EnableStartCdataSectionHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartCdataSectionHandler (m_p, fEnable ? StartCdataSectionHandler : NULL); + assert (m_p != nullptr); + XML_SetStartCdataSectionHandler (m_p, fEnable ? StartCdataSectionHandler : nullptr); } // @cmember Enable/Disable the end CDATA section handler void EnableEndCdataSectionHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetEndCdataSectionHandler (m_p, fEnable ? EndCdataSectionHandler : NULL); + assert (m_p != nullptr); + XML_SetEndCdataSectionHandler (m_p, fEnable ? EndCdataSectionHandler : nullptr); } // @cmember Enable/Disable the CDATA section handlers void EnableCdataSectionHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); EnableStartCdataSectionHandler (fEnable); EnableEndCdataSectionHandler (fEnable); } @@ -248,45 +248,45 @@ protected: void EnableDefaultHandler (bool fEnable = true, bool fExpand = true) { - assert (m_p != NULL); + assert (m_p != nullptr); if (fExpand) { - XML_SetDefaultHandlerExpand (m_p, fEnable ? DefaultHandler : NULL); + XML_SetDefaultHandlerExpand (m_p, fEnable ? DefaultHandler : nullptr); } else - XML_SetDefaultHandler (m_p, fEnable ? DefaultHandler : NULL); + XML_SetDefaultHandler (m_p, fEnable ? DefaultHandler : nullptr); } // @cmember Enable/Disable external entity ref handler void EnableExternalEntityRefHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetExternalEntityRefHandler (m_p, fEnable ? ExternalEntityRefHandler : NULL); + assert (m_p != nullptr); + XML_SetExternalEntityRefHandler (m_p, fEnable ? ExternalEntityRefHandler : nullptr); } // @cmember Enable/Disable unknown encoding handler void EnableUnknownEncodingHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetUnknownEncodingHandler (m_p, fEnable ? UnknownEncodingHandler : NULL); + assert (m_p != nullptr); + XML_SetUnknownEncodingHandler (m_p, fEnable ? UnknownEncodingHandler : nullptr); } // @cmember Enable/Disable start namespace handler void EnableStartNamespaceDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartNamespaceDeclHandler (m_p, fEnable ? StartNamespaceDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetStartNamespaceDeclHandler (m_p, fEnable ? StartNamespaceDeclHandler : nullptr); } // @cmember Enable/Disable end namespace handler void EnableEndNamespaceDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetEndNamespaceDeclHandler (m_p, fEnable ? EndNamespaceDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetEndNamespaceDeclHandler (m_p, fEnable ? EndNamespaceDeclHandler : nullptr); } // @cmember Enable/Disable namespace handlers @@ -301,32 +301,32 @@ protected: void EnableXmlDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetXmlDeclHandler (m_p, fEnable ? XmlDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetXmlDeclHandler (m_p, fEnable ? XmlDeclHandler : nullptr); } // @cmember Enable/Disable the start DOCTYPE declaration handler void EnableStartDoctypeDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartDoctypeDeclHandler (m_p, fEnable ? StartDoctypeDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetStartDoctypeDeclHandler (m_p, fEnable ? StartDoctypeDeclHandler : nullptr); } // @cmember Enable/Disable the end DOCTYPE declaration handler void EnableEndDoctypeDeclHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); XML_SetEndDoctypeDeclHandler (m_p, - fEnable ? EndDoctypeDeclHandler : NULL); + fEnable ? EndDoctypeDeclHandler : nullptr); } // @cmember Enable/Disable the DOCTYPE declaration handler void EnableDoctypeDeclHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); EnableStartDoctypeDeclHandler (fEnable); EnableEndDoctypeDeclHandler (fEnable); } @@ -338,7 +338,7 @@ public: enum XML_Error GetErrorCode () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetErrorCode (m_p); } @@ -346,7 +346,7 @@ public: long GetCurrentByteIndex () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentByteIndex (m_p); } @@ -354,7 +354,7 @@ public: int GetCurrentLineNumber () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentLineNumber (m_p); } @@ -362,7 +362,7 @@ public: int GetCurrentColumnNumber () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentColumnNumber (m_p); } @@ -370,7 +370,7 @@ public: int GetCurrentByteCount () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentByteCount (m_p); } @@ -378,7 +378,7 @@ public: const char *GetInputContext (int *pnOffset, int *pnSize) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetInputContext (m_p, pnOffset, pnSize); } @@ -682,17 +682,17 @@ protected: XML_Parser m_p; - /// Returns the value of the specified attribute, if found; NULL otherwise + /// Returns the value of the specified attribute, if found; nullptr otherwise static const XML_Char * FindAttr(const XML_Char ** iAttrs, const XML_Char * iAttrToFind) { - for (const XML_Char ** Attr = iAttrs; *Attr != NULL; Attr += 2) + for (const XML_Char ** Attr = iAttrs; *Attr != nullptr; Attr += 2) { if (strcmp(*Attr, iAttrToFind) == 0) { return *(Attr + 1); } } // for Attr - iAttrs[] - return NULL; + return nullptr; } } ; diff --git a/src/main.cpp b/src/main.cpp index 86ecd4000..463c54c28 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -133,8 +133,8 @@ LONG WINAPI LastChanceExceptionFilter(__in struct _EXCEPTION_POINTERS * a_Except ExcInformation.ClientPointers = 0; // Write the dump file: - HANDLE dumpFile = CreateFile(g_DumpFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - g_WriteMiniDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, g_DumpFlags, (a_ExceptionInfo) ? &ExcInformation : NULL, NULL, NULL); + HANDLE dumpFile = CreateFile(g_DumpFileName, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + g_WriteMiniDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, g_DumpFlags, (a_ExceptionInfo) ? &ExcInformation : nullptr, nullptr, nullptr); CloseHandle(dumpFile); // Revert to old stack: @@ -187,7 +187,7 @@ int main( int argc, char **argv) #if defined(_WIN32) && !defined(_WIN64) && defined(_MSC_VER) HINSTANCE hDbgHelp = LoadLibrary("DBGHELP.DLL"); g_WriteMiniDump = (pMiniDumpWriteDump)GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); - if (g_WriteMiniDump != NULL) + if (g_WriteMiniDump != nullptr) { _snprintf_s(g_DumpFileName, ARRAYCOUNT(g_DumpFileName), _TRUNCATE, "crash_mcs_%x.dmp", GetCurrentProcessId()); SetUnhandledExceptionFilter(LastChanceExceptionFilter); @@ -269,7 +269,7 @@ int main( int argc, char **argv) } else if (NoCaseCompare(Arg, "nooutbuf") == 0) { - setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); } } // for i - argv[] -- cgit v1.2.3 From 57f822cd0ed728dc37716c99352c20dfaf2e8caa Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Thu, 23 Oct 2014 08:07:20 +0100 Subject: Signs can be placed on wallsigns. Fixes #1438 --- src/Blocks/BlockSignPost.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Blocks/BlockSignPost.h b/src/Blocks/BlockSignPost.h index 40e15c253..d97501651 100644 --- a/src/Blocks/BlockSignPost.h +++ b/src/Blocks/BlockSignPost.h @@ -35,7 +35,7 @@ public: } BLOCKTYPE Type = a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ); - return ((Type == E_BLOCK_SIGN_POST) || cBlockInfo::IsSolid(Type)); + return ((Type == E_BLOCK_SIGN_POST) || (Type == E_BLOCK_WALLSIGN) || cBlockInfo::IsSolid(Type)); } -- cgit v1.2.3 From 154c329a259d937270a23fcbadfa2c01400db0c3 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 23 Oct 2014 10:53:18 +0200 Subject: Removed the "conditional expression is constant" warning. MSVC spits out many of these on its own std libraries. --- src/Globals.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Globals.h b/src/Globals.h index e0a25ed83..582f5fdaa 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -17,7 +17,6 @@ #pragma warning(disable:4100) // Unreferenced formal parameter // Useful warnings from warning level 4: - #pragma warning(3 : 4127) // Conditional expression is constant #pragma warning(3 : 4189) // Local variable is initialized but not referenced #pragma warning(3 : 4245) // Conversion from 'type1' to 'type2', signed/unsigned mismatch #pragma warning(3 : 4310) // Cast truncates constant value @@ -26,7 +25,10 @@ #pragma warning(3 : 4701) // Potentially unitialized local variable used #pragma warning(3 : 4702) // Unreachable code #pragma warning(3 : 4706) // Assignment within conditional expression - + + // 2014-10-23 xoft: Disabled this because the new C++11 headers in MSVC produce tons of these warnings uselessly + // #pragma warning(3 : 4127) // Conditional expression is constant + // Disabling this warning, because we know what we're doing when we're doing this: #pragma warning(disable: 4355) // 'this' used in initializer list -- cgit v1.2.3 From 07bbfd58949d1155617e969651e89c8392a981c0 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 23 Oct 2014 12:51:59 +0200 Subject: Fixed a crash in redstone simulator. --- src/Simulator/IncrementalRedstoneSimulator.inc | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index 200fc0971..2d03584e2 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -2001,7 +2001,6 @@ bool cIncrementalRedstoneSimulatorUnboundedRelGetBlock(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, Block, OtherRepeaterDir) && (Block == E_BLOCK_REDSTONE_REPEATER_ON)) { - NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX -1, a_RelBlockY, a_RelBlockZ) & 0x3; if ((OtherRepeaterDir & 0x03) == 0x1) { return true; -- cgit v1.2.3 From 449d08cb3d1a8ef430430790fcea0ce36b713866 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 23 Oct 2014 15:15:10 +0200 Subject: Merged IniFile into main MCS sources. --- src/Bindings/AllToLua.pkg | 2 +- src/Bindings/PluginManager.cpp | 2 +- src/BlockID.cpp | 2 +- src/CMakeLists.txt | 4 +- src/Entities/Player.cpp | 2 +- src/Generating/BioGen.cpp | 2 +- src/Generating/ChunkGenerator.cpp | 2 +- src/Generating/CompoGen.cpp | 2 +- src/Generating/ComposableGenerator.cpp | 2 +- src/Generating/DistortedHeightmap.cpp | 2 +- src/Generating/EndGen.cpp | 2 +- src/Generating/FinishGen.cpp | 2 +- src/Generating/HeiGen.cpp | 2 +- src/Generating/Noise3DGenerator.cpp | 2 +- src/HTTPServer/HTTPServer.h | 2 +- src/IniFile.cpp | 908 +++++++++++++++++++++++++++++++++ src/IniFile.h | 224 ++++++++ src/MonsterConfig.cpp | 2 +- src/Protocol/Authenticator.cpp | 2 +- src/Protocol/MojangAPI.cpp | 2 +- src/RCONServer.cpp | 2 +- src/RankManager.cpp | 2 +- src/Root.cpp | 5 +- src/Server.cpp | 2 +- src/Simulator/SandSimulator.cpp | 2 +- src/WebAdmin.h | 2 +- src/World.cpp | 2 +- 27 files changed, 1160 insertions(+), 27 deletions(-) create mode 100644 src/IniFile.cpp create mode 100644 src/IniFile.h (limited to 'src') diff --git a/src/Bindings/AllToLua.pkg b/src/Bindings/AllToLua.pkg index 1bff26b0e..7b78578ee 100644 --- a/src/Bindings/AllToLua.pkg +++ b/src/Bindings/AllToLua.pkg @@ -15,7 +15,7 @@ $cfile "../Vector3.h" $cfile "../ChunkDef.h" $cfile "../BiomeDef.h" -$cfile "../../lib/inifile/iniFile.h" +$cfile "../IniFile.h" $cfile "../OSSupport/File.h" diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp index e549aefa3..f63578885 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -9,7 +9,7 @@ #include "../Server.h" #include "../CommandOutput.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../Entities/Player.h" #define FIND_HOOK(a_HookName) HookMap::iterator Plugins = m_Hooks.find(a_HookName); diff --git a/src/BlockID.cpp b/src/BlockID.cpp index 755c721db..c0f3193bb 100644 --- a/src/BlockID.cpp +++ b/src/BlockID.cpp @@ -4,7 +4,7 @@ #include "Globals.h" #include "BlockID.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "Item.h" #include "Mobs/Monster.h" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9d0e2cede..096fa824d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -34,6 +34,7 @@ SET (SRCS FastRandom.cpp FurnaceRecipe.cpp Globals.cpp + IniFile.cpp Inventory.cpp Item.cpp ItemGrid.cpp @@ -98,6 +99,7 @@ SET (HDRS ForEachChunkProvider.h FurnaceRecipe.h Globals.h + IniFile.h Inventory.h Item.h ItemGrid.h @@ -320,4 +322,4 @@ endif () if (WIN32) target_link_libraries(${EXECUTABLE} expat tolualib ws2_32.lib Psapi.lib) endif() -target_link_libraries(${EXECUTABLE} luaexpat iniFile jsoncpp polarssl zlib sqlite lua SQLiteCpp) +target_link_libraries(${EXECUTABLE} luaexpat jsoncpp polarssl zlib sqlite lua SQLiteCpp) diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index 790147fd3..1f1627f8a 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -20,7 +20,7 @@ #include "../WorldStorage/StatSerializer.h" #include "../CompositeChat.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "json/json.h" // 6000 ticks or 5 minutes diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index d86d44bbc..203faff56 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -5,7 +5,7 @@ #include "Globals.h" #include "BioGen.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../LinearUpscale.h" diff --git a/src/Generating/ChunkGenerator.cpp b/src/Generating/ChunkGenerator.cpp index 1eecd6e51..92e1bb31d 100644 --- a/src/Generating/ChunkGenerator.cpp +++ b/src/Generating/ChunkGenerator.cpp @@ -2,7 +2,7 @@ #include "Globals.h" #include "ChunkGenerator.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "ChunkDesc.h" #include "ComposableGenerator.h" #include "Noise3DGenerator.h" diff --git a/src/Generating/CompoGen.cpp b/src/Generating/CompoGen.cpp index 2c88f23f1..29b831dfd 100644 --- a/src/Generating/CompoGen.cpp +++ b/src/Generating/CompoGen.cpp @@ -12,7 +12,7 @@ #include "../BlockID.h" #include "../Item.h" #include "../LinearUpscale.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 9a52588d5..169821050 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -7,7 +7,7 @@ #include "ComposableGenerator.h" #include "../World.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../Root.h" // Individual composed algorithms: diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index e6849fadf..aac1d2bf3 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -7,7 +7,7 @@ #include "DistortedHeightmap.h" #include "../OSSupport/File.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../LinearUpscale.h" diff --git a/src/Generating/EndGen.cpp b/src/Generating/EndGen.cpp index c94cd1eff..0111d2fa3 100644 --- a/src/Generating/EndGen.cpp +++ b/src/Generating/EndGen.cpp @@ -5,7 +5,7 @@ #include "Globals.h" #include "EndGen.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../LinearUpscale.h" diff --git a/src/Generating/FinishGen.cpp b/src/Generating/FinishGen.cpp index 96e3dc26b..0564789dc 100644 --- a/src/Generating/FinishGen.cpp +++ b/src/Generating/FinishGen.cpp @@ -15,7 +15,7 @@ #include "../Simulator/FluidSimulator.h" // for cFluidSimulator::CanWashAway() #include "../Simulator/FireSimulator.h" #include "../World.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index acfefaefc..a0b8770f5 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -6,7 +6,7 @@ #include "Globals.h" #include "HeiGen.h" #include "../LinearUpscale.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "DistortedHeightmap.h" #include "EndGen.h" #include "Noise3DGenerator.h" diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index c3ca30384..5a4cb44cf 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -6,7 +6,7 @@ #include "Globals.h" #include "Noise3DGenerator.h" #include "../OSSupport/File.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../LinearInterpolation.h" #include "../LinearUpscale.h" diff --git a/src/HTTPServer/HTTPServer.h b/src/HTTPServer/HTTPServer.h index 522b7da62..73d4cbdd0 100644 --- a/src/HTTPServer/HTTPServer.h +++ b/src/HTTPServer/HTTPServer.h @@ -11,7 +11,7 @@ #include "../OSSupport/ListenThread.h" #include "../OSSupport/SocketThreads.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "PolarSSL++/RsaPrivateKey.h" #include "PolarSSL++/CryptoKey.h" #include "PolarSSL++/X509Cert.h" diff --git a/src/IniFile.cpp b/src/IniFile.cpp new file mode 100644 index 000000000..517fd36af --- /dev/null +++ b/src/IniFile.cpp @@ -0,0 +1,908 @@ +// IniFile.cpp: Implementation of the CIniFile class. +// Written by: Adam Clauss +// Email: cabadam@houston.rr.com +// You may use this class/code as you wish in your programs. Feel free to distribute it, and +// email suggested changes to me. +// +// Rewritten by: Shane Hill +// Date: 21/08/2001 +// Email: Shane.Hill@dsto.defence.gov.au +// Reason: Remove dependancy on MFC. Code should compile on any +// platform. +////////////////////////////////////////////////////////////////////// + +/* +!! MODIFIED BY FAKETRUTH and xoft !! +*/ + +#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules + +// C++ Includes +#include + +// C Includes +#include + +// Local Includes +#include "IniFile.h" + +#if defined(WIN32) + #define iniEOL endl +#else + #define iniEOL '\r' << endl +#endif + +#ifndef _WIN32 + #define sscanf_s(buffer, stringbuffer, ...) (sscanf(buffer, stringbuffer, __VA_ARGS__)) +#endif + +using namespace std; + + + + + +cIniFile::cIniFile(void) : + m_IsCaseInsensitive(true) +{ +} + + + + + +bool cIniFile::ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect) +{ + // Normally you would use ifstream, but the SGI CC compiler has + // a few bugs with ifstream. So ... fstream used. + fstream f; + AString line; + AString keyname, valuename, value; + AString::size_type pLeft, pRight; + bool IsFromExampleRedirect = false; + + f.open((FILE_IO_PREFIX + a_FileName).c_str(), ios::in); + if (f.fail()) + { + f.clear(); + if (a_AllowExampleRedirect) + { + // Retry with the .example.ini file instead of .ini: + AString ExPath(a_FileName.substr(0, a_FileName.length() - 4)); + ExPath.append(".example.ini"); + f.open((FILE_IO_PREFIX + ExPath).c_str(), ios::in); + if (f.fail()) + { + return false; + } + IsFromExampleRedirect = true; + } + else + { + return false; + } + } + + bool IsFirstLine = true; + + while (getline(f, line)) + { + // To be compatible with Win32, check for existence of '\r'. + // Win32 files have the '\r' and Unix files don't at the end of a line. + // Note that the '\r' will be written to INI files from + // Unix so that the created INI file can be read under Win32 + // without change. + + // Removes UTF-8 Byte Order Markers (BOM) if, present. + if (IsFirstLine) + { + RemoveBom(line); + IsFirstLine = false; + } + + size_t lineLength = line.length(); + if (lineLength == 0) + { + continue; + } + if (line[lineLength - 1] == '\r') + { + line = line.substr(0, lineLength - 1); + } + + if (line.length() == 0) + { + continue; + } + + // Check that the user hasn't opened a binary file by checking the first + // character of each line! + if (!isprint(line[0])) + { + printf("%s: Binary-check failed on char %d\n", __FUNCTION__, line[0]); + f.close(); + return false; + } + if ((pLeft = line.find_first_of(";#[=")) == AString::npos) + { + continue; + } + + switch (line[pLeft]) + { + case '[': + { + if ( + ((pRight = line.find_last_of("]")) != AString::npos) && + (pRight > pLeft) + ) + { + keyname = line.substr(pLeft + 1, pRight - pLeft - 1); + AddKeyName(keyname); + } + break; + } + + case '=': + { + valuename = line.substr(0, pLeft); + value = line.substr(pLeft + 1); + AddValue(keyname, valuename, value); + break; + } + + case ';': + case '#': + { + if (names.empty()) + { + AddHeaderComment(line.substr(pLeft + 1)); + } + else + { + AddKeyComment(keyname, line.substr(pLeft + 1)); + } + break; + } + } // switch (line[pLeft]) + } // while (getline()) + + f.close(); + if (keys.empty() && names.empty() && comments.empty()) + { + // File be empty or unreadable, equivalent to nonexistant + return false; + } + + if (IsFromExampleRedirect) + { + WriteFile(FILE_IO_PREFIX + a_FileName); + } + + return true; +} + + + + + +bool cIniFile::WriteFile(const AString & a_FileName) const +{ + // Normally you would use ofstream, but the SGI CC compiler has + // a few bugs with ofstream. So ... fstream used. + fstream f; + + f.open((FILE_IO_PREFIX + a_FileName).c_str(), ios::out); + if (f.fail()) + { + return false; + } + + // Write header comments. + size_t NumComments = comments.size(); + for (size_t commentID = 0; commentID < NumComments; ++commentID) + { + f << ';' << comments[commentID] << iniEOL; + } + if (NumComments > 0) + { + f << iniEOL; + } + + // Write keys and values. + for (size_t keyID = 0; keyID < keys.size(); ++keyID) + { + f << '[' << names[keyID] << ']' << iniEOL; + + // Comments. + for (size_t commentID = 0; commentID < keys[keyID].comments.size(); ++commentID) + { + f << ';' << keys[keyID].comments[commentID] << iniEOL; + } + + // Values. + for (size_t valueID = 0; valueID < keys[keyID].names.size(); ++valueID) + { + f << keys[keyID].names[valueID] << '=' << keys[keyID].values[valueID] << iniEOL; + } + f << iniEOL; + } + f.close(); + + return true; +} + + + + + +int cIniFile::FindKey(const AString & a_KeyName) const +{ + AString CaseKeyName = CheckCase(a_KeyName); + for (size_t keyID = 0; keyID < names.size(); ++keyID) + { + if (CheckCase(names[keyID]) == CaseKeyName) + { + return (int)keyID; + } + } + return noID; +} + + + + + +int cIniFile::FindValue(const int keyID, const AString & a_ValueName) const +{ + if (!keys.size() || (keyID >= (int)keys.size())) + { + return noID; + } + + AString CaseValueName = CheckCase(a_ValueName); + for (size_t valueID = 0; valueID < keys[keyID].names.size(); ++valueID) + { + if (CheckCase(keys[keyID].names[valueID]) == CaseValueName) + { + return int(valueID); + } + } + return noID; +} + + + + + +int cIniFile::AddKeyName(const AString & keyname) +{ + names.resize(names.size() + 1, keyname); + keys.resize(keys.size() + 1); + return (int)names.size() - 1; +} + + + + + +AString cIniFile::GetKeyName(const int keyID) const +{ + if (keyID < (int)names.size()) + { + return names[keyID]; + } + else + { + return ""; + } +} + + + + + +int cIniFile::GetNumValues(const int keyID) const +{ + if (keyID < (int)keys.size()) + { + return (int)keys[keyID].names.size(); + } + return 0; +} + + + + + +int cIniFile::GetNumValues(const AString & keyname) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return 0; + } + return (int)keys[keyID].names.size(); +} + + + + + +AString cIniFile::GetValueName(const int keyID, const int valueID) const +{ + if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size())) + { + return keys[keyID].names[valueID]; + } + return ""; +} + + + + + +AString cIniFile::GetValueName(const AString & keyname, const int valueID) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return ""; + } + return GetValueName(keyID, valueID); +} + + + + + +void cIniFile::AddValue(const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value) +{ + int keyID = FindKey(a_KeyName); + if (keyID == noID) + { + keyID = int(AddKeyName(a_KeyName)); + } + + keys[keyID].names.push_back(a_ValueName); + keys[keyID].values.push_back(a_Value); +} + + + + + +void cIniFile::AddValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value) +{ + AddValue(a_KeyName, a_ValueName, Printf("%d", a_Value)); +} + + + + + +void cIniFile::AddValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value) +{ + AddValue(a_KeyName, a_ValueName, Printf("%f", a_Value)); +} + + + + + +bool cIniFile::SetValue(const int keyID, const int valueID, const AString & value) +{ + if (((size_t)keyID >= keys.size()) || ((size_t)valueID >= keys[keyID].names.size())) + { + return false; + } + keys[keyID].values[valueID] = value; + return true; +} + + + + + +bool cIniFile::SetValue(const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists) +{ + int keyID = FindKey(a_KeyName); + if (keyID == noID) + { + if (!a_CreateIfNotExists) + { + return false; + } + keyID = AddKeyName(a_KeyName); + } + + int valueID = FindValue(keyID, a_ValueName); + if (valueID == noID) + { + if (!a_CreateIfNotExists) + { + return false; + } + keys[keyID].names.push_back(a_ValueName); + keys[keyID].values.push_back(a_Value); + } + else + { + keys[keyID].values[valueID] = a_Value; + } + + return true; +} + + + + + +bool cIniFile::SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists) +{ + return SetValue(a_KeyName, a_ValueName, Printf("%d", a_Value), a_CreateIfNotExists); +} + + + + + +bool cIniFile::SetValueI(const AString & a_Keyname, const AString & a_ValueName, const Int64 a_Value, const bool a_CreateIfNotExists) +{ + return SetValue(a_Keyname, a_ValueName, Printf("%lld", a_Value), a_CreateIfNotExists); +} + + + + + +bool cIniFile::SetValueF(const AString & a_KeyName, const AString & a_ValueName, double const a_Value, const bool a_CreateIfNotExists) +{ + return SetValue(a_KeyName, a_ValueName, Printf("%f", a_Value), a_CreateIfNotExists); +} + + + + + +bool cIniFile::SetValueV(const AString & a_KeyName, const AString & a_ValueName, const char * a_Format, ...) +{ + va_list args; + va_start(args, a_Format); + AString Data; + AppendVPrintf(Data, a_Format, args); + va_end(args); + return SetValue(a_KeyName, a_ValueName, Data); +} + + + + + +AString cIniFile::GetValue(const int keyID, const int valueID, const AString & defValue) const +{ + if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size())) + { + return keys[keyID].values[valueID]; + } + return defValue; +} + + + + + +AString cIniFile::GetValue(const AString & keyname, const AString & valuename, const AString & defValue) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return defValue; + } + + int valueID = FindValue(int(keyID), valuename); + if (valueID == noID) + { + return defValue; + } + + return keys[keyID].values[valueID]; +} + + + + + +int cIniFile::GetValueI(const AString & keyname, const AString & valuename, const int defValue) const +{ + AString Data; + Printf(Data, "%d", defValue); + return atoi(GetValue(keyname, valuename, Data).c_str()); +} + + + + + +double cIniFile::GetValueF(const AString & keyname, const AString & valuename, double const defValue) const +{ + AString Data; + Printf(Data, "%f", defValue); + return atof(GetValue(keyname, valuename, Data).c_str()); +} + + + + + +AString cIniFile::GetValueSet(const AString & keyname, const AString & valuename, const AString & defValue) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + SetValue(keyname, valuename, defValue); + return defValue; + } + + int valueID = FindValue(int(keyID), valuename); + if (valueID == noID) + { + SetValue(keyname, valuename, defValue); + return defValue; + } + + return keys[keyID].values[valueID]; +} + + + + + +double cIniFile::GetValueSetF(const AString & keyname, const AString & valuename, const double defValue) +{ + AString Data; + Printf(Data, "%f", defValue); + return atof(GetValueSet(keyname, valuename, Data).c_str()); +} + + + + + +int cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, const int defValue) +{ + AString Data; + Printf(Data, "%d", defValue); + return atoi(GetValueSet(keyname, valuename, Data).c_str()); +} + + + + + +Int64 cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, const Int64 defValue) +{ + AString Data; + Printf(Data, "%lld", defValue); + AString resultstring = GetValueSet(keyname, valuename, Data); + Int64 result = defValue; +#ifdef _WIN32 + sscanf_s(resultstring.c_str(), "%lld", &result); +#else + sscanf(resultstring.c_str(), "%lld", &result); +#endif + return result; +} + + + + + +bool cIniFile::DeleteValueByID(const int keyID, const int valueID) +{ + if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size())) + { + // This looks strange, but is neccessary. + vector::iterator npos = keys[keyID].names.begin() + valueID; + vector::iterator vpos = keys[keyID].values.begin() + valueID; + keys[keyID].names.erase(npos, npos + 1); + keys[keyID].values.erase(vpos, vpos + 1); + return true; + } + return false; +} + + + + + +bool cIniFile::DeleteValue(const AString & keyname, const AString & valuename) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + + int valueID = FindValue(int(keyID), valuename); + if (valueID == noID) + { + return false; + } + + return DeleteValueByID(keyID, valueID); +} + + + + + +bool cIniFile::DeleteKey(const AString & keyname) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + + vector::iterator npos = names.begin() + keyID; + vector::iterator kpos = keys.begin() + keyID; + names.erase(npos, npos + 1); + keys.erase(kpos, kpos + 1); + + return true; +} + + + + + +void cIniFile::Clear(void) +{ + names.clear(); + keys.clear(); + comments.clear(); +} + + + + + +bool cIniFile::HasValue(const AString & a_KeyName, const AString & a_ValueName) +{ + // Find the key: + int keyID = FindKey(a_KeyName); + if (keyID == noID) + { + return false; + } + + // Find the value: + int valueID = FindValue(keyID, a_ValueName); + return (valueID != noID); +} + + + + + +void cIniFile::AddHeaderComment(const AString & comment) +{ + comments.push_back(comment); + // comments.resize(comments.size() + 1, comment); +} + + + + + +AString cIniFile::GetHeaderComment(const int commentID) const +{ + if (commentID < (int)comments.size()) + { + return comments[commentID]; + } + return ""; +} + + + + + +bool cIniFile::DeleteHeaderComment(int commentID) +{ + if (commentID < (int)comments.size()) + { + vector::iterator cpos = comments.begin() + commentID; + comments.erase(cpos, cpos + 1); + return true; + } + return false; +} + + + + + +int cIniFile::GetNumKeyComments(const int keyID) const +{ + if (keyID < (int)keys.size()) + { + return (int)keys[keyID].comments.size(); + } + return 0; +} + + + + + +int cIniFile::GetNumKeyComments(const AString & keyname) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return 0; + } + return (int)keys[keyID].comments.size(); +} + + + + + +bool cIniFile::AddKeyComment(const int keyID, const AString & comment) +{ + if (keyID < (int)keys.size()) + { + keys[keyID].comments.resize(keys[keyID].comments.size() + 1, comment); + return true; + } + return false; +} + + + + + +bool cIniFile::AddKeyComment(const AString & keyname, const AString & comment) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + return AddKeyComment(keyID, comment); +} + + + + + +AString cIniFile::GetKeyComment(const int keyID, const int commentID) const +{ + if ((keyID < (int)keys.size()) && (commentID < (int)keys[keyID].comments.size())) + { + return keys[keyID].comments[commentID]; + } + return ""; +} + + + + + +AString cIniFile::GetKeyComment(const AString & keyname, const int commentID) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return ""; + } + return GetKeyComment(int(keyID), commentID); +} + + + + + +bool cIniFile::DeleteKeyComment(const int keyID, const int commentID) +{ + if ((keyID < (int)keys.size()) && (commentID < (int)keys[keyID].comments.size())) + { + vector::iterator cpos = keys[keyID].comments.begin() + commentID; + keys[keyID].comments.erase(cpos, cpos + 1); + return true; + } + return false; +} + + + + + +bool cIniFile::DeleteKeyComment(const AString & keyname, const int commentID) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + return DeleteKeyComment(int(keyID), commentID); +} + + + + + +bool cIniFile::DeleteKeyComments(const int keyID) +{ + if (keyID < (int)keys.size()) + { + keys[keyID].comments.clear(); + return true; + } + return false; +} + + + + + +bool cIniFile::DeleteKeyComments(const AString & keyname) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + return DeleteKeyComments(int(keyID)); +} + + + + + +AString cIniFile::CheckCase(const AString & s) const +{ + if (!m_IsCaseInsensitive) + { + return s; + } + AString res(s); + size_t len = res.length(); + for (size_t i = 0; i < len; i++) + { + res[i] = tolower(res[i]); + } + return res; +} + + + + + +void cIniFile::RemoveBom(AString & a_line) const +{ + // The BOM sequence for UTF-8 is 0xEF,0xBB,0xBF + static unsigned const char BOM[] = { 0xEF, 0xBB, 0xBF }; + + // The BOM sequence, if present, is always th e first three characters of the input. + const AString ref = a_line.substr(0, 3); + + // If any of the first three chars do not match, return and do nothing. + for (int i = 0; i < 3; ++i) + { + if (static_cast(ref[i]) != BOM[i]) + { + return; + } + } + + // First three characters match; erase them. + a_line.erase(0, 3); +} + + + + diff --git a/src/IniFile.h b/src/IniFile.h new file mode 100644 index 000000000..33229bff0 --- /dev/null +++ b/src/IniFile.h @@ -0,0 +1,224 @@ +// IniFile.cpp: Implementation of the CIniFile class. +// Written by: Adam Clauss +// Email: cabadam@tamu.edu +// You may use this class/code as you wish in your programs. Feel free to distribute it, and +// email suggested changes to me. +// +// Rewritten by: Shane Hill +// Date: 21/08/2001 +// Email: Shane.Hill@dsto.defence.gov.au +// Reason: Remove dependancy on MFC. Code should compile on any +// platform. Tested on Windows/Linux/Irix +////////////////////////////////////////////////////////////////////// + +/* +!! MODIFIED BY FAKETRUTH and madmaxoft!! +*/ + +#ifndef CIniFile_H +#define CIniFile_H + + + + + +#define MAX_KEYNAME 128 +#define MAX_VALUENAME 128 +#define MAX_VALUEDATA 2048 + + + + + +// tolua_begin + +class cIniFile +{ +private: + bool m_IsCaseInsensitive; + + struct key + { + std::vector names; + std::vector values; + std::vector comments; + } ; + + std::vector keys; + std::vector names; + std::vector comments; + + /// If the object is case-insensitive, returns s as lowercase; otherwise returns s as-is + AString CheckCase(const AString & s) const; + + /// Removes the UTF-8 BOMs (Byte order makers), if present. + void RemoveBom(AString & a_line) const; + +public: + + enum errors + { + noID = -1, + }; + + /// Creates a new instance with no data + cIniFile(void); + + // Sets whether or not keynames and valuenames should be case sensitive. + // The default is case insensitive. + void CaseSensitive (void) { m_IsCaseInsensitive = false; } + void CaseInsensitive(void) { m_IsCaseInsensitive = true; } + + /** Reads the contents of the specified ini file + If the file doesn't exist and a_AllowExampleRedirect is true, tries to read .example.ini, and + writes its contents as .ini, if successful. + Returns true if successful, false otherwise. + */ + bool ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect = true); + + /// Writes data stored in class to the specified ini file + bool WriteFile(const AString & a_FileName) const; + + /// Deletes all stored ini data (but doesn't touch the file) + void Clear(void); + + /** Returns true iff the specified value exists. */ + bool HasValue(const AString & a_KeyName, const AString & a_ValueName); + + /// Returns index of specified key, or noID if not found + int FindKey(const AString & keyname) const; + + /// Returns index of specified value, in the specified key, or noID if not found + int FindValue(const int keyID, const AString & valuename) const; + + /// Returns number of keys currently in the ini + int GetNumKeys(void) const { return (int)keys.size(); } + + /// Add a key name + int AddKeyName(const AString & keyname); + + // Returns key names by index. + AString GetKeyName(const int keyID) const; + + // Returns number of values stored for specified key. + int GetNumValues(const AString & keyname) const; + int GetNumValues(const int keyID) const; + + // Returns value name by index for a given keyname or keyID. + AString GetValueName(const AString & keyname, const int valueID) const; + AString GetValueName(const int keyID, const int valueID) const; + + // Gets value of [keyname] valuename =. + // Overloaded to return string, int, and double. + // Returns defValue if key/value not found. + AString GetValue (const AString & keyname, const AString & valuename, const AString & defValue = "") const; + AString GetValue (const int keyID, const int valueID, const AString & defValue = "") const; + double GetValueF(const AString & keyname, const AString & valuename, const double defValue = 0) const; + int GetValueI(const AString & keyname, const AString & valuename, const int defValue = 0) const; + bool GetValueB(const AString & keyname, const AString & valuename, const bool defValue = false) const + { + return (GetValueI(keyname, valuename, defValue ? 1 : 0) != 0); + } + + // Gets the value; if not found, write the default to the INI file + AString GetValueSet (const AString & keyname, const AString & valuename, const AString & defValue = ""); + double GetValueSetF(const AString & keyname, const AString & valuename, const double defValue = 0.0); + int GetValueSetI(const AString & keyname, const AString & valuename, const int defValue = 0); + Int64 GetValueSetI(const AString & keyname, const AString & valuename, const Int64 defValue = 0); + bool GetValueSetB(const AString & keyname, const AString & valuename, const bool defValue = false) + { + return (GetValueSetI(keyname, valuename, defValue ? 1 : 0) != 0); + } + + // Adds a new value to the specified key. + // If a value of the same name already exists, creates another one (non-standard INI file) + void AddValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value); + void AddValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value); + void AddValueB(const AString & a_KeyName, const AString & a_ValueName, const bool a_Value) + { + return AddValueI(a_KeyName, a_ValueName, a_Value ? 1 : 0); + } + void AddValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value); + + // Overwrites the value of [keyname].valuename + // Specify the optional parameter as false (0) if you do not want the value created if it doesn't exist. + // Returns true if value set, false otherwise. + // Overloaded to accept string, int, and double. + bool SetValue (const int keyID, const int valueID, const AString & value); + bool SetValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists = true); + bool SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists = true); + bool SetValueI(const AString & a_Keyname, const AString & a_ValueName, const Int64 a_Value, const bool a_CreateIfNotExists = true); + bool SetValueB(const AString & a_KeyName, const AString & a_ValueName, const bool a_Value, const bool a_CreateIfNotExists = true) + { + return SetValueI(a_KeyName, a_ValueName, int(a_Value), a_CreateIfNotExists); + } + bool SetValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value, const bool a_CreateIfNotExists = true); + + // tolua_end + + bool SetValueV( const AString & a_KeyName, const AString & a_ValueName, const char * a_Format, ...); + + // tolua_begin + + // Deletes specified value. + // Returns true if value existed and deleted, false otherwise. + bool DeleteValueByID(const int keyID, const int valueID); + bool DeleteValue(const AString & keyname, const AString & valuename); + + // Deletes specified key and all values contained within. + // Returns true if key existed and deleted, false otherwise. + bool DeleteKey(const AString & keyname); + + // Header comment functions. + // Header comments are those comments before the first key. + + /// Returns the number of header comments + int GetNumHeaderComments(void) {return (int)comments.size();} + + /// Adds a header comment + void AddHeaderComment(const AString & comment); + + /// Returns a header comment, or empty string if out of range + AString GetHeaderComment(const int commentID) const; + + /// Deletes a header comment. Returns true if successful + bool DeleteHeaderComment(int commentID); + + /// Deletes all header comments + void DeleteHeaderComments(void) {comments.clear();} + + + // Key comment functions. + // Key comments are those comments within a key. Any comments + // defined within value names will be added to this list. Therefore, + // these comments will be moved to the top of the key definition when + // the CIniFile::WriteFile() is called. + + /// Get number of key comments + int GetNumKeyComments(const int keyID) const; + + /// Get number of key comments + int GetNumKeyComments(const AString & keyname) const; + + /// Add a key comment + bool AddKeyComment(const int keyID, const AString & comment); + + /// Add a key comment + bool AddKeyComment(const AString & keyname, const AString & comment); + + /// Return a key comment + AString GetKeyComment(const int keyID, const int commentID) const; + AString GetKeyComment(const AString & keyname, const int commentID) const; + + // Delete a key comment. + bool DeleteKeyComment(const int keyID, const int commentID); + bool DeleteKeyComment(const AString & keyname, const int commentID); + + // Delete all comments for a key. + bool DeleteKeyComments(const int keyID); + bool DeleteKeyComments(const AString & keyname); +}; + +// tolua_end + +#endif diff --git a/src/MonsterConfig.cpp b/src/MonsterConfig.cpp index a15e413ba..ae2cbbc6b 100644 --- a/src/MonsterConfig.cpp +++ b/src/MonsterConfig.cpp @@ -3,7 +3,7 @@ #include "MonsterConfig.h" #include "Mobs/Monster.h" -#include "inifile/iniFile.h" +#include "IniFile.h" diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp index 984000795..c9e4296a2 100644 --- a/src/Protocol/Authenticator.cpp +++ b/src/Protocol/Authenticator.cpp @@ -7,7 +7,7 @@ #include "../Server.h" #include "../ClientHandle.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "json/json.h" #include "PolarSSL++/BlockingSslClientSocket.h" diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp index dd0d62af5..67f513e44 100644 --- a/src/Protocol/MojangAPI.cpp +++ b/src/Protocol/MojangAPI.cpp @@ -7,7 +7,7 @@ #include "MojangAPI.h" #include "SQLiteCpp/Database.h" #include "SQLiteCpp/Statement.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "json/json.h" #include "PolarSSL++/BlockingSslClientSocket.h" #include "../RankManager.h" diff --git a/src/RCONServer.cpp b/src/RCONServer.cpp index df027c91f..49ca4fc61 100644 --- a/src/RCONServer.cpp +++ b/src/RCONServer.cpp @@ -4,7 +4,7 @@ // Implements the cRCONServer class representing the RCON server #include "Globals.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "RCONServer.h" #include "Server.h" #include "Root.h" diff --git a/src/RankManager.cpp b/src/RankManager.cpp index 3778f5d64..451de88e7 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -5,7 +5,7 @@ #include "Globals.h" #include "RankManager.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "Protocol/MojangAPI.h" #include "ClientHandle.h" diff --git a/src/Root.cpp b/src/Root.cpp index 6a91ec238..24c1a4cc8 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -19,11 +19,10 @@ #include "OSSupport/Timer.h" #include "LoggerListeners.h" #include "BuildInfo.h" - -#include "inifile/iniFile.h" +#include "IniFile.h" #ifdef _WIN32 - #include "conio.h" + #include #include #elif defined(__linux__) #include diff --git a/src/Server.cpp b/src/Server.cpp index 5085d4c94..bbb5ecff3 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -22,7 +22,7 @@ #include "MersenneTwister.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "Vector3.h" #include diff --git a/src/Simulator/SandSimulator.cpp b/src/Simulator/SandSimulator.cpp index 073518b31..dfbd3e458 100644 --- a/src/Simulator/SandSimulator.cpp +++ b/src/Simulator/SandSimulator.cpp @@ -7,7 +7,7 @@ #include "../Defines.h" #include "../Entities/FallingBlock.h" #include "../Chunk.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" diff --git a/src/WebAdmin.h b/src/WebAdmin.h index 94b95dbcf..a85fb1f0c 100644 --- a/src/WebAdmin.h +++ b/src/WebAdmin.h @@ -7,7 +7,7 @@ #include "OSSupport/Socket.h" #include "Bindings/LuaState.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "HTTPServer/HTTPServer.h" #include "HTTPServer/HTTPFormParser.h" diff --git a/src/World.cpp b/src/World.cpp index ff333ad2a..b77b01c10 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -8,7 +8,7 @@ #include "Server.h" #include "Item.h" #include "Root.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "ChunkMap.h" #include "Generating/ChunkDesc.h" #include "OSSupport/Timer.h" -- cgit v1.2.3 From 1235ccb1e20aa764682d766c18a32804963ecf0a Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 23 Oct 2014 15:26:43 +0200 Subject: Removed iniFile library from linux dependencies. --- src/Generating/CMakeLists.txt | 2 +- src/Generating/Prefabs/CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Generating/CMakeLists.txt b/src/Generating/CMakeLists.txt index 33d622b42..cd3d5a9f3 100644 --- a/src/Generating/CMakeLists.txt +++ b/src/Generating/CMakeLists.txt @@ -65,5 +65,5 @@ SET (HDRS if(NOT MSVC) add_library(Generating ${SRCS} ${HDRS}) - target_link_libraries(Generating OSSupport iniFile Blocks) + target_link_libraries(Generating OSSupport Blocks) endif() diff --git a/src/Generating/Prefabs/CMakeLists.txt b/src/Generating/Prefabs/CMakeLists.txt index 2c62aa73d..68f6491c4 100644 --- a/src/Generating/Prefabs/CMakeLists.txt +++ b/src/Generating/Prefabs/CMakeLists.txt @@ -29,5 +29,5 @@ SET (HDRS if(NOT MSVC) add_library(Generating_Prefabs ${SRCS} ${HDRS}) - target_link_libraries(Generating_Prefabs OSSupport iniFile Blocks) + target_link_libraries(Generating_Prefabs OSSupport Blocks) endif() -- cgit v1.2.3 From 32cab75e438dae9c545e51950f14bf36d39d5ef0 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 23 Oct 2014 16:07:43 +0200 Subject: IniFile: Removed an unused macro. --- src/IniFile.cpp | 4 ---- 1 file changed, 4 deletions(-) (limited to 'src') diff --git a/src/IniFile.cpp b/src/IniFile.cpp index 517fd36af..eff41de33 100644 --- a/src/IniFile.cpp +++ b/src/IniFile.cpp @@ -32,10 +32,6 @@ #define iniEOL '\r' << endl #endif -#ifndef _WIN32 - #define sscanf_s(buffer, stringbuffer, ...) (sscanf(buffer, stringbuffer, __VA_ARGS__)) -#endif - using namespace std; -- cgit v1.2.3 From 9af58a81d6467829b72801169c8e80a2bab01804 Mon Sep 17 00:00:00 2001 From: Howaner Date: Thu, 23 Oct 2014 21:19:43 +0200 Subject: Use 3 priorities. --- src/Chunk.cpp | 2 +- src/ChunkSender.cpp | 44 ++++++++++++++++++++++++++++++++++++++++---- src/ChunkSender.h | 4 +++- src/ClientHandle.cpp | 2 +- 4 files changed, 45 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 35a16edec..a0224322a 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -1742,7 +1742,7 @@ void cChunk::SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_Max // Re-send the chunk to all clients: for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr) { - m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::E_CHUNK_PRIORITY_HIGH, (*itr)); + m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::E_CHUNK_PRIORITY_MEDIUM, (*itr)); } // for itr - m_LoadedByClient[] } diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index 7e2301eab..ef2be167b 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -100,6 +100,7 @@ void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a cCSLock Lock(m_CS); if ( std::find(m_SendChunksLowPriority.begin(), m_SendChunksLowPriority.end(), Chunk) != m_SendChunksLowPriority.end() || + std::find(m_SendChunksMediumPriority.begin(), m_SendChunksMediumPriority.end(), Chunk) != m_SendChunksMediumPriority.end() || std::find(m_SendChunksHighPriority.begin(), m_SendChunksHighPriority.end(), Chunk) != m_SendChunksHighPriority.end() ) { @@ -107,10 +108,27 @@ void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a return; } - if (a_Priority == E_CHUNK_PRIORITY_LOW) { - m_SendChunksLowPriority.push_back(Chunk); - } else if (a_Priority == E_CHUNK_PRIORITY_HIGH) { - m_SendChunksHighPriority.push_back(Chunk); + switch (a_Priority) + { + case E_CHUNK_PRIORITY_LOW: + { + m_SendChunksLowPriority.push_back(Chunk); + break; + } + case E_CHUNK_PRIORITY_MEDIUM: + { + m_SendChunksMediumPriority.push_back(Chunk); + break; + } + case E_CHUNK_PRIORITY_HIGH: + { + m_SendChunksHighPriority.push_back(Chunk); + break; + } + default: + { + ASSERT(!"Unknown chunk priority!"); + } } } m_evtQueue.Set(); @@ -133,6 +151,15 @@ void cChunkSender::RemoveClient(cClientHandle * a_Client) } ++itr; } // for itr - m_SendChunksLowPriority[] + for (sSendChunkList::iterator itr = m_SendChunksMediumPriority.begin(); itr != m_SendChunksMediumPriority.end();) + { + if (itr->m_Client == a_Client) + { + itr = m_SendChunksMediumPriority.erase(itr); + continue; + } + ++itr; + } // for itr - m_SendChunksMediumPriority[] for (sSendChunkList::iterator itr = m_SendChunksHighPriority.begin(); itr != m_SendChunksHighPriority.end();) { if (itr->m_Client == a_Client) @@ -191,6 +218,15 @@ void cChunkSender::Execute(void) SendChunk(Coords.m_ChunkX, Coords.m_ChunkZ, nullptr); } + else if (!m_SendChunksMediumPriority.empty()) + { + // Take one from the queue: + sSendChunk Chunk(m_SendChunksMediumPriority.front()); + m_SendChunksMediumPriority.pop_front(); + Lock.Unlock(); + + SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, Chunk.m_Client); + } else { // Take one from the queue: diff --git a/src/ChunkSender.h b/src/ChunkSender.h index 585d50914..7cd7ddd86 100644 --- a/src/ChunkSender.h +++ b/src/ChunkSender.h @@ -79,7 +79,8 @@ public: enum eChunkPriority { E_CHUNK_PRIORITY_HIGH = 0, - E_CHUNK_PRIORITY_LOW = 1, + E_CHUNK_PRIORITY_MEDIUM = 1, + E_CHUNK_PRIORITY_LOW = 2, }; bool Start(cWorld * a_World); @@ -143,6 +144,7 @@ protected: cCriticalSection m_CS; cChunkCoordsList m_ChunksReady; sSendChunkList m_SendChunksLowPriority; + sSendChunkList m_SendChunksMediumPriority; sSendChunkList m_SendChunksHighPriority; cEvent m_evtQueue; // Set when anything is added to m_ChunksReady cEvent m_evtRemoved; // Set when removed clients are safe to be deleted diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index dc360861e..faee05450 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -463,7 +463,7 @@ bool cClientHandle::StreamNextChunk(void) // Unloaded chunk found -> Send it to the client. Lock.Unlock(); - StreamChunk(ChunkX, ChunkZ, cChunkSender::E_CHUNK_PRIORITY_HIGH); + StreamChunk(ChunkX, ChunkZ, ((Range <= 2) ? cChunkSender::E_CHUNK_PRIORITY_HIGH : cChunkSender::E_CHUNK_PRIORITY_MEDIUM)); return false; } } -- cgit v1.2.3 From 6bcc2c187aff025bb8ab35e8454c0a3e1c62e97e Mon Sep 17 00:00:00 2001 From: archshift Date: Thu, 23 Oct 2014 14:58:42 -0700 Subject: Fix linking on OS X, which does not have librt. --- src/OSSupport/CMakeLists.txt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index 429949c59..a2f46d656 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -38,7 +38,11 @@ SET (HDRS if(NOT MSVC) add_library(OSSupport ${SRCS} ${HDRS}) - if(UNIX) - target_link_libraries(OSSupport pthread rt) + if(NOT APPLE) + target_link_libraries(OSSupport rt) endif() + + if(UNIX) + target_link_libraries(OSSupport pthread) + endif() endif() -- cgit v1.2.3 From 8ccb729504a866b50907993a71d3e35ad19e96a4 Mon Sep 17 00:00:00 2001 From: archshift Date: Thu, 23 Oct 2014 15:03:54 -0700 Subject: Fixed potential linker errors with mingw, as it isn't MSVC and it isn't APPLE. --- src/OSSupport/CMakeLists.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index a2f46d656..3c0a3f1a0 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -38,11 +38,11 @@ SET (HDRS if(NOT MSVC) add_library(OSSupport ${SRCS} ${HDRS}) - if(NOT APPLE) - target_link_libraries(OSSupport rt) - endif() - if(UNIX) + if(NOT APPLE) + target_link_libraries(OSSupport rt) + endif() + target_link_libraries(OSSupport pthread) endif() endif() -- cgit v1.2.3 From d5dfacae8790da4bfed71760c75528da89218596 Mon Sep 17 00:00:00 2001 From: worktycho Date: Thu, 23 Oct 2014 23:23:34 +0100 Subject: Fixed formatstring --- src/IniFile.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/IniFile.h b/src/IniFile.h index 33229bff0..44b3422d0 100644 --- a/src/IniFile.h +++ b/src/IniFile.h @@ -156,7 +156,7 @@ public: // tolua_end - bool SetValueV( const AString & a_KeyName, const AString & a_ValueName, const char * a_Format, ...); + bool SetValueV( const AString & a_KeyName, const AString & a_ValueName, const char * a_Format, ...) FORMATSTRING(3,4); // tolua_begin -- cgit v1.2.3 From dd86c1f4a33cc89cf4316105690f4d8d1cb24c4a Mon Sep 17 00:00:00 2001 From: archshift Date: Thu, 23 Oct 2014 23:49:20 -0700 Subject: OSSupport/CMakeLists.txt: fixed indentation --- src/OSSupport/CMakeLists.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index 3c0a3f1a0..c3eabeef6 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -38,11 +38,11 @@ SET (HDRS if(NOT MSVC) add_library(OSSupport ${SRCS} ${HDRS}) - if(UNIX) + if(UNIX) if(NOT APPLE) target_link_libraries(OSSupport rt) endif() - target_link_libraries(OSSupport pthread) - endif() + target_link_libraries(OSSupport pthread) + endif() endif() -- cgit v1.2.3 From e272637ff582f3e32794bc7b2a1a23564bba54c4 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 24 Oct 2014 08:49:36 +0200 Subject: IniFile: Removed the problematic printf-like Set function. It wasn't used in any client code anyway. --- src/IniFile.cpp | 14 -------------- src/IniFile.h | 6 ------ 2 files changed, 20 deletions(-) (limited to 'src') diff --git a/src/IniFile.cpp b/src/IniFile.cpp index eff41de33..a666a4ff8 100644 --- a/src/IniFile.cpp +++ b/src/IniFile.cpp @@ -461,20 +461,6 @@ bool cIniFile::SetValueF(const AString & a_KeyName, const AString & a_ValueName, -bool cIniFile::SetValueV(const AString & a_KeyName, const AString & a_ValueName, const char * a_Format, ...) -{ - va_list args; - va_start(args, a_Format); - AString Data; - AppendVPrintf(Data, a_Format, args); - va_end(args); - return SetValue(a_KeyName, a_ValueName, Data); -} - - - - - AString cIniFile::GetValue(const int keyID, const int valueID, const AString & defValue) const { if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size())) diff --git a/src/IniFile.h b/src/IniFile.h index 44b3422d0..3f704551f 100644 --- a/src/IniFile.h +++ b/src/IniFile.h @@ -154,12 +154,6 @@ public: } bool SetValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value, const bool a_CreateIfNotExists = true); - // tolua_end - - bool SetValueV( const AString & a_KeyName, const AString & a_ValueName, const char * a_Format, ...) FORMATSTRING(3,4); - - // tolua_begin - // Deletes specified value. // Returns true if value existed and deleted, false otherwise. bool DeleteValueByID(const int keyID, const int valueID); -- cgit v1.2.3 From aff537e7141952f743d6536c8e66d54374d1c2ba Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 26 Oct 2014 10:13:43 +0100 Subject: Added type to block type enum. --- src/BlockID.h | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index bb06722d2..b0cdc2a00 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -1,7 +1,13 @@ #pragma once +// The following hackery is to allow typed C++ enum for C++ code, yet have ToLua pocess the values. +// ToLua doesn't understand typed enums, so we use preprocessor to hide it from ToLua + +enum ENUM_BLOCK_ID : BLOCKTYPE +#if 0 +enum ENUM_BLOCK_ID // tolua_export +#endif // tolua_begin -enum ENUM_BLOCK_ID { E_BLOCK_AIR = 0, E_BLOCK_STONE = 1, @@ -221,6 +227,10 @@ enum ENUM_BLOCK_ID }; // tolua_end + + + + // tolua_begin enum ENUM_ITEM_ID { -- cgit v1.2.3 From ec8c05066600b6c9744f8e9e61650505992bf63f Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 26 Oct 2014 18:17:04 +0100 Subject: Added IsBiomeVeryCold() and IsBiomeCold() functions. --- src/BiomeDef.cpp | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/BiomeDef.h | 9 ++++++++ 2 files changed, 71 insertions(+) (limited to 'src') diff --git a/src/BiomeDef.cpp b/src/BiomeDef.cpp index 02f8c2232..188e06173 100644 --- a/src/BiomeDef.cpp +++ b/src/BiomeDef.cpp @@ -160,3 +160,65 @@ bool IsBiomeNoDownfall(EMCSBiome a_Biome) } } } + + + + + +bool IsBiomeVeryCold(EMCSBiome a_Biome) +{ + switch (a_Biome) + { + case biFrozenOcean: + case biFrozenRiver: + case biIcePlains: + case biIceMountains: + case biColdBeach: + case biColdTaiga: + case biColdTaigaHills: + case biIcePlainsSpikes: + case biColdTaigaM: + { + return true; + } + default: + { + return false; + } + } +} + + + + +bool IsBiomeCold(EMCSBiome a_Biome) +{ + switch (a_Biome) + { + case biExtremeHills: + case biTaiga: + case biTaigaHills: + case biExtremeHillsEdge: + case biStoneBeach: + case biMegaTaiga: + case biMegaTaigaHills: + case biExtremeHillsPlus: + case biExtremeHillsM: + case biTaigaM: + case biColdTaigaM: + case biMegaSpruceTaiga: + case biMegaSpruceTaigaHills: + case biExtremeHillsPlusM: + { + return true; + } + default: + { + return false; + } + } +} + + + + diff --git a/src/BiomeDef.h b/src/BiomeDef.h index f929596e9..dfab50663 100644 --- a/src/BiomeDef.h +++ b/src/BiomeDef.h @@ -113,5 +113,14 @@ extern AString BiomeToString(int a_Biome); /** Returns true if the biome has no downfall - deserts and savannas */ extern bool IsBiomeNoDownfall(EMCSBiome a_Biome); +/** Returns true if the biome is very cold +(has snow on ground everywhere, turns top water to ice, has snowfall instead of rain everywhere). +Doesn't report mildly cold biomes (where it snows above certain elevation), use IsBiomeCold() for those. */ +extern bool IsBiomeVeryCold(EMCSBiome a_Biome); + +/** Returns true if the biome is cold +(has snow and snowfall at higher elevations but not at regular heights). +Doesn't report Very Cold biomes, use IsBiomeVeryCold() for those. */ +extern bool IsBiomeCold(EMCSBiome a_Biome); // tolua_end -- cgit v1.2.3 From 7e1d603080146047bade80ee70982dbe569cdf30 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 26 Oct 2014 19:58:16 +0100 Subject: Added new biomegen: Grown --- src/BiomeDef.h | 6 + src/Generating/BioGen.cpp | 93 +++++ src/Generating/IntGen.h | 954 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1053 insertions(+) create mode 100644 src/Generating/IntGen.h (limited to 'src') diff --git a/src/BiomeDef.h b/src/BiomeDef.h index dfab50663..84751cfd7 100644 --- a/src/BiomeDef.h +++ b/src/BiomeDef.h @@ -113,6 +113,12 @@ extern AString BiomeToString(int a_Biome); /** Returns true if the biome has no downfall - deserts and savannas */ extern bool IsBiomeNoDownfall(EMCSBiome a_Biome); +/** Returns true if the biome is an ocean biome. */ +inline bool IsBiomeOcean(int a_Biome) +{ + return ((a_Biome == biOcean) || (a_Biome == biDeepOcean)); +} + /** Returns true if the biome is very cold (has snow on ground everywhere, turns top water to ice, has snowfall instead of rain everywhere). Doesn't report mildly cold biomes (where it snows above certain elevation), use IsBiomeCold() for those. */ diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 203faff56..c9405040f 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -5,6 +5,7 @@ #include "Globals.h" #include "BioGen.h" +#include "IntGen.h" #include "../IniFile.h" #include "../LinearUpscale.h" @@ -916,6 +917,94 @@ void cBioGenTwoLevel::InitializeBiomeGen(cIniFile & a_IniFile) +//////////////////////////////////////////////////////////////////////////////// +// cBioGenGrown: + +class cBioGenGrown: + public cBiomeGen +{ +public: + cBioGenGrown(int a_Seed) + { + auto FinalRivers = + std::make_shared> (a_Seed + 1, + std::make_shared> (a_Seed + 2, + std::make_shared> (a_Seed + 3, + std::make_shared> (a_Seed + 4, + std::make_shared> (a_Seed + 5, + std::make_shared> (a_Seed + 6, + std::make_shared> (a_Seed + 7, + std::make_shared> (a_Seed + 8, + std::make_shared> (a_Seed + 9, + std::make_shared> (a_Seed + 10, + std::make_shared> (a_Seed + 11, + std::make_shared>(a_Seed + 12 + )))))))))))); + + auto FinalBiomes = + std::make_shared> (a_Seed + 1008, + std::make_shared>(a_Seed + 15, + std::make_shared> (a_Seed + 1000, + std::make_shared> (a_Seed + 16, + std::make_shared> (a_Seed + 1001, + std::make_shared> (a_Seed, + std::make_shared> (a_Seed + 1002, + std::make_shared> (a_Seed + 1, + std::make_shared> ( + std::make_shared> (a_Seed + 1002, + std::make_shared>(a_Seed + 2, + std::make_shared> (a_Seed + 3, + std::make_shared> (a_Seed + 2004, 10, + std::make_shared> (a_Seed + 4, + std::make_shared> (a_Seed + 9, 50, biMushroomIsland, + std::make_shared> (a_Seed + 8, + std::make_shared> (a_Seed + 10, 500, biDeepOcean, + std::make_shared> (a_Seed + 3000, + std::make_shared> (a_Seed + 5, + std::make_shared> ( + std::make_shared> (a_Seed + 1003, + std::make_shared> (a_Seed + 7, + std::make_shared> (bgJungle, bgTemperate, 50, a_Seed + 100, + std::make_shared> (bgIce, bgTemperate, 50, a_Seed + 101, + std::make_shared> (a_Seed + 2000, 70, + std::make_shared> (a_Seed + 1004, + std::make_shared> (a_Seed + 10, + std::make_shared> (a_Seed + 2003, 50, + std::make_shared> (a_Seed + 11, + std::make_shared> (a_Seed + 100, 65 + )))))))))))))))))))))))))))))); + + m_Gen = + std::make_shared>(a_Seed, + std::make_shared>(a_Seed, + std::make_shared>(a_Seed, + std::make_shared>(a_Seed, + std::make_shared> ( + FinalBiomes, FinalRivers + ))))); + } + + virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_Biomes) override + { + cIntGen<16, 16>::Values vals; + m_Gen->GetInts(a_ChunkX * cChunkDef::Width, a_ChunkZ * cChunkDef::Width, vals); + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + cChunkDef::SetBiome(a_Biomes, x, z, (EMCSBiome)vals[x + cChunkDef::Width * z]); + } + } + } + +protected: + cIntGenPtr<16, 16> m_Gen; +}; + + + + + //////////////////////////////////////////////////////////////////////////////// // cBiomeGen: @@ -952,6 +1041,10 @@ cBiomeGenPtr cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & { res = new cBioGenTwoLevel(a_Seed); } + else if (NoCaseCompare(BiomeGenName, "grown") == 0) + { + res = new cBioGenGrown(a_Seed); + } else { if (NoCaseCompare(BiomeGenName, "multistepmap") != 0) diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h new file mode 100644 index 000000000..ae940232f --- /dev/null +++ b/src/Generating/IntGen.h @@ -0,0 +1,954 @@ + +// IntGen.h + +// Declares the cIntGen class and descendants for generating and filtering various 2D arrays of ints + +/* +The integers generated may be interpreted in several ways: +- land/see designators + - 0 = ocean + - >0 = land +- biome group designators + - 0 = ocean + - 1 = desert biomes + - 2 = temperate biomes + - 3 = mountains (hills and forests) + - 4 = jungle + - 5 = ice biomes +- biome IDs +The interpretation depends on the generator used and on the position in the chain. + +The generators can be chained together - one produces data that another one consumes. +Some of such chain connections require changing the data dimensions between the two, which is handled automatically +by using templates. +*/ + + + + + +#pragma once + +#include "../BiomeDef.h" + + + + + +/** Constants representing the biome group designators. */ +const int bgOcean = 0; +const int bgDesert = 1; +const int bgTemperate = 2; +const int bgMountains = 3; +const int bgJungle = 4; +const int bgIce = 5; +const int bgMax = 5; // Maximum biome group value + + + + + +/** Interface that all the generator classes provide. */ +template +class cIntGen +{ +public: + /** Holds the array of values generated by this class (descendant). */ + typedef int Values[SizeX * SizeZ]; + + /** Generates the array of templated size into a_Values, based on given min coords. */ + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) = 0; +}; + +template +using cIntGenPtr = std::shared_ptr>; + + + + + + +/** Provides additional cNoise member and its helper functions. */ +template +class cIntGenWithNoise : + public cIntGen +{ + typedef cIntGen super; + +public: + cIntGenWithNoise(int a_Seed) : + m_Noise(a_Seed) + { + } + +protected: + cNoise m_Noise; + + /** Chooses one of a_Val1 or a_Val2, based on m_Noise and the coordinates for querying the noise. */ + int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + return ((rnd & 1) == 0) ? a_Val1 : a_Val2; + } + + /** Chooses one of a_ValN, based on m_Noise and the coordinates for querying the noise. */ + int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2, int a_Val3, int a_Val4) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + switch (rnd % 4) + { + case 0: return a_Val1; + case 1: return a_Val2; + case 2: return a_Val3; + default: return a_Val4; + } + } +}; + + + + + + +/** Generates a 2D array of random integers in the specified range [0 .. Range). */ +template +class cIntGenChoice : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + cIntGenChoice(int a_Seed) : + super(a_Seed) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + for (int z = 0; z < SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < SizeX; x++) + { + a_Values[x + SizeX * z] = (m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7) % Range; + } + } // for z + } +}; + + + + + + +/** Decides between the ocean and landmass biomes. +Has a threshold (in percent) of how much land, the larger the threshold, the more land. +Generates 0 for ocean, biome group ID for landmass. */ +template +class cIntLandOcean : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + cIntLandOcean(int a_Seed, int a_Threshold) : + super(a_Seed), + m_Threshold(a_Threshold) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + for (int z = 0; z < SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < SizeX; x++) + { + int rnd = (m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); + a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgMax + 1) : 0; + } + } + } + +protected: + int m_Threshold; +}; + + + + + +template +class cIntGenZoom : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +protected: + static const int m_LowerSizeX = (SizeX / 2) + 2; + static const int m_LowerSizeZ = (SizeZ / 2) + 2; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenZoom(int a_Seed, Underlying a_UnderlyingGen) : + super(a_Seed), + m_UnderlyingGen(a_UnderlyingGen) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Generate the underlying data with half the resolution: + int lowerMinX = a_MinX >> 1; + int lowerMinZ = a_MinZ >> 1; + int Underlying[m_LowerSizeX * m_LowerSizeZ]; + m_UnderlyingGen->GetInts(lowerMinX, lowerMinZ, Underlying); + const int lowStepX = (m_LowerSizeX - 1) * 2; + const int lowStepZ = (m_LowerSizeZ - 1) * 2; + int Cache[lowStepX * lowStepZ]; + + // Discreet-interpolate the values into twice the size: + for (int z = 0; z < m_LowerSizeZ - 1; ++z) + { + int idx = (z * 2) * lowStepX; + int PrevZ0 = Underlying[z * m_LowerSizeX]; + int PrevZ1 = Underlying[(z + 1) * m_LowerSizeX]; + + for (int x = 0; x < m_LowerSizeX - 1; ++x) + { + int ValX1Z0 = Underlying[x + 1 + z * m_LowerSizeX]; + int ValX1Z1 = Underlying[x + 1 + (z + 1) * m_LowerSizeX]; + int RndX = (x + lowerMinX) * 2; + int RndZ = (z + lowerMinZ) * 2; + Cache[idx] = PrevZ0; + Cache[idx + lowStepX] = ChooseRandomOne(RndX, RndZ, PrevZ0, PrevZ1); + idx++; + Cache[idx] = ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0); + Cache[idx + lowStepX] = ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); + idx++; + PrevZ0 = ValX1Z0; + PrevZ1 = ValX1Z1; + } + } + + // Copy from Cache into a_Values; take into account the even/odd offsets in a_Min: + for (int z = 0; z < SizeZ; ++z) + { + memcpy(a_Values + z * SizeX, Cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), SizeX * sizeof(int)); + } + } + +protected: + Underlying m_UnderlyingGen; +}; + + + + + +template +class cIntGenSmooth : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + static const int m_UnderlyingSizeX = SizeX + 2; + static const int m_UnderlyingSizeZ = SizeZ + 2; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenSmooth(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Generate the underlying values: + int Cache[(SizeX + 2) * (SizeZ + 2)]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + + // Smooth - for each square check if the surroundings are the same, if so, expand them diagonally. + // Also get rid of single-pixel irregularities (A-B-A): + for (int z = 0; z < SizeZ; z++) + { + int NoiseZ = a_MinZ + z; + for (int x = 0; x < SizeX; x++) + { + int val = Cache[x + 1 + (z + 1) * m_UnderlyingSizeX]; + int Above = Cache[x + 1 + z * m_UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * m_UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * m_UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * m_UnderlyingSizeX]; + + if ((Left == Right) && (Above == Below)) + { + if (((m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) + { + val = Left; + } + else + { + val = Above; + } + } + else + { + if (Left == Right) + { + val = Left; + } + + if (Above == Below) + { + val = Above; + } + } + + a_Values[x + z * SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +template +class cIntGenBeaches : + public cIntGen +{ + typedef cIntGen super; + static const int m_UnderlyingSizeX = SizeX + 2; + static const int m_UnderlyingSizeZ = SizeZ + 2; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenBeaches(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Map for biome -> its beach: + static const int ToBeach[] = + { + /* biOcean */ biOcean, + /* biPlains */ biBeach, + /* biDesert */ biBeach, + /* biExtremeHills */ biStoneBeach, + /* biForest */ biBeach, + /* biTaiga */ biColdBeach, + /* biSwampland */ biSwampland, + /* biRiver */ biRiver, + /* biNether */ biNether, + /* biEnd */ biEnd, + /* biFrozenOcean */ biColdBeach, + /* biFrozenRiver */ biColdBeach, + /* biIcePlains */ biColdBeach, + /* biIceMountains */ biColdBeach, + /* biMushroomIsland */ biMushroomShore, + /* biMushroomShore */ biMushroomShore, + /* biBeach */ biBeach, + /* biDesertHills */ biBeach, + /* biForestHills */ biBeach, + /* biTaigaHills */ biColdBeach, + /* biExtremeHillsEdge */ biStoneBeach, + /* biJungle */ biBeach, + /* biJungleHills */ biBeach, + /* biJungleEdge */ biBeach, + /* biDeepOcean */ biOcean, + /* biStoneBeach */ biStoneBeach, + /* biColdBeach */ biColdBeach, + /* biBirchForest */ biBeach, + /* biBirchForestHills */ biBeach, + /* biRoofedForest */ biBeach, + /* biColdTaiga */ biColdBeach, + /* biColdTaigaHills */ biColdBeach, + /* biMegaTaiga */ biStoneBeach, + /* biMegaTaigaHills */ biStoneBeach, + /* biExtremeHillsPlus */ biStoneBeach, + /* biSavanna */ biBeach, + /* biSavannaPlateau */ biBeach, + /* biMesa */ biMesa, + /* biMesaPlateauF */ biMesa, + /* biMesaPlateau */ biMesa, + }; + + // Generate the underlying values: + int Cache[m_UnderlyingSizeX * m_UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + + // Add beaches between ocean and biomes: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int val = Cache[x + 1 + (z + 1) * m_UnderlyingSizeX]; + int Above = Cache[x + 1 + z * m_UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * m_UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * m_UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * m_UnderlyingSizeX]; + if (!IsBiomeOcean(val)) + { + if (IsBiomeOcean(Above) || IsBiomeOcean(Below) || IsBiomeOcean(Left) || IsBiomeOcean(Right)) + { + val = ToBeach[(val % 128) % ARRAYCOUNT(ToBeach)]; + } + } + a_Values[x + z * SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Generates the underlying numbers and then randomly changes some zeroes into nonzeroes. */ +template +class cIntGenAddIslands : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenAddIslands(int a_Seed, int a_Threshold, Underlying a_Underlying) : + super(a_Seed), + m_Threshold(a_Threshold), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + if (a_Values[x + z * SizeX] == 0) + { + int rnd = m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; + if (rnd % 100 < m_Threshold) + { + a_Values[x + z * SizeX] = (rnd / 100) % 4; + } + } + } + } + } + +protected: + int m_Threshold; + + Underlying m_Underlying; +}; + + + + + +/** A filter that adds an edge biome group between two biome groups that need an edge between them. */ +template +class cIntGenBiomeGroupEdges : + public cIntGen +{ + typedef cIntGen super; + + static const int m_UnderlyingSizeX = SizeX + 2; + static const int m_UnderlyingSizeZ = SizeZ + 2; + +public: + + typedef cIntGenPtr Underlying; + + cIntGenBiomeGroupEdges(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) + { + // Generate the underlying biome groups: + int Cache[m_UnderlyingSizeX * m_UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX, a_MinZ, Cache); + + // Change the biomes on incompatible edges into an edge biome: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int v = Cache[x + 1 + (z + 1) * m_UnderlyingSizeX]; + int Above = Cache[x + 1 + z * m_UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * m_UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * m_UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * m_UnderlyingSizeX]; + switch (v) + { + // Oceans don't need any edges: + case bgOcean: + { + v = bgOcean; + break; + } + + // Desert should neighbor only oceans, desert and temperates; change to temperate when another: + case bgDesert: + { + if ( + !IsDesertCompatible(Above) || + !IsDesertCompatible(Below) || + !IsDesertCompatible(Left) || + !IsDesertCompatible(Right) + ) + { + v = bgTemperate; + } + break; + } + + // Ice should not neighbor deserts; change to temperate: + case bgIce: + { + if ( + (Above == bgDesert) || + (Below == bgDesert) || + (Left == bgDesert) || + (Right == bgDesert) + ) + { + v = bgTemperate; + } + break; + } + + // Jungle should not neighbor Desert or Ice; change to temperate: + case bgJungle: + { + if ( + !IsJungleCompatible(Above) || + !IsJungleCompatible(Below) || + !IsJungleCompatible(Left) || + !IsJungleCompatible(Right) + ) + { + v = bgTemperate; + } + } + } + a_Values[x + z * SizeX] = v; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; + + + inline bool IsDesertCompatible(int a_BiomeGroup) + { + return ((a_BiomeGroup == bgOcean) || (a_BiomeGroup == bgDesert) || (a_BiomeGroup == bgTemperate)); + } + + inline bool IsJungleCompatible(int a_BiomeGroup) + { + return ((a_BiomeGroup != bgDesert) && (a_BiomeGroup != bgIce)); + } +}; + + + + + +template +class cIntGenBiomes : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenBiomes(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Define the per-biome-group biomes: + static const int OceanBiomes[] = + { + biOcean, // biDeepOcean, + }; + + static const int DesertBiomes[] = + { + biDesert, biDesert, biSavanna, biPlains, + }; + + static const int TemperateBiomes[] = + { + biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, + }; + + static const int MountainBiomes[] = + { + biExtremeHills, biForest, biTaiga, biPlains, + }; + + static const int JungleBiomes[] = + { + biJungle, biJungle, biForest, + }; + + static const int IceBiomes[] = + { + biIcePlains, biIcePlains, biColdTaiga, + }; + + static const cBiomesInGroups BiomesInGroups[] = + { + { static_cast(ARRAYCOUNT(OceanBiomes)), OceanBiomes}, + { static_cast(ARRAYCOUNT(DesertBiomes)), DesertBiomes}, + { static_cast(ARRAYCOUNT(TemperateBiomes)), TemperateBiomes}, + { static_cast(ARRAYCOUNT(MountainBiomes)), MountainBiomes}, + { static_cast(ARRAYCOUNT(JungleBiomes)), JungleBiomes}, + { static_cast(ARRAYCOUNT(IceBiomes)), IceBiomes}, + }; + + // Generate the underlying values, representing biome groups: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Overwrite each biome group with a random biome from that group: + for (int z = 0; z < SizeZ; z++) + { + int IdxZ = z * SizeX; + for (int x = 0; x < SizeX; x++) + { + int val = a_Values[x + IdxZ]; + const cBiomesInGroups & Biomes = BiomesInGroups[val % ARRAYCOUNT(BiomesInGroups)]; + int rnd = (m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); + a_Values[x + IdxZ] = Biomes.Biomes[rnd % Biomes.Count]; + } + } + } + +protected: + + struct cBiomesInGroups + { + const int Count; + const int * Biomes; + }; + + + /** The underlying int generator */ + Underlying m_Underlying; +}; + + + + + +template +class cIntGenReplaceRandomly : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenReplaceRandomly(int a_From, int a_To, int a_Chance, int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_From(a_From), + m_To(a_To), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Generate the underlying values: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Replace some of the values: + for (int z = 0; z < SizeZ; z++) + { + int idxZ = z * SizeX; + for (int x = 0; x < SizeX; x++) + { + int idx = x + idxZ; + if (a_Values[idx] == m_From) + { + int rnd = m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 100 < m_Chance) + { + a_Values[idx] = m_To; + } + } + } + } // for z + } + + +protected: + int m_From; + int m_To; + int m_Chance; + Underlying m_Underlying; +}; + + + + + +/** Mixer that joins together finalized biomes and rivers. +It first checks for oceans; if there's no ocean, it checks for a river. */ +template +class cIntGenMixRivers: + public cIntGen +{ + typedef cIntGen super; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenMixRivers(Underlying a_Biomes, Underlying a_Rivers): + m_Biomes(a_Biomes), + m_Rivers(a_Rivers) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Generate the underlying data: + m_Biomes->GetInts(a_MinX, a_MinZ, a_Values); + Values Rivers; + m_Rivers->GetInts(a_MinX, a_MinZ, Rivers); + + // Mix the values: + for (int z = 0; z < SizeZ; z++) + { + int idxZ = z * SizeX; + for (int x = 0; x < SizeX; x++) + { + int idx = x + idxZ; + if (IsBiomeOcean(a_Values[idx])) + { + // Oceans are kept without any changes + continue; + } + if (Rivers[idx] != biRiver) + { + // There's no river, keep the current value + continue; + } + + // There's a river, change the output to a river or a frozen river, based on the original biome: + if (IsBiomeVeryCold((EMCSBiome)a_Values[idx])) + { + a_Values[idx] = biFrozenRiver; + } + else + { + a_Values[idx] = biRiver; + } + } // for x + } // for z + } + +protected: + Underlying m_Biomes; + Underlying m_Rivers; +}; + + + + + +/** Generates a river based on the underlying data. +This is basically an edge detector over the underlying data. The rivers are the edges where the underlying data +changes from one pixel to its neighbor. */ +template +class cIntGenRiver: + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + static const int UnderlyingSizeX = SizeX + 2; + static const int UnderlyingSizeZ = SizeZ + 2; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenRiver(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Generate the underlying data: + int Cache[UnderlyingSizeX * UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + + // Detect the edges: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int Above = Cache[x + 1 + z * UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * UnderlyingSizeX]; + int val = Cache[x + 1 + (z + 1) * UnderlyingSizeX]; + + if ((val == Above) && (val == Below) && (val == Left) && (val == Right)) + { + val = 0; + } + else + { + val = biRiver; + } + a_Values[x + z * SizeX] = val; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Turns some of the oceans into the specified biome. Used for mushroom and deep ocean. +The biome is only placed if at least 3 of its neighbors are ocean and only with the specified chance. */ +template +class cIntGenAddToOcean: + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + static const int UnderlyingSizeX = SizeX + 2; + static const int UnderlyingSizeZ = SizeZ + 2; + +public: + typedef cIntGenPtr Underlying; + + + cIntGenAddToOcean(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + { + // Generate the underlying data: + int Cache[UnderlyingSizeX * UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + + // Add the mushroom islands: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int val = Cache[x + 1 + (z + 1) * UnderlyingSizeX]; + if (!IsBiomeOcean(val)) + { + a_Values[x + z * SizeX] = val; + continue; + } + + // Count the ocean neighbors: + int Above = Cache[x + 1 + z * UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * UnderlyingSizeX]; + int NumOceanNeighbors = 0; + if (IsBiomeOcean(Above)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Above)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Above)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Above)) + { + NumOceanNeighbors += 1; + } + + // If at least 3 ocean neighbors and the chance is right, change: + if ((NumOceanNeighbors >= 3) && ((m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance)) + { + a_Values[x + z * SizeX] = m_ToValue; + } + else + { + a_Values[x + z * SizeX] = val; + } + } // for x + } // for z + } + +protected: + /** Chance, in permille, of changing the biome. */ + int m_Chance; + + /** The value to change the ocean into. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + -- cgit v1.2.3 From dcad6d362685367d996f7acf7c3783f684d269f6 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 26 Oct 2014 20:12:29 +0100 Subject: Added a missing header to CMakeLists. --- src/Generating/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/Generating/CMakeLists.txt b/src/Generating/CMakeLists.txt index cd3d5a9f3..afe30533e 100644 --- a/src/Generating/CMakeLists.txt +++ b/src/Generating/CMakeLists.txt @@ -46,6 +46,7 @@ SET (HDRS FinishGen.h GridStructGen.h HeiGen.h + IntGen.h MineShafts.h NetherFortGen.h Noise3DGenerator.h -- cgit v1.2.3 From dcbe1717cc4e86b3d48c93da9654592ef2373073 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 26 Oct 2014 21:35:24 +0100 Subject: Fixed a copypasta error in cIntGenAddToOcean. --- src/Generating/IntGen.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index ae940232f..a0064715f 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -124,7 +124,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename Values & a_Values) override { for (int z = 0; z < SizeZ; z++) { @@ -913,15 +913,15 @@ public: { NumOceanNeighbors += 1; } - if (IsBiomeOcean(Above)) + if (IsBiomeOcean(Below)) { NumOceanNeighbors += 1; } - if (IsBiomeOcean(Above)) + if (IsBiomeOcean(Left)) { NumOceanNeighbors += 1; } - if (IsBiomeOcean(Above)) + if (IsBiomeOcean(Right)) { NumOceanNeighbors += 1; } -- cgit v1.2.3 From 74df4618de1c52c22f892e0bf82ec612521a10c0 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 26 Oct 2014 22:56:02 +0100 Subject: BioGenGrown: Smaller biomes, add land to map center. --- src/Generating/BioGen.cpp | 6 ++---- src/Generating/IntGen.h | 23 +++++++++++------------ 2 files changed, 13 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index c9405040f..fcb4d74ed 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -969,10 +969,8 @@ public: std::make_shared> (a_Seed + 2000, 70, std::make_shared> (a_Seed + 1004, std::make_shared> (a_Seed + 10, - std::make_shared> (a_Seed + 2003, 50, - std::make_shared> (a_Seed + 11, - std::make_shared> (a_Seed + 100, 65 - )))))))))))))))))))))))))))))); + std::make_shared> (a_Seed + 100, 65 + )))))))))))))))))))))))))))); m_Gen = std::make_shared>(a_Seed, diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index a0064715f..1eb20711d 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -124,7 +124,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, typename Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { for (int z = 0; z < SizeZ; z++) { @@ -146,13 +146,13 @@ public: Has a threshold (in percent) of how much land, the larger the threshold, the more land. Generates 0 for ocean, biome group ID for landmass. */ template -class cIntLandOcean : +class cIntGenLandOcean : public cIntGenWithNoise { typedef cIntGenWithNoise super; public: - cIntLandOcean(int a_Seed, int a_Threshold) : + cIntGenLandOcean(int a_Seed, int a_Threshold) : super(a_Seed), m_Threshold(a_Threshold) { @@ -170,6 +170,12 @@ public: a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgMax + 1) : 0; } } + + // If the centerpoint of the world is within the area, set it to bgTemperate, always: + if ((a_MinX <= 0) && (a_MinZ <= 0) && (a_MinX + SizeX > 0) && (a_MinZ + SizeZ > 0)) + { + a_Values[-a_MinX - a_MinZ * SizeX] = bgTemperate; + } } protected: @@ -451,12 +457,12 @@ public: { for (int x = 0; x < SizeX; x++) { - if (a_Values[x + z * SizeX] == 0) + if (a_Values[x + z * SizeX] == bgOcean) { int rnd = m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; if (rnd % 100 < m_Threshold) { - a_Values[x + z * SizeX] = (rnd / 100) % 4; + a_Values[x + z * SizeX] = (rnd / 100) % bgMax; } } } @@ -511,13 +517,6 @@ public: int Right = Cache[x + 2 + (z + 1) * m_UnderlyingSizeX]; switch (v) { - // Oceans don't need any edges: - case bgOcean: - { - v = bgOcean; - break; - } - // Desert should neighbor only oceans, desert and temperates; change to temperate when another: case bgDesert: { -- cgit v1.2.3 From 7d6db6f33d60a7976e714478ec27e65faa79a46b Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 26 Oct 2014 22:59:59 +0100 Subject: IntGen: Attempt at fixing Linux compilation. --- src/Generating/IntGen.h | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index 1eb20711d..20927f7fb 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -131,7 +131,7 @@ public: int BaseZ = a_MinZ + z; for (int x = 0; x < SizeX; x++) { - a_Values[x + SizeX * z] = (m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7) % Range; + a_Values[x + SizeX * z] = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7) % Range; } } // for z } @@ -159,7 +159,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { for (int z = 0; z < SizeZ; z++) { @@ -207,7 +207,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying data with half the resolution: int lowerMinX = a_MinX >> 1; @@ -276,7 +276,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying values: int Cache[(SizeX + 2) * (SizeZ + 2)]; @@ -350,7 +350,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Map for biome -> its beach: static const int ToBeach[] = @@ -450,7 +450,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); for (int z = 0; z < SizeZ; z++) @@ -499,7 +499,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) { // Generate the underlying biome groups: int Cache[m_UnderlyingSizeX * m_UnderlyingSizeZ]; @@ -602,7 +602,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Define the per-biome-group biomes: static const int OceanBiomes[] = @@ -699,7 +699,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying values: m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); @@ -754,11 +754,11 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying data: m_Biomes->GetInts(a_MinX, a_MinZ, a_Values); - Values Rivers; + typename super::Values Rivers; m_Rivers->GetInts(a_MinX, a_MinZ, Rivers); // Mix the values: @@ -823,7 +823,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying data: int Cache[UnderlyingSizeX * UnderlyingSizeZ]; @@ -884,7 +884,7 @@ public: } - virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) override + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying data: int Cache[UnderlyingSizeX * UnderlyingSizeZ]; -- cgit v1.2.3 From 7d08d34693706ef70cff6cfc796d4f7cbd396bc5 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 27 Oct 2014 09:35:21 +0100 Subject: Removed too advanced C++11 features. We need to keep gcc 4.6 compatibility; these features were not implemented in that version yet. --- src/Generating/BioGen.cpp | 2 +- src/Generating/IntGen.h | 58 ++++++++++++++++++++++------------------------- 2 files changed, 28 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index fcb4d74ed..96c181915 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -996,7 +996,7 @@ public: } protected: - cIntGenPtr<16, 16> m_Gen; + std::shared_ptr> m_Gen; }; diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index 20927f7fb..94a17abd9 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -60,10 +60,6 @@ public: virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) = 0; }; -template -using cIntGenPtr = std::shared_ptr>; - - @@ -166,7 +162,7 @@ public: int BaseZ = a_MinZ + z; for (int x = 0; x < SizeX; x++) { - int rnd = (m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); + int rnd = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgMax + 1) : 0; } } @@ -197,7 +193,7 @@ protected: static const int m_LowerSizeZ = (SizeZ / 2) + 2; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenZoom(int a_Seed, Underlying a_UnderlyingGen) : @@ -232,10 +228,10 @@ public: int RndX = (x + lowerMinX) * 2; int RndZ = (z + lowerMinZ) * 2; Cache[idx] = PrevZ0; - Cache[idx + lowStepX] = ChooseRandomOne(RndX, RndZ, PrevZ0, PrevZ1); + Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, PrevZ1); idx++; - Cache[idx] = ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0); - Cache[idx + lowStepX] = ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); + Cache[idx] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0); + Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); idx++; PrevZ0 = ValX1Z0; PrevZ1 = ValX1Z1; @@ -262,11 +258,11 @@ class cIntGenSmooth : public cIntGenWithNoise { typedef cIntGenWithNoise super; - static const int m_UnderlyingSizeX = SizeX + 2; - static const int m_UnderlyingSizeZ = SizeZ + 2; + static const int UnderlyingSizeX = SizeX + 2; + static const int UnderlyingSizeZ = SizeZ + 2; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenSmooth(int a_Seed, Underlying a_Underlying) : @@ -279,7 +275,7 @@ public: virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying values: - int Cache[(SizeX + 2) * (SizeZ + 2)]; + int Cache[UnderlyingSizeX * UnderlyingSizeZ]; m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); // Smooth - for each square check if the surroundings are the same, if so, expand them diagonally. @@ -289,15 +285,15 @@ public: int NoiseZ = a_MinZ + z; for (int x = 0; x < SizeX; x++) { - int val = Cache[x + 1 + (z + 1) * m_UnderlyingSizeX]; - int Above = Cache[x + 1 + z * m_UnderlyingSizeX]; - int Below = Cache[x + 1 + (z + 2) * m_UnderlyingSizeX]; - int Left = Cache[x + (z + 1) * m_UnderlyingSizeX]; - int Right = Cache[x + 2 + (z + 1) * m_UnderlyingSizeX]; + int val = Cache[x + 1 + (z + 1) * UnderlyingSizeX]; + int Above = Cache[x + 1 + z * UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * UnderlyingSizeX]; if ((Left == Right) && (Above == Below)) { - if (((m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) + if (((super::m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) { val = Left; } @@ -341,7 +337,7 @@ class cIntGenBeaches : static const int m_UnderlyingSizeZ = SizeZ + 2; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenBeaches(Underlying a_Underlying) : @@ -439,7 +435,7 @@ class cIntGenAddIslands : typedef cIntGenWithNoise super; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenAddIslands(int a_Seed, int a_Threshold, Underlying a_Underlying) : @@ -459,7 +455,7 @@ public: { if (a_Values[x + z * SizeX] == bgOcean) { - int rnd = m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; + int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; if (rnd % 100 < m_Threshold) { a_Values[x + z * SizeX] = (rnd / 100) % bgMax; @@ -491,7 +487,7 @@ class cIntGenBiomeGroupEdges : public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenBiomeGroupEdges(Underlying a_Underlying) : m_Underlying(a_Underlying) @@ -592,7 +588,7 @@ class cIntGenBiomes : typedef cIntGenWithNoise super; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenBiomes(int a_Seed, Underlying a_Underlying) : @@ -656,7 +652,7 @@ public: { int val = a_Values[x + IdxZ]; const cBiomesInGroups & Biomes = BiomesInGroups[val % ARRAYCOUNT(BiomesInGroups)]; - int rnd = (m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); + int rnd = (super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); a_Values[x + IdxZ] = Biomes.Biomes[rnd % Biomes.Count]; } } @@ -686,7 +682,7 @@ class cIntGenReplaceRandomly : typedef cIntGenWithNoise super; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenReplaceRandomly(int a_From, int a_To, int a_Chance, int a_Seed, Underlying a_Underlying) : @@ -713,7 +709,7 @@ public: int idx = x + idxZ; if (a_Values[idx] == m_From) { - int rnd = m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; if (rnd % 100 < m_Chance) { a_Values[idx] = m_To; @@ -744,7 +740,7 @@ class cIntGenMixRivers: typedef cIntGen super; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenMixRivers(Underlying a_Biomes, Underlying a_Rivers): @@ -813,7 +809,7 @@ class cIntGenRiver: static const int UnderlyingSizeZ = SizeZ + 2; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenRiver(int a_Seed, Underlying a_Underlying): @@ -872,7 +868,7 @@ class cIntGenAddToOcean: static const int UnderlyingSizeZ = SizeZ + 2; public: - typedef cIntGenPtr Underlying; + typedef std::shared_ptr> Underlying; cIntGenAddToOcean(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying): @@ -926,7 +922,7 @@ public: } // If at least 3 ocean neighbors and the chance is right, change: - if ((NumOceanNeighbors >= 3) && ((m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance)) + if ((NumOceanNeighbors >= 3) && ((super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance)) { a_Values[x + z * SizeX] = m_ToValue; } -- cgit v1.2.3 From a068ebf3e022f72ae703b762215abb5039cd35c8 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 27 Oct 2014 09:48:57 +0100 Subject: cIntGen: Added a virtual destructor. --- src/Generating/IntGen.h | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index 94a17abd9..d7ed9275a 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -53,6 +53,10 @@ template class cIntGen { public: + /** Force a virtual destructor in all descendants. + Descendants contain virtual functions and are referred to via pointer-to-base, so they need a virtual destructor. */ + virtual ~cIntGen() {} + /** Holds the array of values generated by this class (descendant). */ typedef int Values[SizeX * SizeZ]; -- cgit v1.2.3 From 11a80b5d09241ade0a740d1db0d0d2084ab81e3a Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 16:46:17 +0000 Subject: Pocess? --- src/BlockID.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index b0cdc2a00..98eef2684 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -1,7 +1,7 @@ #pragma once -// The following hackery is to allow typed C++ enum for C++ code, yet have ToLua pocess the values. -// ToLua doesn't understand typed enums, so we use preprocessor to hide it from ToLua +// The following hackery is to allow typed C++ enum for C++ code, yet have ToLua peocess the values. +// ToLua doesn't understand typed enums, so we use preprocessor to hide it from ToLua. enum ENUM_BLOCK_ID : BLOCKTYPE #if 0 -- cgit v1.2.3 From cbb637187e4ca3435bddc0c07285ba4933445fba Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 16:46:30 +0000 Subject: Fixed typo. --- src/BlockID.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/BlockID.h b/src/BlockID.h index 98eef2684..24de2dc8a 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -1,6 +1,6 @@ #pragma once -// The following hackery is to allow typed C++ enum for C++ code, yet have ToLua peocess the values. +// The following hackery is to allow typed C++ enum for C++ code, yet have ToLua process the values. // ToLua doesn't understand typed enums, so we use preprocessor to hide it from ToLua. enum ENUM_BLOCK_ID : BLOCKTYPE -- cgit v1.2.3 From 8a443c028f6c24659b0a65ff709c8b5f01fd6f5a Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 17:11:31 +0000 Subject: Test warning fix. --- src/Generating/DistortedHeightmap.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index aac1d2bf3..d6474b3ca 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -270,6 +270,17 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biMesaBryce */ { 0.5f, 0.5f}, // 165 /* biMesaPlateauFM */ { 2.0f, 2.0f}, // 166 /* biMesaPlateauM */ { 2.0f, 2.0f}, // 167 + + // biomes 168 .. 255 are unused, 88 empty placeholders here: + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 168 .. 177 + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 178 .. 187 + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 188 .. 197 + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 198 .. 207 + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 208 .. 217 + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 218 .. 227 + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 228 .. 237 + {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 238 .. 247 + {}, {}, {}, {}, {}, {}, {}, {}, // 248 .. 255 } ; -- cgit v1.2.3 From c0a9a83abfb7c161b3d5ed994d6b5bb7bb7a1fb8 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 18:09:34 +0000 Subject: Actually fixed the warning. --- src/Generating/DistortedHeightmap.cpp | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index d6474b3ca..5ece4dce5 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -227,15 +227,15 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biMesaPlateau */ { 2.0f, 2.0f}, // 39 // biomes 40 .. 128 are unused, 89 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 40 .. 49 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 50 .. 59 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 60 .. 69 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 70 .. 79 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 80 .. 89 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 90 .. 99 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 100 .. 109 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 110 .. 119 - {}, {}, {}, {}, {}, {}, {}, {}, {}, // 120 .. 128 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 40 .. 49 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 50 .. 59 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 60 .. 69 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 70 .. 79 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 80 .. 89 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 90 .. 99 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 100 .. 109 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 110 .. 119 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 120 .. 128 // Release 1.7 /* biome variants: /* biSunflowerPlains */ { 1.0f, 1.0f}, // 129 @@ -270,17 +270,6 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biMesaBryce */ { 0.5f, 0.5f}, // 165 /* biMesaPlateauFM */ { 2.0f, 2.0f}, // 166 /* biMesaPlateauM */ { 2.0f, 2.0f}, // 167 - - // biomes 168 .. 255 are unused, 88 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 168 .. 177 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 178 .. 187 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 188 .. 197 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 198 .. 207 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 208 .. 217 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 218 .. 227 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 228 .. 237 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 238 .. 247 - {}, {}, {}, {}, {}, {}, {}, {}, // 248 .. 255 } ; -- cgit v1.2.3 From 6e21897bc6404f8e95ab61ea4203e5b2d73b19a3 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 19:49:52 +0000 Subject: Fixed remaining warnings. --- src/Generating/DistortedHeightmap.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index 5ece4dce5..974aabccd 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -246,22 +246,22 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biSwamplandM */ { 0.0f, 0.0f}, // 134 // Biomes 135 .. 139 unused, 5 empty placeholders here: - {}, {}, {}, {}, {}, // 135 .. 139 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 135 .. 139 /* biIcePlainsSpikes */ { 1.0f, 1.0f}, // 140 // Biomes 141 .. 148 unused, 8 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, // 141 .. 148 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 141 .. 148 /* biJungleM */ { 4.0f, 4.0f}, // 149 - {}, // 150 + {0.0f,0.0f}, // 150 /* biJungleEdgeM */ { 3.0f, 3.0f}, // 151 - {}, {}, {}, // 152 .. 154 + {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 152 .. 154 /* biBirchForestM */ { 3.0f, 3.0f}, // 155 /* biBirchForestHillsM */ { 5.0f, 5.0f}, // 156 /* biRoofedForestM */ { 2.0f, 2.0f}, // 157 /* biColdTaigaM */ { 1.0f, 1.0f}, // 158 - {}, // 159 + {0.0f,0.0f}, // 159 /* biMegaSpruceTaiga */ { 3.0f, 3.0f}, // 160 /* biMegaSpruceTaigaHills */ { 3.0f, 3.0f}, // 161 /* biExtremeHillsPlusM */ {32.0f, 32.0f}, // 162 -- cgit v1.2.3 From 0cdf262053129cf75c9158f269efa52b29d5b7df Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 19:52:04 +0000 Subject: Fix missing biomes in enum. --- src/Generating/FinishGen.cpp | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/Generating/FinishGen.cpp b/src/Generating/FinishGen.cpp index 0564789dc..6b0bd686c 100644 --- a/src/Generating/FinishGen.cpp +++ b/src/Generating/FinishGen.cpp @@ -414,6 +414,11 @@ void cFinishGenSnow::GenFinish(cChunkDesc & a_ChunkDesc) } break; } + default: + { + // There's no snow in the other biomes. + break; + } } } } // for z -- cgit v1.2.3 From 59ca542c28edefc9454dd2be06ca66f5c7a0c18f Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 19:53:16 +0000 Subject: Another switch. --- src/Generating/FinishGen.cpp | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/Generating/FinishGen.cpp b/src/Generating/FinishGen.cpp index 6b0bd686c..18f8ee2bc 100644 --- a/src/Generating/FinishGen.cpp +++ b/src/Generating/FinishGen.cpp @@ -459,6 +459,11 @@ void cFinishGenIce::GenFinish(cChunkDesc & a_ChunkDesc) } break; } + default: + { + // No icy water in other biomes. + break; + } } } } // for z -- cgit v1.2.3 From 7de8757ac98cff40a5da575d58e40425f2130057 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 20:05:34 +0000 Subject: Fixed more warnings. It's ugly though. --- src/Generating/HeiGen.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index a0b8770f5..0f883f156 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -430,15 +430,15 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = /* biMesaPlateau */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80}, // biomes 40 .. 128 are unused, 89 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 40 .. 49 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 50 .. 59 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 60 .. 69 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 70 .. 79 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 80 .. 89 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 90 .. 99 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 100 .. 109 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 110 .. 119 - {}, {}, {}, {}, {}, {}, {}, {}, {}, // 120 .. 128 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 40 .. 49 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 50 .. 59 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 60 .. 69 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 70 .. 79 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 80 .. 89 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 90 .. 99 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 100 .. 109 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 110 .. 119 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 120 .. 128 /* biSunflowerPlains */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 129 /* biDesertM */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 130 @@ -448,22 +448,22 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = /* biSwamplandM */ { 1.0f, 3.0f, 1.10f, 7.0f, 0.01f, 0.01f, 60}, // 134 // Biomes 135 .. 139 unused, 5 empty placeholders here: - {}, {}, {}, {}, {}, // 135 .. 139 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 135 .. 139 /* biIcePlainsSpikes */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 140 // Biomes 141 .. 148 unused, 8 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, // 141 .. 148 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 141 .. 148 /* biJungleM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 149 - {}, // 150 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 150 /* biJungleEdgeM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 151 - {}, {}, {}, // 152 .. 154 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 152 .. 154 /* biBirchForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 155 /* biBirchForestHillsM */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 156 /* biRoofedForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 157 /* biColdTaigaM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 158 - {}, // 159 + {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 159 /* biMegaSpruceTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 160 /* biMegaSpruceTaigaHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 161 /* biExtremeHillsPlusM */ { 0.2f, 4.0f, 0.05f, 20.0f, 0.01f, 16.0f, 120}, // 162 -- cgit v1.2.3 From b67eb2169eba24b767163d882dbf667a429bfbd6 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 20:16:51 +0000 Subject: Another one.# --- src/WorldStorage/NBTChunkSerializer.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'src') diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp index d85a5c329..1ecdcb5fd 100644 --- a/src/WorldStorage/NBTChunkSerializer.cpp +++ b/src/WorldStorage/NBTChunkSerializer.cpp @@ -604,6 +604,28 @@ void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster) m_Writer.AddByte("IsConverting", (((const cZombie *)a_Monster)->IsConverting() ? 1 : 0)); break; } + case mtInvalidType: + case mtBlaze: + case mtCaveSpider: + case mtChicken: + case mtCow: + case mtEnderDragon: + case mtGhast: + case mtGiant: + case mtIronGolem + case mtMooshroom: + case mtOcelot: + case mtPig: + case mtSilverfish: + case mtSnowGolem: + case meSpider: + case mtSquid: + case mtWitch: + case mtZombiePigman: + { + // Other mobs have no special tags. + break; + } } m_Writer.EndCompound(); } -- cgit v1.2.3 From a4932bbd8b08ed2f5d6de94fcfcc4d10484c45a2 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 21:34:02 +0000 Subject: CheckBasicStyle'd --- src/Generating/DistortedHeightmap.cpp | 28 ++++++++++++++-------------- src/Generating/HeiGen.cpp | 28 ++++++++++++++-------------- src/IniFile.cpp | 6 +++--- src/IniFile.h | 2 +- 4 files changed, 32 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index 974aabccd..7c1ab9997 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -227,15 +227,15 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biMesaPlateau */ { 2.0f, 2.0f}, // 39 // biomes 40 .. 128 are unused, 89 empty placeholders here: - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 40 .. 49 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 50 .. 59 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 60 .. 69 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 70 .. 79 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 80 .. 89 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 90 .. 99 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 100 .. 109 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 110 .. 119 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 120 .. 128 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 40 .. 49 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 50 .. 59 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 60 .. 69 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 70 .. 79 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 80 .. 89 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 90 .. 99 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 100 .. 109 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 110 .. 119 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 120 .. 128 // Release 1.7 /* biome variants: /* biSunflowerPlains */ { 1.0f, 1.0f}, // 129 @@ -246,22 +246,22 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biSwamplandM */ { 0.0f, 0.0f}, // 134 // Biomes 135 .. 139 unused, 5 empty placeholders here: - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 135 .. 139 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 135 .. 139 /* biIcePlainsSpikes */ { 1.0f, 1.0f}, // 140 // Biomes 141 .. 148 unused, 8 empty placeholders here: - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 141 .. 148 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 141 .. 148 /* biJungleM */ { 4.0f, 4.0f}, // 149 - {0.0f,0.0f}, // 150 + {0.0f, 0.0f}, // 150 /* biJungleEdgeM */ { 3.0f, 3.0f}, // 151 - {0.0f,0.0f}, {0.0f,0.0f}, {0.0f,0.0f}, // 152 .. 154 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 152 .. 154 /* biBirchForestM */ { 3.0f, 3.0f}, // 155 /* biBirchForestHillsM */ { 5.0f, 5.0f}, // 156 /* biRoofedForestM */ { 2.0f, 2.0f}, // 157 /* biColdTaigaM */ { 1.0f, 1.0f}, // 158 - {0.0f,0.0f}, // 159 + {0.0f, 0.0f}, // 159 /* biMegaSpruceTaiga */ { 3.0f, 3.0f}, // 160 /* biMegaSpruceTaigaHills */ { 3.0f, 3.0f}, // 161 /* biExtremeHillsPlusM */ {32.0f, 32.0f}, // 162 diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index 0f883f156..04154dfec 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -430,15 +430,15 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = /* biMesaPlateau */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80}, // biomes 40 .. 128 are unused, 89 empty placeholders here: - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 40 .. 49 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 50 .. 59 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 60 .. 69 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 70 .. 79 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 80 .. 89 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 90 .. 99 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 100 .. 109 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 110 .. 119 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 120 .. 128 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 40 .. 49 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 50 .. 59 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 60 .. 69 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 70 .. 79 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 80 .. 89 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 90 .. 99 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 100 .. 109 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 110 .. 119 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 120 .. 128 /* biSunflowerPlains */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 129 /* biDesertM */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 130 @@ -448,22 +448,22 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = /* biSwamplandM */ { 1.0f, 3.0f, 1.10f, 7.0f, 0.01f, 0.01f, 60}, // 134 // Biomes 135 .. 139 unused, 5 empty placeholders here: - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 135 .. 139 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 135 .. 139 /* biIcePlainsSpikes */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 140 // Biomes 141 .. 148 unused, 8 empty placeholders here: - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 141 .. 148 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 141 .. 148 /* biJungleM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 149 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 150 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 150 /* biJungleEdgeM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 151 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 152 .. 154 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 152 .. 154 /* biBirchForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 155 /* biBirchForestHillsM */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 156 /* biRoofedForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 157 /* biColdTaigaM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 158 - {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0}, // 159 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 159 /* biMegaSpruceTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 160 /* biMegaSpruceTaigaHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 161 /* biExtremeHillsPlusM */ { 0.2f, 4.0f, 0.05f, 20.0f, 0.01f, 16.0f, 120}, // 162 diff --git a/src/IniFile.cpp b/src/IniFile.cpp index a666a4ff8..ded7e4199 100644 --- a/src/IniFile.cpp +++ b/src/IniFile.cpp @@ -9,7 +9,7 @@ // Email: Shane.Hill@dsto.defence.gov.au // Reason: Remove dependancy on MFC. Code should compile on any // platform. -////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// /* !! MODIFIED BY FAKETRUTH and xoft !! @@ -79,7 +79,7 @@ bool cIniFile::ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect) } } - bool IsFirstLine = true; + bool IsFirstLine = true; while (getline(f, line)) { @@ -866,7 +866,7 @@ AString cIniFile::CheckCase(const AString & s) const void cIniFile::RemoveBom(AString & a_line) const { - // The BOM sequence for UTF-8 is 0xEF,0xBB,0xBF + // The BOM sequence for UTF-8 is 0xEF, 0xBB, 0xBF static unsigned const char BOM[] = { 0xEF, 0xBB, 0xBF }; // The BOM sequence, if present, is always th e first three characters of the input. diff --git a/src/IniFile.h b/src/IniFile.h index 3f704551f..e5879f46c 100644 --- a/src/IniFile.h +++ b/src/IniFile.h @@ -9,7 +9,7 @@ // Email: Shane.Hill@dsto.defence.gov.au // Reason: Remove dependancy on MFC. Code should compile on any // platform. Tested on Windows/Linux/Irix -////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// /* !! MODIFIED BY FAKETRUTH and madmaxoft!! -- cgit v1.2.3 From dbe7c8b1702d4141ae0f9d11b74b3d763b8a08c7 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 21:38:00 +0000 Subject: Comment alignment. --- src/Generating/DistortedHeightmap.cpp | 8 ++++---- src/Generating/HeiGen.cpp | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index 7c1ab9997..d5bc6ab55 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -235,7 +235,7 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 90 .. 99 {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 100 .. 109 {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 110 .. 119 - {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 120 .. 128 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 120 .. 128 // Release 1.7 /* biome variants: /* biSunflowerPlains */ { 1.0f, 1.0f}, // 129 @@ -254,14 +254,14 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 141 .. 148 /* biJungleM */ { 4.0f, 4.0f}, // 149 - {0.0f, 0.0f}, // 150 + {0.0f, 0.0f}, // 150 /* biJungleEdgeM */ { 3.0f, 3.0f}, // 151 - {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 152 .. 154 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 152 .. 154 /* biBirchForestM */ { 3.0f, 3.0f}, // 155 /* biBirchForestHillsM */ { 5.0f, 5.0f}, // 156 /* biRoofedForestM */ { 2.0f, 2.0f}, // 157 /* biColdTaigaM */ { 1.0f, 1.0f}, // 158 - {0.0f, 0.0f}, // 159 + {0.0f, 0.0f}, // 159 /* biMegaSpruceTaiga */ { 3.0f, 3.0f}, // 160 /* biMegaSpruceTaigaHills */ { 3.0f, 3.0f}, // 161 /* biExtremeHillsPlusM */ {32.0f, 32.0f}, // 162 diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index 04154dfec..f4e231470 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -438,7 +438,7 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 90 .. 99 {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 100 .. 109 {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 110 .. 119 - {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 120 .. 128 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 120 .. 128 /* biSunflowerPlains */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 129 /* biDesertM */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 130 @@ -456,14 +456,14 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 141 .. 148 /* biJungleM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 149 - {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 150 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 150 /* biJungleEdgeM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 151 - {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 152 .. 154 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 152 .. 154 /* biBirchForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 155 /* biBirchForestHillsM */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 156 /* biRoofedForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 157 /* biColdTaigaM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 158 - {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 159 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 159 /* biMegaSpruceTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 160 /* biMegaSpruceTaigaHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 161 /* biExtremeHillsPlusM */ { 0.2f, 4.0f, 0.05f, 20.0f, 0.01f, 16.0f, 120}, // 162 -- cgit v1.2.3 From 232343065f508c3ec32a612d15c6cab7a1553721 Mon Sep 17 00:00:00 2001 From: Alexander Harkness Date: Mon, 27 Oct 2014 22:03:11 +0000 Subject: Fixed compile (typos). --- src/WorldStorage/NBTChunkSerializer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp index 1ecdcb5fd..4daa8cc7b 100644 --- a/src/WorldStorage/NBTChunkSerializer.cpp +++ b/src/WorldStorage/NBTChunkSerializer.cpp @@ -612,13 +612,13 @@ void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster) case mtEnderDragon: case mtGhast: case mtGiant: - case mtIronGolem + case mtIronGolem: case mtMooshroom: case mtOcelot: case mtPig: case mtSilverfish: case mtSnowGolem: - case meSpider: + case mtSpider: case mtSquid: case mtWitch: case mtZombiePigman: -- cgit v1.2.3 From 373b139ed63bd8ed28962d0836ee6b6ababb3045 Mon Sep 17 00:00:00 2001 From: Howaner Date: Tue, 28 Oct 2014 21:32:01 +0100 Subject: Forgotten m_SendChunksMediumPriority.empty() check. --- src/ChunkSender.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index ef2be167b..83d82884e 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -184,7 +184,7 @@ void cChunkSender::Execute(void) while (!m_ShouldTerminate) { cCSLock Lock(m_CS); - while (m_ChunksReady.empty() && m_SendChunksLowPriority.empty() && m_SendChunksHighPriority.empty()) + while (m_ChunksReady.empty() && m_SendChunksLowPriority.empty() && m_SendChunksMediumPriority.empty() && m_SendChunksHighPriority.empty()) { int RemoveCount = m_RemoveCount; m_RemoveCount = 0; -- cgit v1.2.3 From f34b1291beb81b4fcf82e155e66f4a43d7caf915 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Wed, 29 Oct 2014 15:28:27 +0100 Subject: Grown biomes: made biomes smaller, made beaches smaller. --- src/Generating/BioGen.cpp | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 96c181915..6fab1b9d9 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -946,18 +946,15 @@ public: std::make_shared>(a_Seed + 15, std::make_shared> (a_Seed + 1000, std::make_shared> (a_Seed + 16, - std::make_shared> (a_Seed + 1001, - std::make_shared> (a_Seed, - std::make_shared> (a_Seed + 1002, - std::make_shared> (a_Seed + 1, std::make_shared> ( std::make_shared> (a_Seed + 1002, - std::make_shared>(a_Seed + 2, - std::make_shared> (a_Seed + 3, - std::make_shared> (a_Seed + 2004, 10, - std::make_shared> (a_Seed + 4, - std::make_shared> (a_Seed + 9, 50, biMushroomIsland, - std::make_shared> (a_Seed + 8, + std::make_shared>(a_Seed + 1, + std::make_shared> (a_Seed + 1002, + std::make_shared> (a_Seed + 2, + std::make_shared> (a_Seed + 2004, 10, + std::make_shared> (a_Seed + 4, + std::make_shared> (a_Seed + 9, 50, biMushroomIsland, + std::make_shared> (a_Seed + 8, std::make_shared> (a_Seed + 10, 500, biDeepOcean, std::make_shared> (a_Seed + 3000, std::make_shared> (a_Seed + 5, @@ -970,7 +967,7 @@ public: std::make_shared> (a_Seed + 1004, std::make_shared> (a_Seed + 10, std::make_shared> (a_Seed + 100, 65 - )))))))))))))))))))))))))))); + ))))))))))))))))))))))))); m_Gen = std::make_shared>(a_Seed, -- cgit v1.2.3 From 165533c27e380300f5e9411e4d46aa553bf2fdeb Mon Sep 17 00:00:00 2001 From: Howaner Date: Wed, 29 Oct 2014 15:47:43 +0100 Subject: Fixed 1.8 world item format reading. --- src/BlockID.cpp | 7 ++++++- src/WorldStorage/WSSAnvil.cpp | 21 +++++++++++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/BlockID.cpp b/src/BlockID.cpp index c0f3193bb..c98e0cad1 100644 --- a/src/BlockID.cpp +++ b/src/BlockID.cpp @@ -217,7 +217,12 @@ BLOCKTYPE BlockStringToType(const AString & a_BlockTypeString) bool StringToItem(const AString & a_ItemTypeString, cItem & a_Item) { - return gsBlockIDMap.ResolveItem(TrimString(a_ItemTypeString), a_Item); + AString ItemName = TrimString(a_ItemTypeString); + if (ItemName.substr(0, 10) == "minecraft:") + { + ItemName = ItemName.substr(10); + } + return gsBlockIDMap.ResolveItem(ItemName, a_Item); } diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp index af7551ee4..0c77b4d67 100644 --- a/src/WorldStorage/WSSAnvil.cpp +++ b/src/WorldStorage/WSSAnvil.cpp @@ -696,11 +696,28 @@ cBlockEntity * cWSSAnvil::LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a bool cWSSAnvil::LoadItemFromNBT(cItem & a_Item, const cParsedNBT & a_NBT, int a_TagIdx) { int Type = a_NBT.FindChildByName(a_TagIdx, "id"); - if ((Type < 0) || (a_NBT.GetType(Type) != TAG_Short)) + if (Type <= 0) { return false; } - a_Item.m_ItemType = a_NBT.GetShort(Type); + + if (a_NBT.GetType(Type) == TAG_String) + { + if (!StringToItem(a_NBT.GetString(Type), a_Item)) + { + // Can't resolve item type + return false; + } + } + else if (a_NBT.GetType(Type) == TAG_Short) + { + a_Item.m_ItemType = a_NBT.GetShort(Type); + } + else + { + return false; + } + if (a_Item.m_ItemType < 0) { a_Item.Empty(); -- cgit v1.2.3 From 8c04abf9aa749af3b15bc92f517b636c9593109e Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 30 Oct 2014 16:24:35 +0100 Subject: QtBiomeVisualiser: Added a prototyping int generator flavor. This generator is easier to manipulate, since it doesn't require rewriting the sizes in the template parameters. On the other hand, it doesn't optimize so well, so it's a bit slower. --- src/Generating/BioGen.cpp | 124 ++++- src/Generating/CMakeLists.txt | 1 + src/Generating/IntGen.h | 173 +++++-- src/Generating/ProtIntGen.h | 1008 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 1253 insertions(+), 53 deletions(-) create mode 100644 src/Generating/ProtIntGen.h (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 6fab1b9d9..f9a0a571b 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -6,6 +6,7 @@ #include "Globals.h" #include "BioGen.h" #include "IntGen.h" +#include "ProtIntGen.h" #include "../IniFile.h" #include "../LinearUpscale.h" @@ -927,9 +928,9 @@ public: cBioGenGrown(int a_Seed) { auto FinalRivers = - std::make_shared> (a_Seed + 1, - std::make_shared> (a_Seed + 2, - std::make_shared> (a_Seed + 3, + std::make_shared> (a_Seed + 1, + std::make_shared> (a_Seed + 3, + std::make_shared> (a_Seed + 2, std::make_shared> (a_Seed + 4, std::make_shared> (a_Seed + 5, std::make_shared> (a_Seed + 6, @@ -942,10 +943,10 @@ public: )))))))))))); auto FinalBiomes = - std::make_shared> (a_Seed + 1008, - std::make_shared>(a_Seed + 15, - std::make_shared> (a_Seed + 1000, - std::make_shared> (a_Seed + 16, + std::make_shared> (a_Seed + 1008, + std::make_shared>(a_Seed + 15, + std::make_shared> (a_Seed + 1000, + std::make_shared> (a_Seed + 16, std::make_shared> ( std::make_shared> (a_Seed + 1002, std::make_shared>(a_Seed + 1, @@ -953,7 +954,8 @@ public: std::make_shared> (a_Seed + 2, std::make_shared> (a_Seed + 2004, 10, std::make_shared> (a_Seed + 4, - std::make_shared> (a_Seed + 9, 50, biMushroomIsland, + std::make_shared> (a_Seed + 9, 10, biMushroomIsland, + std::make_shared> (biIcePlains, biIcePlainsSpikes, 5, a_Seed + 99, std::make_shared> (a_Seed + 8, std::make_shared> (a_Seed + 10, 500, biDeepOcean, std::make_shared> (a_Seed + 3000, @@ -961,22 +963,26 @@ public: std::make_shared> ( std::make_shared> (a_Seed + 1003, std::make_shared> (a_Seed + 7, + std::make_shared> (a_Seed + 8, 50, bgOcean, std::make_shared> (bgJungle, bgTemperate, 50, a_Seed + 100, std::make_shared> (bgIce, bgTemperate, 50, a_Seed + 101, + std::make_shared> (bgDesert, bgMesa, 30, a_Seed + 102, std::make_shared> (a_Seed + 2000, 70, + std::make_shared> (a_Seed + 9, 50, bgOcean, std::make_shared> (a_Seed + 1004, std::make_shared> (a_Seed + 10, std::make_shared> (a_Seed + 100, 65 - ))))))))))))))))))))))))); + ))))))))))))))))))))))))))))); m_Gen = std::make_shared>(a_Seed, std::make_shared>(a_Seed, - std::make_shared>(a_Seed, - std::make_shared>(a_Seed, - std::make_shared> ( + std::make_shared>(a_Seed, + std::make_shared>(a_Seed, + std::make_shared>(a_Seed, + std::make_shared> ( FinalBiomes, FinalRivers - ))))); + )))))); } virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_Biomes) override @@ -1000,6 +1006,94 @@ protected: +//////////////////////////////////////////////////////////////////////////////// +// cBioGenGrown: + +class cBioGenProtGrown: + public cBiomeGen +{ +public: + cBioGenProtGrown(int a_Seed) + { + auto FinalRivers = + std::make_shared(a_Seed + 1, + std::make_shared(a_Seed + 3, + std::make_shared(a_Seed + 2, + std::make_shared(a_Seed + 4, + std::make_shared(a_Seed + 5, + std::make_shared(a_Seed + 6, + std::make_shared(a_Seed + 7, + std::make_shared(a_Seed + 8, + std::make_shared(a_Seed + 9, + std::make_shared(a_Seed + 10, + std::make_shared(a_Seed + 11, + std::make_shared(a_Seed + 12, 2 + )))))))))))); + + auto FinalBiomes = + std::make_shared(a_Seed + 1008, + std::make_shared(a_Seed + 15, + std::make_shared(a_Seed + 1000, + std::make_shared(a_Seed + 16, + std::make_shared( + std::make_shared(a_Seed + 1002, + std::make_shared(a_Seed + 1, + std::make_shared(a_Seed + 1002, + std::make_shared(a_Seed + 2, + std::make_shared(a_Seed + 2004, 10, + std::make_shared(a_Seed + 4, + std::make_shared(a_Seed + 9, 10, biMushroomIsland, + std::make_shared(biIcePlains, biIcePlainsSpikes, 5, a_Seed + 99, + std::make_shared(a_Seed + 8, + std::make_shared(a_Seed + 10, 500, biDeepOcean, + std::make_shared(a_Seed + 3000, + std::make_shared(a_Seed + 5, + std::make_shared( + std::make_shared(a_Seed + 1003, + std::make_shared(a_Seed + 7, + std::make_shared(a_Seed + 8, 50, bgOcean, + std::make_shared(bgJungle, bgTemperate, 50, a_Seed + 100, + std::make_shared(bgIce, bgTemperate, 50, a_Seed + 101, + std::make_shared(bgDesert, bgMesa, 30, a_Seed + 102, + std::make_shared(a_Seed + 2000, 70, + std::make_shared(a_Seed + 9, 50, bgOcean, + std::make_shared(a_Seed + 1004, + std::make_shared(a_Seed + 10, + std::make_shared(a_Seed + 100, 65 + ))))))))))))))))))))))))))))); + + m_Gen = + std::make_shared(a_Seed, + std::make_shared(a_Seed, + std::make_shared(a_Seed, + std::make_shared(a_Seed, + std::make_shared(a_Seed, + std::make_shared( + FinalBiomes, FinalRivers + )))))); + } + + virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_Biomes) override + { + int vals[16 * 16]; + m_Gen->GetInts(a_ChunkX * cChunkDef::Width, a_ChunkZ * cChunkDef::Width, 16, 16, vals); + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + cChunkDef::SetBiome(a_Biomes, x, z, (EMCSBiome)vals[x + cChunkDef::Width * z]); + } + } + } + +protected: + std::shared_ptr m_Gen; +}; + + + + + //////////////////////////////////////////////////////////////////////////////// // cBiomeGen: @@ -1040,6 +1134,10 @@ cBiomeGenPtr cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & { res = new cBioGenGrown(a_Seed); } + else if (NoCaseCompare(BiomeGenName, "grownprot") == 0) + { + res = new cBioGenProtGrown(a_Seed); + } else { if (NoCaseCompare(BiomeGenName, "multistepmap") != 0) diff --git a/src/Generating/CMakeLists.txt b/src/Generating/CMakeLists.txt index afe30533e..1a26bd0d5 100644 --- a/src/Generating/CMakeLists.txt +++ b/src/Generating/CMakeLists.txt @@ -54,6 +54,7 @@ SET (HDRS PieceGenerator.h Prefab.h PrefabPiecePool.h + ProtIntGen.h RainbowRoadsGen.h Ravines.h RoughRavines.h diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index d7ed9275a..5f0394060 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -36,13 +36,14 @@ by using templates. /** Constants representing the biome group designators. */ -const int bgOcean = 0; -const int bgDesert = 1; -const int bgTemperate = 2; -const int bgMountains = 3; -const int bgJungle = 4; -const int bgIce = 5; -const int bgMax = 5; // Maximum biome group value +const int bgOcean = 0; +const int bgDesert = 1; +const int bgTemperate = 2; +const int bgMountains = 3; +const int bgJungle = 4; +const int bgIce = 5; +const int bgLandOceanMax = 5; // Maximum biome group value generated in the landOcean generator +const int bgMesa = 6; @@ -167,7 +168,7 @@ public: for (int x = 0; x < SizeX; x++) { int rnd = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); - a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgMax + 1) : 0; + a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgLandOceanMax + 1) : 0; } } @@ -462,7 +463,7 @@ public: int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; if (rnd % 100 < m_Threshold) { - a_Values[x + z * SizeX] = (rnd / 100) % bgMax; + a_Values[x + z * SizeX] = (rnd / 100) % bgLandOceanMax; } } } @@ -521,16 +522,16 @@ public: case bgDesert: { if ( - !IsDesertCompatible(Above) || - !IsDesertCompatible(Below) || - !IsDesertCompatible(Left) || - !IsDesertCompatible(Right) + !isDesertCompatible(Above) || + !isDesertCompatible(Below) || + !isDesertCompatible(Left) || + !isDesertCompatible(Right) ) { v = bgTemperate; } break; - } + } // case bgDesert // Ice should not neighbor deserts; change to temperate: case bgIce: @@ -545,21 +546,36 @@ public: v = bgTemperate; } break; - } + } // case bgIce // Jungle should not neighbor Desert or Ice; change to temperate: case bgJungle: { if ( - !IsJungleCompatible(Above) || - !IsJungleCompatible(Below) || - !IsJungleCompatible(Left) || - !IsJungleCompatible(Right) + !isJungleCompatible(Above) || + !isJungleCompatible(Below) || + !isJungleCompatible(Left) || + !isJungleCompatible(Right) ) { v = bgTemperate; } - } + } // case bgJungle + + // Mesa should neighbor only oceans and deserts; change to desert when another: + case bgMesa: + { + if ( + !isMesaCompatible(Above) || + !isMesaCompatible(Below) || + !isMesaCompatible(Left) || + !isMesaCompatible(Right) + ) + { + v = bgDesert; + } + break; + } // case bgDesert } a_Values[x + z * SizeX] = v; } // for x @@ -570,14 +586,32 @@ protected: Underlying m_Underlying; - inline bool IsDesertCompatible(int a_BiomeGroup) + inline bool isDesertCompatible(int a_BiomeGroup) + { + switch (a_BiomeGroup) + { + case bgOcean: + case bgDesert: + case bgTemperate: + case bgMesa: + { + return true; + } + default: + { + return false; + } + } + } + + inline bool isJungleCompatible(int a_BiomeGroup) { - return ((a_BiomeGroup == bgOcean) || (a_BiomeGroup == bgDesert) || (a_BiomeGroup == bgTemperate)); + return ((a_BiomeGroup != bgDesert) && (a_BiomeGroup != bgMesa) && (a_BiomeGroup != bgIce)); } - inline bool IsJungleCompatible(int a_BiomeGroup) + inline bool isMesaCompatible(int a_BiomeGroup) { - return ((a_BiomeGroup != bgDesert) && (a_BiomeGroup != bgIce)); + return ((a_BiomeGroup == bgOcean) || (a_BiomeGroup == bgDesert)); } }; @@ -605,44 +639,50 @@ public: virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Define the per-biome-group biomes: - static const int OceanBiomes[] = + static const int oceanBiomes[] = { biOcean, // biDeepOcean, }; - static const int DesertBiomes[] = + static const int desertBiomes[] = { - biDesert, biDesert, biSavanna, biPlains, + biDesert, biDesert, biDesert, biDesert, biDesert, biDesert, biSavanna, biSavanna, biPlains, }; - static const int TemperateBiomes[] = + static const int temperateBiomes[] = { - biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, + biForest, biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, }; - static const int MountainBiomes[] = + static const int mountainBiomes[] = { biExtremeHills, biForest, biTaiga, biPlains, }; - static const int JungleBiomes[] = + static const int jungleBiomes[] = + { + biJungle, biJungle, biJungle, biForest, + }; + + static const int iceBiomes[] = { - biJungle, biJungle, biForest, + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, }; - static const int IceBiomes[] = + static const int mesaBiomes[] = { - biIcePlains, biIcePlains, biColdTaiga, + biMesa, biMesaPlateau, }; static const cBiomesInGroups BiomesInGroups[] = { - { static_cast(ARRAYCOUNT(OceanBiomes)), OceanBiomes}, - { static_cast(ARRAYCOUNT(DesertBiomes)), DesertBiomes}, - { static_cast(ARRAYCOUNT(TemperateBiomes)), TemperateBiomes}, - { static_cast(ARRAYCOUNT(MountainBiomes)), MountainBiomes}, - { static_cast(ARRAYCOUNT(JungleBiomes)), JungleBiomes}, - { static_cast(ARRAYCOUNT(IceBiomes)), IceBiomes}, + /* bgOcean */ { static_cast(ARRAYCOUNT(oceanBiomes)), oceanBiomes}, + /* bgDesert */ { static_cast(ARRAYCOUNT(desertBiomes)), desertBiomes}, + /* bgTemperate */ { static_cast(ARRAYCOUNT(temperateBiomes)), temperateBiomes}, + /* bgMountains */ { static_cast(ARRAYCOUNT(mountainBiomes)), mountainBiomes}, + /* bgJungle */ { static_cast(ARRAYCOUNT(jungleBiomes)), jungleBiomes}, + /* bgIce */ { static_cast(ARRAYCOUNT(iceBiomes)), iceBiomes}, + /* bgMesa */ { static_cast(ARRAYCOUNT(mesaBiomes)), mesaBiomes}, }; // Generate the underlying values, representing biome groups: @@ -951,3 +991,56 @@ protected: + +/** Changes random pixels of the underlying data to the specified value. */ +template +class cIntGenSetRandomly : + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + typedef std::shared_ptr> Underlying; + + cIntGenSetRandomly(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying) : + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Change random pixels to bgOcean: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[x + z * SizeX] = m_ToValue; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel. */ + int m_Chance; + + /** The value to which to set the pixel. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + + diff --git a/src/Generating/ProtIntGen.h b/src/Generating/ProtIntGen.h new file mode 100644 index 000000000..a3d10c4ef --- /dev/null +++ b/src/Generating/ProtIntGen.h @@ -0,0 +1,1008 @@ + +// ProtIntGen.h + +// Declares the prototyping integer generators - cProtIntGen class and its descendants + +/* +These classes generate 2D arrays of integers that have various interpretations. The main purpose of these +classes is to provide fast prototyping for cIntGen classes - unlike cIntGen classes, these are not +template-based and so they take care of the underlying sizes automatically. This makes them easier to chain +and re-chain, since the size parameters don't need to be adjusted after each such case. Their performance is, +however, slightly worse, which is why we use cIntGen classes in the final generator. + +Because there is no SizeX / SizeZ template param, the generators would have to either alloc memory for each +underlying generator's values, or use a maximum-size buffer. We chose the latter, to avoid memory allocation +overhead; this however means that there's (an arbitrary) limit to the size of the generated data. +*/ + + + + + +#pragma once + +// We need the biome group constants defined there: +#include "IntGen.h" + + + + + +/** Interface that all the generator classes provide. */ +class cProtIntGen +{ +protected: + /** Maximum size of the generated area. + Adjust the constant if you need larger areas, these are just so that we can use fixed-size buffers. */ + static const int m_BufferSize = 900; + +public: + + /** Type of the generic interface used for storing links to the underlying generators. */ + typedef std::shared_ptr Underlying; + + + /** Force a virtual destructor in all descendants. + Descendants contain virtual functions and are referred to via pointer-to-base, so they need a virtual destructor. */ + virtual ~cProtIntGen() {} + + /** Generates the array of specified size into a_Values, based on given min coords. */ + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) = 0; +}; + + + + + +/** Provides additional cNoise member and its helper functions. */ +class cProtIntGenWithNoise : + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenWithNoise(int a_Seed) : + m_Noise(a_Seed) + { + } + +protected: + cNoise m_Noise; + + /** Chooses one of a_Val1 or a_Val2, based on m_Noise and the coordinates for querying the noise. */ + int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + return ((rnd & 1) == 0) ? a_Val1 : a_Val2; + } + + /** Chooses one of a_ValN, based on m_Noise and the coordinates for querying the noise. */ + int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2, int a_Val3, int a_Val4) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + switch (rnd % 4) + { + case 0: return a_Val1; + case 1: return a_Val2; + case 2: return a_Val3; + default: return a_Val4; + } + } +}; + + + + + + +/** Generates a 2D array of random integers in the specified range [0 .. Range). */ +class cProtIntGenChoice : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenChoice(int a_Seed, int a_Range) : + super(a_Seed), + m_Range(a_Range) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + for (int z = 0; z < a_SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < a_SizeX; x++) + { + a_Values[x + a_SizeX * z] = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7) % m_Range; + } + } // for z + } + +protected: + int m_Range; +}; + + + + + + +/** Decides between the ocean and landmass biomes. +Has a threshold (in percent) of how much land, the larger the threshold, the more land. +Generates 0 for ocean, biome group ID for landmass. */ +class cProtIntGenLandOcean : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenLandOcean(int a_Seed, int a_Threshold) : + super(a_Seed), + m_Threshold(a_Threshold) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + for (int z = 0; z < a_SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < a_SizeX; x++) + { + int rnd = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); + a_Values[x + a_SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgLandOceanMax + 1) : 0; + } + } + + // If the centerpoint of the world is within the area, set it to bgTemperate, always: + if ((a_MinX <= 0) && (a_MinZ <= 0) && (a_MinX + a_SizeX > 0) && (a_MinZ + a_SizeZ > 0)) + { + a_Values[-a_MinX - a_MinZ * a_SizeX] = bgTemperate; + } + } + +protected: + int m_Threshold; +}; + + + + + +class cProtIntGenZoom : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenZoom(int a_Seed, Underlying a_UnderlyingGen) : + super(a_Seed), + m_UnderlyingGen(a_UnderlyingGen) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Get the coords for the lower generator: + int lowerMinX = a_MinX >> 1; + int lowerMinZ = a_MinZ >> 1; + int lowerSizeX = a_SizeX / 2 + 2; + int lowerSizeZ = a_SizeZ / 2 + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + ASSERT(lowerSizeX > 0); + ASSERT(lowerSizeZ > 0); + + // Generate the underlying data with half the resolution: + int lowerData[m_BufferSize]; + m_UnderlyingGen->GetInts(lowerMinX, lowerMinZ, lowerSizeX, lowerSizeZ, lowerData); + const int lowStepX = (lowerSizeX - 1) * 2; + int Cache[m_BufferSize]; + + // Discreet-interpolate the values into twice the size: + for (int z = 0; z < lowerSizeZ - 1; ++z) + { + int idx = (z * 2) * lowStepX; + int PrevZ0 = lowerData[z * lowerSizeX]; + int PrevZ1 = lowerData[(z + 1) * lowerSizeX]; + + for (int x = 0; x < lowerSizeX - 1; ++x) + { + int ValX1Z0 = lowerData[x + 1 + z * lowerSizeX]; + int ValX1Z1 = lowerData[x + 1 + (z + 1) * lowerSizeX]; + int RndX = (x + lowerMinX) * 2; + int RndZ = (z + lowerMinZ) * 2; + Cache[idx] = PrevZ0; + Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, PrevZ1); + idx++; + Cache[idx] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0); + Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); + idx++; + PrevZ0 = ValX1Z0; + PrevZ1 = ValX1Z1; + } + } + + // Copy from Cache into a_Values; take into account the even/odd offsets in a_Min: + for (int z = 0; z < a_SizeZ; ++z) + { + memcpy(a_Values + z * a_SizeX, Cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), a_SizeX * sizeof(int)); + } + } + +protected: + Underlying m_UnderlyingGen; +}; + + + + + +class cProtIntGenSmooth : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenSmooth(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying values: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerData[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerData); + + // Smooth - for each square check if the surroundings are the same, if so, expand them diagonally. + // Also get rid of single-pixel irregularities (A-B-A): + for (int z = 0; z < a_SizeZ; z++) + { + int NoiseZ = a_MinZ + z; + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerData[x + 1 + (z + 1) * lowerSizeX]; + int Above = lowerData[x + 1 + z * lowerSizeX]; + int Below = lowerData[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerData[x + (z + 1) * lowerSizeX]; + int Right = lowerData[x + 2 + (z + 1) * lowerSizeX]; + + if ((Left == Right) && (Above == Below)) + { + if (((super::m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) + { + val = Left; + } + else + { + val = Above; + } + } + else + { + if (Left == Right) + { + val = Left; + } + + if (Above == Below) + { + val = Above; + } + } + + a_Values[x + z * a_SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +class cProtIntGenBeaches : + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenBeaches(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Map for biome -> its beach: + static const int ToBeach[] = + { + /* biOcean */ biOcean, + /* biPlains */ biBeach, + /* biDesert */ biBeach, + /* biExtremeHills */ biStoneBeach, + /* biForest */ biBeach, + /* biTaiga */ biColdBeach, + /* biSwampland */ biSwampland, + /* biRiver */ biRiver, + /* biNether */ biNether, + /* biEnd */ biEnd, + /* biFrozenOcean */ biColdBeach, + /* biFrozenRiver */ biColdBeach, + /* biIcePlains */ biColdBeach, + /* biIceMountains */ biColdBeach, + /* biMushroomIsland */ biMushroomShore, + /* biMushroomShore */ biMushroomShore, + /* biBeach */ biBeach, + /* biDesertHills */ biBeach, + /* biForestHills */ biBeach, + /* biTaigaHills */ biColdBeach, + /* biExtremeHillsEdge */ biStoneBeach, + /* biJungle */ biBeach, + /* biJungleHills */ biBeach, + /* biJungleEdge */ biBeach, + /* biDeepOcean */ biOcean, + /* biStoneBeach */ biStoneBeach, + /* biColdBeach */ biColdBeach, + /* biBirchForest */ biBeach, + /* biBirchForestHills */ biBeach, + /* biRoofedForest */ biBeach, + /* biColdTaiga */ biColdBeach, + /* biColdTaigaHills */ biColdBeach, + /* biMegaTaiga */ biStoneBeach, + /* biMegaTaigaHills */ biStoneBeach, + /* biExtremeHillsPlus */ biStoneBeach, + /* biSavanna */ biBeach, + /* biSavannaPlateau */ biBeach, + /* biMesa */ biMesa, + /* biMesaPlateauF */ biMesa, + /* biMesaPlateau */ biMesa, + }; + + // Generate the underlying values: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Add beaches between ocean and biomes: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + int Above = lowerValues[x + 1 + z * lowerSizeX]; + int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerValues[x + (z + 1) * lowerSizeX]; + int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + if (!IsBiomeOcean(val)) + { + if (IsBiomeOcean(Above) || IsBiomeOcean(Below) || IsBiomeOcean(Left) || IsBiomeOcean(Right)) + { + val = ToBeach[(val % 128) % ARRAYCOUNT(ToBeach)]; + } + } + a_Values[x + z * a_SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Generates the underlying numbers and then randomly changes some zeroes into nonzeroes. */ +class cProtIntGenAddIslands : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + typedef std::shared_ptr Underlying; + + + cProtIntGenAddIslands(int a_Seed, int a_Threshold, Underlying a_Underlying) : + super(a_Seed), + m_Threshold(a_Threshold), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + if (a_Values[x + z * a_SizeX] == bgOcean) + { + int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; + if (rnd % 100 < m_Threshold) + { + a_Values[x + z * a_SizeX] = (rnd / 100) % bgLandOceanMax; + } + } + } + } + } + +protected: + int m_Threshold; + + Underlying m_Underlying; +}; + + + + + +/** A filter that adds an edge biome group between two biome groups that need an edge between them. */ +class cProtIntGenBiomeGroupEdges : + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenBiomeGroupEdges(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) + { + // Generate the underlying biome groups: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX, a_MinZ, lowerSizeX, lowerSizeZ, lowerValues); + + // Change the biomes on incompatible edges into an edge biome: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + int Above = lowerValues[x + 1 + z * lowerSizeX]; + int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerValues[x + (z + 1) * lowerSizeX]; + int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + switch (val) + { + // Desert should neighbor only oceans, desert and temperates; change to temperate when another: + case bgDesert: + { + if ( + !isDesertCompatible(Above) || + !isDesertCompatible(Below) || + !isDesertCompatible(Left) || + !isDesertCompatible(Right) + ) + { + val = bgTemperate; + } + break; + } // case bgDesert + + // Ice should not neighbor deserts; change to temperate: + case bgIce: + { + if ( + (Above == bgDesert) || + (Below == bgDesert) || + (Left == bgDesert) || + (Right == bgDesert) + ) + { + val = bgTemperate; + } + break; + } // case bgIce + + // Jungle should not neighbor Desert or Ice; change to temperate: + case bgJungle: + { + if ( + !isJungleCompatible(Above) || + !isJungleCompatible(Below) || + !isJungleCompatible(Left) || + !isJungleCompatible(Right) + ) + { + val = bgTemperate; + } + } // case bgJungle + + // Mesa should neighbor only oceans and deserts; change to desert when another: + case bgMesa: + { + if ( + !isMesaCompatible(Above) || + !isMesaCompatible(Below) || + !isMesaCompatible(Left) || + !isMesaCompatible(Right) + ) + { + val = bgDesert; + } + break; + } // case bgDesert + } + a_Values[x + z * a_SizeX] = val; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; + + + inline bool isDesertCompatible(int a_BiomeGroup) + { + switch (a_BiomeGroup) + { + case bgOcean: + case bgDesert: + case bgTemperate: + case bgMesa: + { + return true; + } + default: + { + return false; + } + } + } + + inline bool isJungleCompatible(int a_BiomeGroup) + { + return ((a_BiomeGroup != bgDesert) && (a_BiomeGroup != bgMesa) && (a_BiomeGroup != bgIce)); + } + + inline bool isMesaCompatible(int a_BiomeGroup) + { + return ((a_BiomeGroup == bgOcean) || (a_BiomeGroup == bgDesert)); + } +}; + + + + + +/** Turns biome group indices into real biomes. +For each pixel, takes its biome group and chooses a random biome from that group; replaces the value with +that biome. */ +class cProtIntGenBiomes : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenBiomes(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Define the per-biome-group biomes: + static const int oceanBiomes[] = + { + biOcean, // biDeepOcean, + }; + + static const int desertBiomes[] = + { + biDesert, biDesert, biDesert, biDesert, biDesert, biDesert, biSavanna, biSavanna, biPlains, + }; + + static const int temperateBiomes[] = + { + biForest, biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, + }; + + static const int mountainBiomes[] = + { + biExtremeHills, biForest, biTaiga, biPlains, + }; + + static const int jungleBiomes[] = + { + biJungle, biJungle, biJungle, biForest, + }; + + static const int iceBiomes[] = + { + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, + }; + + static const int mesaBiomes[] = + { + biMesa, biMesaPlateau, + }; + + static const cBiomesInGroups BiomesInGroups[] = + { + /* bgOcean */ { static_cast(ARRAYCOUNT(oceanBiomes)), oceanBiomes}, + /* bgDesert */ { static_cast(ARRAYCOUNT(desertBiomes)), desertBiomes}, + /* bgTemperate */ { static_cast(ARRAYCOUNT(temperateBiomes)), temperateBiomes}, + /* bgMountains */ { static_cast(ARRAYCOUNT(mountainBiomes)), mountainBiomes}, + /* bgJungle */ { static_cast(ARRAYCOUNT(jungleBiomes)), jungleBiomes}, + /* bgIce */ { static_cast(ARRAYCOUNT(iceBiomes)), iceBiomes}, + /* bgMesa */ { static_cast(ARRAYCOUNT(mesaBiomes)), mesaBiomes}, + }; + + // Generate the underlying values, representing biome groups: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Overwrite each biome group with a random biome from that group: + for (int z = 0; z < a_SizeZ; z++) + { + int IdxZ = z * a_SizeX; + for (int x = 0; x < a_SizeX; x++) + { + int val = a_Values[x + IdxZ]; + const cBiomesInGroups & Biomes = BiomesInGroups[val % ARRAYCOUNT(BiomesInGroups)]; + int rnd = (super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); + a_Values[x + IdxZ] = Biomes.Biomes[rnd % Biomes.Count]; + } + } + } + +protected: + + struct cBiomesInGroups + { + const int Count; + const int * Biomes; + }; + + + /** The underlying int generator */ + Underlying m_Underlying; +}; + + + + + +class cProtIntGenReplaceRandomly : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + typedef std::shared_ptr Underlying; + + + cProtIntGenReplaceRandomly(int a_From, int a_To, int a_Chance, int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_From(a_From), + m_To(a_To), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying values: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Replace some of the values: + for (int z = 0; z < a_SizeZ; z++) + { + int idxZ = z * a_SizeX; + for (int x = 0; x < a_SizeX; x++) + { + int idx = x + idxZ; + if (a_Values[idx] == m_From) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 100 < m_Chance) + { + a_Values[idx] = m_To; + } + } + } + } // for z + } + + +protected: + int m_From; + int m_To; + int m_Chance; + Underlying m_Underlying; +}; + + + + + +/** Mixer that joins together finalized biomes and rivers. +It first checks for oceans; if there's no ocean, it checks for a river. */ +class cProtIntGenMixRivers: + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenMixRivers(Underlying a_Biomes, Underlying a_Rivers): + m_Biomes(a_Biomes), + m_Rivers(a_Rivers) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + ASSERT(a_SizeX * a_SizeZ <= m_BufferSize); + m_Biomes->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + int riverData[m_BufferSize]; + m_Rivers->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, riverData); + + // Mix the values: + for (int z = 0; z < a_SizeZ; z++) + { + int idxZ = z * a_SizeX; + for (int x = 0; x < a_SizeX; x++) + { + int idx = x + idxZ; + if (IsBiomeOcean(a_Values[idx])) + { + // Oceans are kept without any changes + continue; + } + if (riverData[idx] != biRiver) + { + // There's no river, keep the current value + continue; + } + + // There's a river, change the output to a river or a frozen river, based on the original biome: + if (IsBiomeVeryCold((EMCSBiome)a_Values[idx])) + { + a_Values[idx] = biFrozenRiver; + } + else + { + a_Values[idx] = biRiver; + } + } // for x + } // for z + } + +protected: + Underlying m_Biomes; + Underlying m_Rivers; +}; + + + + + +/** Generates a river based on the underlying data. +This is basically an edge detector over the underlying data. The rivers are the edges where the underlying +data changes from one pixel to its neighbor. */ +class cProtIntGenRiver: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenRiver(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Detect the edges: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int Above = lowerValues[x + 1 + z * lowerSizeX]; + int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerValues[x + (z + 1) * lowerSizeX]; + int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + + if ((val == Above) && (val == Below) && (val == Left) && (val == Right)) + { + val = 0; + } + else + { + val = biRiver; + } + a_Values[x + z * a_SizeX] = val; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Turns some of the oceans into the specified biome. Used for mushroom and deep ocean. +The biome is only placed if at least 3 of its neighbors are ocean and only with the specified chance. */ +class cProtIntGenAddToOcean: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenAddToOcean(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Add the mushroom islands: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + if (!IsBiomeOcean(val)) + { + a_Values[x + z * a_SizeX] = val; + continue; + } + + // Count the ocean neighbors: + int Above = lowerValues[x + 1 + z * lowerSizeX]; + int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerValues[x + (z + 1) * lowerSizeX]; + int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + int NumOceanNeighbors = 0; + if (IsBiomeOcean(Above)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Below)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Left)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Right)) + { + NumOceanNeighbors += 1; + } + + // If at least 3 ocean neighbors and the chance is right, change: + if ( + (NumOceanNeighbors >= 3) && + ((super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance) + ) + { + a_Values[x + z * a_SizeX] = m_ToValue; + } + else + { + a_Values[x + z * a_SizeX] = val; + } + } // for x + } // for z + } + +protected: + /** Chance, in permille, of changing the biome. */ + int m_Chance; + + /** The value to change the ocean into. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + + +/** Changes random pixels of the underlying data to the specified value. */ +class cProtIntGenSetRandomly : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenSetRandomly(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying) : + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Change random pixels to bgOcean: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[x + z * a_SizeX] = m_ToValue; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel. */ + int m_Chance; + + /** The value to which to set the pixel. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + + -- cgit v1.2.3 From 9c7661f50f82fe265836f3279bf20b15aebba5b3 Mon Sep 17 00:00:00 2001 From: Howaner Date: Thu, 30 Oct 2014 21:24:10 +0100 Subject: Added a MaxViewDistance option. --- src/ClientHandle.cpp | 4 +++- src/World.cpp | 3 +++ src/World.h | 10 ++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index faee05450..9b3bd9545 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -2847,7 +2847,9 @@ void cClientHandle::SetUsername( const AString & a_Username) void cClientHandle::SetViewDistance(int a_ViewDistance) { - m_ViewDistance = Clamp(a_ViewDistance, MIN_VIEW_DISTANCE, MAX_VIEW_DISTANCE); + ASSERT(m_Player->GetWorld() == NULL); + + m_ViewDistance = Clamp(a_ViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); LOGD("Setted %s's view distance to %i", GetUsername().c_str(), m_ViewDistance); } diff --git a/src/World.cpp b/src/World.cpp index 2e079d447..4e6ca264f 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -283,6 +283,7 @@ cWorld::cWorld(const AString & a_WorldName, eDimension a_Dimension, const AStrin m_bCommandBlocksEnabled(true), m_bUseChatPrefixes(false), m_TNTShrapnelLevel(slNone), + m_MaxViewDistance(12), m_Scoreboard(this), m_MapManager(this), m_GeneratorCallbacks(*this), @@ -561,6 +562,8 @@ void cWorld::Start(void) m_BroadcastDeathMessages = IniFile.GetValueSetB("Broadcasting", "BroadcastDeathMessages", true); m_BroadcastAchievementMessages = IniFile.GetValueSetB("Broadcasting", "BroadcastAchievementMessages", true); + SetMaxViewDistance(IniFile.GetValueSetI("SpawnPosition", "MaxViewDistance", 12)); + // Try to find the "SpawnPosition" key and coord values in the world configuration, set the flag if found int KeyNum = IniFile.FindKey("SpawnPosition"); m_IsSpawnExplicitlySet = diff --git a/src/World.h b/src/World.h index ec6dcadde..cc8906d95 100644 --- a/src/World.h +++ b/src/World.h @@ -26,6 +26,7 @@ #include "MapManager.h" #include "Blocks/WorldInterface.h" #include "Blocks/BroadcastInterface.h" +#include "ClientHandle.h" @@ -646,6 +647,12 @@ public: eShrapnelLevel GetTNTShrapnelLevel(void) const { return m_TNTShrapnelLevel; } void SetTNTShrapnelLevel(eShrapnelLevel a_Flag) { m_TNTShrapnelLevel = a_Flag; } + int GetMaxViewDistance(void) const { return m_MaxViewDistance; } + void SetMaxViewDistance(int a_MaxViewDistance) + { + m_MaxViewDistance = Clamp(a_MaxViewDistance, cClientHandle::MIN_VIEW_DISTANCE, cClientHandle::MAX_VIEW_DISTANCE); + } + bool ShouldUseChatPrefixes(void) const { return m_bUseChatPrefixes; } void SetShouldUseChatPrefixes(bool a_Flag) { m_bUseChatPrefixes = a_Flag; } @@ -961,6 +968,9 @@ private: */ eShrapnelLevel m_TNTShrapnelLevel; + /** The maximum view distance that a player can have. */ + int m_MaxViewDistance; + /** Name of the nether world */ AString m_NetherWorldName; -- cgit v1.2.3 From 415c0e128e0a333f69e1785c4d49a6161e1c6f34 Mon Sep 17 00:00:00 2001 From: Howaner Date: Thu, 30 Oct 2014 21:38:32 +0100 Subject: ... in this world --- src/World.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/World.h b/src/World.h index cc8906d95..a782bb5ec 100644 --- a/src/World.h +++ b/src/World.h @@ -968,7 +968,7 @@ private: */ eShrapnelLevel m_TNTShrapnelLevel; - /** The maximum view distance that a player can have. */ + /** The maximum view distance that a player can have in this world. */ int m_MaxViewDistance; /** Name of the nether world */ -- cgit v1.2.3 From d93acb841f5d78a25ced74e01c984c1604459e5e Mon Sep 17 00:00:00 2001 From: Howaner Date: Thu, 30 Oct 2014 22:04:04 +0100 Subject: Fixed m_SentChunks list chunk removing. --- src/ClientHandle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index faee05450..94bace43a 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -557,7 +557,7 @@ void cClientHandle::UnloadOutOfRangeChunks(void) for (cChunkCoordsList::iterator itr = ChunksToRemove.begin(); itr != ChunksToRemove.end(); ++itr) { m_Player->GetWorld()->RemoveChunkClient(itr->m_ChunkX, itr->m_ChunkZ, this); - m_Protocol->SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); + SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); } } -- cgit v1.2.3 From 13f0e93d690ef5ca96689190356b5c6c9cceb434 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 31 Oct 2014 12:52:07 +0100 Subject: GrownProt biomes: added alterations. --- src/Generating/BioGen.cpp | 56 ++++++------ src/Generating/IntGen.h | 53 ++--------- src/Generating/ProtIntGen.h | 213 ++++++++++++++++++++++++++++++++------------ 3 files changed, 192 insertions(+), 130 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index f9a0a571b..b3701a32a 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -964,15 +964,13 @@ public: std::make_shared> (a_Seed + 1003, std::make_shared> (a_Seed + 7, std::make_shared> (a_Seed + 8, 50, bgOcean, - std::make_shared> (bgJungle, bgTemperate, 50, a_Seed + 100, std::make_shared> (bgIce, bgTemperate, 50, a_Seed + 101, - std::make_shared> (bgDesert, bgMesa, 30, a_Seed + 102, std::make_shared> (a_Seed + 2000, 70, std::make_shared> (a_Seed + 9, 50, bgOcean, std::make_shared> (a_Seed + 1004, std::make_shared> (a_Seed + 10, std::make_shared> (a_Seed + 100, 65 - ))))))))))))))))))))))))))))); + ))))))))))))))))))))))))))); m_Gen = std::make_shared>(a_Seed, @@ -1017,60 +1015,66 @@ public: { auto FinalRivers = std::make_shared(a_Seed + 1, - std::make_shared(a_Seed + 3, - std::make_shared(a_Seed + 2, - std::make_shared(a_Seed + 4, - std::make_shared(a_Seed + 5, - std::make_shared(a_Seed + 6, - std::make_shared(a_Seed + 7, + std::make_shared(a_Seed + 2, + std::make_shared(a_Seed + 3, + std::make_shared(a_Seed + 4, + std::make_shared(a_Seed + 5, std::make_shared(a_Seed + 8, + std::make_shared(a_Seed + 5, std::make_shared(a_Seed + 9, + std::make_shared(a_Seed + 5, std::make_shared(a_Seed + 10, + std::make_shared(a_Seed + 5, + std::make_shared(a_Seed + 5, std::make_shared(a_Seed + 11, std::make_shared(a_Seed + 12, 2 - )))))))))))); + )))))))))))))); + + auto alteration = + std::make_shared(a_Seed, + std::make_shared(a_Seed, 20 + )); auto FinalBiomes = - std::make_shared(a_Seed + 1008, + std::make_shared(a_Seed + 1, std::make_shared(a_Seed + 15, - std::make_shared(a_Seed + 1000, + std::make_shared(a_Seed + 1, std::make_shared(a_Seed + 16, std::make_shared( - std::make_shared(a_Seed + 1002, std::make_shared(a_Seed + 1, - std::make_shared(a_Seed + 1002, std::make_shared(a_Seed + 2, std::make_shared(a_Seed + 2004, 10, + std::make_shared(a_Seed + 10, 500, biDeepOcean, + std::make_shared(a_Seed + 1, biPlains, biSunflowerPlains, 20, + std::make_shared(a_Seed + 1, alteration, std::make_shared(a_Seed + 4, - std::make_shared(a_Seed + 9, 10, biMushroomIsland, - std::make_shared(biIcePlains, biIcePlainsSpikes, 5, a_Seed + 99, + std::make_shared(a_Seed + 99, biIcePlains, biIcePlainsSpikes, 50, std::make_shared(a_Seed + 8, - std::make_shared(a_Seed + 10, 500, biDeepOcean, + std::make_shared(a_Seed + 10, 300, biDeepOcean, + std::make_shared(a_Seed + 9, 8, biMushroomIsland, std::make_shared(a_Seed + 3000, + std::make_shared(a_Seed + 2000, 200, std::make_shared(a_Seed + 5, + std::make_shared(a_Seed + 5, 50, std::make_shared( - std::make_shared(a_Seed + 1003, + std::make_shared(a_Seed + 2000, 200, std::make_shared(a_Seed + 7, std::make_shared(a_Seed + 8, 50, bgOcean, - std::make_shared(bgJungle, bgTemperate, 50, a_Seed + 100, - std::make_shared(bgIce, bgTemperate, 50, a_Seed + 101, - std::make_shared(bgDesert, bgMesa, 30, a_Seed + 102, - std::make_shared(a_Seed + 2000, 70, + std::make_shared(a_Seed + 101, bgIce, bgTemperate, 150, + std::make_shared(a_Seed + 2000, 200, std::make_shared(a_Seed + 9, 50, bgOcean, - std::make_shared(a_Seed + 1004, std::make_shared(a_Seed + 10, - std::make_shared(a_Seed + 100, 65 + std::make_shared(a_Seed + 100, 30 ))))))))))))))))))))))))))))); m_Gen = std::make_shared(a_Seed, std::make_shared(a_Seed, - std::make_shared(a_Seed, std::make_shared(a_Seed, std::make_shared(a_Seed, std::make_shared( FinalBiomes, FinalRivers - )))))); + ))))); } virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_Biomes) override diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index 5f0394060..15a5c9157 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -8,13 +8,13 @@ The integers generated may be interpreted in several ways: - land/see designators - 0 = ocean - >0 = land -- biome group designators +- biome group - 0 = ocean - 1 = desert biomes - 2 = temperate biomes - 3 = mountains (hills and forests) - - 4 = jungle - - 5 = ice biomes + - 4 = ice biomes +- biome group with "bgfRare" flag (for generating rare biomes for the group) - biome IDs The interpretation depends on the generator used and on the position in the chain. @@ -40,10 +40,9 @@ const int bgOcean = 0; const int bgDesert = 1; const int bgTemperate = 2; const int bgMountains = 3; -const int bgJungle = 4; -const int bgIce = 5; -const int bgLandOceanMax = 5; // Maximum biome group value generated in the landOcean generator -const int bgMesa = 6; +const int bgIce = 4; +const int bgLandOceanMax = 4; // Maximum biome group value generated in the landOcean generator +const int bgfRare = 1024; // Flag added to values to generate rare biomes for the group @@ -547,35 +546,6 @@ public: } break; } // case bgIce - - // Jungle should not neighbor Desert or Ice; change to temperate: - case bgJungle: - { - if ( - !isJungleCompatible(Above) || - !isJungleCompatible(Below) || - !isJungleCompatible(Left) || - !isJungleCompatible(Right) - ) - { - v = bgTemperate; - } - } // case bgJungle - - // Mesa should neighbor only oceans and deserts; change to desert when another: - case bgMesa: - { - if ( - !isMesaCompatible(Above) || - !isMesaCompatible(Below) || - !isMesaCompatible(Left) || - !isMesaCompatible(Right) - ) - { - v = bgDesert; - } - break; - } // case bgDesert } a_Values[x + z * SizeX] = v; } // for x @@ -593,7 +563,6 @@ protected: case bgOcean: case bgDesert: case bgTemperate: - case bgMesa: { return true; } @@ -603,16 +572,6 @@ protected: } } } - - inline bool isJungleCompatible(int a_BiomeGroup) - { - return ((a_BiomeGroup != bgDesert) && (a_BiomeGroup != bgMesa) && (a_BiomeGroup != bgIce)); - } - - inline bool isMesaCompatible(int a_BiomeGroup) - { - return ((a_BiomeGroup == bgOcean) || (a_BiomeGroup == bgDesert)); - } }; diff --git a/src/Generating/ProtIntGen.h b/src/Generating/ProtIntGen.h index a3d10c4ef..e2b3e592a 100644 --- a/src/Generating/ProtIntGen.h +++ b/src/Generating/ProtIntGen.h @@ -154,7 +154,7 @@ public: for (int x = 0; x < a_SizeX; x++) { int rnd = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); - a_Values[x + a_SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgLandOceanMax + 1) : 0; + a_Values[x + a_SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 101) % bgLandOceanMax + 1) : 0; } } @@ -410,7 +410,8 @@ protected: -/** Generates the underlying numbers and then randomly changes some zeroes into nonzeroes. */ +/** Generates the underlying numbers and then randomly changes some ocean group pixels into random land +group pixels, based on the predefined chance. */ class cProtIntGenAddIslands : public cProtIntGenWithNoise { @@ -420,9 +421,9 @@ public: typedef std::shared_ptr Underlying; - cProtIntGenAddIslands(int a_Seed, int a_Threshold, Underlying a_Underlying) : + cProtIntGenAddIslands(int a_Seed, int a_Chance, Underlying a_Underlying) : super(a_Seed), - m_Threshold(a_Threshold), + m_Chance(a_Chance), m_Underlying(a_Underlying) { } @@ -438,9 +439,9 @@ public: if (a_Values[x + z * a_SizeX] == bgOcean) { int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; - if (rnd % 100 < m_Threshold) + if (rnd % 1000 < m_Chance) { - a_Values[x + z * a_SizeX] = (rnd / 100) % bgLandOceanMax; + a_Values[x + z * a_SizeX] = (rnd / 101) % bgLandOceanMax; } } } @@ -448,7 +449,8 @@ public: } protected: - int m_Threshold; + /** Chance of each ocean pixel being converted, in permille. */ + int m_Chance; Underlying m_Underlying; }; @@ -520,35 +522,6 @@ public: } break; } // case bgIce - - // Jungle should not neighbor Desert or Ice; change to temperate: - case bgJungle: - { - if ( - !isJungleCompatible(Above) || - !isJungleCompatible(Below) || - !isJungleCompatible(Left) || - !isJungleCompatible(Right) - ) - { - val = bgTemperate; - } - } // case bgJungle - - // Mesa should neighbor only oceans and deserts; change to desert when another: - case bgMesa: - { - if ( - !isMesaCompatible(Above) || - !isMesaCompatible(Below) || - !isMesaCompatible(Left) || - !isMesaCompatible(Right) - ) - { - val = bgDesert; - } - break; - } // case bgDesert } a_Values[x + z * a_SizeX] = val; } // for x @@ -566,7 +539,6 @@ protected: case bgOcean: case bgDesert: case bgTemperate: - case bgMesa: { return true; } @@ -576,16 +548,6 @@ protected: } } } - - inline bool isJungleCompatible(int a_BiomeGroup) - { - return ((a_BiomeGroup != bgDesert) && (a_BiomeGroup != bgMesa) && (a_BiomeGroup != bgIce)); - } - - inline bool isMesaCompatible(int a_BiomeGroup) - { - return ((a_BiomeGroup == bgOcean) || (a_BiomeGroup == bgDesert)); - } }; @@ -616,24 +578,40 @@ public: biOcean, // biDeepOcean, }; + // Same as oceanBiomes, there are no rare oceanic biomes (mushroom islands are handled separately) + static const int rareOceanBiomes[] = + { + biOcean, + }; + static const int desertBiomes[] = { biDesert, biDesert, biDesert, biDesert, biDesert, biDesert, biSavanna, biSavanna, biPlains, }; + static const int rareDesertBiomes[] = + { + biMesaPlateau, biMesaPlateauF, + }; + static const int temperateBiomes[] = { biForest, biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, }; + static const int rareTemperateBiomes[] = + { + biJungle, // Jungle is not strictly temperate, but let's piggyback it here + }; + static const int mountainBiomes[] = { biExtremeHills, biForest, biTaiga, biPlains, }; - static const int jungleBiomes[] = + static const int rareMountainBiomes[] = { - biJungle, biJungle, biJungle, biForest, + biMegaTaiga, }; static const int iceBiomes[] = @@ -641,33 +619,44 @@ public: biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, }; - static const int mesaBiomes[] = + // Same as iceBiomes, there's no rare ice biome + static const int rareIceBiomes[] = { - biMesa, biMesaPlateau, + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, }; - static const cBiomesInGroups BiomesInGroups[] = + static const cBiomesInGroups biomesInGroups[] = { /* bgOcean */ { static_cast(ARRAYCOUNT(oceanBiomes)), oceanBiomes}, /* bgDesert */ { static_cast(ARRAYCOUNT(desertBiomes)), desertBiomes}, /* bgTemperate */ { static_cast(ARRAYCOUNT(temperateBiomes)), temperateBiomes}, /* bgMountains */ { static_cast(ARRAYCOUNT(mountainBiomes)), mountainBiomes}, - /* bgJungle */ { static_cast(ARRAYCOUNT(jungleBiomes)), jungleBiomes}, /* bgIce */ { static_cast(ARRAYCOUNT(iceBiomes)), iceBiomes}, - /* bgMesa */ { static_cast(ARRAYCOUNT(mesaBiomes)), mesaBiomes}, + }; + + static const cBiomesInGroups rareBiomesInGroups[] = + { + /* bgOcean */ { static_cast(ARRAYCOUNT(rareOceanBiomes)), rareOceanBiomes}, + /* bgDesert */ { static_cast(ARRAYCOUNT(rareDesertBiomes)), rareDesertBiomes}, + /* bgTemperate */ { static_cast(ARRAYCOUNT(rareTemperateBiomes)), rareTemperateBiomes}, + /* bgMountains */ { static_cast(ARRAYCOUNT(rareMountainBiomes)), rareMountainBiomes}, + /* bgIce */ { static_cast(ARRAYCOUNT(rareIceBiomes)), rareIceBiomes}, }; // Generate the underlying values, representing biome groups: m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); // Overwrite each biome group with a random biome from that group: + // Take care of the bgfRare flag for (int z = 0; z < a_SizeZ; z++) { int IdxZ = z * a_SizeX; for (int x = 0; x < a_SizeX; x++) { int val = a_Values[x + IdxZ]; - const cBiomesInGroups & Biomes = BiomesInGroups[val % ARRAYCOUNT(BiomesInGroups)]; + const cBiomesInGroups & Biomes = (val > bgfRare) ? + rareBiomesInGroups[(val & (bgfRare - 1)) % ARRAYCOUNT(rareBiomesInGroups)] : + biomesInGroups[val % ARRAYCOUNT(biomesInGroups)]; int rnd = (super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); a_Values[x + IdxZ] = Biomes.Biomes[rnd % Biomes.Count]; } @@ -700,7 +689,7 @@ public: typedef std::shared_ptr Underlying; - cProtIntGenReplaceRandomly(int a_From, int a_To, int a_Chance, int a_Seed, Underlying a_Underlying) : + cProtIntGenReplaceRandomly(int a_Seed, int a_From, int a_To, int a_Chance, Underlying a_Underlying) : super(a_Seed), m_From(a_From), m_To(a_To), @@ -725,7 +714,7 @@ public: if (a_Values[idx] == m_From) { int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; - if (rnd % 100 < m_Chance) + if (rnd % 1000 < m_Chance) { a_Values[idx] = m_To; } @@ -1006,3 +995,113 @@ protected: + +/** Adds a "rare" flag to random biome groups, based on the given chance. */ +class cProtIntGenRareBiomeGroups: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenRareBiomeGroups(int a_Seed, int a_Chance, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Change some of the biome groups into rare biome groups: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + int idx = x + a_SizeX * z; + a_Values[idx] = a_Values[idx] | bgfRare; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel into the rare biome group. */ + int m_Chance; + + /** The underlying generator. */ + Underlying m_Underlying; +}; + + + + + +/** Changes biomes in the parent data into their alternate verions ("M" variants), in such places that +have their alterations set. */ +class cProtIntGenAlternateBiomes: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenAlternateBiomes(int a_Seed, Underlying a_Alterations, Underlying a_BaseBiomes): + super(a_Seed), + m_Alterations(a_Alterations), + m_BaseBiomes(a_BaseBiomes) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the base biomes and the alterations: + m_BaseBiomes->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + int alterations[m_BufferSize]; + m_Alterations->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, alterations); + + // Change the biomes into their alternate versions: + int len = a_SizeX * a_SizeZ; + for (int idx = 0; idx < len; ++idx) + { + if (alterations[idx] == 0) + { + // No change + continue; + } + + // Change to alternate biomes: + int val = a_Values[idx]; + switch (val) + { + case biBirchForest: val = biBirchForest; break; + case biDesert: val = biDesertHills; break; + case biExtremeHills: val = biExtremeHillsPlus; break; + case biForest: val = biForestHills; break; + case biIcePlains: val = biIceMountains; break; + case biJungle: val = biJungleHills; break; + case biMegaTaiga: val = biMegaTaigaHills; break; + case biMesaPlateau: val = biMesa; break; + case biPlains: val = biForest; break; + case biRoofedForest: val = biPlains; break; + case biSavanna: val = biSavannaPlateau; break; + case biTaiga: val = biTaigaHills; break; + } + a_Values[idx] = val; + } // for idx - a_Values[] + } + +protected: + Underlying m_Alterations; + Underlying m_BaseBiomes; +}; + + + + -- cgit v1.2.3 From e2ffd5429c22753916b207f5fea5a01a65a31987 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 31 Oct 2014 19:23:47 +0100 Subject: Fixed missing CS lock in cChunkMap::WakeUpSimulatorsInArea(). --- src/ChunkMap.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index 595040a54..8a8f17a1b 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -822,6 +822,7 @@ void cChunkMap::WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_M int MinChunkX, MinChunkZ, MaxChunkX, MaxChunkZ; cChunkDef::BlockToChunk(a_MinBlockX, a_MinBlockZ, MinChunkX, MinChunkZ); cChunkDef::BlockToChunk(a_MaxBlockX, a_MaxBlockZ, MaxChunkX, MaxChunkZ); + cCSLock Lock(m_CSLayers); for (int z = MinChunkZ; z <= MaxChunkZ; z++) { int MinZ = std::max(a_MinBlockZ, z * cChunkDef::Width); -- cgit v1.2.3 From 2b7f34515a837ea02ebd19be3326b490f33ad012 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 31 Oct 2014 19:25:31 +0100 Subject: cLuaState: Fixed errors on non-existent callbacks. This mostly affected table-based callbacks, such as the cLineBlockTracer. If a callback didn't exist, the code would still push its arguments on the stack, breaking the next callback. --- src/Bindings/LuaState.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index d1e9923b4..c13e36188 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -247,7 +247,11 @@ public: template bool Call(const FnT & a_Function, Args &&... args) { - PushFunction(a_Function); + if (!PushFunction(a_Function)) + { + // Pushing the function failed + return false; + } return PushCallPop(args...); } -- cgit v1.2.3 From 4873890cfbb0c1a2ede464c44ffb58bfe4a1c1cd Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sat, 1 Nov 2014 16:37:56 +0100 Subject: GrownProt biome gen: Added biome edges. --- src/Generating/BioGen.cpp | 5 +- src/Generating/ProtIntGen.h | 159 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index b3701a32a..e4a3a3629 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -1042,11 +1042,12 @@ public: std::make_shared(a_Seed + 16, std::make_shared( std::make_shared(a_Seed + 1, - std::make_shared(a_Seed + 2, std::make_shared(a_Seed + 2004, 10, std::make_shared(a_Seed + 10, 500, biDeepOcean, std::make_shared(a_Seed + 1, biPlains, biSunflowerPlains, 20, std::make_shared(a_Seed + 1, alteration, + std::make_shared(a_Seed + 3, + std::make_shared(a_Seed + 2, std::make_shared(a_Seed + 4, std::make_shared(a_Seed + 99, biIcePlains, biIcePlainsSpikes, 50, std::make_shared(a_Seed + 8, @@ -1065,7 +1066,7 @@ public: std::make_shared(a_Seed + 9, 50, bgOcean, std::make_shared(a_Seed + 10, std::make_shared(a_Seed + 100, 30 - ))))))))))))))))))))))))))))); + )))))))))))))))))))))))))))))); m_Gen = std::make_shared(a_Seed, diff --git a/src/Generating/ProtIntGen.h b/src/Generating/ProtIntGen.h index e2b3e592a..c523d9d52 100644 --- a/src/Generating/ProtIntGen.h +++ b/src/Generating/ProtIntGen.h @@ -1088,6 +1088,7 @@ public: case biJungle: val = biJungleHills; break; case biMegaTaiga: val = biMegaTaigaHills; break; case biMesaPlateau: val = biMesa; break; + case biMesaPlateauF: val = biMesa; break; case biPlains: val = biForest; break; case biRoofedForest: val = biPlains; break; case biSavanna: val = biSavannaPlateau; break; @@ -1105,3 +1106,161 @@ protected: + +/** Adds an edge between two specifically incompatible biomes, such as mesa and forest. */ +class cProtIntGenBiomeEdges: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenBiomeEdges(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying biomes: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Convert incompatible edges into neutral biomes: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int biome = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + int above = lowerValues[x + 1 + z * lowerSizeX]; + int below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int left = lowerValues[x + (z + 1) * lowerSizeX]; + int right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + + switch (biome) + { + case biDesert: + case biDesertM: + case biDesertHills: + { + if ( + IsBiomeVeryCold(static_cast(above)) || + IsBiomeVeryCold(static_cast(below)) || + IsBiomeVeryCold(static_cast(left)) || + IsBiomeVeryCold(static_cast(right)) + ) + { + biome = biPlains; + } + break; + } // case biDesert + + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + { + if ( + !isMesaCompatible(above) || + !isMesaCompatible(below) || + !isMesaCompatible(left) || + !isMesaCompatible(right) + ) + { + biome = biDesert; + } + break; + } // Mesa biomes + + case biJungle: + case biJungleM: + { + if ( + !isJungleCompatible(above) || + !isJungleCompatible(below) || + !isJungleCompatible(left) || + !isJungleCompatible(right) + ) + { + biome = (biome == biJungle) ? biJungleEdge : biJungleEdgeM; + } + break; + } // Jungle biomes + + case biSwampland: + case biSwamplandM: + { + if ( + IsBiomeNoDownfall(static_cast(above)) || + IsBiomeNoDownfall(static_cast(below)) || + IsBiomeNoDownfall(static_cast(left)) || + IsBiomeNoDownfall(static_cast(right)) + ) + { + biome = biPlains; + } + break; + } // Swampland biomes + } // switch (biome) + + a_Values[x + z * a_SizeX] = biome; + } // for x + } // for z + } + + +protected: + Underlying m_Underlying; + + + bool isMesaCompatible(int a_Biome) + { + switch (a_Biome) + { + case biDesert: + case biMesa: + case biMesaBryce: + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + case biOcean: + case biDeepOcean: + { + return true; + } + default: + { + return false; + } + } + } + + + bool isJungleCompatible(int a_Biome) + { + switch (a_Biome) + { + case biJungle: + case biJungleM: + case biJungleEdge: + case biJungleEdgeM: + case biJungleHills: + { + return true; + } + default: + { + return false; + } + } + } +}; + + + + -- cgit v1.2.3 From d868346491cf35ea9d52d60786904b0552d9d67c Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sat, 1 Nov 2014 21:01:33 +0100 Subject: GrownProt: Added the rest of rare and M biomes. --- src/Generating/BioGen.cpp | 11 +++++- src/Generating/ProtIntGen.h | 94 ++++++++++++++++++++++++++++++++++++++------- 2 files changed, 91 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index e4a3a3629..dc5f715ca 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -1035,6 +1035,14 @@ public: std::make_shared(a_Seed, 20 )); + auto alteration2 = + std::make_shared(a_Seed + 1, + std::make_shared(a_Seed + 2, + std::make_shared(a_Seed + 1, + std::make_shared(a_Seed + 2, + std::make_shared(a_Seed + 1, 10 + ))))); + auto FinalBiomes = std::make_shared(a_Seed + 1, std::make_shared(a_Seed + 15, @@ -1045,6 +1053,7 @@ public: std::make_shared(a_Seed + 2004, 10, std::make_shared(a_Seed + 10, 500, biDeepOcean, std::make_shared(a_Seed + 1, biPlains, biSunflowerPlains, 20, + std::make_shared(a_Seed + 5, alteration2, std::make_shared(a_Seed + 1, alteration, std::make_shared(a_Seed + 3, std::make_shared(a_Seed + 2, @@ -1066,7 +1075,7 @@ public: std::make_shared(a_Seed + 9, 50, bgOcean, std::make_shared(a_Seed + 10, std::make_shared(a_Seed + 100, 30 - )))))))))))))))))))))))))))))); + ))))))))))))))))))))))))))))))); m_Gen = std::make_shared(a_Seed, diff --git a/src/Generating/ProtIntGen.h b/src/Generating/ProtIntGen.h index c523d9d52..9c3eb36cc 100644 --- a/src/Generating/ProtIntGen.h +++ b/src/Generating/ProtIntGen.h @@ -1080,19 +1080,21 @@ public: int val = a_Values[idx]; switch (val) { - case biBirchForest: val = biBirchForest; break; - case biDesert: val = biDesertHills; break; - case biExtremeHills: val = biExtremeHillsPlus; break; - case biForest: val = biForestHills; break; - case biIcePlains: val = biIceMountains; break; - case biJungle: val = biJungleHills; break; - case biMegaTaiga: val = biMegaTaigaHills; break; - case biMesaPlateau: val = biMesa; break; - case biMesaPlateauF: val = biMesa; break; - case biPlains: val = biForest; break; - case biRoofedForest: val = biPlains; break; - case biSavanna: val = biSavannaPlateau; break; - case biTaiga: val = biTaigaHills; break; + case biBirchForest: val = biBirchForest; break; + case biDesert: val = biDesertHills; break; + case biExtremeHills: val = biExtremeHillsPlus; break; + case biForest: val = biForestHills; break; + case biIcePlains: val = biIceMountains; break; + case biJungle: val = biJungleHills; break; + case biMegaTaiga: val = biMegaTaigaHills; break; + case biMesaPlateau: val = biMesa; break; + case biMesaPlateauF: val = biMesa; break; + case biMesaPlateauM: val = biMesa; break; + case biMesaPlateauFM: val = biMesa; break; + case biPlains: val = biForest; break; + case biRoofedForest: val = biPlains; break; + case biSavanna: val = biSavannaPlateau; break; + case biTaiga: val = biTaigaHills; break; } a_Values[idx] = val; } // for idx - a_Values[] @@ -1264,3 +1266,69 @@ protected: + +class cProtIntGenMBiomes: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenMBiomes(int a_Seed, Underlying a_Alteration, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying), + m_Alteration(a_Alteration) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying biomes and the alterations: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + int alterations[m_BufferSize]; + m_Alteration->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, alterations); + + // Wherever alterations are nonzero, change into alternate biome, if available: + int len = a_SizeX * a_SizeZ; + for (int idx = 0; idx < len; ++idx) + { + if (alterations[idx] == 0) + { + continue; + } + + // Ice spikes biome was removed from here, because it was generated way too often + switch (a_Values[idx]) + { + case biPlains: a_Values[idx] = biSunflowerPlains; break; + case biDesert: a_Values[idx] = biDesertM; break; + case biExtremeHills: a_Values[idx] = biExtremeHillsM; break; + case biForest: a_Values[idx] = biFlowerForest; break; + case biTaiga: a_Values[idx] = biTaigaM; break; + case biSwampland: a_Values[idx] = biSwamplandM; break; + case biJungle: a_Values[idx] = biJungleM; break; + case biJungleEdge: a_Values[idx] = biJungleEdgeM; break; + case biBirchForest: a_Values[idx] = biBirchForestM; break; + case biBirchForestHills: a_Values[idx] = biBirchForestHillsM; break; + case biRoofedForest: a_Values[idx] = biRoofedForestM; break; + case biColdTaiga: a_Values[idx] = biColdTaigaM; break; + case biMegaSpruceTaiga: a_Values[idx] = biMegaSpruceTaiga; break; + case biMegaSpruceTaigaHills: a_Values[idx] = biMegaSpruceTaigaHills; break; + case biExtremeHillsPlus: a_Values[idx] = biExtremeHillsPlusM; break; + case biSavanna: a_Values[idx] = biSavannaM; break; + case biSavannaPlateau: a_Values[idx] = biSavannaPlateauM; break; + case biMesa: a_Values[idx] = biMesaBryce; break; + case biMesaPlateauF: a_Values[idx] = biMesaPlateauFM; break; + case biMesaPlateau: a_Values[idx] = biMesaBryce; break; + } + } // for idx - a_Values[] / alterations[] + } + +protected: + Underlying m_Underlying; + Underlying m_Alteration; +}; + + + + -- cgit v1.2.3 From d5b6353493868ac14b277155f398bd87f08c484c Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 2 Nov 2014 16:36:59 +0100 Subject: Grown biomes: Unified with GrownProt biomes. Also fixed a Zoom filter randomness. --- src/Generating/BioGen.cpp | 104 ++++---- src/Generating/IntGen.h | 567 +++++++++++++++++++++++++++++++++++++------- src/Generating/ProtIntGen.h | 83 ++++--- 3 files changed, 595 insertions(+), 159 deletions(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index dc5f715ca..0f2b0a73d 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -928,59 +928,77 @@ public: cBioGenGrown(int a_Seed) { auto FinalRivers = - std::make_shared> (a_Seed + 1, - std::make_shared> (a_Seed + 3, - std::make_shared> (a_Seed + 2, - std::make_shared> (a_Seed + 4, - std::make_shared> (a_Seed + 5, - std::make_shared> (a_Seed + 6, - std::make_shared> (a_Seed + 7, - std::make_shared> (a_Seed + 8, - std::make_shared> (a_Seed + 9, - std::make_shared> (a_Seed + 10, - std::make_shared> (a_Seed + 11, - std::make_shared>(a_Seed + 12 - )))))))))))); + std::make_shared> (a_Seed + 1, + std::make_shared> (a_Seed + 2, + std::make_shared> (a_Seed + 3, + std::make_shared> (a_Seed + 4, + std::make_shared> (a_Seed + 5, + std::make_shared> (a_Seed + 8, + std::make_shared> (a_Seed + 5, + std::make_shared> (a_Seed + 9, + std::make_shared> (a_Seed + 5, + std::make_shared> (a_Seed + 10, + std::make_shared> (a_Seed + 5, + std::make_shared> (a_Seed + 6, + std::make_shared> (a_Seed + 11, + std::make_shared>(a_Seed + 12 + )))))))))))))); + + auto alteration = + std::make_shared>(a_Seed, + std::make_shared>(a_Seed, 20 + )); + + auto alteration2 = + std::make_shared>(a_Seed + 1, + std::make_shared>(a_Seed + 2, + std::make_shared>(a_Seed + 1, + std::make_shared>(a_Seed + 2, + std::make_shared>(a_Seed + 1, 10 + ))))); auto FinalBiomes = - std::make_shared> (a_Seed + 1008, - std::make_shared>(a_Seed + 15, - std::make_shared> (a_Seed + 1000, - std::make_shared> (a_Seed + 16, + std::make_shared> (a_Seed + 1, + std::make_shared>(a_Seed + 15, + std::make_shared> (a_Seed + 1, + std::make_shared> (a_Seed + 16, std::make_shared> ( - std::make_shared> (a_Seed + 1002, - std::make_shared>(a_Seed + 1, - std::make_shared> (a_Seed + 1002, - std::make_shared> (a_Seed + 2, + std::make_shared> (a_Seed + 1, std::make_shared> (a_Seed + 2004, 10, - std::make_shared> (a_Seed + 4, - std::make_shared> (a_Seed + 9, 10, biMushroomIsland, - std::make_shared> (biIcePlains, biIcePlainsSpikes, 5, a_Seed + 99, - std::make_shared> (a_Seed + 8, - std::make_shared> (a_Seed + 10, 500, biDeepOcean, - std::make_shared> (a_Seed + 3000, - std::make_shared> (a_Seed + 5, - std::make_shared> ( - std::make_shared> (a_Seed + 1003, - std::make_shared> (a_Seed + 7, + std::make_shared> (a_Seed + 10, 500, biDeepOcean, + std::make_shared> (a_Seed + 1, biPlains, biSunflowerPlains, 20, + std::make_shared> (a_Seed + 5, alteration2, + std::make_shared> (a_Seed + 1, alteration, + std::make_shared> (a_Seed + 3, + std::make_shared>(a_Seed + 2, + std::make_shared> (a_Seed + 4, + std::make_shared> (a_Seed + 99, biIcePlains, biIcePlainsSpikes, 50, + std::make_shared> (a_Seed + 8, + std::make_shared> (a_Seed + 10, 300, biDeepOcean, + std::make_shared> (a_Seed + 9, 8, biMushroomIsland, + std::make_shared> (a_Seed + 3000, + std::make_shared> (a_Seed + 2000, 200, + std::make_shared> (a_Seed + 5, + std::make_shared> (a_Seed + 5, 50, + std::make_shared> ( + std::make_shared> (a_Seed + 2000, 200, + std::make_shared> (a_Seed + 7, std::make_shared> (a_Seed + 8, 50, bgOcean, - std::make_shared> (bgIce, bgTemperate, 50, a_Seed + 101, - std::make_shared> (a_Seed + 2000, 70, + std::make_shared> (a_Seed + 101, bgIce, bgTemperate, 150, + std::make_shared> (a_Seed + 2000, 200, std::make_shared> (a_Seed + 9, 50, bgOcean, - std::make_shared> (a_Seed + 1004, - std::make_shared> (a_Seed + 10, - std::make_shared> (a_Seed + 100, 65 - ))))))))))))))))))))))))))); + std::make_shared> (a_Seed + 10, + std::make_shared> (a_Seed + 100, 30 + ))))))))))))))))))))))))))))))); m_Gen = std::make_shared>(a_Seed, std::make_shared>(a_Seed, - std::make_shared>(a_Seed, - std::make_shared>(a_Seed, - std::make_shared>(a_Seed, - std::make_shared> ( + std::make_shared>(a_Seed, + std::make_shared>(a_Seed, + std::make_shared> ( FinalBiomes, FinalRivers - )))))); + ))))); } virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_Biomes) override @@ -1025,7 +1043,7 @@ public: std::make_shared(a_Seed + 5, std::make_shared(a_Seed + 10, std::make_shared(a_Seed + 5, - std::make_shared(a_Seed + 5, + std::make_shared(a_Seed + 6, std::make_shared(a_Seed + 11, std::make_shared(a_Seed + 12, 2 )))))))))))))); diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index 15a5c9157..83a0e569a 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -167,7 +167,7 @@ public: for (int x = 0; x < SizeX; x++) { int rnd = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); - a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 128) % bgLandOceanMax + 1) : 0; + a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 101) % bgLandOceanMax + 1) : 0; } } @@ -186,6 +186,9 @@ protected: +/** Zooms the underlying value array to twice the size. Uses random-neighbor for the pixels in-between. +This means that the zoome out image is randomly distorted. Applying zoom several times provides all +the distortion that the generators need. */ template class cIntGenZoom : public cIntGenWithNoise @@ -212,31 +215,30 @@ public: // Generate the underlying data with half the resolution: int lowerMinX = a_MinX >> 1; int lowerMinZ = a_MinZ >> 1; - int Underlying[m_LowerSizeX * m_LowerSizeZ]; - m_UnderlyingGen->GetInts(lowerMinX, lowerMinZ, Underlying); + int lowerData[m_LowerSizeX * m_LowerSizeZ]; + m_UnderlyingGen->GetInts(lowerMinX, lowerMinZ, lowerData); const int lowStepX = (m_LowerSizeX - 1) * 2; const int lowStepZ = (m_LowerSizeZ - 1) * 2; - int Cache[lowStepX * lowStepZ]; + int cache[lowStepX * lowStepZ]; // Discreet-interpolate the values into twice the size: for (int z = 0; z < m_LowerSizeZ - 1; ++z) { int idx = (z * 2) * lowStepX; - int PrevZ0 = Underlying[z * m_LowerSizeX]; - int PrevZ1 = Underlying[(z + 1) * m_LowerSizeX]; + int PrevZ0 = lowerData[z * m_LowerSizeX]; + int PrevZ1 = lowerData[(z + 1) * m_LowerSizeX]; for (int x = 0; x < m_LowerSizeX - 1; ++x) { - int ValX1Z0 = Underlying[x + 1 + z * m_LowerSizeX]; - int ValX1Z1 = Underlying[x + 1 + (z + 1) * m_LowerSizeX]; + int ValX1Z0 = lowerData[x + 1 + z * m_LowerSizeX]; + int ValX1Z1 = lowerData[x + 1 + (z + 1) * m_LowerSizeX]; int RndX = (x + lowerMinX) * 2; int RndZ = (z + lowerMinZ) * 2; - Cache[idx] = PrevZ0; - Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, PrevZ1); - idx++; - Cache[idx] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0); - Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); - idx++; + cache[idx] = PrevZ0; + cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ + 1, PrevZ0, PrevZ1); + cache[idx + 1] = super::ChooseRandomOne(RndX, RndZ - 1, PrevZ0, ValX1Z0); + cache[idx + 1 + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); + idx += 2; PrevZ0 = ValX1Z0; PrevZ1 = ValX1Z1; } @@ -245,7 +247,7 @@ public: // Copy from Cache into a_Values; take into account the even/odd offsets in a_Min: for (int z = 0; z < SizeZ; ++z) { - memcpy(a_Values + z * SizeX, Cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), SizeX * sizeof(int)); + memcpy(a_Values + z * SizeX, cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), SizeX * sizeof(int)); } } @@ -257,16 +259,18 @@ protected: +/** Smoothes out some artifacts generated by the zooming - mostly single-pixel values. +Compares each pixel to its neighbors and if the neighbors are equal, changes the pixel to their value. */ template class cIntGenSmooth : public cIntGenWithNoise { typedef cIntGenWithNoise super; - static const int UnderlyingSizeX = SizeX + 2; - static const int UnderlyingSizeZ = SizeZ + 2; + static const int m_LowerSizeX = SizeX + 2; + static const int m_LowerSizeZ = SizeZ + 2; public: - typedef std::shared_ptr> Underlying; + typedef std::shared_ptr> Underlying; cIntGenSmooth(int a_Seed, Underlying a_Underlying) : @@ -279,8 +283,8 @@ public: virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying values: - int Cache[UnderlyingSizeX * UnderlyingSizeZ]; - m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + int lowerData[m_LowerSizeX * m_LowerSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerData); // Smooth - for each square check if the surroundings are the same, if so, expand them diagonally. // Also get rid of single-pixel irregularities (A-B-A): @@ -289,33 +293,33 @@ public: int NoiseZ = a_MinZ + z; for (int x = 0; x < SizeX; x++) { - int val = Cache[x + 1 + (z + 1) * UnderlyingSizeX]; - int Above = Cache[x + 1 + z * UnderlyingSizeX]; - int Below = Cache[x + 1 + (z + 2) * UnderlyingSizeX]; - int Left = Cache[x + (z + 1) * UnderlyingSizeX]; - int Right = Cache[x + 2 + (z + 1) * UnderlyingSizeX]; + int val = lowerData[x + 1 + (z + 1) * m_LowerSizeX]; + int above = lowerData[x + 1 + z * m_LowerSizeX]; + int below = lowerData[x + 1 + (z + 2) * m_LowerSizeX]; + int left = lowerData[x + (z + 1) * m_LowerSizeX]; + int right = lowerData[x + 2 + (z + 1) * m_LowerSizeX]; - if ((Left == Right) && (Above == Below)) + if ((left == right) && (above == below)) { if (((super::m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) { - val = Left; + val = left; } else { - val = Above; + val = above; } } else { - if (Left == Right) + if (left == right) { - val = Left; + val = left; } - if (Above == Below) + if (above == below) { - val = Above; + val = above; } } @@ -332,7 +336,8 @@ protected: -template +/** Converts land biomes at the edge of an ocean into the respective beach biome. */ +template class cIntGenBeaches : public cIntGen { @@ -398,23 +403,24 @@ public: }; // Generate the underlying values: - int Cache[m_UnderlyingSizeX * m_UnderlyingSizeZ]; - m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + int lowerValues[m_UnderlyingSizeX * m_UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerValues); // Add beaches between ocean and biomes: for (int z = 0; z < SizeZ; z++) { for (int x = 0; x < SizeX; x++) { - int val = Cache[x + 1 + (z + 1) * m_UnderlyingSizeX]; - int Above = Cache[x + 1 + z * m_UnderlyingSizeX]; - int Below = Cache[x + 1 + (z + 2) * m_UnderlyingSizeX]; - int Left = Cache[x + (z + 1) * m_UnderlyingSizeX]; - int Right = Cache[x + 2 + (z + 1) * m_UnderlyingSizeX]; + int val = lowerValues[x + 1 + (z + 1) * m_UnderlyingSizeX]; + int above = lowerValues[x + 1 + z * m_UnderlyingSizeX]; + int below = lowerValues[x + 1 + (z + 2) * m_UnderlyingSizeX]; + int left = lowerValues[x + (z + 1) * m_UnderlyingSizeX]; + int right = lowerValues[x + 2 + (z + 1) * m_UnderlyingSizeX]; if (!IsBiomeOcean(val)) { - if (IsBiomeOcean(Above) || IsBiomeOcean(Below) || IsBiomeOcean(Left) || IsBiomeOcean(Right)) + if (IsBiomeOcean(above) || IsBiomeOcean(below) || IsBiomeOcean(left) || IsBiomeOcean(right)) { + // First convert the value to a regular biome (drop the M flag), then modulo by our biome count: val = ToBeach[(val % 128) % ARRAYCOUNT(ToBeach)]; } } @@ -431,7 +437,8 @@ protected: -/** Generates the underlying numbers and then randomly changes some zeroes into nonzeroes. */ +/** Generates the underlying numbers and then randomly changes some ocean group pixels into random land +biome group pixels, based on the predefined chance. */ template class cIntGenAddIslands : public cIntGenWithNoise @@ -442,9 +449,9 @@ public: typedef std::shared_ptr> Underlying; - cIntGenAddIslands(int a_Seed, int a_Threshold, Underlying a_Underlying) : + cIntGenAddIslands(int a_Seed, int a_Chance, Underlying a_Underlying) : super(a_Seed), - m_Threshold(a_Threshold), + m_Chance(a_Chance), m_Underlying(a_Underlying) { } @@ -460,17 +467,18 @@ public: if (a_Values[x + z * SizeX] == bgOcean) { int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; - if (rnd % 100 < m_Threshold) + if (rnd % 1000 < m_Chance) { - a_Values[x + z * SizeX] = (rnd / 100) % bgLandOceanMax; + a_Values[x + z * SizeX] = (rnd / 1003) % bgLandOceanMax; } } - } - } + } // for x + } // for z } protected: - int m_Threshold; + /** Chance, in permille, of an island being generated in ocean. */ + int m_Chance; Underlying m_Underlying; }; @@ -502,32 +510,32 @@ public: virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) { // Generate the underlying biome groups: - int Cache[m_UnderlyingSizeX * m_UnderlyingSizeZ]; - m_Underlying->GetInts(a_MinX, a_MinZ, Cache); + int lowerValues[m_UnderlyingSizeX * m_UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX, a_MinZ, lowerValues); // Change the biomes on incompatible edges into an edge biome: for (int z = 0; z < SizeZ; z++) { for (int x = 0; x < SizeX; x++) { - int v = Cache[x + 1 + (z + 1) * m_UnderlyingSizeX]; - int Above = Cache[x + 1 + z * m_UnderlyingSizeX]; - int Below = Cache[x + 1 + (z + 2) * m_UnderlyingSizeX]; - int Left = Cache[x + (z + 1) * m_UnderlyingSizeX]; - int Right = Cache[x + 2 + (z + 1) * m_UnderlyingSizeX]; - switch (v) + int val = lowerValues[x + 1 + (z + 1) * m_UnderlyingSizeX]; + int above = lowerValues[x + 1 + z * m_UnderlyingSizeX]; + int below = lowerValues[x + 1 + (z + 2) * m_UnderlyingSizeX]; + int left = lowerValues[x + (z + 1) * m_UnderlyingSizeX]; + int right = lowerValues[x + 2 + (z + 1) * m_UnderlyingSizeX]; + switch (val) { // Desert should neighbor only oceans, desert and temperates; change to temperate when another: case bgDesert: { if ( - !isDesertCompatible(Above) || - !isDesertCompatible(Below) || - !isDesertCompatible(Left) || - !isDesertCompatible(Right) + !isDesertCompatible(above) || + !isDesertCompatible(below) || + !isDesertCompatible(left) || + !isDesertCompatible(right) ) { - v = bgTemperate; + val = bgTemperate; } break; } // case bgDesert @@ -536,18 +544,18 @@ public: case bgIce: { if ( - (Above == bgDesert) || - (Below == bgDesert) || - (Left == bgDesert) || - (Right == bgDesert) + (above == bgDesert) || + (below == bgDesert) || + (left == bgDesert) || + (right == bgDesert) ) { - v = bgTemperate; + val = bgTemperate; } break; } // case bgIce } - a_Values[x + z * SizeX] = v; + a_Values[x + z * SizeX] = val; } // for x } // for z } @@ -578,6 +586,9 @@ protected: +/** Turns biome group indices into real biomes. +For each pixel, takes its biome group and chooses a random biome from that group; replaces the value with +that biome. */ template class cIntGenBiomes : public cIntGenWithNoise @@ -600,7 +611,13 @@ public: // Define the per-biome-group biomes: static const int oceanBiomes[] = { - biOcean, // biDeepOcean, + biOcean, // biDeepOcean, + }; + + // Same as oceanBiomes, there are no rare oceanic biomes (mushroom islands are handled separately) + static const int rareOceanBiomes[] = + { + biOcean, }; static const int desertBiomes[] = @@ -608,19 +625,29 @@ public: biDesert, biDesert, biDesert, biDesert, biDesert, biDesert, biSavanna, biSavanna, biPlains, }; + static const int rareDesertBiomes[] = + { + biMesaPlateau, biMesaPlateauF, + }; + static const int temperateBiomes[] = { biForest, biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, }; + static const int rareTemperateBiomes[] = + { + biJungle, // Jungle is not strictly temperate, but let's piggyback it here + }; + static const int mountainBiomes[] = { biExtremeHills, biForest, biTaiga, biPlains, }; - static const int jungleBiomes[] = + static const int rareMountainBiomes[] = { - biJungle, biJungle, biJungle, biForest, + biMegaTaiga, }; static const int iceBiomes[] = @@ -628,20 +655,28 @@ public: biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, }; - static const int mesaBiomes[] = + // Same as iceBiomes, there's no rare ice biome + static const int rareIceBiomes[] = { - biMesa, biMesaPlateau, + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, }; - static const cBiomesInGroups BiomesInGroups[] = + static const cBiomesInGroups biomesInGroups[] = { /* bgOcean */ { static_cast(ARRAYCOUNT(oceanBiomes)), oceanBiomes}, /* bgDesert */ { static_cast(ARRAYCOUNT(desertBiomes)), desertBiomes}, /* bgTemperate */ { static_cast(ARRAYCOUNT(temperateBiomes)), temperateBiomes}, /* bgMountains */ { static_cast(ARRAYCOUNT(mountainBiomes)), mountainBiomes}, - /* bgJungle */ { static_cast(ARRAYCOUNT(jungleBiomes)), jungleBiomes}, /* bgIce */ { static_cast(ARRAYCOUNT(iceBiomes)), iceBiomes}, - /* bgMesa */ { static_cast(ARRAYCOUNT(mesaBiomes)), mesaBiomes}, + }; + + static const cBiomesInGroups rareBiomesInGroups[] = + { + /* bgOcean */ { static_cast(ARRAYCOUNT(rareOceanBiomes)), rareOceanBiomes}, + /* bgDesert */ { static_cast(ARRAYCOUNT(rareDesertBiomes)), rareDesertBiomes}, + /* bgTemperate */ { static_cast(ARRAYCOUNT(rareTemperateBiomes)), rareTemperateBiomes}, + /* bgMountains */ { static_cast(ARRAYCOUNT(rareMountainBiomes)), rareMountainBiomes}, + /* bgIce */ { static_cast(ARRAYCOUNT(rareIceBiomes)), rareIceBiomes}, }; // Generate the underlying values, representing biome groups: @@ -654,7 +689,9 @@ public: for (int x = 0; x < SizeX; x++) { int val = a_Values[x + IdxZ]; - const cBiomesInGroups & Biomes = BiomesInGroups[val % ARRAYCOUNT(BiomesInGroups)]; + const cBiomesInGroups & Biomes = (val > bgfRare) ? + rareBiomesInGroups[(val & (bgfRare - 1)) % ARRAYCOUNT(rareBiomesInGroups)] : + biomesInGroups[val % ARRAYCOUNT(biomesInGroups)]; int rnd = (super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); a_Values[x + IdxZ] = Biomes.Biomes[rnd % Biomes.Count]; } @@ -678,6 +715,7 @@ protected: +/** Randomly replaces pixels of one value to another value, using the given chance. */ template class cIntGenReplaceRandomly : public cIntGenWithNoise @@ -713,7 +751,7 @@ public: if (a_Values[idx] == m_From) { int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; - if (rnd % 100 < m_Chance) + if (rnd % 1000 < m_Chance) { a_Values[idx] = m_To; } @@ -724,9 +762,15 @@ public: protected: + /** The original value to be replaced. */ int m_From; + + /** The destination value to which to replace. */ int m_To; + + /** Chance, in permille, of replacing the value. */ int m_Chance; + Underlying m_Underlying; }; @@ -735,7 +779,9 @@ protected: /** Mixer that joins together finalized biomes and rivers. -It first checks for oceans; if there's no ocean, it checks for a river. */ +It first checks for oceans, if there is an ocean in the Biomes, it keeps the ocean. +If there's no ocean, it checks Rivers for a river, if there is a river, it uses the Biomes to select either +regular river or frozen river, based on the biome. */ template class cIntGenMixRivers: public cIntGen @@ -757,8 +803,8 @@ public: { // Generate the underlying data: m_Biomes->GetInts(a_MinX, a_MinZ, a_Values); - typename super::Values Rivers; - m_Rivers->GetInts(a_MinX, a_MinZ, Rivers); + typename super::Values riverData; + m_Rivers->GetInts(a_MinX, a_MinZ, riverData); // Mix the values: for (int z = 0; z < SizeZ; z++) @@ -772,7 +818,7 @@ public: // Oceans are kept without any changes continue; } - if (Rivers[idx] != biRiver) + if (riverData[idx] != biRiver) { // There's no river, keep the current value continue; @@ -925,7 +971,10 @@ public: } // If at least 3 ocean neighbors and the chance is right, change: - if ((NumOceanNeighbors >= 3) && ((super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance)) + if ( + (NumOceanNeighbors >= 3) && + ((super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance) + ) { a_Values[x + z * SizeX] = m_ToValue; } @@ -1003,3 +1052,355 @@ protected: + +/** Adds a "rare" flag to random biome groups, based on the given chance. */ +template +class cIntGenRareBiomeGroups: + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + typedef std::shared_ptr> Underlying; + + + cIntGenRareBiomeGroups(int a_Seed, int a_Chance, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Change some of the biome groups into rare biome groups: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + int idx = x + SizeX * z; + a_Values[idx] = a_Values[idx] | bgfRare; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel into the rare biome group. */ + int m_Chance; + + /** The underlying generator. */ + Underlying m_Underlying; +}; + + + + + +/** Changes biomes in the parent data into an alternate versions (usually "hill" variants), in such places +that have their alterations set. */ +template +class cIntGenAlternateBiomes: + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + typedef std::shared_ptr> Underlying; + + + cIntGenAlternateBiomes(int a_Seed, Underlying a_Alterations, Underlying a_BaseBiomes): + super(a_Seed), + m_Alterations(a_Alterations), + m_BaseBiomes(a_BaseBiomes) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the base biomes and the alterations: + m_BaseBiomes->GetInts(a_MinX, a_MinZ, a_Values); + super::Values alterations; + m_Alterations->GetInts(a_MinX, a_MinZ, alterations); + + // Change the biomes into their alternate versions: + for (int idx = 0; idx < SizeX * SizeZ; ++idx) + { + if (alterations[idx] == 0) + { + // No change + continue; + } + + // Change to alternate biomes: + int val = a_Values[idx]; + switch (val) + { + case biBirchForest: val = biBirchForestHills; break; + case biDesert: val = biDesertHills; break; + case biExtremeHills: val = biExtremeHillsPlus; break; + case biForest: val = biForestHills; break; + case biIcePlains: val = biIceMountains; break; + case biJungle: val = biJungleHills; break; + case biMegaTaiga: val = biMegaTaigaHills; break; + case biMesaPlateau: val = biMesa; break; + case biMesaPlateauF: val = biMesa; break; + case biMesaPlateauM: val = biMesa; break; + case biMesaPlateauFM: val = biMesa; break; + case biPlains: val = biForest; break; + case biRoofedForest: val = biPlains; break; + case biSavanna: val = biSavannaPlateau; break; + case biTaiga: val = biTaigaHills; break; + } + a_Values[idx] = val; + } // for idx - a_Values[] + } + +protected: + Underlying m_Alterations; + Underlying m_BaseBiomes; +}; + + + + + +/** Adds an edge between two specifically incompatible biomes, such as mesa and forest. */ +template +class cIntGenBiomeEdges: + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + static const int m_LowerSizeX = SizeX + 2; + static const int m_LowerSizeZ = SizeZ + 2; + +public: + typedef std::shared_ptr> Underlying; + + + cIntGenBiomeEdges(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying biomes: + Underlying::element_type::Values lowerValues; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerValues); + + // Convert incompatible edges into neutral biomes: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int biome = lowerValues[x + 1 + (z + 1) * m_LowerSizeX]; + int above = lowerValues[x + 1 + z * m_LowerSizeX]; + int below = lowerValues[x + 1 + (z + 2) * m_LowerSizeX]; + int left = lowerValues[x + (z + 1) * m_LowerSizeX]; + int right = lowerValues[x + 2 + (z + 1) * m_LowerSizeX]; + + switch (biome) + { + case biDesert: + case biDesertM: + case biDesertHills: + { + if ( + IsBiomeVeryCold(static_cast(above)) || + IsBiomeVeryCold(static_cast(below)) || + IsBiomeVeryCold(static_cast(left)) || + IsBiomeVeryCold(static_cast(right)) + ) + { + biome = biPlains; + } + break; + } // case biDesert + + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + { + if ( + !isMesaCompatible(above) || + !isMesaCompatible(below) || + !isMesaCompatible(left) || + !isMesaCompatible(right) + ) + { + biome = biDesert; + } + break; + } // Mesa biomes + + case biJungle: + case biJungleM: + { + if ( + !isJungleCompatible(above) || + !isJungleCompatible(below) || + !isJungleCompatible(left) || + !isJungleCompatible(right) + ) + { + biome = (biome == biJungle) ? biJungleEdge : biJungleEdgeM; + } + break; + } // Jungle biomes + + case biSwampland: + case biSwamplandM: + { + if ( + IsBiomeNoDownfall(static_cast(above)) || + IsBiomeNoDownfall(static_cast(below)) || + IsBiomeNoDownfall(static_cast(left)) || + IsBiomeNoDownfall(static_cast(right)) + ) + { + biome = biPlains; + } + break; + } // Swampland biomes + } // switch (biome) + + a_Values[x + z * SizeX] = biome; + } // for x + } // for z + } + + +protected: + Underlying m_Underlying; + + + bool isMesaCompatible(int a_Biome) + { + switch (a_Biome) + { + case biDesert: + case biMesa: + case biMesaBryce: + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + case biOcean: + case biDeepOcean: + { + return true; + } + default: + { + return false; + } + } + } + + + bool isJungleCompatible(int a_Biome) + { + switch (a_Biome) + { + case biJungle: + case biJungleM: + case biJungleEdge: + case biJungleEdgeM: + case biJungleHills: + { + return true; + } + default: + { + return false; + } + } + } +}; + + + + + +/** Changes biomes in the parent data into their alternate versions ("M" variants), in such places that +have their alterations set. */ +template +class cIntGenMBiomes: + public cIntGenWithNoise +{ + typedef cIntGenWithNoise super; + +public: + typedef std::shared_ptr> Underlying; + + + cIntGenMBiomes(int a_Seed, Underlying a_Alteration, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying), + m_Alteration(a_Alteration) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying biomes and the alterations: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + super::Values alterations; + m_Alteration->GetInts(a_MinX, a_MinZ, alterations); + + // Wherever alterations are nonzero, change into alternate biome, if available: + for (int idx = 0; idx < SizeX * SizeZ; ++idx) + { + if (alterations[idx] == 0) + { + continue; + } + + // Ice spikes biome was removed from here, because it was generated way too often + switch (a_Values[idx]) + { + case biPlains: a_Values[idx] = biSunflowerPlains; break; + case biDesert: a_Values[idx] = biDesertM; break; + case biExtremeHills: a_Values[idx] = biExtremeHillsM; break; + case biForest: a_Values[idx] = biFlowerForest; break; + case biTaiga: a_Values[idx] = biTaigaM; break; + case biSwampland: a_Values[idx] = biSwamplandM; break; + case biJungle: a_Values[idx] = biJungleM; break; + case biJungleEdge: a_Values[idx] = biJungleEdgeM; break; + case biBirchForest: a_Values[idx] = biBirchForestM; break; + case biBirchForestHills: a_Values[idx] = biBirchForestHillsM; break; + case biRoofedForest: a_Values[idx] = biRoofedForestM; break; + case biColdTaiga: a_Values[idx] = biColdTaigaM; break; + case biMegaSpruceTaiga: a_Values[idx] = biMegaSpruceTaiga; break; + case biMegaSpruceTaigaHills: a_Values[idx] = biMegaSpruceTaigaHills; break; + case biExtremeHillsPlus: a_Values[idx] = biExtremeHillsPlusM; break; + case biSavanna: a_Values[idx] = biSavannaM; break; + case biSavannaPlateau: a_Values[idx] = biSavannaPlateauM; break; + case biMesa: a_Values[idx] = biMesaBryce; break; + case biMesaPlateauF: a_Values[idx] = biMesaPlateauFM; break; + case biMesaPlateau: a_Values[idx] = biMesaBryce; break; + } + } // for idx - a_Values[] / alterations[] + } + +protected: + Underlying m_Underlying; + Underlying m_Alteration; +}; + + + + diff --git a/src/Generating/ProtIntGen.h b/src/Generating/ProtIntGen.h index 9c3eb36cc..73ed27096 100644 --- a/src/Generating/ProtIntGen.h +++ b/src/Generating/ProtIntGen.h @@ -70,14 +70,14 @@ protected: cNoise m_Noise; /** Chooses one of a_Val1 or a_Val2, based on m_Noise and the coordinates for querying the noise. */ - int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2) + int chooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2) { int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; return ((rnd & 1) == 0) ? a_Val1 : a_Val2; } /** Chooses one of a_ValN, based on m_Noise and the coordinates for querying the noise. */ - int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2, int a_Val3, int a_Val4) + int chooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2, int a_Val3, int a_Val4) { int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; switch (rnd % 4) @@ -173,6 +173,9 @@ protected: +/** Zooms the underlying value array to twice the size. Uses random-neighbor for the pixels in-between. +This means that the zoome out image is randomly distorted. Applying zoom several times provides all +the distortion that the generators need. */ class cProtIntGenZoom : public cProtIntGenWithNoise { @@ -201,7 +204,7 @@ public: int lowerData[m_BufferSize]; m_UnderlyingGen->GetInts(lowerMinX, lowerMinZ, lowerSizeX, lowerSizeZ, lowerData); const int lowStepX = (lowerSizeX - 1) * 2; - int Cache[m_BufferSize]; + int cache[m_BufferSize]; // Discreet-interpolate the values into twice the size: for (int z = 0; z < lowerSizeZ - 1; ++z) @@ -216,12 +219,11 @@ public: int ValX1Z1 = lowerData[x + 1 + (z + 1) * lowerSizeX]; int RndX = (x + lowerMinX) * 2; int RndZ = (z + lowerMinZ) * 2; - Cache[idx] = PrevZ0; - Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, PrevZ1); - idx++; - Cache[idx] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0); - Cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); - idx++; + cache[idx] = PrevZ0; + cache[idx + lowStepX] = super::chooseRandomOne(RndX, RndZ + 1, PrevZ0, PrevZ1); + cache[idx + 1] = super::chooseRandomOne(RndX, RndZ - 1, PrevZ0, ValX1Z0); + cache[idx + 1 + lowStepX] = super::chooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); + idx += 2; PrevZ0 = ValX1Z0; PrevZ1 = ValX1Z1; } @@ -230,7 +232,7 @@ public: // Copy from Cache into a_Values; take into account the even/odd offsets in a_Min: for (int z = 0; z < a_SizeZ; ++z) { - memcpy(a_Values + z * a_SizeX, Cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), a_SizeX * sizeof(int)); + memcpy(a_Values + z * a_SizeX, cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), a_SizeX * sizeof(int)); } } @@ -242,6 +244,8 @@ protected: +/** Smoothes out some artifacts generated by the zooming - mostly single-pixel values. +Compares each pixel to its neighbors and if the neighbors are equal, changes the pixel to their value. */ class cProtIntGenSmooth : public cProtIntGenWithNoise { @@ -272,32 +276,32 @@ public: for (int x = 0; x < a_SizeX; x++) { int val = lowerData[x + 1 + (z + 1) * lowerSizeX]; - int Above = lowerData[x + 1 + z * lowerSizeX]; - int Below = lowerData[x + 1 + (z + 2) * lowerSizeX]; - int Left = lowerData[x + (z + 1) * lowerSizeX]; - int Right = lowerData[x + 2 + (z + 1) * lowerSizeX]; + int above = lowerData[x + 1 + z * lowerSizeX]; + int below = lowerData[x + 1 + (z + 2) * lowerSizeX]; + int left = lowerData[x + (z + 1) * lowerSizeX]; + int right = lowerData[x + 2 + (z + 1) * lowerSizeX]; - if ((Left == Right) && (Above == Below)) + if ((left == right) && (above == below)) { if (((super::m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) { - val = Left; + val = left; } else { - val = Above; + val = above; } } else { - if (Left == Right) + if (left == right) { - val = Left; + val = left; } - if (Above == Below) + if (above == below) { - val = Above; + val = above; } } @@ -314,6 +318,7 @@ protected: +/** Converts land biomes at the edge of an ocean into the respective beach biome. */ class cProtIntGenBeaches : public cProtIntGen { @@ -386,14 +391,15 @@ public: for (int x = 0; x < a_SizeX; x++) { int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; - int Above = lowerValues[x + 1 + z * lowerSizeX]; - int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; - int Left = lowerValues[x + (z + 1) * lowerSizeX]; - int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + int above = lowerValues[x + 1 + z * lowerSizeX]; + int below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int left = lowerValues[x + (z + 1) * lowerSizeX]; + int right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; if (!IsBiomeOcean(val)) { - if (IsBiomeOcean(Above) || IsBiomeOcean(Below) || IsBiomeOcean(Left) || IsBiomeOcean(Right)) + if (IsBiomeOcean(above) || IsBiomeOcean(below) || IsBiomeOcean(left) || IsBiomeOcean(right)) { + // First convert the value to a regular biome (drop the M flag), then modulo by our biome count: val = ToBeach[(val % 128) % ARRAYCOUNT(ToBeach)]; } } @@ -411,7 +417,7 @@ protected: /** Generates the underlying numbers and then randomly changes some ocean group pixels into random land -group pixels, based on the predefined chance. */ +biome group pixels, based on the predefined chance. */ class cProtIntGenAddIslands : public cProtIntGenWithNoise { @@ -441,7 +447,7 @@ public: int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; if (rnd % 1000 < m_Chance) { - a_Values[x + z * a_SizeX] = (rnd / 101) % bgLandOceanMax; + a_Values[x + z * a_SizeX] = (rnd / 1003) % bgLandOceanMax; } } } @@ -575,7 +581,7 @@ public: // Define the per-biome-group biomes: static const int oceanBiomes[] = { - biOcean, // biDeepOcean, + biOcean, // biDeepOcean, }; // Same as oceanBiomes, there are no rare oceanic biomes (mushroom islands are handled separately) @@ -680,6 +686,7 @@ protected: +/** Randomly replaces pixels of one value to another value, using the given chance. */ class cProtIntGenReplaceRandomly : public cProtIntGenWithNoise { @@ -725,9 +732,15 @@ public: protected: + /** The original value to be replaced. */ int m_From; + + /** The destination value to which to replace. */ int m_To; + + /** Chance, in permille, of replacing the value. */ int m_Chance; + Underlying m_Underlying; }; @@ -736,7 +749,9 @@ protected: /** Mixer that joins together finalized biomes and rivers. -It first checks for oceans; if there's no ocean, it checks for a river. */ +It first checks for oceans, if there is an ocean in the Biomes, it keeps the ocean. +If there's no ocean, it checks Rivers for a river, if there is a river, it uses the Biomes to select either +regular river or frozen river, based on the biome. */ class cProtIntGenMixRivers: public cProtIntGen { @@ -1043,8 +1058,8 @@ protected: -/** Changes biomes in the parent data into their alternate verions ("M" variants), in such places that -have their alterations set. */ +/** Changes biomes in the parent data into an alternate versions (usually "hill" variants), in such places +that have their alterations set. */ class cProtIntGenAlternateBiomes: public cProtIntGenWithNoise { @@ -1080,7 +1095,7 @@ public: int val = a_Values[idx]; switch (val) { - case biBirchForest: val = biBirchForest; break; + case biBirchForest: val = biBirchForestHills; break; case biDesert: val = biDesertHills; break; case biExtremeHills: val = biExtremeHillsPlus; break; case biForest: val = biForestHills; break; @@ -1267,6 +1282,8 @@ protected: +/** Changes biomes in the parent data into their alternate versions ("M" variants), in such places that +have their alterations set. */ class cProtIntGenMBiomes: public cProtIntGenWithNoise { -- cgit v1.2.3 From dbed5c0726f69a2ff43a869491d93030d6d9c742 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 2 Nov 2014 16:47:56 +0100 Subject: Grown biomes: fixed Linux build. --- src/Generating/IntGen.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h index 83a0e569a..b25e378c0 100644 --- a/src/Generating/IntGen.h +++ b/src/Generating/IntGen.h @@ -1128,7 +1128,7 @@ public: { // Generate the base biomes and the alterations: m_BaseBiomes->GetInts(a_MinX, a_MinZ, a_Values); - super::Values alterations; + typename super::Values alterations; m_Alterations->GetInts(a_MinX, a_MinZ, alterations); // Change the biomes into their alternate versions: @@ -1196,7 +1196,7 @@ public: virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override { // Generate the underlying biomes: - Underlying::element_type::Values lowerValues; + typename Underlying::element_type::Values lowerValues; m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerValues); // Convert incompatible edges into neutral biomes: @@ -1358,7 +1358,7 @@ public: { // Generate the underlying biomes and the alterations: m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); - super::Values alterations; + typename super::Values alterations; m_Alteration->GetInts(a_MinX, a_MinZ, alterations); // Wherever alterations are nonzero, change into alternate biome, if available: -- cgit v1.2.3 From 9f71a4e7aec04c4c7fa57ac4b82f27a21044f798 Mon Sep 17 00:00:00 2001 From: Lukas Pioch Date: Sun, 2 Nov 2014 21:01:23 +0100 Subject: Added FindAndDoWithUUID --- src/Bindings/ManualBindings.cpp | 2 ++ src/Root.cpp | 16 ++++++++++++++++ src/Root.h | 3 +++ src/World.cpp | 22 ++++++++++++++++++++++ src/World.h | 3 +++ 5 files changed, 46 insertions(+) (limited to 'src') diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index a4a5d79b4..5343090d9 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -3368,6 +3368,7 @@ void ManualBindings::Bind(lua_State * tolua_S) tolua_beginmodule(tolua_S, "cRoot"); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith ); + tolua_function(tolua_S, "FindAndDoWithUUID", tolua_DoWith ); tolua_function(tolua_S, "ForEachPlayer", tolua_ForEach); tolua_function(tolua_S, "ForEachWorld", tolua_ForEach); tolua_function(tolua_S, "GetFurnaceRecipe", tolua_cRoot_GetFurnaceRecipe); @@ -3389,6 +3390,7 @@ void ManualBindings::Bind(lua_State * tolua_S) tolua_function(tolua_S, "DoWithFlowerPotAt", tolua_DoWithXYZ); tolua_function(tolua_S, "DoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::DoWithPlayer>); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::FindAndDoWithPlayer>); + tolua_function(tolua_S, "FindAndDoWithUUID", tolua_DoWith< cWorld, cPlayer, &cWorld::FindAndDoWithUUID>); tolua_function(tolua_S, "ForEachBlockEntityInChunk", tolua_ForEachInChunk); tolua_function(tolua_S, "ForEachChestInChunk", tolua_ForEachInChunk); tolua_function(tolua_S, "ForEachEntity", tolua_ForEach< cWorld, cEntity, &cWorld::ForEachEntity>); diff --git a/src/Root.cpp b/src/Root.cpp index 24c1a4cc8..539284665 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -633,6 +633,22 @@ bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallbac +bool cRoot::FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) +{ + for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end();itr++) + { + if (itr->second->FindAndDoWithUUID(a_PlayerUUID, a_Callback)) + { + return true; + } + } + return false; +} + + + + + AString cRoot::GetProtocolVersionTextFromInt(int a_ProtocolVersion) { return cProtocolRecognizer::GetVersionTextFromInt(a_ProtocolVersion); diff --git a/src/Root.h b/src/Root.h index 020a6cff0..456217140 100644 --- a/src/Root.h +++ b/src/Root.h @@ -125,6 +125,9 @@ public: /// Finds a player from a partial or complete player name and calls the callback - case-insensitive bool FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << + + /// Finds a player with the same uuid and call the callback */ + bool FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << // tolua_begin diff --git a/src/World.cpp b/src/World.cpp index 2e079d447..212566194 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -2729,6 +2729,28 @@ bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCa +bool cWorld::FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) +{ + cPlayer * FoundPlayer = nullptr; + cCSLock Lock(m_CSPlayers); + for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) + { + if ((*itr)->GetUUID() == a_PlayerUUID) { // Match found and exit + FoundPlayer = *itr; + break; + } + } + if (FoundPlayer != nullptr) + { + return a_Callback.Item (FoundPlayer); + } + return false; +} + + + + + // TODO: This interface is dangerous! cPlayer * cWorld::FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, bool a_CheckLineOfSight) { diff --git a/src/World.h b/src/World.h index ec6dcadde..aeb8abf81 100644 --- a/src/World.h +++ b/src/World.h @@ -323,6 +323,9 @@ public: // TODO: This interface is dangerous - rewrite to DoWithClosestPlayer(pos, sight, action) cPlayer * FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, bool a_CheckLineOfSight = true); + /** Finds a player with the same uuid and call the callback */ + bool FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << + void SendPlayerList(cPlayer * a_DestPlayer); // Sends playerlist to the player /** Adds the entity into its appropriate chunk; takes ownership of the entity ptr. -- cgit v1.2.3 From 269d76a208fcfc58c3c79d6e6a887b823d4f8f00 Mon Sep 17 00:00:00 2001 From: Lukas Pioch Date: Sun, 2 Nov 2014 21:38:17 +0100 Subject: Simplified FindAndDoWithUUID, formatted line --- src/Root.h | 2 +- src/World.cpp | 8 +------- 2 files changed, 2 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/Root.h b/src/Root.h index 456217140..f0cdf14d1 100644 --- a/src/Root.h +++ b/src/Root.h @@ -126,7 +126,7 @@ public: /// Finds a player from a partial or complete player name and calls the callback - case-insensitive bool FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << - /// Finds a player with the same uuid and call the callback */ + /// Finds a player with the same uuid and call the callback bool FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << // tolua_begin diff --git a/src/World.cpp b/src/World.cpp index 212566194..1b4f4f171 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -2731,19 +2731,13 @@ bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCa bool cWorld::FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) { - cPlayer * FoundPlayer = nullptr; cCSLock Lock(m_CSPlayers); for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { if ((*itr)->GetUUID() == a_PlayerUUID) { // Match found and exit - FoundPlayer = *itr; - break; + return a_Callback.Item (*itr); } } - if (FoundPlayer != nullptr) - { - return a_Callback.Item (FoundPlayer); - } return false; } -- cgit v1.2.3 From ca296837386f428c50206ccdea4ba63ce014f8a3 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 3 Nov 2014 08:17:19 +0100 Subject: HeiGen: Moved construction to the end of file. This will allow us to define generators in the cpp file instead of needing them in the header, thus speeding up compilation on changes. --- src/Generating/HeiGen.cpp | 150 +++++++++++++++++++++++----------------------- 1 file changed, 75 insertions(+), 75 deletions(-) (limited to 'src') diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index f4e231470..f7a26544c 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -16,81 +16,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// cTerrainHeightGen: - -cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault) -{ - AString HeightGenName = a_IniFile.GetValueSet("Generator", "HeightGen", ""); - if (HeightGenName.empty()) - { - LOGWARN("[Generator] HeightGen value not set in world.ini, using \"Biomal\"."); - HeightGenName = "Biomal"; - } - - a_CacheOffByDefault = false; - cTerrainHeightGen * res = nullptr; - if (NoCaseCompare(HeightGenName, "flat") == 0) - { - res = new cHeiGenFlat; - a_CacheOffByDefault = true; // We're generating faster than a cache would retrieve data - } - else if (NoCaseCompare(HeightGenName, "classic") == 0) - { - res = new cHeiGenClassic(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "DistortedHeightmap") == 0) - { - res = new cDistortedHeightmap(a_Seed, a_BiomeGen); - } - else if (NoCaseCompare(HeightGenName, "End") == 0) - { - res = new cEndGen(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "Mountains") == 0) - { - res = new cHeiGenMountains(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "Noise3D") == 0) - { - res = new cNoise3DComposable(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "biomal") == 0) - { - res = new cHeiGenBiomal(a_Seed, a_BiomeGen); - - /* - // Performance-testing: - LOGINFO("Measuring performance of cHeiGenBiomal..."); - clock_t BeginTick = clock(); - for (int x = 0; x < 500; x++) - { - cChunkDef::HeightMap Heights; - res->GenHeightMap(x * 5, x * 5, Heights); - } - clock_t Duration = clock() - BeginTick; - LOGINFO("HeightGen for 500 chunks took %d ticks (%.02f sec)", Duration, (double)Duration / CLOCKS_PER_SEC); - //*/ - } - else - { - // No match found, force-set the default and retry - LOGWARN("Unknown HeightGen \"%s\", using \"Biomal\" instead.", HeightGenName.c_str()); - a_IniFile.DeleteValue("Generator", "HeightGen"); - a_IniFile.SetValue("Generator", "HeightGen", "Biomal"); - return CreateHeightGen(a_IniFile, a_BiomeGen, a_Seed, a_CacheOffByDefault); - } - - // Read the settings: - res->InitializeHeightGen(a_IniFile); - - return cTerrainHeightGenPtr(res); -} - - - - - //////////////////////////////////////////////////////////////////////////////// // cHeiGenFlat: @@ -611,3 +536,78 @@ NOISE_DATATYPE cHeiGenBiomal::GetHeightAt(int a_RelX, int a_RelZ, int a_ChunkX, +//////////////////////////////////////////////////////////////////////////////// +// cTerrainHeightGen: + +cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault) +{ + AString HeightGenName = a_IniFile.GetValueSet("Generator", "HeightGen", ""); + if (HeightGenName.empty()) + { + LOGWARN("[Generator] HeightGen value not set in world.ini, using \"Biomal\"."); + HeightGenName = "Biomal"; + } + + a_CacheOffByDefault = false; + cTerrainHeightGen * res = nullptr; + if (NoCaseCompare(HeightGenName, "flat") == 0) + { + res = new cHeiGenFlat; + a_CacheOffByDefault = true; // We're generating faster than a cache would retrieve data + } + else if (NoCaseCompare(HeightGenName, "classic") == 0) + { + res = new cHeiGenClassic(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "DistortedHeightmap") == 0) + { + res = new cDistortedHeightmap(a_Seed, a_BiomeGen); + } + else if (NoCaseCompare(HeightGenName, "End") == 0) + { + res = new cEndGen(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "Mountains") == 0) + { + res = new cHeiGenMountains(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "Noise3D") == 0) + { + res = new cNoise3DComposable(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "biomal") == 0) + { + res = new cHeiGenBiomal(a_Seed, a_BiomeGen); + + /* + // Performance-testing: + LOGINFO("Measuring performance of cHeiGenBiomal..."); + clock_t BeginTick = clock(); + for (int x = 0; x < 500; x++) + { + cChunkDef::HeightMap Heights; + res->GenHeightMap(x * 5, x * 5, Heights); + } + clock_t Duration = clock() - BeginTick; + LOGINFO("HeightGen for 500 chunks took %d ticks (%.02f sec)", Duration, (double)Duration / CLOCKS_PER_SEC); + //*/ + } + else + { + // No match found, force-set the default and retry + LOGWARN("Unknown HeightGen \"%s\", using \"Biomal\" instead.", HeightGenName.c_str()); + a_IniFile.DeleteValue("Generator", "HeightGen"); + a_IniFile.SetValue("Generator", "HeightGen", "Biomal"); + return CreateHeightGen(a_IniFile, a_BiomeGen, a_Seed, a_CacheOffByDefault); + } + + // Read the settings: + res->InitializeHeightGen(a_IniFile); + + return cTerrainHeightGenPtr(res); +} + + + + + -- cgit v1.2.3 From f5c4a6a27d7c35afbbb57e0798d1473e2795ca22 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 3 Nov 2014 10:36:12 +0100 Subject: Added a (disabled) perf test for biome generators. --- src/Generating/BioGen.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 0f2b0a73d..5480d8d4c 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -5,6 +5,8 @@ #include "Globals.h" #include "BioGen.h" +#include +#include #include "IntGen.h" #include "ProtIntGen.h" #include "../IniFile.h" @@ -1199,3 +1201,47 @@ cBiomeGenPtr cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & + +//////////////////////////////////////////////////////////////////////////////// +// Performance tests: + +// Change to 1 to enable the perf test: +#if 0 + +class cBioGenPerfTest +{ +public: + cBioGenPerfTest() + { + std::cout << "BioGen performance tests commencing, please wait..." << std::endl; + TestGen("MultiStepMap", std::make_unique(1).get()); + TestGen("Grown", std::make_unique(1).get()); + TestGen("GrownProt", std::make_unique(1).get()); + std::cout << "BioGen performance tests complete." << std::endl; + } + +protected: + void TestGen(const AString && a_GenName, cBiomeGen * a_BioGen) + { + // Initialize the default settings for the generator: + cIniFile iniFile; + a_BioGen->InitializeBiomeGen(iniFile); + + // Generate the biomes: + auto start = std::chrono::system_clock::now(); + for (int z = 0; z < 100; z++) + { + for (int x = 0; x < 100; x++) + { + cChunkDef::BiomeMap biomes; + a_BioGen->GenBiomes(x, z, biomes); + } // for x + } // for z + auto dur = std::chrono::system_clock::now() - start; + double milliseconds = static_cast((std::chrono::duration_cast(dur)).count()); + + std::cout << a_GenName << ": " << 1000.0 * 100.0 * 100.0 / milliseconds << " chunks per second" << std::endl; + } +} g_BioGenPerfTest; + +#endif \ No newline at end of file -- cgit v1.2.3 From c5f3663bea6e24226217fe91402704a04f118831 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 3 Nov 2014 11:48:03 +0100 Subject: Fixed a missing endline. --- src/Generating/BioGen.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 5480d8d4c..2a4dbe794 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -1244,4 +1244,8 @@ protected: } } g_BioGenPerfTest; -#endif \ No newline at end of file +#endif + + + + -- cgit v1.2.3 From f239a28d0661cbcfa7480d81008bb66607e55742 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Tue, 4 Nov 2014 08:40:23 +0100 Subject: Added MinMax height generator. Fixes #1578. --- src/Generating/HeiGen.cpp | 207 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) (limited to 'src') diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index f7a26544c..de97bc1a0 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -536,6 +536,209 @@ NOISE_DATATYPE cHeiGenBiomal::GetHeightAt(int a_RelX, int a_RelZ, int a_ChunkX, +//////////////////////////////////////////////////////////////////////////////// +// cHeiGenMinMax: + +class cHeiGenMinMax: + public cTerrainHeightGen +{ + typedef cTerrainHeightGen super; + + /** Size of the averaging process, in columns (for each direction). Must be less than 16. */ + static const int AVERAGING_SIZE = 4; + +public: + cHeiGenMinMax(int a_Seed, cBiomeGenPtr a_BiomeGen): + m_Noise(a_Seed), + m_BiomeGen(a_BiomeGen), + m_TotalWeight(0) + { + // Initialize the weights: + for (int z = 0; z <= AVERAGING_SIZE * 2; z++) + { + for (int x = 0; x <= AVERAGING_SIZE * 2; x++) + { + m_Weights[z][x] = 1 + 2 * AVERAGING_SIZE - std::abs(x - AVERAGING_SIZE) - std::abs(z - AVERAGING_SIZE); + m_TotalWeight += m_Weights[z][x]; + } + } + + // Initialize the Perlin generator: + m_Perlin.AddOctave(0.04f, 0.2f); + m_Perlin.AddOctave(0.02f, 0.1f); + m_Perlin.AddOctave(0.01f, 0.05f); + m_Perlin.AddOctave(0.005f, 0.025f); + m_Perlin.AddOctave(0.0025f, 0.0125f); + } + + + virtual void GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) + { + // Generate the biomes for the 3*3 neighbors: + cChunkDef::BiomeMap neighborBiomes[3][3]; + for (int z = 0; z < 3; z++) for (int x = 0; x < 3; x++) + { + m_BiomeGen->GenBiomes(a_ChunkX + x - 1, a_ChunkZ + z - 1, neighborBiomes[z][x]); + } + + // Get the min and max heights based on the biomes: + double minHeight[cChunkDef::Width * cChunkDef::Width]; + double maxHeight[cChunkDef::Width * cChunkDef::Width]; + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + // For each column, sum the min and max values of the neighborhood around it: + double min = 0, max = 0; + for (int relz = 0; relz <= AVERAGING_SIZE * 2; relz++) + { + int bz = z + 16 + relz - AVERAGING_SIZE; // Biome Z coord relative to the neighborBiomes start + int cz = bz / 16; // Chunk Z coord relative to the neighborBiomes start + bz = bz % 16; // Biome Z coord relative to cz in neighborBiomes + for (int relx = 0; relx <= AVERAGING_SIZE * 2; relx++) + { + int bx = x + 16 + relx - AVERAGING_SIZE; // Biome X coord relative to the neighborBiomes start + int cx = bx / 16; // Chunk X coord relative to the neighborBiomes start + bx = bx % 16; // Biome X coord relative to cz in neighborBiomes + + // Get the biome's min and max heights: + double bmin, bmax; + getBiomeMinMax(cChunkDef::GetBiome(neighborBiomes[cz][cx], bx, bz), bmin, bmax); + + // Add them to the total, with the weight depending on their relative position to the column: + min += bmin * m_Weights[relz][relx]; + max += bmax * m_Weights[relz][relx]; + } // for relx + } // for relz + minHeight[x + z * cChunkDef::Width] = min / m_TotalWeight; + maxHeight[x + z * cChunkDef::Width] = max / m_TotalWeight; + } // for x + } // for z + + // Generate the base noise: + NOISE_DATATYPE noise[cChunkDef::Width * cChunkDef::Width]; + NOISE_DATATYPE workspace[cChunkDef::Width * cChunkDef::Width]; + NOISE_DATATYPE startX = static_cast(a_ChunkX * cChunkDef::Width); + NOISE_DATATYPE endX = startX + cChunkDef::Width - 1; + NOISE_DATATYPE startZ = static_cast(a_ChunkZ * cChunkDef::Width); + NOISE_DATATYPE endZ = startZ + cChunkDef::Width - 1; + m_Perlin.Generate2D(noise, 16, 16, startX, endX, startZ, endZ, workspace); + + // Make the height by ranging the noise between min and max: + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + double min = minHeight[x + z * cChunkDef::Width]; + double max = maxHeight[x + z * cChunkDef::Width]; + double h = (max + min) / 2 + noise[x + z * cChunkDef::Width] * (max - min); + cChunkDef::SetHeight(a_HeightMap, x, z, static_cast(h)); + } + } + } + + + virtual void InitializeHeightGen(cIniFile & a_IniFile) + { + // No settings available + } + +protected: + cNoise m_Noise; + + cPerlinNoise m_Perlin; + + /** The biome generator to query for the underlying biomes. */ + cBiomeGenPtr m_BiomeGen; + + /** Weights applied to each of the min / max values in the neighborhood of the currently evaluated column. */ + double m_Weights[AVERAGING_SIZE * 2 + 1][AVERAGING_SIZE * 2 + 1]; + + /** Sum of all the m_Weights items. */ + double m_TotalWeight; + + + /** Returns the minimum and maximum heights for the given biome. */ + void getBiomeMinMax(EMCSBiome a_Biome, double & a_Min, double & a_Max) + { + switch (a_Biome) + { + case biBeach: a_Min = 61; a_Max = 64; break; + case biBirchForest: a_Min = 63; a_Max = 75; break; + case biBirchForestHills: a_Min = 63; a_Max = 90; break; + case biBirchForestHillsM: a_Min = 63; a_Max = 90; break; + case biBirchForestM: a_Min = 63; a_Max = 75; break; + case biColdBeach: a_Min = 61; a_Max = 64; break; + case biColdTaiga: a_Min = 63; a_Max = 75; break; + case biColdTaigaHills: a_Min = 63; a_Max = 90; break; + case biColdTaigaM: a_Min = 63; a_Max = 75; break; + case biDeepOcean: a_Min = 30; a_Max = 60; break; + case biDesert: a_Min = 63; a_Max = 70; break; + case biDesertHills: a_Min = 63; a_Max = 85; break; + case biDesertM: a_Min = 63; a_Max = 70; break; + case biEnd: a_Min = 10; a_Max = 100; break; + case biExtremeHills: a_Min = 60; a_Max = 120; break; + case biExtremeHillsEdge: a_Min = 63; a_Max = 100; break; + case biExtremeHillsM: a_Min = 60; a_Max = 120; break; + case biExtremeHillsPlus: a_Min = 60; a_Max = 140; break; + case biExtremeHillsPlusM: a_Min = 60; a_Max = 140; break; + case biFlowerForest: a_Min = 63; a_Max = 75; break; + case biForest: a_Min = 63; a_Max = 75; break; + case biForestHills: a_Min = 63; a_Max = 90; break; + case biFrozenOcean: a_Min = 45; a_Max = 64; break; + case biFrozenRiver: a_Min = 60; a_Max = 62; break; + case biIceMountains: a_Min = 63; a_Max = 90; break; + case biIcePlains: a_Min = 63; a_Max = 70; break; + case biIcePlainsSpikes: a_Min = 60; a_Max = 70; break; + case biJungle: a_Min = 60; a_Max = 80; break; + case biJungleEdge: a_Min = 62; a_Max = 75; break; + case biJungleEdgeM: a_Min = 62; a_Max = 75; break; + case biJungleHills: a_Min = 60; a_Max = 90; break; + case biJungleM: a_Min = 60; a_Max = 75; break; + case biMegaSpruceTaiga: a_Min = 63; a_Max = 75; break; + case biMegaSpruceTaigaHills: a_Min = 63; a_Max = 90; break; + case biMegaTaiga: a_Min = 63; a_Max = 75; break; + case biMegaTaigaHills: a_Min = 63; a_Max = 90; break; + case biMesa: a_Min = 63; a_Max = 90; break; + case biMesaBryce: a_Min = 60; a_Max = 67; break; + case biMesaPlateau: a_Min = 75; a_Max = 85; break; + case biMesaPlateauF: a_Min = 80; a_Max = 90; break; + case biMesaPlateauFM: a_Min = 80; a_Max = 90; break; + case biMesaPlateauM: a_Min = 75; a_Max = 85; break; + case biMushroomIsland: a_Min = 63; a_Max = 90; break; + case biMushroomShore: a_Min = 60; a_Max = 75; break; + case biNether: a_Min = 10; a_Max = 100; break; + case biOcean: a_Min = 45; a_Max = 64; break; + case biPlains: a_Min = 63; a_Max = 70; break; + case biRiver: a_Min = 60; a_Max = 62; break; + case biRoofedForest: a_Min = 63; a_Max = 75; break; + case biRoofedForestM: a_Min = 63; a_Max = 75; break; + case biSavanna: a_Min = 63; a_Max = 75; break; + case biSavannaM: a_Min = 63; a_Max = 80; break; + case biSavannaPlateau: a_Min = 75; a_Max = 100; break; + case biSavannaPlateauM: a_Min = 80; a_Max = 160; break; + case biStoneBeach: a_Min = 60; a_Max = 64; break; + case biSunflowerPlains: a_Min = 63; a_Max = 70; break; + case biSwampland: a_Min = 60; a_Max = 67; break; + case biSwamplandM: a_Min = 61; a_Max = 67; break; + case biTaiga: a_Min = 63; a_Max = 75; break; + case biTaigaHills: a_Min = 63; a_Max = 90; break; + case biTaigaM: a_Min = 63; a_Max = 80; break; + default: + { + ASSERT(!"Unknown biome"); + a_Min = 10; + a_Max = 10; + break; + } + } + } +}; + + + + + //////////////////////////////////////////////////////////////////////////////// // cTerrainHeightGen: @@ -567,6 +770,10 @@ cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cB { res = new cEndGen(a_Seed); } + else if (NoCaseCompare(HeightGenName, "MinMax") == 0) + { + res = new cHeiGenMinMax(a_Seed, a_BiomeGen); + } else if (NoCaseCompare(HeightGenName, "Mountains") == 0) { res = new cHeiGenMountains(a_Seed); -- cgit v1.2.3 From 7d2b2f90b6190d8fb5280ba0dd43671cd3012f20 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Tue, 4 Nov 2014 08:41:18 +0100 Subject: MinMax heigen: Reduced the number of octaves. They didn't affect the terrain that much anyway. --- src/Generating/HeiGen.cpp | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index de97bc1a0..28a5698e4 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -567,8 +567,6 @@ public: m_Perlin.AddOctave(0.04f, 0.2f); m_Perlin.AddOctave(0.02f, 0.1f); m_Perlin.AddOctave(0.01f, 0.05f); - m_Perlin.AddOctave(0.005f, 0.025f); - m_Perlin.AddOctave(0.0025f, 0.0125f); } -- cgit v1.2.3 From 13b20d6fe29ebccc60b6be0d3baa17e0353f4a06 Mon Sep 17 00:00:00 2001 From: Lukas Pioch Date: Wed, 5 Nov 2014 21:57:38 +0100 Subject: renamed FindAndDoWithUUID to DoWithPlayerByUUID, fixed style and comments, added description to APIDump --- src/Bindings/ManualBindings.cpp | 4 ++-- src/Root.cpp | 4 ++-- src/Root.h | 4 ++-- src/World.cpp | 5 +++-- src/World.h | 4 ++-- 5 files changed, 11 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index 5343090d9..3d10e2abb 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -3368,7 +3368,7 @@ void ManualBindings::Bind(lua_State * tolua_S) tolua_beginmodule(tolua_S, "cRoot"); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith ); - tolua_function(tolua_S, "FindAndDoWithUUID", tolua_DoWith ); + tolua_function(tolua_S, "DoWithPlayerByUUID", tolua_DoWith ); tolua_function(tolua_S, "ForEachPlayer", tolua_ForEach); tolua_function(tolua_S, "ForEachWorld", tolua_ForEach); tolua_function(tolua_S, "GetFurnaceRecipe", tolua_cRoot_GetFurnaceRecipe); @@ -3390,7 +3390,7 @@ void ManualBindings::Bind(lua_State * tolua_S) tolua_function(tolua_S, "DoWithFlowerPotAt", tolua_DoWithXYZ); tolua_function(tolua_S, "DoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::DoWithPlayer>); tolua_function(tolua_S, "FindAndDoWithPlayer", tolua_DoWith< cWorld, cPlayer, &cWorld::FindAndDoWithPlayer>); - tolua_function(tolua_S, "FindAndDoWithUUID", tolua_DoWith< cWorld, cPlayer, &cWorld::FindAndDoWithUUID>); + tolua_function(tolua_S, "DoWithPlayerByUUID", tolua_DoWith< cWorld, cPlayer, &cWorld::DoWithPlayerByUUID>); tolua_function(tolua_S, "ForEachBlockEntityInChunk", tolua_ForEachInChunk); tolua_function(tolua_S, "ForEachChestInChunk", tolua_ForEachInChunk); tolua_function(tolua_S, "ForEachEntity", tolua_ForEach< cWorld, cEntity, &cWorld::ForEachEntity>); diff --git a/src/Root.cpp b/src/Root.cpp index 539284665..49d6117eb 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -633,11 +633,11 @@ bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallbac -bool cRoot::FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) +bool cRoot::DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) { for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end();itr++) { - if (itr->second->FindAndDoWithUUID(a_PlayerUUID, a_Callback)) + if (itr->second->DoWithPlayerByUUID(a_PlayerUUID, a_Callback)) { return true; } diff --git a/src/Root.h b/src/Root.h index f0cdf14d1..618f70fb8 100644 --- a/src/Root.h +++ b/src/Root.h @@ -126,8 +126,8 @@ public: /// Finds a player from a partial or complete player name and calls the callback - case-insensitive bool FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << - /// Finds a player with the same uuid and call the callback - bool FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << + /** Finds the player over his uuid and calls the callback */ + bool DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << // tolua_begin diff --git a/src/World.cpp b/src/World.cpp index 1b4f4f171..1954854f3 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -2729,12 +2729,13 @@ bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCa -bool cWorld::FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) +bool cWorld::DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) { cCSLock Lock(m_CSPlayers); for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { - if ((*itr)->GetUUID() == a_PlayerUUID) { // Match found and exit + if ((*itr)->GetUUID() == a_PlayerUUID) + { return a_Callback.Item (*itr); } } diff --git a/src/World.h b/src/World.h index aeb8abf81..f1bf9371a 100644 --- a/src/World.h +++ b/src/World.h @@ -323,8 +323,8 @@ public: // TODO: This interface is dangerous - rewrite to DoWithClosestPlayer(pos, sight, action) cPlayer * FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, bool a_CheckLineOfSight = true); - /** Finds a player with the same uuid and call the callback */ - bool FindAndDoWithUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << + /** Finds the player over his uuid and calls the callback */ + bool DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << void SendPlayerList(cPlayer * a_DestPlayer); // Sends playerlist to the player -- cgit v1.2.3 From 136d6b5c3080df039a5be047c27911c2d03c9fc5 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 6 Nov 2014 19:25:42 +0100 Subject: Noise3D CompoGen: Fixed missing initialization. --- src/Generating/Noise3DGenerator.h | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/Generating/Noise3DGenerator.h b/src/Generating/Noise3DGenerator.h index 42f61a854..c59b3f933 100644 --- a/src/Generating/Noise3DGenerator.h +++ b/src/Generating/Noise3DGenerator.h @@ -96,9 +96,11 @@ protected: // cTerrainHeightGen overrides: virtual void GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) override; + virtual void InitializeHeightGen(cIniFile & a_IniFile) override { Initialize(a_IniFile); } // cTerrainCompositionGen overrides: virtual void ComposeTerrain(cChunkDesc & a_ChunkDesc) override; + virtual void InitializeCompoGen(cIniFile & a_IniFile) override { Initialize(a_IniFile); } } ; -- cgit v1.2.3 From c43391fd8cfb50746493c103e504d38359c366b2 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 9 Nov 2014 14:33:37 +0100 Subject: Noise3D generator: rewritten from scratch. Now it uses three 3D and one 2D perlin noises to generate the terrain, and is highly parametrizable. --- src/Generating/Noise3DGenerator.cpp | 177 +++++++++++++++++++++--------------- src/Generating/Noise3DGenerator.h | 46 ++++++++-- 2 files changed, 145 insertions(+), 78 deletions(-) (limited to 'src') diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index 5a4cb44cf..4292c66e5 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -61,6 +61,35 @@ public: +/** Linearly interpolates between two values. +Assumes that a_Ratio is in range [0, 1]. */ +inline static NOISE_DATATYPE Lerp(NOISE_DATATYPE a_Val1, NOISE_DATATYPE a_Val2, NOISE_DATATYPE a_Ratio) +{ + return a_Val1 + (a_Val2 - a_Val1) * a_Ratio; +} + + + + + +/** Linearly interpolates between two values, clamping the ratio to [0, 1] first. */ +inline static NOISE_DATATYPE ClampedLerp(NOISE_DATATYPE a_Val1, NOISE_DATATYPE a_Val2, NOISE_DATATYPE a_Ratio) +{ + if (a_Ratio < 0) + { + return a_Val1; + } + if (a_Ratio > 1) + { + return a_Val2; + } + return a_Val1 + (a_Val2 - a_Val1) * a_Ratio; +} + + + + + //////////////////////////////////////////////////////////////////////////////// // cNoise3DGenerator: @@ -346,9 +375,10 @@ void cNoise3DGenerator::ComposeTerrain(cChunkDesc & a_ChunkDesc) // cNoise3DComposable: cNoise3DComposable::cNoise3DComposable(int a_Seed) : - m_Noise1(a_Seed + 1000), - m_Noise2(a_Seed + 2000), - m_Noise3(a_Seed + 3000) + m_ChoiceNoise(a_Seed), + m_DensityNoiseA(a_Seed + 1), + m_DensityNoiseB(a_Seed + 2), + m_BaseNoise(a_Seed + 3) { } @@ -359,13 +389,51 @@ cNoise3DComposable::cNoise3DComposable(int a_Seed) : void cNoise3DComposable::Initialize(cIniFile & a_IniFile) { // Params: + // The defaults generate extreme hills terrain m_SeaLevel = a_IniFile.GetValueSetI("Generator", "Noise3DSeaLevel", 62); - m_HeightAmplification = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DHeightAmplification", 0); + m_HeightAmplification = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DHeightAmplification", 0.045); m_MidPoint = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DMidPoint", 75); - m_FrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyX", 10); - m_FrequencyY = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyY", 10); - m_FrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyZ", 10); - m_AirThreshold = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DAirThreshold", 0.5); + m_FrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyX", 40); + m_FrequencyY = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyY", 40); + m_FrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DFrequencyZ", 40); + m_BaseFrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DBaseFrequencyX", 40); + m_BaseFrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DBaseFrequencyZ", 40); + m_ChoiceFrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DChoiceFrequencyX", 40); + m_ChoiceFrequencyY = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DChoiceFrequencyY", 80); + m_ChoiceFrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DChoiceFrequencyZ", 40); + m_AirThreshold = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DAirThreshold", 0); + int NumChoiceOctaves = a_IniFile.GetValueSetI("Generator", "Noise3DNumChoiceOctaves", 4); + int NumDensityOctaves = a_IniFile.GetValueSetI("Generator", "Noise3DNumDensityOctaves", 6); + int NumBaseOctaves = a_IniFile.GetValueSetI("Generator", "Noise3DNumBaseOctaves", 6); + NOISE_DATATYPE BaseNoiseAmplitude = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DBaseAmplitude", 1); + + // Add octaves for the choice noise: + NOISE_DATATYPE wavlen = 1, ampl = 0.5; + for (int i = 0; i < NumChoiceOctaves; i++) + { + m_ChoiceNoise.AddOctave(wavlen, ampl); + wavlen = wavlen * 2; + ampl = ampl / 2; + } + + // Add octaves for the density noises: + wavlen = 1, ampl = 1; + for (int i = 0; i < NumDensityOctaves; i++) + { + m_DensityNoiseA.AddOctave(wavlen, ampl); + m_DensityNoiseB.AddOctave(wavlen, ampl); + wavlen = wavlen * 2; + ampl = ampl / 2; + } + + // Add octaves for the base noise: + wavlen = 1, ampl = BaseNoiseAmplitude; + for (int i = 0; i < NumBaseOctaves; i++) + { + m_BaseNoise.AddOctave(wavlen, ampl); + wavlen = wavlen * 2; + ampl = ampl / 2; + } } @@ -382,77 +450,44 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) m_LastChunkX = a_ChunkX; m_LastChunkZ = a_ChunkZ; - // Upscaling parameters: - const int UPSCALE_X = 8; - const int UPSCALE_Y = 4; - const int UPSCALE_Z = 8; - - // Precalculate a "height" array: - NOISE_DATATYPE Height[17 * 17]; // x + 17 * z - for (int z = 0; z < 17; z += UPSCALE_Z) + // Generate all the noises: + NOISE_DATATYPE ChoiceNoise[5 * 5 * 33]; + NOISE_DATATYPE Workspace[5 * 5 * 33]; + NOISE_DATATYPE DensityNoiseA[5 * 5 * 33]; + NOISE_DATATYPE DensityNoiseB[5 * 5 * 33]; + NOISE_DATATYPE BaseNoise[5 * 5]; + NOISE_DATATYPE BlockX = static_cast(a_ChunkX * cChunkDef::Width); + NOISE_DATATYPE BlockZ = static_cast(a_ChunkZ * cChunkDef::Width); + // Note that we have to swap the coords, because noise generator uses [x + SizeX * y + SizeX * SizeY * z] ordering and we want "BlockY" to be "z": + m_ChoiceNoise.Generate3D (ChoiceNoise, 5, 5, 33, BlockX / m_ChoiceFrequencyX, (BlockX + 17) / m_ChoiceFrequencyX, BlockZ / m_ChoiceFrequencyZ, (BlockZ + 17) / m_ChoiceFrequencyZ, 0, 257 / m_ChoiceFrequencyY, Workspace); + m_DensityNoiseA.Generate3D(DensityNoiseA, 5, 5, 33, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, 0, 257 / m_FrequencyY, Workspace); + m_DensityNoiseB.Generate3D(DensityNoiseB, 5, 5, 33, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, 0, 257 / m_FrequencyY, Workspace); + m_BaseNoise.Generate2D (BaseNoise, 5, 5, BlockX / m_BaseFrequencyX, (BlockX + 17) / m_BaseFrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); + + // Calculate the final noise based on the partial noises: + for (int y = 0; y < 33; y++) { - NOISE_DATATYPE NoiseZ = ((NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width + z)) / m_FrequencyZ; - for (int x = 0; x < 17; x += UPSCALE_X) - { - NOISE_DATATYPE NoiseX = ((NOISE_DATATYPE)(a_ChunkX * cChunkDef::Width + x)) / m_FrequencyX; - NOISE_DATATYPE val = std::abs(m_Noise1.CubicNoise2D(NoiseX / 5, NoiseZ / 5)) * m_HeightAmplification + 1; - Height[x + 17 * z] = val * val * val; - } - } + NOISE_DATATYPE AddHeight = (static_cast(y * 8) - m_MidPoint) * m_HeightAmplification; - for (int y = 0; y < 257; y += UPSCALE_Y) - { - NOISE_DATATYPE NoiseY = ((NOISE_DATATYPE)y) / m_FrequencyY; - NOISE_DATATYPE AddHeight = (y - m_MidPoint) / 20; - AddHeight *= AddHeight * AddHeight; - NOISE_DATATYPE * CurFloor = &(m_NoiseArray[y * 17 * 17]); - for (int z = 0; z < 17; z += UPSCALE_Z) + // If "underground", make the terrain smoother by forcing the vertical linear gradient into steeper slope: + if (AddHeight < 0) { - NOISE_DATATYPE NoiseZ = ((NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width + z)) / m_FrequencyZ; - for (int x = 0; x < 17; x += UPSCALE_X) - { - NOISE_DATATYPE NoiseX = ((NOISE_DATATYPE)(a_ChunkX * cChunkDef::Width + x)) / m_FrequencyX; - CurFloor[x + 17 * z] = ( - m_Noise1.CubicNoise3D(NoiseX, NoiseY, NoiseZ) * (NOISE_DATATYPE)0.5 + - m_Noise2.CubicNoise3D(NoiseX / 2, NoiseY / 2, NoiseZ / 2) + - m_Noise3.CubicNoise3D(NoiseX / 4, NoiseY / 4, NoiseZ / 4) * 2 + - AddHeight / Height[x + 17 * z] - ); - } + AddHeight *= 4; } - // Linear-interpolate this XZ floor: - LinearUpscale2DArrayInPlace<17, 17, UPSCALE_X, UPSCALE_Z>(CurFloor); - } - // Finish the 3D linear interpolation by interpolating between each XZ-floors on the Y axis - for (int y = 1; y < cChunkDef::Height; y++) - { - if ((y % UPSCALE_Y) == 0) + for (int z = 0; z < 5; z++) { - // This is the interpolation source floor, already calculated - continue; - } - int LoFloorY = (y / UPSCALE_Y) * UPSCALE_Y; - int HiFloorY = LoFloorY + UPSCALE_Y; - NOISE_DATATYPE * LoFloor = &(m_NoiseArray[LoFloorY * 17 * 17]); - NOISE_DATATYPE * HiFloor = &(m_NoiseArray[HiFloorY * 17 * 17]); - NOISE_DATATYPE * CurFloor = &(m_NoiseArray[y * 17 * 17]); - NOISE_DATATYPE Ratio = ((NOISE_DATATYPE)(y % UPSCALE_Y)) / UPSCALE_Y; - int idx = 0; - for (int z = 0; z < cChunkDef::Width; z++) - { - for (int x = 0; x < cChunkDef::Width; x++) + for (int x = 0; x < 5; x++) { - CurFloor[idx] = LoFloor[idx] + (HiFloor[idx] - LoFloor[idx]) * Ratio; - idx += 1; + int idx = x + 5 * z + 5 * 5 * y; + Workspace[idx] = ClampedLerp(DensityNoiseA[idx], DensityNoiseB[idx], 8 * (ChoiceNoise[idx] + 0.5f)) + AddHeight + BaseNoise[x + 5 * z]; } - idx += 1; // Skipping one X column } } + LinearUpscale3DArray(Workspace, 5, 5, 33, m_NoiseArray, 4, 4, 8); - // The noise array is now fully interpolated - /* - // DEBUG: Output two images of the array, sliced by XY and XZ: + #if 0 + // DEBUG: Output two images of m_NoiseArray, sliced by XY and XZ, into grayscale files, to be inspected by Grabber: cFile f1; if (f1.Open(Printf("Chunk_%d_%d_XY.raw", a_ChunkX, a_ChunkZ), cFile::fmWrite)) { @@ -464,7 +499,7 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) unsigned char buf[16]; for (int x = 0; x < cChunkDef::Width; x++) { - buf[x] = (unsigned char)(std::min(256, std::max(0, (int)(128 + 128 * m_Noise[idx++])))); + buf[x] = (unsigned char)(std::min(256, std::max(0, (int)(128 + 32 * m_NoiseArray[idx++])))); } f1.Write(buf, 16); } // for y @@ -482,13 +517,13 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) unsigned char buf[16]; for (int x = 0; x < cChunkDef::Width; x++) { - buf[x] = (unsigned char)(std::min(256, std::max(0, (int)(128 + 128 * m_Noise[idx++])))); + buf[x] = (unsigned char)(std::min(256, std::max(0, (int)(128 + 32 * m_NoiseArray[idx++])))); } f2.Write(buf, 16); } // for z } // for y } // if (XZ file open) - */ + #endif } diff --git a/src/Generating/Noise3DGenerator.h b/src/Generating/Noise3DGenerator.h index c59b3f933..207aeab97 100644 --- a/src/Generating/Noise3DGenerator.h +++ b/src/Generating/Noise3DGenerator.h @@ -1,7 +1,11 @@ // Noise3DGenerator.h -// Generates terrain using 3D noise, rather than composing. Is a test. +// Declares cNoise3DGenerator and cNoise3DComposable classes, representing 3D-noise-based generators. +// They generate terrain shape by combining a lerp of two 3D noises with a vertical linear gradient +// cNoise3DGenerator is obsolete and unmaintained. +// cNoise3DComposable is used to test parameter combinations for single-biome worlds. + @@ -74,24 +78,52 @@ public: void Initialize(cIniFile & a_IniFile); protected: - cNoise m_Noise1; - cNoise m_Noise2; - cNoise m_Noise3; + /** The noise that is used to choose between density noise A and B. */ + cPerlinNoise m_ChoiceNoise; + + /** Density 3D noise, variant A. */ + cPerlinNoise m_DensityNoiseA; + + /** Density 3D noise, variant B. */ + cPerlinNoise m_DensityNoiseB; + + /** Heightmap-like noise used to provide variance for low-amplitude biomes. */ + cPerlinNoise m_BaseNoise; - int m_SeaLevel; + /** Block height of the sealevel, used for composing the terrain. */ + int m_SeaLevel; + + /** The main parameter of the generator, specifies the slope of the vertical linear gradient. + A higher value means a steeper slope and a smaller total amplitude of the generated terrain. */ NOISE_DATATYPE m_HeightAmplification; - NOISE_DATATYPE m_MidPoint; // Where the vertical "center" of the noise should be + + /** Where the vertical "center" of the noise should be, as block height. */ + NOISE_DATATYPE m_MidPoint; + + // Frequency of the 3D noise's first octave: NOISE_DATATYPE m_FrequencyX; NOISE_DATATYPE m_FrequencyY; NOISE_DATATYPE m_FrequencyZ; + + // Frequency of the base terrain noise: + NOISE_DATATYPE m_BaseFrequencyX; + NOISE_DATATYPE m_BaseFrequencyZ; + + // Frequency of the choice noise: + NOISE_DATATYPE m_ChoiceFrequencyX; + NOISE_DATATYPE m_ChoiceFrequencyY; + NOISE_DATATYPE m_ChoiceFrequencyZ; + + // Threshold for when the values are considered air: NOISE_DATATYPE m_AirThreshold; + // Cache for the last calculated chunk (reused between heightmap and composition queries): int m_LastChunkX; int m_LastChunkZ; NOISE_DATATYPE m_NoiseArray[17 * 17 * 257]; // x + 17 * z + 17 * 17 * y - /// Generates the 3D noise array used for terrain generation, unless the LastChunk coords are equal to coords given + /** Generates the 3D noise array used for terrain generation (m_NoiseArray), unless the LastChunk coords are equal to coords given */ void GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ); // cTerrainHeightGen overrides: -- cgit v1.2.3 From 5993c06bd7ab5f02aabb4790570c86699189e219 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 9 Nov 2014 15:33:01 +0100 Subject: Noise3d Generator: Fixed unused function error. --- src/Generating/Noise3DGenerator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index 4292c66e5..885a9bab3 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -83,7 +83,7 @@ inline static NOISE_DATATYPE ClampedLerp(NOISE_DATATYPE a_Val1, NOISE_DATATYPE a { return a_Val2; } - return a_Val1 + (a_Val2 - a_Val1) * a_Ratio; + return Lerp(a_Val1, a_Val2, a_Ratio); } -- cgit v1.2.3 From 4b95f7c69a1b3a3aac8855d5e026238ed0f61fa7 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 10 Nov 2014 17:00:14 +0100 Subject: Added BiomalNoise3D shape generator. --- src/Generating/ComposableGenerator.cpp | 4 + src/Generating/HeiGen.cpp | 4 + src/Generating/Noise3DGenerator.cpp | 304 +++++++++++++++++++++++++++++---- src/Generating/Noise3DGenerator.h | 86 ++++++++++ 4 files changed, 369 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 169821050..5f46574c7 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -73,6 +73,10 @@ cTerrainCompositionGenPtr cTerrainCompositionGen::CreateCompositionGen(cIniFile { res = new cCompoGenNether(a_Seed); } + else if (NoCaseCompare(CompoGenName, "BiomalNoise3D") == 0) + { + res = new cBiomalNoise3DComposable(a_Seed, a_BiomeGen); + } else if (NoCaseCompare(CompoGenName, "Noise3D") == 0) { res = new cNoise3DComposable(a_Seed); diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index 28a5698e4..1d9f1e3aa 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -776,6 +776,10 @@ cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cB { res = new cHeiGenMountains(a_Seed); } + else if (NoCaseCompare(HeightGenName, "BiomalNoise3D") == 0) + { + res = new cBiomalNoise3DComposable(a_Seed, a_BiomeGen); + } else if (NoCaseCompare(HeightGenName, "Noise3D") == 0) { res = new cNoise3DComposable(a_Seed); diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index 885a9bab3..3f50ea0e9 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -444,7 +444,7 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) { if ((a_ChunkX == m_LastChunkX) && (a_ChunkZ == m_LastChunkZ)) { - // The noise for this chunk is already generated in m_Noise + // The noise for this chunk is already generated in m_NoiseArray return; } m_LastChunkX = a_ChunkX; @@ -485,52 +485,298 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) } } LinearUpscale3DArray(Workspace, 5, 5, 33, m_NoiseArray, 4, 4, 8); +} - #if 0 - // DEBUG: Output two images of m_NoiseArray, sliced by XY and XZ, into grayscale files, to be inspected by Grabber: - cFile f1; - if (f1.Open(Printf("Chunk_%d_%d_XY.raw", a_ChunkX, a_ChunkZ), cFile::fmWrite)) + + + + +void cNoise3DComposable::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) +{ + GenerateNoiseArrayIfNeeded(a_ChunkX, a_ChunkZ); + + for (int z = 0; z < cChunkDef::Width; z++) { - for (int z = 0; z < cChunkDef::Width; z++) + for (int x = 0; x < cChunkDef::Width; x++) { - for (int y = 0; y < cChunkDef::Height; y++) + cChunkDef::SetHeight(a_HeightMap, x, z, m_SeaLevel); + for (int y = cChunkDef::Height - 1; y > m_SeaLevel; y--) { - int idx = y * 17 * 17 + z * 17; - unsigned char buf[16]; - for (int x = 0; x < cChunkDef::Width; x++) + if (m_NoiseArray[y * 17 * 17 + z * 17 + x] <= m_AirThreshold) { - buf[x] = (unsigned char)(std::min(256, std::max(0, (int)(128 + 32 * m_NoiseArray[idx++])))); + cChunkDef::SetHeight(a_HeightMap, x, z, y); + break; } - f1.Write(buf, 16); } // for y - } // for z - } // if (XY file open) + } // for x + } // for z +} - cFile f2; - if (f2.Open(Printf("Chunk_%d_%d_XZ.raw", a_ChunkX, a_ChunkZ), cFile::fmWrite)) + + + + +void cNoise3DComposable::ComposeTerrain(cChunkDesc & a_ChunkDesc) +{ + GenerateNoiseArrayIfNeeded(a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ()); + + a_ChunkDesc.FillBlocks(E_BLOCK_AIR, 0); + + // Make basic terrain composition: + for (int z = 0; z < cChunkDef::Width; z++) { - for (int y = 0; y < cChunkDef::Height; y++) + for (int x = 0; x < cChunkDef::Width; x++) { - for (int z = 0; z < cChunkDef::Width; z++) + int LastAir = a_ChunkDesc.GetHeight(x, z) + 1; + bool HasHadWater = false; + for (int y = LastAir; y < m_SeaLevel; y++) { - int idx = y * 17 * 17 + z * 17; - unsigned char buf[16]; - for (int x = 0; x < cChunkDef::Width; x++) + a_ChunkDesc.SetBlockType(x, y, z, E_BLOCK_STATIONARY_WATER); + } + for (int y = LastAir - 1; y > 0; y--) + { + if (m_NoiseArray[x + 17 * z + 17 * 17 * y] > m_AirThreshold) { - buf[x] = (unsigned char)(std::min(256, std::max(0, (int)(128 + 32 * m_NoiseArray[idx++])))); + // "air" part + LastAir = y; + if (y < m_SeaLevel) + { + a_ChunkDesc.SetBlockType(x, y, z, E_BLOCK_STATIONARY_WATER); + HasHadWater = true; + } + continue; } - f2.Write(buf, 16); - } // for z - } // for y - } // if (XZ file open) - #endif + // "ground" part: + if (LastAir - y > 4) + { + a_ChunkDesc.SetBlockType(x, y, z, E_BLOCK_STONE); + continue; + } + if (HasHadWater) + { + a_ChunkDesc.SetBlockType(x, y, z, E_BLOCK_SAND); + } + else + { + a_ChunkDesc.SetBlockType(x, y, z, (LastAir == y + 1) ? E_BLOCK_GRASS : E_BLOCK_DIRT); + } + } // for y + a_ChunkDesc.SetBlockType(x, 0, z, E_BLOCK_BEDROCK); + } // for x + } // for z } -void cNoise3DComposable::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) +//////////////////////////////////////////////////////////////////////////////// +// cBiomalNoise3DComposable: + +cBiomalNoise3DComposable::cBiomalNoise3DComposable(int a_Seed, cBiomeGenPtr a_BiomeGen) : + m_ChoiceNoise(a_Seed), + m_DensityNoiseA(a_Seed + 1), + m_DensityNoiseB(a_Seed + 2), + m_BaseNoise(a_Seed + 3), + m_BiomeGen(a_BiomeGen) +{ + // Generate the weight distribution for summing up neighboring biomes: + m_WeightSum = 0; + for (int z = 0; z <= AVERAGING_SIZE * 2; z++) + { + for (int x = 0; x <= AVERAGING_SIZE * 2; x++) + { + m_Weight[z][x] = static_cast((5 - std::abs(5 - x)) + (5 - std::abs(5 - z))); + m_WeightSum += m_Weight[z][x]; + } + } +} + + + + + +void cBiomalNoise3DComposable::Initialize(cIniFile & a_IniFile) +{ + // Params: + // The defaults generate extreme hills terrain + m_SeaLevel = a_IniFile.GetValueSetI("Generator", "BiomalNoise3DSeaLevel", 62); + m_FrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DFrequencyX", 40); + m_FrequencyY = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DFrequencyY", 40); + m_FrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DFrequencyZ", 40); + m_BaseFrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DBaseFrequencyX", 40); + m_BaseFrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DBaseFrequencyZ", 40); + m_ChoiceFrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DChoiceFrequencyX", 40); + m_ChoiceFrequencyY = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DChoiceFrequencyY", 80); + m_ChoiceFrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DChoiceFrequencyZ", 40); + m_AirThreshold = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DAirThreshold", 0); + int NumChoiceOctaves = a_IniFile.GetValueSetI("Generator", "BiomalNoise3DNumChoiceOctaves", 4); + int NumDensityOctaves = a_IniFile.GetValueSetI("Generator", "BiomalNoise3DNumDensityOctaves", 6); + int NumBaseOctaves = a_IniFile.GetValueSetI("Generator", "BiomalNoise3DNumBaseOctaves", 6); + NOISE_DATATYPE BaseNoiseAmplitude = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "BiomalNoise3DBaseAmplitude", 1); + + // Add octaves for the choice noise: + NOISE_DATATYPE wavlen = 1, ampl = 0.5; + for (int i = 0; i < NumChoiceOctaves; i++) + { + m_ChoiceNoise.AddOctave(wavlen, ampl); + wavlen = wavlen * 2; + ampl = ampl / 2; + } + + // Add octaves for the density noises: + wavlen = 1, ampl = 1; + for (int i = 0; i < NumDensityOctaves; i++) + { + m_DensityNoiseA.AddOctave(wavlen, ampl); + m_DensityNoiseB.AddOctave(wavlen, ampl); + wavlen = wavlen * 2; + ampl = ampl / 2; + } + + // Add octaves for the base noise: + wavlen = 1, ampl = BaseNoiseAmplitude; + for (int i = 0; i < NumBaseOctaves; i++) + { + m_BaseNoise.AddOctave(wavlen, ampl); + wavlen = wavlen * 2; + ampl = ampl / 2; + } +} + + + + + +void cBiomalNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ) +{ + if ((a_ChunkX == m_LastChunkX) && (a_ChunkZ == m_LastChunkZ)) + { + // The noise for this chunk is already generated in m_NoiseArray + return; + } + m_LastChunkX = a_ChunkX; + m_LastChunkZ = a_ChunkZ; + + // Calculate the parameters for the biomes: + ChunkParam MidPoint; + ChunkParam HeightAmp; + CalcBiomeParamArrays(a_ChunkX, a_ChunkZ, HeightAmp, MidPoint); + + // Generate all the noises: + NOISE_DATATYPE ChoiceNoise[5 * 5 * 33]; + NOISE_DATATYPE Workspace[5 * 5 * 33]; + NOISE_DATATYPE DensityNoiseA[5 * 5 * 33]; + NOISE_DATATYPE DensityNoiseB[5 * 5 * 33]; + NOISE_DATATYPE BaseNoise[5 * 5]; + NOISE_DATATYPE BlockX = static_cast(a_ChunkX * cChunkDef::Width); + NOISE_DATATYPE BlockZ = static_cast(a_ChunkZ * cChunkDef::Width); + // Note that we have to swap the coords, because noise generator uses [x + SizeX * y + SizeX * SizeY * z] ordering and we want "BlockY" to be "z": + m_ChoiceNoise.Generate3D (ChoiceNoise, 5, 5, 33, BlockX / m_ChoiceFrequencyX, (BlockX + 17) / m_ChoiceFrequencyX, BlockZ / m_ChoiceFrequencyZ, (BlockZ + 17) / m_ChoiceFrequencyZ, 0, 257 / m_ChoiceFrequencyY, Workspace); + m_DensityNoiseA.Generate3D(DensityNoiseA, 5, 5, 33, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, 0, 257 / m_FrequencyY, Workspace); + m_DensityNoiseB.Generate3D(DensityNoiseB, 5, 5, 33, BlockX / m_FrequencyX, (BlockX + 17) / m_FrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, 0, 257 / m_FrequencyY, Workspace); + m_BaseNoise.Generate2D (BaseNoise, 5, 5, BlockX / m_BaseFrequencyX, (BlockX + 17) / m_BaseFrequencyX, BlockZ / m_FrequencyZ, (BlockZ + 17) / m_FrequencyZ, Workspace); + + // Calculate the final noise based on the partial noises: + for (int y = 0; y < 33; y++) + { + NOISE_DATATYPE BlockHeight = static_cast(y * 8); + for (int z = 0; z < 5; z++) + { + for (int x = 0; x < 5; x++) + { + NOISE_DATATYPE AddHeight = (BlockHeight - MidPoint[x + 5 * z]) * HeightAmp[x + 5 * z]; + + // If "underground", make the terrain smoother by forcing the vertical linear gradient into steeper slope: + if (AddHeight < 0) + { + AddHeight *= 4; + } + + int idx = x + 5 * z + 5 * 5 * y; + Workspace[idx] = ClampedLerp(DensityNoiseA[idx], DensityNoiseB[idx], 8 * (ChoiceNoise[idx] + 0.5f)) + AddHeight + BaseNoise[x + 5 * z]; + } + } + } + LinearUpscale3DArray(Workspace, 5, 5, 33, m_NoiseArray, 4, 4, 8); +} + + + + + +void cBiomalNoise3DComposable::CalcBiomeParamArrays(int a_ChunkX, int a_ChunkZ, ChunkParam & a_HeightAmp, ChunkParam & a_MidPoint) +{ + // Generate the 3*3 chunks of biomes around this chunk: + cChunkDef::BiomeMap neighborBiomes[3 * 3]; + for (int z = 0; z < 3; z++) + { + for (int x = 0; x < 3; x++) + { + m_BiomeGen->GenBiomes(a_ChunkX + x - 1, a_ChunkZ + z - 1, neighborBiomes[x + 3 * z]); + } + } + + // Sum up the biome values: + for (int z = 0; z < 5; z++) + { + for (int x = 0; x < 5; x++) + { + NOISE_DATATYPE totalHeightAmp = 0; + NOISE_DATATYPE totalMidPoint = 0; + // Add up the biomes around this point: + for (int relz = 0; relz <= AVERAGING_SIZE * 2; ++relz) + { + int colz = 16 + z * 4 + relz - AVERAGING_SIZE; // Biome Z coord relative to the neighborBiomes start + int neicellz = colz / 16; // Chunk Z coord relative to the neighborBiomes start + int neirelz = colz % 16; // Biome Z coord relative to cz in neighborBiomes + for (int relx = 0; relx <= AVERAGING_SIZE * 2; ++relx) + { + int colx = 16 + x * 4 + relx - AVERAGING_SIZE; // Biome X coord relative to the neighborBiomes start + int neicellx = colx / 16; // Chunk X coord relative to the neighborBiomes start + int neirelx = colx % 16; // Biome X coord relative to cz in neighborBiomes + EMCSBiome biome = cChunkDef::GetBiome(neighborBiomes[neicellx + neicellz * 3], neirelx, neirelz); + NOISE_DATATYPE heightAmp, midPoint; + GetBiomeParams(biome, heightAmp, midPoint); + totalHeightAmp += heightAmp * m_Weight[relz][relx]; + totalMidPoint += midPoint * m_Weight[relz][relx]; + } // for relx + } // for relz + a_HeightAmp[x + 5 * z] = totalHeightAmp / m_WeightSum; + a_MidPoint[x + 5 * z] = totalMidPoint / m_WeightSum; + } // for x + } // for z +} + + + + + +void cBiomalNoise3DComposable::GetBiomeParams(EMCSBiome a_Biome, NOISE_DATATYPE & a_HeightAmp, NOISE_DATATYPE & a_MidPoint) +{ + switch (a_Biome) + { + case biDesert: a_HeightAmp = 0.29f; a_MidPoint = 62; break; // Needs verification + case biExtremeHills: a_HeightAmp = 0.045f; a_MidPoint = 75; break; + case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; // Needs verification + case biSwampland: a_HeightAmp = 0.25f; a_MidPoint = 59; break; + case biSwamplandM: a_HeightAmp = 0.11f; a_MidPoint = 59; break; + + default: + { + // Make a crazy terrain so that it stands out + a_HeightAmp = 0.001f; + a_MidPoint = 90; + break; + } + } +} + + + + + +void cBiomalNoise3DComposable::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) { GenerateNoiseArrayIfNeeded(a_ChunkX, a_ChunkZ); @@ -555,7 +801,7 @@ void cNoise3DComposable::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Hei -void cNoise3DComposable::ComposeTerrain(cChunkDesc & a_ChunkDesc) +void cBiomalNoise3DComposable::ComposeTerrain(cChunkDesc & a_ChunkDesc) { GenerateNoiseArrayIfNeeded(a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ()); diff --git a/src/Generating/Noise3DGenerator.h b/src/Generating/Noise3DGenerator.h index 207aeab97..ba541fbcc 100644 --- a/src/Generating/Noise3DGenerator.h +++ b/src/Generating/Noise3DGenerator.h @@ -138,3 +138,89 @@ protected: + +class cBiomalNoise3DComposable : + public cTerrainHeightGen, + public cTerrainCompositionGen +{ +public: + cBiomalNoise3DComposable(int a_Seed, cBiomeGenPtr a_BiomeGen); + + void Initialize(cIniFile & a_IniFile); + +protected: + /** Number of columns around the pixel to query for biomes for averaging. */ + static const int AVERAGING_SIZE = 5; + + /** Type used for a single parameter across the entire (downscaled) chunk. */ + typedef NOISE_DATATYPE ChunkParam[5 * 5]; + + + /** The noise that is used to choose between density noise A and B. */ + cPerlinNoise m_ChoiceNoise; + + /** Density 3D noise, variant A. */ + cPerlinNoise m_DensityNoiseA; + + /** Density 3D noise, variant B. */ + cPerlinNoise m_DensityNoiseB; + + /** Heightmap-like noise used to provide variance for low-amplitude biomes. */ + cPerlinNoise m_BaseNoise; + + /** The underlying biome generator. */ + cBiomeGenPtr m_BiomeGen; + + /** Block height of the sealevel, used for composing the terrain. */ + int m_SeaLevel; + + // Frequency of the 3D noise's first octave: + NOISE_DATATYPE m_FrequencyX; + NOISE_DATATYPE m_FrequencyY; + NOISE_DATATYPE m_FrequencyZ; + + // Frequency of the base terrain noise: + NOISE_DATATYPE m_BaseFrequencyX; + NOISE_DATATYPE m_BaseFrequencyZ; + + // Frequency of the choice noise: + NOISE_DATATYPE m_ChoiceFrequencyX; + NOISE_DATATYPE m_ChoiceFrequencyY; + NOISE_DATATYPE m_ChoiceFrequencyZ; + + // Threshold for when the values are considered air: + NOISE_DATATYPE m_AirThreshold; + + // Cache for the last calculated chunk (reused between heightmap and composition queries): + int m_LastChunkX; + int m_LastChunkZ; + NOISE_DATATYPE m_NoiseArray[17 * 17 * 257]; // x + 17 * z + 17 * 17 * y + + /** Weights for summing up neighboring biomes. */ + NOISE_DATATYPE m_Weight[AVERAGING_SIZE * 2 + 1][AVERAGING_SIZE * 2 + 1]; + + /** The sum of m_Weight[]. */ + NOISE_DATATYPE m_WeightSum; + + + /** Generates the 3D noise array used for terrain generation (m_NoiseArray), unless the LastChunk coords are equal to coords given */ + void GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ); + + /** Calculates the biome-related parameters for the chunk. */ + void CalcBiomeParamArrays(int a_ChunkX, int a_ChunkZ, ChunkParam & a_HeightAmp, ChunkParam & a_MidPoint); + + /** Returns the parameters for the specified biome. */ + void GetBiomeParams(EMCSBiome a_Biome, NOISE_DATATYPE & a_HeightAmp, NOISE_DATATYPE & a_MidPoint); + + // cTerrainHeightGen overrides: + virtual void GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) override; + virtual void InitializeHeightGen(cIniFile & a_IniFile) override { Initialize(a_IniFile); } + + // cTerrainCompositionGen overrides: + virtual void ComposeTerrain(cChunkDesc & a_ChunkDesc) override; + virtual void InitializeCompoGen(cIniFile & a_IniFile) override { Initialize(a_IniFile); } +} ; + + + + -- cgit v1.2.3 From 9a50a1fe0cc641a4ec931d733702b775292a6ab6 Mon Sep 17 00:00:00 2001 From: STRWarrior Date: Mon, 10 Nov 2014 21:55:13 +0100 Subject: TallGrassGenerator: Fixed crash when too high --- src/Generating/FinishGen.cpp | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/Generating/FinishGen.cpp b/src/Generating/FinishGen.cpp index 18f8ee2bc..b8afac09a 100644 --- a/src/Generating/FinishGen.cpp +++ b/src/Generating/FinishGen.cpp @@ -199,6 +199,11 @@ void cFinishGenTallGrass::GenFinish(cChunkDesc & a_ChunkDesc) // Get the top block + 1. This is the place where the grass would finaly be placed: int y = a_ChunkDesc.GetHeight(x, z) + 1; + + if (y >= 255) + { + continue; + } // Check if long grass can be placed: if ( -- cgit v1.2.3 From b525eee8e001676d54cf43cb6c74794a60038a5c Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 10 Nov 2014 22:08:07 +0100 Subject: BiomalNoise3D: Added a few biomes. --- src/Generating/Noise3DGenerator.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index 3f50ea0e9..4e45aa18b 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -756,11 +756,14 @@ void cBiomalNoise3DComposable::GetBiomeParams(EMCSBiome a_Biome, NOISE_DATATYPE { switch (a_Biome) { - case biDesert: a_HeightAmp = 0.29f; a_MidPoint = 62; break; // Needs verification - case biExtremeHills: a_HeightAmp = 0.045f; a_MidPoint = 75; break; - case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; // Needs verification - case biSwampland: a_HeightAmp = 0.25f; a_MidPoint = 59; break; - case biSwamplandM: a_HeightAmp = 0.11f; a_MidPoint = 59; break; + case biDesert: a_HeightAmp = 0.29f; a_MidPoint = 62; break; // Needs verification + case biExtremeHills: a_HeightAmp = 0.045f; a_MidPoint = 75; break; + case biExtremeHillsPlus: a_HeightAmp = 0.04f; a_MidPoint = 80; break; + case biFrozenRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; + case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; // Needs verification + case biRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; + case biSwampland: a_HeightAmp = 0.25f; a_MidPoint = 59; break; + case biSwamplandM: a_HeightAmp = 0.11f; a_MidPoint = 59; break; default: { -- cgit v1.2.3 From c9a3cb4d3f9fa9262b5adf775a8af0cc39234f5e Mon Sep 17 00:00:00 2001 From: Mattes D Date: Wed, 12 Nov 2014 21:59:42 +0100 Subject: Fixed trailing whitespace. --- src/Root.cpp | 2 +- src/Root.h | 2 +- src/World.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Root.cpp b/src/Root.cpp index 49d6117eb..55e1c1156 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -634,7 +634,7 @@ bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallbac bool cRoot::DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback) -{ +{ for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end();itr++) { if (itr->second->DoWithPlayerByUUID(a_PlayerUUID, a_Callback)) diff --git a/src/Root.h b/src/Root.h index 618f70fb8..ec6b83fcc 100644 --- a/src/Root.h +++ b/src/Root.h @@ -125,7 +125,7 @@ public: /// Finds a player from a partial or complete player name and calls the callback - case-insensitive bool FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << - + /** Finds the player over his uuid and calls the callback */ bool DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << diff --git a/src/World.h b/src/World.h index f1bf9371a..1a9f60a5c 100644 --- a/src/World.h +++ b/src/World.h @@ -325,7 +325,7 @@ public: /** Finds the player over his uuid and calls the callback */ bool DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback); // >> EXPORTED IN MANUALBINDINGS << - + void SendPlayerList(cPlayer * a_DestPlayer); // Sends playerlist to the player /** Adds the entity into its appropriate chunk; takes ownership of the entity ptr. -- cgit v1.2.3 From 2789fafeb7445a69ccd31e7867e5c9f27654725f Mon Sep 17 00:00:00 2001 From: Mattes D Date: Thu, 13 Nov 2014 21:47:39 +0100 Subject: Noise3D: Added oceans. --- src/Generating/Noise3DGenerator.cpp | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index 4e45aa18b..d516b612c 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -756,10 +756,13 @@ void cBiomalNoise3DComposable::GetBiomeParams(EMCSBiome a_Biome, NOISE_DATATYPE { switch (a_Biome) { + case biDeepOcean: a_HeightAmp = 0.17f; a_MidPoint = 35; break; case biDesert: a_HeightAmp = 0.29f; a_MidPoint = 62; break; // Needs verification case biExtremeHills: a_HeightAmp = 0.045f; a_MidPoint = 75; break; case biExtremeHillsPlus: a_HeightAmp = 0.04f; a_MidPoint = 80; break; case biFrozenRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; + case biFrozenOcean: a_HeightAmp = 0.17f; a_MidPoint = 47; break; + case biOcean: a_HeightAmp = 0.17f; a_MidPoint = 47; break; case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; // Needs verification case biRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; case biSwampland: a_HeightAmp = 0.25f; a_MidPoint = 59; break; -- cgit v1.2.3 From 644240a0e5b03889fb202ff173337cdf389d197b Mon Sep 17 00:00:00 2001 From: Mattes D Date: Fri, 14 Nov 2014 22:17:11 +0100 Subject: Noise3D: Added jungles. --- src/Generating/Noise3DGenerator.cpp | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index d516b612c..91bdce458 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -762,6 +762,8 @@ void cBiomalNoise3DComposable::GetBiomeParams(EMCSBiome a_Biome, NOISE_DATATYPE case biExtremeHillsPlus: a_HeightAmp = 0.04f; a_MidPoint = 80; break; case biFrozenRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; case biFrozenOcean: a_HeightAmp = 0.17f; a_MidPoint = 47; break; + case biJungle: a_HeightAmp = 0.1f; a_MidPoint = 63; break; + case biJungleM: a_HeightAmp = 0.1f; a_MidPoint = 63; break; case biOcean: a_HeightAmp = 0.17f; a_MidPoint = 47; break; case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; // Needs verification case biRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; -- cgit v1.2.3 From 83d3f3347b5c812b06be87804b7582a92d0294d3 Mon Sep 17 00:00:00 2001 From: Howaner Date: Fri, 14 Nov 2014 22:53:12 +0100 Subject: Use m_UsedViewDistance and m_SetViewDistance. --- src/ClientHandle.cpp | 18 ++++++++++-------- src/ClientHandle.h | 20 +++++++++++++------- src/Entities/Player.cpp | 3 +++ 3 files changed, 26 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index d7d97c6c4..d5882da06 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -65,7 +65,8 @@ int cClientHandle::s_ClientCount = 0; // cClientHandle: cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : - m_ViewDistance(a_ViewDistance), + m_UsedViewDistance(a_ViewDistance), + m_SetViewDistance(a_ViewDistance), m_IPString(a_Socket->GetIPString()), m_OutgoingData(64 KiB), m_Player(nullptr), @@ -430,7 +431,7 @@ bool cClientHandle::StreamNextChunk(void) cCSLock Lock(m_CSChunkLists); // High priority: Load the chunks that are in the view-direction of the player (with a radius of 3) - for (int Range = 0; Range < m_ViewDistance; Range++) + for (int Range = 0; Range < m_UsedViewDistance; Range++) { Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; @@ -447,7 +448,7 @@ bool cClientHandle::StreamNextChunk(void) cChunkCoords Coords(ChunkX, ChunkZ); // Checks if the chunk is in distance - if ((Diff(ChunkX, ChunkPosX) > m_ViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_ViewDistance)) + if ((Diff(ChunkX, ChunkPosX) > m_UsedViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_UsedViewDistance)) { continue; } @@ -470,7 +471,7 @@ bool cClientHandle::StreamNextChunk(void) } // Low priority: Add all chunks that are in range. (From the center out to the edge) - for (int d = 0; d <= m_ViewDistance; ++d) // cycle through (square) distance, from nearest to furthest + for (int d = 0; d <= m_UsedViewDistance; ++d) // cycle through (square) distance, from nearest to furthest { // For each distance add chunks in a hollow square centered around current position: cChunkCoordsList CurcleChunks; @@ -528,7 +529,7 @@ void cClientHandle::UnloadOutOfRangeChunks(void) { int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); - if ((DiffX > m_ViewDistance) || (DiffZ > m_ViewDistance)) + if ((DiffX > m_UsedViewDistance) || (DiffZ > m_UsedViewDistance)) { ChunksToRemove.push_back(*itr); itr = m_LoadedChunks.erase(itr); @@ -543,7 +544,7 @@ void cClientHandle::UnloadOutOfRangeChunks(void) { int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); - if ((DiffX > m_ViewDistance) || (DiffZ > m_ViewDistance)) + if ((DiffX > m_UsedViewDistance) || (DiffZ > m_UsedViewDistance)) { itr = m_ChunksToSend.erase(itr); } @@ -2849,8 +2850,9 @@ void cClientHandle::SetViewDistance(int a_ViewDistance) { ASSERT(m_Player->GetWorld() == NULL); - m_ViewDistance = Clamp(a_ViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); - LOGD("Setted %s's view distance to %i", GetUsername().c_str(), m_ViewDistance); + m_SetViewDistance = a_ViewDistance; + m_UsedViewDistance = Clamp(m_SetViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); + LOGD("Setted view distance from %s to %i!", GetUsername().c_str(), m_UsedViewDistance); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 082ed2fcc..20789621d 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -217,9 +217,15 @@ public: inline short GetPing(void) const { return m_Ping; } + /** Sets the maximal view distance. */ void SetViewDistance(int a_ViewDistance); - int GetViewDistance(void) const { return m_ViewDistance; } - + + /** Returns the view distance that the player currently have. */ + int GetViewDistance(void) const { return m_UsedViewDistance; } + + /** Returns the view distance that the player set, not the used view distance. */ + int GetSettedViewDistance(void) const { return m_SetViewDistance; } + void SetLocale(AString & a_Locale) { m_Locale = a_Locale; } AString GetLocale(void) const { return m_Locale; } @@ -334,11 +340,11 @@ private: typedef std::set cChannels; /** Number of chunks the player can see in each direction */ - int m_ViewDistance; - - /** Server generates this many chunks AHEAD of player sight. */ - static const int GENERATEDISTANCE = 2; - + int m_UsedViewDistance; + + /** The original view distance from the player. It isn't clamped with 1 and the max view distance of the world. */ + int m_SetViewDistance; + AString m_IPString; AString m_Username; diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index 5c18d8f96..1fe14ff65 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -1602,6 +1602,9 @@ bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) a_World->AddPlayer(this); SetWorld(a_World); // Chunks may be streamed before cWorld::AddPlayer() sets the world to the new value + // Update the view distance. + m_ClientHandle->SetViewDistance(m_ClientHandle->GetSettedViewDistance()); + return true; } -- cgit v1.2.3 From 8c3c11d6b33c8ff71ad3f4e2c6ca67fc835dea33 Mon Sep 17 00:00:00 2001 From: Howaner Date: Sat, 15 Nov 2014 14:27:50 +0100 Subject: Renamed GetSettedViewDistance() to GetRequestedViewDistance() --- src/ClientHandle.h | 4 ++-- src/Entities/Player.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 20789621d..db386d8a3 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -223,8 +223,8 @@ public: /** Returns the view distance that the player currently have. */ int GetViewDistance(void) const { return m_UsedViewDistance; } - /** Returns the view distance that the player set, not the used view distance. */ - int GetSettedViewDistance(void) const { return m_SetViewDistance; } + /** Returns the view distance that the player request, not the used view distance. */ + int GetRequestedViewDistance(void) const { return m_SetViewDistance; } void SetLocale(AString & a_Locale) { m_Locale = a_Locale; } AString GetLocale(void) const { return m_Locale; } diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index 1fe14ff65..edcdb4799 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -1603,7 +1603,7 @@ bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) SetWorld(a_World); // Chunks may be streamed before cWorld::AddPlayer() sets the world to the new value // Update the view distance. - m_ClientHandle->SetViewDistance(m_ClientHandle->GetSettedViewDistance()); + m_ClientHandle->SetViewDistance(m_ClientHandle->GetRequestedViewDistance()); return true; } -- cgit v1.2.3 From 78fb7896313f2074fa814309901e30d4a4f218e2 Mon Sep 17 00:00:00 2001 From: Howaner Date: Sat, 15 Nov 2014 15:16:52 +0100 Subject: Fixed a security problem with signs. --- src/Bindings/ManualBindings.cpp | 2 +- src/ClientHandle.cpp | 9 +++++++-- src/ClientHandle.h | 6 ++++++ src/World.cpp | 12 +++--------- src/World.h | 5 +---- 5 files changed, 18 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index 3d10e2abb..e259e2e91 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -1038,7 +1038,7 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) } #endif { - bool res = self->UpdateSign(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player); + bool res = self->SetSignLines(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player); tolua_pushboolean(tolua_S, res ? 1 : 0); } } diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 94bace43a..9bf4875e2 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -93,6 +93,7 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_UniqueID(0), m_HasSentPlayerChunk(false), m_Locale("en_GB"), + m_LastPlacedBlock(0, -1, 0), m_ProtocolVersion(0) { m_Protocol = new cProtocolRecognizer(this); @@ -1500,6 +1501,8 @@ void cClientHandle::HandlePlaceBlock(int a_BlockX, int a_BlockY, int a_BlockZ, e { m_Player->GetInventory().RemoveOneEquippedItem(); } + m_LastPlacedBlock.Set(a_BlockX, a_BlockY, a_BlockZ); + cChunkInterface ChunkInterface(World->GetChunkMap()); NewBlock->OnPlacedByPlayer(ChunkInterface, *World, m_Player, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_CursorX, a_CursorY, a_CursorZ, BlockType, BlockMeta); @@ -1677,8 +1680,10 @@ void cClientHandle::HandleUpdateSign( const AString & a_Line3, const AString & a_Line4 ) { - cWorld * World = m_Player->GetWorld(); - World->UpdateSign(a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, m_Player); + if (m_LastPlacedBlock.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) + { + m_Player->GetWorld()->SetSignLines(a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, m_Player); + } } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 082ed2fcc..a0dd4ff7a 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -125,6 +125,9 @@ public: inline bool IsLoggedIn(void) const { return (m_State >= csAuthenticating); } + /** Returns the positions from the last block that the player placed. */ + const Vector3i & GetLastPlacedBlock(void) const { return m_LastPlacedBlock; } // tolua_export + /** Called while the client is being ticked from the world via its cPlayer object */ void Tick(float a_Dt); @@ -432,6 +435,9 @@ private: /** Client Settings */ AString m_Locale; + + /** The positions from the last block that the player placed. It's needed to verify the sign text change. */ + Vector3i m_LastPlacedBlock; /** The plugin channels that the client has registered. */ cChannels m_PluginChannels; diff --git a/src/World.cpp b/src/World.cpp index 68855e617..3178d41a6 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -2926,25 +2926,19 @@ bool cWorld::SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AStrin AString Line2(a_Line2); AString Line3(a_Line3); AString Line4(a_Line4); + if (cRoot::Get()->GetPluginManager()->CallHookUpdatingSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player)) { return false; } + if (m_ChunkMap->SetSignLines(a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4)) { cRoot::Get()->GetPluginManager()->CallHookUpdatedSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player); return true; } - return false; -} - - - - -bool cWorld::UpdateSign(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) -{ - return SetSignLines(a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player); + return false; } diff --git a/src/World.h b/src/World.h index 1a9f60a5c..b209f71a7 100644 --- a/src/World.h +++ b/src/World.h @@ -377,11 +377,8 @@ public: /** Marks the chunk as failed-to-load: */ void ChunkLoadFailed(int a_ChunkX, int a_ChunkZ); - /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be nullptr. Returns true if sign text changed. Same as UpdateSign() */ + /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be nullptr. Returns true if sign text changed. */ bool SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = nullptr); // Exported in ManualBindings.cpp - - /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be nullptr. Returns true if sign text changed. Same as SetSignLines() */ - bool UpdateSign(int a_X, int a_Y, int a_Z, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = nullptr); // Exported in ManualBindings.cpp /** Sets the command block command. Returns true if command changed. */ bool SetCommandBlockCommand(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Command); // tolua_export -- cgit v1.2.3 From 927d8d7702b71baa64dc70593ea71e1081c33a9c Mon Sep 17 00:00:00 2001 From: Howaner Date: Sat, 15 Nov 2014 15:33:42 +0100 Subject: Renamed m_SetViewDistance to m_RequestedViewDistance --- src/ClientHandle.cpp | 8 ++++---- src/ClientHandle.h | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index d5882da06..3feb4c596 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -66,7 +66,7 @@ int cClientHandle::s_ClientCount = 0; cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_UsedViewDistance(a_ViewDistance), - m_SetViewDistance(a_ViewDistance), + m_RequestedViewDistance(a_ViewDistance), m_IPString(a_Socket->GetIPString()), m_OutgoingData(64 KiB), m_Player(nullptr), @@ -2850,9 +2850,9 @@ void cClientHandle::SetViewDistance(int a_ViewDistance) { ASSERT(m_Player->GetWorld() == NULL); - m_SetViewDistance = a_ViewDistance; - m_UsedViewDistance = Clamp(m_SetViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); - LOGD("Setted view distance from %s to %i!", GetUsername().c_str(), m_UsedViewDistance); + m_RequestedViewDistance = a_ViewDistance; + m_UsedViewDistance = Clamp(a_ViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); + LOGD("Setted view distance from %s to %d!", GetUsername().c_str(), m_UsedViewDistance); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index db386d8a3..c0826d7c4 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -224,7 +224,7 @@ public: int GetViewDistance(void) const { return m_UsedViewDistance; } /** Returns the view distance that the player request, not the used view distance. */ - int GetRequestedViewDistance(void) const { return m_SetViewDistance; } + int GetRequestedViewDistance(void) const { return m_RequestedViewDistance; } void SetLocale(AString & a_Locale) { m_Locale = a_Locale; } AString GetLocale(void) const { return m_Locale; } @@ -342,8 +342,8 @@ private: /** Number of chunks the player can see in each direction */ int m_UsedViewDistance; - /** The original view distance from the player. It isn't clamped with 1 and the max view distance of the world. */ - int m_SetViewDistance; + /** The requested view distance from the player. It isn't clamped with 1 and the max view distance of the world. */ + int m_RequestedViewDistance; AString m_IPString; -- cgit v1.2.3 From 09cea625fcf2d1eb1fb37a57c5712d992c96e4fd Mon Sep 17 00:00:00 2001 From: Howaner Date: Sat, 15 Nov 2014 22:26:54 +0100 Subject: Renamed m_UsedViewDistance to m_CurrentViewDistance --- src/ClientHandle.cpp | 16 ++++++++-------- src/ClientHandle.h | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 3feb4c596..0b9d84bf7 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -65,7 +65,7 @@ int cClientHandle::s_ClientCount = 0; // cClientHandle: cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : - m_UsedViewDistance(a_ViewDistance), + m_CurrentViewDistance(a_ViewDistance), m_RequestedViewDistance(a_ViewDistance), m_IPString(a_Socket->GetIPString()), m_OutgoingData(64 KiB), @@ -431,7 +431,7 @@ bool cClientHandle::StreamNextChunk(void) cCSLock Lock(m_CSChunkLists); // High priority: Load the chunks that are in the view-direction of the player (with a radius of 3) - for (int Range = 0; Range < m_UsedViewDistance; Range++) + for (int Range = 0; Range < m_CurrentViewDistance; Range++) { Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; @@ -448,7 +448,7 @@ bool cClientHandle::StreamNextChunk(void) cChunkCoords Coords(ChunkX, ChunkZ); // Checks if the chunk is in distance - if ((Diff(ChunkX, ChunkPosX) > m_UsedViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_UsedViewDistance)) + if ((Diff(ChunkX, ChunkPosX) > m_CurrentViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_CurrentViewDistance)) { continue; } @@ -471,7 +471,7 @@ bool cClientHandle::StreamNextChunk(void) } // Low priority: Add all chunks that are in range. (From the center out to the edge) - for (int d = 0; d <= m_UsedViewDistance; ++d) // cycle through (square) distance, from nearest to furthest + for (int d = 0; d <= m_CurrentViewDistance; ++d) // cycle through (square) distance, from nearest to furthest { // For each distance add chunks in a hollow square centered around current position: cChunkCoordsList CurcleChunks; @@ -529,7 +529,7 @@ void cClientHandle::UnloadOutOfRangeChunks(void) { int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); - if ((DiffX > m_UsedViewDistance) || (DiffZ > m_UsedViewDistance)) + if ((DiffX > m_CurrentViewDistance) || (DiffZ > m_CurrentViewDistance)) { ChunksToRemove.push_back(*itr); itr = m_LoadedChunks.erase(itr); @@ -544,7 +544,7 @@ void cClientHandle::UnloadOutOfRangeChunks(void) { int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); - if ((DiffX > m_UsedViewDistance) || (DiffZ > m_UsedViewDistance)) + if ((DiffX > m_CurrentViewDistance) || (DiffZ > m_CurrentViewDistance)) { itr = m_ChunksToSend.erase(itr); } @@ -2851,8 +2851,8 @@ void cClientHandle::SetViewDistance(int a_ViewDistance) ASSERT(m_Player->GetWorld() == NULL); m_RequestedViewDistance = a_ViewDistance; - m_UsedViewDistance = Clamp(a_ViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); - LOGD("Setted view distance from %s to %d!", GetUsername().c_str(), m_UsedViewDistance); + m_CurrentViewDistance = Clamp(a_ViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); + LOGD("Setted view distance from %s to %d!", GetUsername().c_str(), m_CurrentViewDistance); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index c0826d7c4..8d241c1e7 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -221,7 +221,7 @@ public: void SetViewDistance(int a_ViewDistance); /** Returns the view distance that the player currently have. */ - int GetViewDistance(void) const { return m_UsedViewDistance; } + int GetViewDistance(void) const { return m_CurrentViewDistance; } /** Returns the view distance that the player request, not the used view distance. */ int GetRequestedViewDistance(void) const { return m_RequestedViewDistance; } @@ -339,8 +339,8 @@ private: /** The type used for storing the names of registered plugin channels. */ typedef std::set cChannels; - /** Number of chunks the player can see in each direction */ - int m_UsedViewDistance; + /** The actual view distance used, the minimum of client's requested view distance and world's max view distance. */ + int m_CurrentViewDistance; /** The requested view distance from the player. It isn't clamped with 1 and the max view distance of the world. */ int m_RequestedViewDistance; -- cgit v1.2.3 From 277151582fbb0652dcf4e15f67d41f90e08bdeeb Mon Sep 17 00:00:00 2001 From: Howaner Date: Sat, 15 Nov 2014 22:36:31 +0100 Subject: Use LastPlacedSign instead of LastPlacedBlock. --- src/ClientHandle.cpp | 7 ++++--- src/ClientHandle.h | 7 ++----- 2 files changed, 6 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 9bf4875e2..83fb283b6 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -93,7 +93,7 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_UniqueID(0), m_HasSentPlayerChunk(false), m_Locale("en_GB"), - m_LastPlacedBlock(0, -1, 0), + m_LastPlacedSign(0, -1, 0), m_ProtocolVersion(0) { m_Protocol = new cProtocolRecognizer(this); @@ -1501,7 +1501,6 @@ void cClientHandle::HandlePlaceBlock(int a_BlockX, int a_BlockY, int a_BlockZ, e { m_Player->GetInventory().RemoveOneEquippedItem(); } - m_LastPlacedBlock.Set(a_BlockX, a_BlockY, a_BlockZ); cChunkInterface ChunkInterface(World->GetChunkMap()); NewBlock->OnPlacedByPlayer(ChunkInterface, *World, m_Player, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_CursorX, a_CursorY, a_CursorZ, BlockType, BlockMeta); @@ -1680,8 +1679,9 @@ void cClientHandle::HandleUpdateSign( const AString & a_Line3, const AString & a_Line4 ) { - if (m_LastPlacedBlock.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) + if (m_LastPlacedSign.Equals(Vector3i(a_BlockX, a_BlockY, a_BlockZ))) { + m_LastPlacedSign.Set(0, -1, 0); m_Player->GetWorld()->SetSignLines(a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, m_Player); } } @@ -2262,6 +2262,7 @@ void cClientHandle::SendDisconnect(const AString & a_Reason) void cClientHandle::SendEditSign(int a_BlockX, int a_BlockY, int a_BlockZ) { + m_LastPlacedSign.Set(a_BlockX, a_BlockY, a_BlockZ); m_Protocol->SendEditSign(a_BlockX, a_BlockY, a_BlockZ); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index a0dd4ff7a..d8cc3c643 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -125,9 +125,6 @@ public: inline bool IsLoggedIn(void) const { return (m_State >= csAuthenticating); } - /** Returns the positions from the last block that the player placed. */ - const Vector3i & GetLastPlacedBlock(void) const { return m_LastPlacedBlock; } // tolua_export - /** Called while the client is being ticked from the world via its cPlayer object */ void Tick(float a_Dt); @@ -436,8 +433,8 @@ private: /** Client Settings */ AString m_Locale; - /** The positions from the last block that the player placed. It's needed to verify the sign text change. */ - Vector3i m_LastPlacedBlock; + /** The positions from the last sign that the player placed. It's needed to verify the sign text change. */ + Vector3i m_LastPlacedSign; /** The plugin channels that the client has registered. */ cChannels m_PluginChannels; -- cgit v1.2.3 From 95e59056a187fe51091b5ee4b3870fa94b7df12f Mon Sep 17 00:00:00 2001 From: Mattes D Date: Sun, 16 Nov 2014 19:02:37 +0100 Subject: BiomalNoise3D: Added more biomes. --- src/Generating/Noise3DGenerator.cpp | 78 ++++++++++++++++++++++++++++++------- 1 file changed, 65 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index 91bdce458..f2af75999 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -756,19 +756,71 @@ void cBiomalNoise3DComposable::GetBiomeParams(EMCSBiome a_Biome, NOISE_DATATYPE { switch (a_Biome) { - case biDeepOcean: a_HeightAmp = 0.17f; a_MidPoint = 35; break; - case biDesert: a_HeightAmp = 0.29f; a_MidPoint = 62; break; // Needs verification - case biExtremeHills: a_HeightAmp = 0.045f; a_MidPoint = 75; break; - case biExtremeHillsPlus: a_HeightAmp = 0.04f; a_MidPoint = 80; break; - case biFrozenRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; - case biFrozenOcean: a_HeightAmp = 0.17f; a_MidPoint = 47; break; - case biJungle: a_HeightAmp = 0.1f; a_MidPoint = 63; break; - case biJungleM: a_HeightAmp = 0.1f; a_MidPoint = 63; break; - case biOcean: a_HeightAmp = 0.17f; a_MidPoint = 47; break; - case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; // Needs verification - case biRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; - case biSwampland: a_HeightAmp = 0.25f; a_MidPoint = 59; break; - case biSwamplandM: a_HeightAmp = 0.11f; a_MidPoint = 59; break; + case biBeach: a_HeightAmp = 0.3f; a_MidPoint = 62; break; + case biBirchForest: a_HeightAmp = 0.1f; a_MidPoint = 64; break; + case biBirchForestHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biBirchForestHillsM: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biBirchForestM: a_HeightAmp = 0.1f; a_MidPoint = 64; break; + case biColdBeach: a_HeightAmp = 0.3f; a_MidPoint = 62; break; + case biDesertHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biDeepOcean: a_HeightAmp = 0.17f; a_MidPoint = 35; break; + case biDesert: a_HeightAmp = 0.29f; a_MidPoint = 62; break; + case biEnd: a_HeightAmp = 0.15f; a_MidPoint = 64; break; + case biExtremeHills: a_HeightAmp = 0.045f; a_MidPoint = 75; break; + case biExtremeHillsPlus: a_HeightAmp = 0.04f; a_MidPoint = 80; break; + case biFlowerForest: a_HeightAmp = 0.1f; a_MidPoint = 64; break; + case biForest: a_HeightAmp = 0.1f; a_MidPoint = 64; break; + case biForestHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biFrozenRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; + case biFrozenOcean: a_HeightAmp = 0.17f; a_MidPoint = 47; break; + case biIceMountains: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biIcePlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; + case biIcePlainsSpikes: a_HeightAmp = 0.3f; a_MidPoint = 62; break; + case biJungle: a_HeightAmp = 0.1f; a_MidPoint = 63; break; + case biJungleHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biJungleM: a_HeightAmp = 0.1f; a_MidPoint = 63; break; + case biMegaSpruceTaigaHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biMegaTaigaHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + case biMushroomShore: a_HeightAmp = 0.15f; a_MidPoint = 15; break; + case biOcean: a_HeightAmp = 0.3f; a_MidPoint = 62; break; + case biPlains: a_HeightAmp = 0.3f; a_MidPoint = 62; break; + case biRiver: a_HeightAmp = 0.4f; a_MidPoint = 53; break; + case biSwampland: a_HeightAmp = 0.25f; a_MidPoint = 59; break; + case biSwamplandM: a_HeightAmp = 0.11f; a_MidPoint = 59; break; + case biTaigaHills: a_HeightAmp = 0.075f; a_MidPoint = 68; break; + + /* + // Still missing: + case biColdTaiga: a_HeightAmp = 0.15f; a_MidPoint = 30; break; + case biColdTaigaHills: a_HeightAmp = 0.15f; a_MidPoint = 31; break; + case biColdTaigaM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biDesertM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biExtremeHillsEdge: a_HeightAmp = 0.15f; a_MidPoint = 20; break; + case biExtremeHillsM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biExtremeHillsPlusM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biJungleEdge: a_HeightAmp = 0.15f; a_MidPoint = 23; break; + case biJungleEdgeM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biMegaSpruceTaiga: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biMegaTaiga: a_HeightAmp = 0.15f; a_MidPoint = 32; break; + case biMesa: a_HeightAmp = 0.15f; a_MidPoint = 37; break; + case biMesaBryce: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biMesaPlateau: a_HeightAmp = 0.15f; a_MidPoint = 39; break; + case biMesaPlateauF: a_HeightAmp = 0.15f; a_MidPoint = 38; break; + case biMesaPlateauFM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biMesaPlateauM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biMushroomIsland: a_HeightAmp = 0.15f; a_MidPoint = 14; break; + case biNether: a_HeightAmp = 0.15f; a_MidPoint = 68; break; + case biRoofedForest: a_HeightAmp = 0.15f; a_MidPoint = 29; break; + case biRoofedForestM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biSavanna: a_HeightAmp = 0.15f; a_MidPoint = 35; break; + case biSavannaM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biSavannaPlateau: a_HeightAmp = 0.15f; a_MidPoint = 36; break; + case biSavannaPlateauM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biStoneBeach: a_HeightAmp = 0.15f; a_MidPoint = 25; break; + case biSunflowerPlains: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + case biTaiga: a_HeightAmp = 0.15f; a_MidPoint = 65; break; + case biTaigaM: a_HeightAmp = 0.15f; a_MidPoint = 70; break; + */ default: { -- cgit v1.2.3 From ae15c2f78e85c8a6ee192d48d8befc5ee4b478b6 Mon Sep 17 00:00:00 2001 From: Mattes D Date: Mon, 17 Nov 2014 12:34:14 +0100 Subject: Fixed a wrong assert in cClientHandle::SetViewDistance(). --- src/ClientHandle.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 0b9d84bf7..8b4d6d0cc 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -2848,11 +2848,15 @@ void cClientHandle::SetUsername( const AString & a_Username) void cClientHandle::SetViewDistance(int a_ViewDistance) { - ASSERT(m_Player->GetWorld() == NULL); - m_RequestedViewDistance = a_ViewDistance; - m_CurrentViewDistance = Clamp(a_ViewDistance, cClientHandle::MIN_VIEW_DISTANCE, m_Player->GetWorld()->GetMaxViewDistance()); - LOGD("Setted view distance from %s to %d!", GetUsername().c_str(), m_CurrentViewDistance); + LOGD("%s is requesting ViewDistance of %d!", GetUsername().c_str(), m_RequestedViewDistance); + + // Set the current view distance based on the requested VD and world max VD: + cWorld * world = m_Player->GetWorld(); + if (world != nullptr) + { + m_CurrentViewDistance = Clamp(a_ViewDistance, cClientHandle::MIN_VIEW_DISTANCE, world->GetMaxViewDistance()); + } } -- cgit v1.2.3 From 0e491273c1e942b73adc78db03a71d76d529b009 Mon Sep 17 00:00:00 2001 From: Howaner Date: Mon, 17 Nov 2014 14:57:24 +0100 Subject: Added UpdateSign() method to DeprecatedBindings.cpp --- src/Bindings/DeprecatedBindings.cpp | 86 +++++++++++++++++++++++++++++++++++++ src/Bindings/ManualBindings.cpp | 5 +-- 2 files changed, 88 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Bindings/DeprecatedBindings.cpp b/src/Bindings/DeprecatedBindings.cpp index ded7a0142..442d9add5 100644 --- a/src/Bindings/DeprecatedBindings.cpp +++ b/src/Bindings/DeprecatedBindings.cpp @@ -7,6 +7,33 @@ #include "../BlockInfo.h" +#include "../World.h" +#include "../Entities/Player.h" + + + + + +static void lua_do_warning(lua_State* L, const char * a_pFormat, ...) +{ + // Retrieve current function name + lua_Debug entry; + VERIFY(lua_getstack(L, 0, &entry)); + VERIFY(lua_getinfo(L, "n", &entry)); + + // Insert function name into error msg + AString msg(a_pFormat); + ReplaceString(msg, "#funcname#", entry.name?entry.name:"?"); + + // Copied from luaL_error and modified + va_list argp; + va_start(argp, a_pFormat); + luaL_where(L, 1); + lua_pushvfstring(L, msg.c_str(), argp); + va_end(argp); + lua_concat(L, 2); + lua_error(L); +} @@ -222,6 +249,61 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S) +/** function: cWorld:SetSignLines */ +static int tolua_cWorld_SetSignLines(lua_State * tolua_S) +{ + #ifndef TOLUA_RELEASE + tolua_Error tolua_err; + if ( + !tolua_isusertype (tolua_S, 1, "cWorld", 0, &tolua_err) || + !tolua_isnumber (tolua_S, 2, 0, &tolua_err) || + !tolua_isnumber (tolua_S, 3, 0, &tolua_err) || + !tolua_isnumber (tolua_S, 4, 0, &tolua_err) || + !tolua_iscppstring(tolua_S, 5, 0, &tolua_err) || + !tolua_iscppstring(tolua_S, 6, 0, &tolua_err) || + !tolua_iscppstring(tolua_S, 7, 0, &tolua_err) || + !tolua_iscppstring(tolua_S, 8, 0, &tolua_err) || + !tolua_isusertype (tolua_S, 9, "cPlayer", 1, &tolua_err) || + !tolua_isnoobj (tolua_S, 10, &tolua_err) + ) + goto tolua_lerror; + else + #endif + { + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); + int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); + int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); + int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); + const AString Line1 = tolua_tocppstring(tolua_S, 5, 0); + const AString Line2 = tolua_tocppstring(tolua_S, 6, 0); + const AString Line3 = tolua_tocppstring(tolua_S, 7, 0); + const AString Line4 = tolua_tocppstring(tolua_S, 8, 0); + cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, nullptr); + #ifndef TOLUA_RELEASE + if (self == nullptr) + { + tolua_error(tolua_S, "invalid 'self' in function 'UpdateSign'", nullptr); + } + #endif + { + bool res = self->SetSignLines(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player); + tolua_pushboolean(tolua_S, res ? 1 : 0); + } + } + lua_do_warning(tolua_S, "Warning in function call '#funcname#': UpdateSign() is deprecated. Please use SetSignLines()"); + return 1; + + #ifndef TOLUA_RELEASE +tolua_lerror: + tolua_error(tolua_S, "#ferror in function 'UpdateSign'.", &tolua_err); + return 0; + #endif +} + + + + + void DeprecatedBindings::Bind(lua_State * tolua_S) { tolua_beginmodule(tolua_S, nullptr); @@ -235,6 +317,10 @@ void DeprecatedBindings::Bind(lua_State * tolua_S) tolua_array(tolua_S, "g_BlockIsSolid", tolua_get_AllToLua_g_BlockIsSolid, nullptr); tolua_array(tolua_S, "g_BlockFullyOccupiesVoxel", tolua_get_AllToLua_g_BlockFullyOccupiesVoxel, nullptr); + tolua_beginmodule(tolua_S, "cWorld"); + tolua_function(tolua_S, "UpdateSign", tolua_cWorld_SetSignLines); + tolua_endmodule(tolua_S); + tolua_endmodule(tolua_S); } diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index e259e2e91..750f7c65a 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -1034,7 +1034,7 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) #ifndef TOLUA_RELEASE if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines' / 'UpdateSign'", nullptr); + tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines'", nullptr); } #endif { @@ -1046,7 +1046,7 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) #ifndef TOLUA_RELEASE tolua_lerror: - tolua_error(tolua_S, "#ferror in function 'SetSignLines' / 'UpdateSign'.", &tolua_err); + tolua_error(tolua_S, "#ferror in function 'SetSignLines'.", &tolua_err); return 0; #endif } @@ -3405,7 +3405,6 @@ void ManualBindings::Bind(lua_State * tolua_S) tolua_function(tolua_S, "ScheduleTask", tolua_cWorld_ScheduleTask); tolua_function(tolua_S, "SetSignLines", tolua_cWorld_SetSignLines); tolua_function(tolua_S, "TryGetHeight", tolua_cWorld_TryGetHeight); - tolua_function(tolua_S, "UpdateSign", tolua_cWorld_SetSignLines); tolua_endmodule(tolua_S); tolua_beginmodule(tolua_S, "cMapManager"); -- cgit v1.2.3 From d7efece5f2efcbaa93c36f26c325fea66f3700f1 Mon Sep 17 00:00:00 2001 From: Howaner Date: Mon, 17 Nov 2014 18:01:56 +0100 Subject: Use cLuaState's stack trace. --- src/Bindings/DeprecatedBindings.cpp | 75 +++++++++++++------------------------ 1 file changed, 27 insertions(+), 48 deletions(-) (limited to 'src') diff --git a/src/Bindings/DeprecatedBindings.cpp b/src/Bindings/DeprecatedBindings.cpp index 442d9add5..345ab2a07 100644 --- a/src/Bindings/DeprecatedBindings.cpp +++ b/src/Bindings/DeprecatedBindings.cpp @@ -9,31 +9,7 @@ #include "../BlockInfo.h" #include "../World.h" #include "../Entities/Player.h" - - - - - -static void lua_do_warning(lua_State* L, const char * a_pFormat, ...) -{ - // Retrieve current function name - lua_Debug entry; - VERIFY(lua_getstack(L, 0, &entry)); - VERIFY(lua_getinfo(L, "n", &entry)); - - // Insert function name into error msg - AString msg(a_pFormat); - ReplaceString(msg, "#funcname#", entry.name?entry.name:"?"); - - // Copied from luaL_error and modified - va_list argp; - va_start(argp, a_pFormat); - luaL_where(L, 1); - lua_pushvfstring(L, msg.c_str(), argp); - va_end(argp); - lua_concat(L, 2); - lua_error(L); -} +#include "LuaState.h" @@ -252,50 +228,53 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S) /** function: cWorld:SetSignLines */ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) { + cLuaState LuaState(tolua_S); + #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype (tolua_S, 1, "cWorld", 0, &tolua_err) || - !tolua_isnumber (tolua_S, 2, 0, &tolua_err) || - !tolua_isnumber (tolua_S, 3, 0, &tolua_err) || - !tolua_isnumber (tolua_S, 4, 0, &tolua_err) || - !tolua_iscppstring(tolua_S, 5, 0, &tolua_err) || - !tolua_iscppstring(tolua_S, 6, 0, &tolua_err) || - !tolua_iscppstring(tolua_S, 7, 0, &tolua_err) || - !tolua_iscppstring(tolua_S, 8, 0, &tolua_err) || - !tolua_isusertype (tolua_S, 9, "cPlayer", 1, &tolua_err) || - !tolua_isnoobj (tolua_S, 10, &tolua_err) + !tolua_isusertype (LuaState, 1, "cWorld", 0, &tolua_err) || + !tolua_isnumber (LuaState, 2, 0, &tolua_err) || + !tolua_isnumber (LuaState, 3, 0, &tolua_err) || + !tolua_isnumber (LuaState, 4, 0, &tolua_err) || + !tolua_iscppstring(LuaState, 5, 0, &tolua_err) || + !tolua_iscppstring(LuaState, 6, 0, &tolua_err) || + !tolua_iscppstring(LuaState, 7, 0, &tolua_err) || + !tolua_iscppstring(LuaState, 8, 0, &tolua_err) || + !tolua_isusertype (LuaState, 9, "cPlayer", 1, &tolua_err) || + !tolua_isnoobj (LuaState, 10, &tolua_err) ) goto tolua_lerror; else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); - int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); - int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); - int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); - const AString Line1 = tolua_tocppstring(tolua_S, 5, 0); - const AString Line2 = tolua_tocppstring(tolua_S, 6, 0); - const AString Line3 = tolua_tocppstring(tolua_S, 7, 0); - const AString Line4 = tolua_tocppstring(tolua_S, 8, 0); - cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, nullptr); + cWorld * self = (cWorld *) tolua_tousertype (LuaState, 1, nullptr); + int BlockX = (int) tolua_tonumber (LuaState, 2, 0); + int BlockY = (int) tolua_tonumber (LuaState, 3, 0); + int BlockZ = (int) tolua_tonumber (LuaState, 4, 0); + const AString Line1 = tolua_tocppstring(LuaState, 5, 0); + const AString Line2 = tolua_tocppstring(LuaState, 6, 0); + const AString Line3 = tolua_tocppstring(LuaState, 7, 0); + const AString Line4 = tolua_tocppstring(LuaState, 8, 0); + cPlayer * Player = (cPlayer *)tolua_tousertype (LuaState, 9, nullptr); #ifndef TOLUA_RELEASE if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'UpdateSign'", nullptr); + tolua_error(LuaState, "invalid 'self' in function 'UpdateSign'", nullptr); } #endif { bool res = self->SetSignLines(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player); - tolua_pushboolean(tolua_S, res ? 1 : 0); + tolua_pushboolean(LuaState, res ? 1 : 0); } } - lua_do_warning(tolua_S, "Warning in function call '#funcname#': UpdateSign() is deprecated. Please use SetSignLines()"); + LOGWARNING("Warning in function call 'UpdateSign': UpdateSign() is deprecated. Please use SetSignLines()"); + LuaState.LogStackTrace(0); return 1; #ifndef TOLUA_RELEASE tolua_lerror: - tolua_error(tolua_S, "#ferror in function 'UpdateSign'.", &tolua_err); + tolua_error(LuaState, "#ferror in function 'UpdateSign'.", &tolua_err); return 0; #endif } -- cgit v1.2.3