file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
SavannaTreePopulator.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/populator/tree/SavannaTreePopulator.java | package cn.nukkit.level.generator.populator.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockSapling;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.level.generator.object.tree.ObjectSavannaTree;
import cn.nukkit.level.generator.populator.Populator;
import cn.nukkit.math.NukkitMath;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
public class SavannaTreePopulator extends Populator {
private ChunkManager level;
private int randomAmount;
private int baseAmount;
private final int type;
public SavannaTreePopulator() {
this(BlockSapling.ACACIA);
}
public SavannaTreePopulator(int type) {
this.type = type;
}
public void setRandomAmount(int randomAmount) {
this.randomAmount = randomAmount;
}
public void setBaseAmount(int baseAmount) {
this.baseAmount = baseAmount;
}
@Override
public void populate(ChunkManager level, int chunkX, int chunkZ, NukkitRandom random) {
this.level = level;
int amount = random.nextBoundedInt(this.randomAmount + 1) + this.baseAmount;
Vector3 v = new Vector3();
for (int i = 0; i < amount; ++i) {
int x = NukkitMath.randomRange(random, chunkX << 4, (chunkX << 4) + 15);
int z = NukkitMath.randomRange(random, chunkZ << 4, (chunkZ << 4) + 15);
int y = this.getHighestWorkableBlock(x, z);
if (y == -1) {
continue;
}
new ObjectSavannaTree().generate(level, random, v.setComponents(x, y, z));
}
}
private int getHighestWorkableBlock(int x, int z) {
int y;
for (y = 127; y > 0; --y) {
int b = this.level.getBlockIdAt(x, y, z);
if (b == Block.DIRT || b == Block.GRASS) {
break;
} else if (b != Block.AIR && b != Block.SNOW_LAYER) {
return -1;
}
}
return ++y;
}
}
| 1,979 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BasicGenerator.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/BasicGenerator.java | package cn.nukkit.level.generator.object;
import cn.nukkit.block.Block;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.BlockVector3;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
public abstract class BasicGenerator {
public abstract boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position);
public void setDecorationDefaults() {
}
protected void setBlockAndNotifyAdequately(ChunkManager level, BlockVector3 pos, Block state) {
setBlock(level, new Vector3(pos.x, pos.y, pos.z), state);
}
protected void setBlockAndNotifyAdequately(ChunkManager level, Vector3 pos, Block state) {
setBlock(level, pos, state);
}
protected void setBlock(ChunkManager level, Vector3 v, Block b) {
level.setBlockIdAt((int) v.x, (int) v.y, (int) v.z, b.getId());
level.setBlockDataAt((int) v.x, (int) v.y, (int) v.z, b.getDamage());
}
}
| 939 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectTallGrass.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/ObjectTallGrass.java | package cn.nukkit.level.generator.object;
import cn.nukkit.block.Block;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
/**
* author: ItsLucas
* Nukkit Project
*/
public class ObjectTallGrass {
public static void growGrass(ChunkManager level, Vector3 pos, NukkitRandom random, int count, int radius) {
int[][] arr = {
{Block.DANDELION, 0},
{Block.POPPY, 0},
{Block.TALL_GRASS, 1},
{Block.TALL_GRASS, 1},
{Block.TALL_GRASS, 1},
{Block.TALL_GRASS, 1}
};
int arrC = arr.length - 1;
for (int c = 0; c < count; c++) {
int x = random.nextRange((int) (pos.x - radius), (int) (pos.x + radius));
int z = random.nextRange((int) (pos.z) - radius, (int) (pos.z + radius));
if (level.getBlockIdAt(x, (int) (pos.y + 1), z) == Block.AIR && level.getBlockIdAt(x, (int) (pos.y), z) == Block.GRASS) {
int[] t = arr[random.nextRange(0, arrC)];
level.setBlockIdAt(x, (int) (pos.y + 1), z, t[0]);
level.setBlockDataAt(x, (int) (pos.y + 1), z, t[1]);
}
}
}
}
| 1,240 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectTallBirchTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTallBirchTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ObjectTallBirchTree extends ObjectBirchTree {
@Override
public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) {
this.treeHeight = random.nextBoundedInt(3) + 10;
super.placeObject(level, x, y, z, random);
}
}
| 453 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectDarkOakTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectDarkOakTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockLeaves2;
import cn.nukkit.block.BlockWood2;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
/**
* Created by CreeperFace on 23. 10. 2016.
*/
public class ObjectDarkOakTree extends TreeGenerator {
private static final Block DARK_OAK_LOG = new BlockWood2(BlockWood2.DARK_OAK);
private static final Block DARK_OAK_LEAVES = new BlockLeaves2(BlockLeaves2.DARK_OAK);
@Override
public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) {
int i = rand.nextBoundedInt(3) + rand.nextBoundedInt(2) + 6;
int j = position.getFloorX();
int k = position.getFloorY();
int l = position.getFloorZ();
if (k >= 1 && k + i + 1 < 256) {
Vector3 blockpos = position.down();
int block = level.getBlockIdAt(blockpos.getFloorX(), blockpos.getFloorY(), blockpos.getFloorZ());
if (block != Block.GRASS && block != Block.DIRT) {
return false;
} else if (!this.placeTreeOfHeight(level, position, i)) {
return false;
} else {
this.setDirtAt(level, blockpos);
this.setDirtAt(level, blockpos.east());
this.setDirtAt(level, blockpos.south());
this.setDirtAt(level, blockpos.south().east());
BlockFace enumfacing = BlockFace.Plane.HORIZONTAL.random(rand);
int i1 = i - rand.nextBoundedInt(4);
int j1 = 2 - rand.nextBoundedInt(3);
int k1 = j;
int l1 = l;
int i2 = k + i - 1;
for (int j2 = 0; j2 < i; ++j2) {
if (j2 >= i1 && j1 > 0) {
k1 += enumfacing.getXOffset();
l1 += enumfacing.getZOffset();
--j1;
}
int k2 = k + j2;
Vector3 blockpos1 = new Vector3(k1, k2, l1);
int material = level.getBlockIdAt(blockpos1.getFloorX(), blockpos1.getFloorY(), blockpos1.getFloorZ());
if (material == Block.AIR || material == Block.LEAVES) {
this.placeLogAt(level, blockpos1);
this.placeLogAt(level, blockpos1.east());
this.placeLogAt(level, blockpos1.south());
this.placeLogAt(level, blockpos1.east().south());
}
}
for (int i3 = -2; i3 <= 0; ++i3) {
for (int l3 = -2; l3 <= 0; ++l3) {
int k4 = -1;
this.placeLeafAt(level, k1 + i3, i2 + k4, l1 + l3);
this.placeLeafAt(level, 1 + k1 - i3, i2 + k4, l1 + l3);
this.placeLeafAt(level, k1 + i3, i2 + k4, 1 + l1 - l3);
this.placeLeafAt(level, 1 + k1 - i3, i2 + k4, 1 + l1 - l3);
if ((i3 > -2 || l3 > -1) && (i3 != -1 || l3 != -2)) {
k4 = 1;
this.placeLeafAt(level, k1 + i3, i2 + k4, l1 + l3);
this.placeLeafAt(level, 1 + k1 - i3, i2 + k4, l1 + l3);
this.placeLeafAt(level, k1 + i3, i2 + k4, 1 + l1 - l3);
this.placeLeafAt(level, 1 + k1 - i3, i2 + k4, 1 + l1 - l3);
}
}
}
if (rand.nextBoolean()) {
this.placeLeafAt(level, k1, i2 + 2, l1);
this.placeLeafAt(level, k1 + 1, i2 + 2, l1);
this.placeLeafAt(level, k1 + 1, i2 + 2, l1 + 1);
this.placeLeafAt(level, k1, i2 + 2, l1 + 1);
}
for (int j3 = -3; j3 <= 4; ++j3) {
for (int i4 = -3; i4 <= 4; ++i4) {
if ((j3 != -3 || i4 != -3) && (j3 != -3 || i4 != 4) && (j3 != 4 || i4 != -3) && (j3 != 4 || i4 != 4) && (Math.abs(j3) < 3 || Math.abs(i4) < 3)) {
this.placeLeafAt(level, k1 + j3, i2, l1 + i4);
}
}
}
for (int k3 = -1; k3 <= 2; ++k3) {
for (int j4 = -1; j4 <= 2; ++j4) {
if ((k3 < 0 || k3 > 1 || j4 < 0 || j4 > 1) && rand.nextBoundedInt(3) <= 0) {
int l4 = rand.nextBoundedInt(3) + 2;
for (int i5 = 0; i5 < l4; ++i5) {
this.placeLogAt(level, new Vector3(j + k3, i2 - i5 - 1, l + j4));
}
for (int j5 = -1; j5 <= 1; ++j5) {
for (int l2 = -1; l2 <= 1; ++l2) {
this.placeLeafAt(level, k1 + k3 + j5, i2, l1 + j4 + l2);
}
}
for (int k5 = -2; k5 <= 2; ++k5) {
for (int l5 = -2; l5 <= 2; ++l5) {
if (Math.abs(k5) != 2 || Math.abs(l5) != 2) {
this.placeLeafAt(level, k1 + k3 + k5, i2 - 1, l1 + j4 + l5);
}
}
}
}
}
}
return true;
}
} else {
return false;
}
}
private boolean placeTreeOfHeight(ChunkManager worldIn, Vector3 pos, int height) {
int i = pos.getFloorX();
int j = pos.getFloorY();
int k = pos.getFloorZ();
Vector3 blockPos = new Vector3();
for (int l = 0; l <= height + 1; ++l) {
int i1 = 1;
if (l == 0) {
i1 = 0;
}
if (l >= height - 1) {
i1 = 2;
}
for (int j1 = -i1; j1 <= i1; ++j1) {
for (int k1 = -i1; k1 <= i1; ++k1) {
blockPos.setComponents(i + j1, j + l, k + k1);
if (!this.canGrowInto(worldIn.getBlockIdAt(blockPos.getFloorX(), blockPos.getFloorY(), blockPos.getFloorZ()))) {
return false;
}
}
}
}
return true;
}
private void placeLogAt(ChunkManager worldIn, Vector3 pos) {
if (this.canGrowInto(worldIn.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ()))) {
this.setBlockAndNotifyAdequately(worldIn, pos, DARK_OAK_LOG);
}
}
private void placeLeafAt(ChunkManager worldIn, int x, int y, int z) {
Vector3 blockpos = new Vector3(x, y, z);
int material = worldIn.getBlockIdAt(blockpos.getFloorX(), blockpos.getFloorY(), blockpos.getFloorZ());
if (material == Block.AIR) {
this.setBlockAndNotifyAdequately(worldIn, blockpos, DARK_OAK_LEAVES);
}
}
}
| 7,205 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectJungleBigTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleBigTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockVine;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.MathHelper;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
public class ObjectJungleBigTree extends HugeTreesGenerator {
public ObjectJungleBigTree(int baseHeightIn, int extraRandomHeight, Block woodMetadata, Block leavesMetadata) {
super(baseHeightIn, extraRandomHeight, woodMetadata, leavesMetadata);
}
public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) {
int height = this.getHeight(rand);
if (!this.ensureGrowable(level, rand, position, height)) {
return false;
} else {
this.createCrown(level, position.up(height), 2);
for (int j = (int) position.getY() + height - 2 - rand.nextBoundedInt(4); j > position.getY() + height / 2; j -= 2 + rand.nextBoundedInt(4)) {
float f = rand.nextFloat() * ((float) Math.PI * 2F);
int k = (int) (position.getX() + (0.5F + MathHelper.cos(f) * 4.0F));
int l = (int) (position.getZ() + (0.5F + MathHelper.sin(f) * 4.0F));
for (int i1 = 0; i1 < 5; ++i1) {
k = (int) (position.getX() + (1.5F + MathHelper.cos(f) * (float) i1));
l = (int) (position.getZ() + (1.5F + MathHelper.sin(f) * (float) i1));
this.setBlockAndNotifyAdequately(level, new Vector3(k, j - 3 + i1 / 2, l), this.woodMetadata);
}
int j2 = 1 + rand.nextBoundedInt(2);
int j1 = j;
for (int k1 = j - j2; k1 <= j1; ++k1) {
int l1 = k1 - j1;
this.growLeavesLayer(level, new Vector3(k, k1, l), 1 - l1);
}
}
for (int i2 = 0; i2 < height; ++i2) {
Vector3 blockpos = position.up(i2);
if (this.canGrowInto(level.getBlockIdAt((int) blockpos.x, (int) blockpos.y, (int) blockpos.z))) {
this.setBlockAndNotifyAdequately(level, blockpos, this.woodMetadata);
if (i2 > 0) {
this.placeVine(level, rand, blockpos.west(), 8);
this.placeVine(level, rand, blockpos.north(), 1);
}
}
if (i2 < height - 1) {
Vector3 blockpos1 = blockpos.east();
if (this.canGrowInto(level.getBlockIdAt((int) blockpos1.x, (int) blockpos1.y, (int) blockpos1.z))) {
this.setBlockAndNotifyAdequately(level, blockpos1, this.woodMetadata);
if (i2 > 0) {
this.placeVine(level, rand, blockpos1.east(), 2);
this.placeVine(level, rand, blockpos1.north(), 1);
}
}
Vector3 blockpos2 = blockpos.south().east();
if (this.canGrowInto(level.getBlockIdAt((int) blockpos2.x, (int) blockpos2.y, (int) blockpos2.z))) {
this.setBlockAndNotifyAdequately(level, blockpos2, this.woodMetadata);
if (i2 > 0) {
this.placeVine(level, rand, blockpos2.east(), 2);
this.placeVine(level, rand, blockpos2.south(), 4);
}
}
Vector3 blockpos3 = blockpos.south();
if (this.canGrowInto(level.getBlockIdAt((int) blockpos3.x, (int) blockpos3.y, (int) blockpos3.z))) {
this.setBlockAndNotifyAdequately(level, blockpos3, this.woodMetadata);
if (i2 > 0) {
this.placeVine(level, rand, blockpos3.west(), 8);
this.placeVine(level, rand, blockpos3.south(), 4);
}
}
}
}
return true;
}
}
private void placeVine(ChunkManager level, NukkitRandom random, Vector3 pos, int meta) {
if (random.nextBoundedInt(3) > 0 && level.getBlockIdAt((int) pos.x, (int) pos.y, (int) pos.z) == 0) {
this.setBlockAndNotifyAdequately(level, pos, new BlockVine(meta));
}
}
private void createCrown(ChunkManager level, Vector3 pos, int i1) {
for (int j = -2; j <= 0; ++j) {
this.growLeavesLayerStrict(level, pos.up(j), i1 + 1 - j);
}
}
}
| 4,574 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectBirchTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectBirchTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockWood;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ObjectBirchTree extends ObjectTree {
protected int treeHeight = 7;
@Override
public int getTrunkBlock() {
return Block.LOG;
}
@Override
public int getLeafBlock() {
return Block.LEAVES;
}
@Override
public int getType() {
return BlockWood.BIRCH;
}
@Override
public int getTreeHeight() {
return this.treeHeight;
}
@Override
public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) {
this.treeHeight = random.nextBoundedInt(3) + 5;
super.placeObject(level, x, y, z, random);
}
}
| 869 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectOakTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectOakTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockWood;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ObjectOakTree extends ObjectTree {
private int treeHeight = 7;
@Override
public int getTrunkBlock() {
return Block.LOG;
}
@Override
public int getLeafBlock() {
return Block.LEAVES;
}
@Override
public int getType() {
return BlockWood.OAK;
}
@Override
public int getTreeHeight() {
return this.treeHeight;
}
@Override
public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) {
this.treeHeight = random.nextBoundedInt(3) + 4;
super.placeObject(level, x, y, z, random);
}
}
| 863 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectJungleTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectJungleTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockWood;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ObjectJungleTree extends ObjectTree {
private int treeHeight = 8;
@Override
public int getTrunkBlock() {
return Block.LOG;
}
@Override
public int getLeafBlock() {
return Block.LEAVES;
}
@Override
public int getType() {
return BlockWood.JUNGLE;
}
@Override
public int getTreeHeight() {
return this.treeHeight;
}
@Override
public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) {
this.treeHeight = random.nextBoundedInt(6) + 4;
super.placeObject(level, x, y, z, random);
}
}
| 869 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
TreeGenerator.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/TreeGenerator.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.BlockDirt;
import cn.nukkit.item.Item;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.level.Level;
import cn.nukkit.math.BlockVector3;
import cn.nukkit.math.Vector3;
import java.util.Random;
public abstract class TreeGenerator extends cn.nukkit.level.generator.object.BasicGenerator {
/**
* returns whether or not a tree can grow into a block
* For example, a tree will not grow into stone
*/
protected boolean canGrowInto(int id) {
return id == Item.AIR || id == Item.LEAVES || id == Item.GRASS || id == Item.DIRT || id == Item.LOG || id == Item.LOG2 || id == Item.SAPLING || id == Item.VINE;
}
public void generateSaplings(Level level, Random random, Vector3 pos) {
}
protected void setDirtAt(ChunkManager level, BlockVector3 pos) {
setDirtAt(level, new Vector3(pos.x, pos.y, pos.z));
}
/**
* sets dirt at a specific location if it isn't already dirt
*/
protected void setDirtAt(ChunkManager level, Vector3 pos) {
if (level.getBlockIdAt((int) pos.x, (int) pos.y, (int) pos.z) != Item.DIRT) {
this.setBlockAndNotifyAdequately(level, pos, new BlockDirt());
}
}
}
| 1,256 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockSapling;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class ObjectTree {
private boolean overridable(int id) {
switch (id) {
case Block.AIR:
case Block.SAPLING:
case Block.LOG:
case Block.LEAVES:
case Block.SNOW_LAYER:
case Block.LOG2:
case Block.LEAVES2:
return true;
default:
return false;
}
}
public int getType() {
return 0;
}
public int getTrunkBlock() {
return Block.LOG;
}
public int getLeafBlock() {
return Block.LEAVES;
}
public int getTreeHeight() {
return 7;
}
public static void growTree(ChunkManager level, int x, int y, int z, NukkitRandom random) {
growTree(level, x, y, z, random, 0);
}
public static void growTree(ChunkManager level, int x, int y, int z, NukkitRandom random, int type) {
ObjectTree tree;
switch (type) {
case BlockSapling.SPRUCE:
if (random.nextBoundedInt(39) == 0) {
tree = new ObjectSpruceTree();
} else {
tree = new ObjectSpruceTree();
}
break;
case BlockSapling.BIRCH:
if (random.nextBoundedInt(39) == 0) {
tree = new ObjectTallBirchTree();
} else {
tree = new ObjectBirchTree();
}
break;
case BlockSapling.JUNGLE:
tree = new ObjectJungleTree();
break;
case BlockSapling.OAK:
default:
tree = new ObjectOakTree();
//todo: more complex treeeeeeeeeeeeeeeee
break;
}
if (tree.canPlaceObject(level, x, y, z, random)) {
tree.placeObject(level, x, y, z, random);
}
}
public boolean canPlaceObject(ChunkManager level, int x, int y, int z, NukkitRandom random) {
int radiusToCheck = 0;
for (int yy = 0; yy < this.getTreeHeight() + 3; ++yy) {
if (yy == 1 || yy == this.getTreeHeight()) {
++radiusToCheck;
}
for (int xx = -radiusToCheck; xx < (radiusToCheck + 1); ++xx) {
for (int zz = -radiusToCheck; zz < (radiusToCheck + 1); ++zz) {
if (!this.overridable(level.getBlockIdAt(x + xx, y + yy, z + zz))) {
return false;
}
}
}
}
return true;
}
public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) {
this.placeTrunk(level, x, y, z, random, this.getTreeHeight() - 1);
for (int yy = y - 3 + this.getTreeHeight(); yy <= y + this.getTreeHeight(); ++yy) {
double yOff = yy - (y + this.getTreeHeight());
int mid = (int) (1 - yOff / 2);
for (int xx = x - mid; xx <= x + mid; ++xx) {
int xOff = Math.abs(xx - x);
for (int zz = z - mid; zz <= z + mid; ++zz) {
int zOff = Math.abs(zz - z);
if (xOff == mid && zOff == mid && (yOff == 0 || random.nextBoundedInt(2) == 0)) {
continue;
}
if (!Block.solid[level.getBlockIdAt(xx, yy, zz)]) {
level.setBlockIdAt(xx, yy, zz, this.getLeafBlock());
level.setBlockDataAt(xx, yy, zz, this.getType());
}
}
}
}
}
protected void placeTrunk(ChunkManager level, int x, int y, int z, NukkitRandom random, int trunkHeight) {
// The base dirt block
level.setBlockIdAt(x, y - 1, z, Block.DIRT);
for (int yy = 0; yy < trunkHeight; ++yy) {
int blockId = level.getBlockIdAt(x, y + yy, z);
if (this.overridable(blockId)) {
level.setBlockIdAt(x, y + yy, z, this.getTrunkBlock());
level.setBlockDataAt(x, y + yy, z, this.getType());
}
}
}
}
| 4,375 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectSwampTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSwampTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockLeaves;
import cn.nukkit.block.BlockVine;
import cn.nukkit.block.BlockWood;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.BlockVector3;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
public class ObjectSwampTree extends TreeGenerator {
/**
* The metadata value of the wood to use in tree generation.
*/
private final Block metaWood = new BlockWood(BlockWood.OAK);
/**
* The metadata value of the leaves to use in tree generation.
*/
private final Block metaLeaves = new BlockLeaves(BlockLeaves.OAK);
@Override
public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorPosition) {
BlockVector3 position = new BlockVector3(vectorPosition.getFloorX(), vectorPosition.getFloorY(), vectorPosition.getFloorZ());
int i = rand.nextBoundedInt(4) + 5;
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 <= 256) {
for (int j = position.getY(); j <= position.getY() + 1 + i; ++j) {
int k = 1;
if (j == position.getY()) {
k = 0;
}
if (j >= position.getY() + 1 + i - 2) {
k = 3;
}
BlockVector3 pos2 = new BlockVector3();
for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l) {
for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1) {
if (j >= 0 && j < 256) {
pos2.setComponents(l, j, i1);
if (!this.canGrowInto(worldIn.getBlockIdAt(pos2.x, pos2.y, pos2.z))) {
flag = false;
}
} else {
flag = false;
}
}
}
}
if (!flag) {
return false;
} else {
BlockVector3 down = position.down();
int block = worldIn.getBlockIdAt(down.x, down.y, down.z);
if ((block == Block.GRASS || block == Block.DIRT) && position.getY() < 256 - i - 1) {
this.setDirtAt(worldIn, down);
for (int k1 = position.getY() - 3 + i; k1 <= position.getY() + i; ++k1) {
int j2 = k1 - (position.getY() + i);
int l2 = 2 - j2 / 2;
for (int j3 = position.getX() - l2; j3 <= position.getX() + l2; ++j3) {
int k3 = j3 - position.getX();
for (int i4 = position.getZ() - l2; i4 <= position.getZ() + l2; ++i4) {
int j1 = i4 - position.getZ();
if (Math.abs(k3) != l2 || Math.abs(j1) != l2 || rand.nextBoundedInt(2) != 0 && j2 != 0) {
BlockVector3 blockpos = new BlockVector3(j3, k1, i4);
int id = worldIn.getBlockIdAt(blockpos.x, blockpos.y, blockpos.z);
if (id == Block.AIR || id == Block.LEAVES || id == Block.VINE) {
this.setBlockAndNotifyAdequately(worldIn, blockpos, this.metaLeaves);
}
}
}
}
}
for (int l1 = 0; l1 < i; ++l1) {
BlockVector3 up = position.up(l1);
int id = worldIn.getBlockIdAt(up.x, up.y, up.z);
if (id == Block.AIR || id == Block.LEAVES || id == Block.WATER || id == Block.STILL_WATER) {
this.setBlockAndNotifyAdequately(worldIn, up, this.metaWood);
}
}
for (int i2 = position.getY() - 3 + i; i2 <= position.getY() + i; ++i2) {
int k2 = i2 - (position.getY() + i);
int i3 = 2 - k2 / 2;
BlockVector3 pos2 = new BlockVector3();
for (int l3 = position.getX() - i3; l3 <= position.getX() + i3; ++l3) {
for (int j4 = position.getZ() - i3; j4 <= position.getZ() + i3; ++j4) {
pos2.setComponents(l3, i2, j4);
if (worldIn.getBlockIdAt(pos2.x, pos2.y, pos2.z) == Block.LEAVES) {
BlockVector3 blockpos2 = pos2.west();
BlockVector3 blockpos3 = pos2.east();
BlockVector3 blockpos4 = pos2.north();
BlockVector3 blockpos1 = pos2.south();
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos2.x, blockpos2.y, blockpos2.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos2, 8);
}
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos3.x, blockpos3.y, blockpos3.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos3, 2);
}
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos4.x, blockpos4.y, blockpos4.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos4, 1);
}
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos1.x, blockpos1.y, blockpos1.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos1, 4);
}
}
}
}
}
return true;
} else {
return false;
}
}
} else {
return false;
}
}
private void addVine(ChunkManager worldIn, BlockVector3 pos, int meta) {
this.setBlockAndNotifyAdequately(worldIn, pos, new BlockVine(meta));
}
private void addHangingVine(ChunkManager worldIn, BlockVector3 pos, int meta) {
this.addVine(worldIn, pos, meta);
int i = 4;
for (pos = pos.down(); i > 0 && worldIn.getBlockIdAt(pos.x, pos.y, pos.z) == Block.AIR; --i) {
this.addVine(worldIn, pos, meta);
pos = pos.down();
}
}
}
| 6,853 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectSavannaTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSavannaTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockLeaves2;
import cn.nukkit.block.BlockWood2;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
public class ObjectSavannaTree extends TreeGenerator {
private static final Block TRUNK = new BlockWood2(BlockWood2.ACACIA);
private static final Block LEAF = new BlockLeaves2(BlockLeaves2.ACACIA);
public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) {
int i = rand.nextBoundedInt(3) + rand.nextBoundedInt(3) + 5;
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 <= 256) {
for (int j = (int) position.getY(); j <= position.getY() + 1 + i; ++j) {
int k = 1;
if (j == position.getY()) {
k = 0;
}
if (j >= position.getY() + 1 + i - 2) {
k = 2;
}
Vector3 vector3 = new Vector3();
for (int l = (int) position.getX() - k; l <= position.getX() + k && flag; ++l) {
for (int i1 = (int) position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1) {
if (j >= 0 && j < 256) {
vector3.setComponents(l, j, i1);
if (!this.canGrowInto(level.getBlockIdAt((int) vector3.x, (int) vector3.y, (int) vector3.z))) {
flag = false;
}
} else {
flag = false;
}
}
}
}
if (!flag) {
return false;
} else {
Vector3 down = position.down();
int block = level.getBlockIdAt(down.getFloorX(), down.getFloorY(), down.getFloorZ());
if ((block == Block.GRASS || block == Block.DIRT) && position.getY() < 256 - i - 1) {
this.setDirtAt(level, position.down());
BlockFace face = BlockFace.Plane.HORIZONTAL.random(rand);
int k2 = i - rand.nextBoundedInt(4) - 1;
int l2 = 3 - rand.nextBoundedInt(3);
int i3 = position.getFloorX();
int j1 = position.getFloorZ();
int k1 = 0;
for (int l1 = 0; l1 < i; ++l1) {
int i2 = position.getFloorY() + l1;
if (l1 >= k2 && l2 > 0) {
i3 += face.getXOffset();
j1 += face.getZOffset();
--l2;
}
Vector3 blockpos = new Vector3(i3, i2, j1);
int material = level.getBlockIdAt(blockpos.getFloorX(), blockpos.getFloorY(), blockpos.getFloorZ());
if (material == Block.AIR || material == Block.LEAVES) {
this.placeLogAt(level, blockpos);
k1 = i2;
}
}
Vector3 blockpos2 = new Vector3(i3, k1, j1);
for (int j3 = -3; j3 <= 3; ++j3) {
for (int i4 = -3; i4 <= 3; ++i4) {
if (Math.abs(j3) != 3 || Math.abs(i4) != 3) {
this.placeLeafAt(level, blockpos2.add(j3, 0, i4));
}
}
}
blockpos2 = blockpos2.up();
for (int k3 = -1; k3 <= 1; ++k3) {
for (int j4 = -1; j4 <= 1; ++j4) {
this.placeLeafAt(level, blockpos2.add(k3, 0, j4));
}
}
this.placeLeafAt(level, blockpos2.east(2));
this.placeLeafAt(level, blockpos2.west(2));
this.placeLeafAt(level, blockpos2.south(2));
this.placeLeafAt(level, blockpos2.north(2));
i3 = position.getFloorX();
j1 = position.getFloorZ();
BlockFace face1 = BlockFace.Plane.HORIZONTAL.random(rand);
if (face1 != face) {
int l3 = k2 - rand.nextBoundedInt(2) - 1;
int k4 = 1 + rand.nextBoundedInt(3);
k1 = 0;
for (int l4 = l3; l4 < i && k4 > 0; --k4) {
if (l4 >= 1) {
int j2 = position.getFloorY() + l4;
i3 += face1.getXOffset();
j1 += face1.getZOffset();
Vector3 blockpos1 = new Vector3(i3, j2, j1);
int material1 = level.getBlockIdAt(blockpos1.getFloorX(), blockpos1.getFloorY(), blockpos1.getFloorZ());
if (material1 == Block.AIR || material1 == Block.LEAVES) {
this.placeLogAt(level, blockpos1);
k1 = j2;
}
}
++l4;
}
if (k1 > 0) {
Vector3 blockpos3 = new Vector3(i3, k1, j1);
for (int i5 = -2; i5 <= 2; ++i5) {
for (int k5 = -2; k5 <= 2; ++k5) {
if (Math.abs(i5) != 2 || Math.abs(k5) != 2) {
this.placeLeafAt(level, blockpos3.add(i5, 0, k5));
}
}
}
blockpos3 = blockpos3.up();
for (int j5 = -1; j5 <= 1; ++j5) {
for (int l5 = -1; l5 <= 1; ++l5) {
this.placeLeafAt(level, blockpos3.add(j5, 0, l5));
}
}
}
}
return true;
} else {
return false;
}
}
} else {
return false;
}
}
private void placeLogAt(ChunkManager worldIn, Vector3 pos) {
this.setBlockAndNotifyAdequately(worldIn, pos, TRUNK);
}
private void placeLeafAt(ChunkManager worldIn, Vector3 pos) {
int material = worldIn.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ());
if (material == Block.AIR || material == Block.LEAVES) {
this.setBlockAndNotifyAdequately(worldIn, pos, LEAF);
}
}
}
| 6,967 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
HugeTreesGenerator.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/HugeTreesGenerator.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
public abstract class HugeTreesGenerator extends TreeGenerator {
/**
* The base height of the tree
*/
protected final int baseHeight;
/**
* Sets the metadata for the wood blocks used
*/
protected final Block woodMetadata;
/**
* Sets the metadata for the leaves used in huge trees
*/
protected final Block leavesMetadata;
protected int extraRandomHeight;
public HugeTreesGenerator(int baseHeightIn, int extraRandomHeightIn, Block woodMetadataIn, Block leavesMetadataIn) {
this.baseHeight = baseHeightIn;
this.extraRandomHeight = extraRandomHeightIn;
this.woodMetadata = woodMetadataIn;
this.leavesMetadata = leavesMetadataIn;
}
/**
* calculates the height based on this trees base height and its extra random height
*/
protected int getHeight(NukkitRandom rand) {
int i = rand.nextBoundedInt(3) + this.baseHeight;
if (this.extraRandomHeight > 1) {
i += rand.nextBoundedInt(this.extraRandomHeight);
}
return i;
}
/**
* returns whether or not there is space for a tree to grow at a certain position
*/
private boolean isSpaceAt(ChunkManager worldIn, Vector3 leavesPos, int height) {
boolean flag = true;
if (leavesPos.getY() >= 1 && leavesPos.getY() + height + 1 <= 256) {
for (int i = 0; i <= 1 + height; ++i) {
int j = 2;
if (i == 0) {
j = 1;
} else if (i >= 1 + height - 2) {
j = 2;
}
for (int k = -j; k <= j && flag; ++k) {
for (int l = -j; l <= j && flag; ++l) {
Vector3 blockPos = leavesPos.add(k, i, l);
if (leavesPos.getY() + i < 0 || leavesPos.getY() + i >= 256 || !this.canGrowInto(worldIn.getBlockIdAt((int) blockPos.x, (int) blockPos.y, (int) blockPos.z))) {
flag = false;
}
}
}
}
return flag;
} else {
return false;
}
}
/**
* returns whether or not there is dirt underneath the block where the tree will be grown.
* It also generates dirt around the block in a 2x2 square if there is dirt underneath the blockpos.
*/
private boolean ensureDirtsUnderneath(Vector3 pos, ChunkManager worldIn) {
Vector3 blockpos = pos.down();
int block = worldIn.getBlockIdAt((int) blockpos.x, (int) blockpos.y, (int) blockpos.z);
if ((block == Block.GRASS || block == Block.DIRT) && pos.getY() >= 2) {
this.setDirtAt(worldIn, blockpos);
this.setDirtAt(worldIn, blockpos.east());
this.setDirtAt(worldIn, blockpos.south());
this.setDirtAt(worldIn, blockpos.south().east());
return true;
} else {
return false;
}
}
/**
* returns whether or not a tree can grow at a specific position.
* If it can, it generates surrounding dirt underneath.
*/
protected boolean ensureGrowable(ChunkManager worldIn, NukkitRandom rand, Vector3 treePos, int p_175929_4_) {
return this.isSpaceAt(worldIn, treePos, p_175929_4_) && this.ensureDirtsUnderneath(treePos, worldIn);
}
/**
* grow leaves in a circle with the outsides being within the circle
*/
protected void growLeavesLayerStrict(ChunkManager worldIn, Vector3 layerCenter, int width) {
int i = width * width;
for (int j = -width; j <= width + 1; ++j) {
for (int k = -width; k <= width + 1; ++k) {
int l = j - 1;
int i1 = k - 1;
if (j * j + k * k <= i || l * l + i1 * i1 <= i || j * j + i1 * i1 <= i || l * l + k * k <= i) {
Vector3 blockpos = layerCenter.add(j, 0, k);
int id = worldIn.getBlockIdAt((int) blockpos.x, (int) blockpos.y, (int) blockpos.z);
if (id == Block.AIR || id == Block.LEAVES) {
this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata);
}
}
}
}
}
/**
* grow leaves in a circle
*/
protected void growLeavesLayer(ChunkManager worldIn, Vector3 layerCenter, int width) {
int i = width * width;
for (int j = -width; j <= width; ++j) {
for (int k = -width; k <= width; ++k) {
if (j * j + k * k <= i) {
Vector3 blockpos = layerCenter.add(j, 0, k);
int id = worldIn.getBlockIdAt((int) blockpos.x, (int) blockpos.y, (int) blockpos.z);
if (id == Block.AIR || id == Block.LEAVES) {
this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata);
}
}
}
}
}
}
| 5,184 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectSpruceTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/ObjectSpruceTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockWood;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ObjectSpruceTree extends ObjectTree {
private int treeHeight = 15;
@Override
public int getTrunkBlock() {
return Block.LOG;
}
@Override
public int getLeafBlock() {
return Block.LEAVES;
}
@Override
public int getType() {
return BlockWood.SPRUCE;
}
@Override
public int getTreeHeight() {
return this.treeHeight;
}
@Override
public void placeObject(ChunkManager level, int x, int y, int z, NukkitRandom random) {
this.treeHeight = random.nextBoundedInt(4) + 6;
int topSize = this.getTreeHeight() - (1 + random.nextBoundedInt(2));
int lRadius = 2 + random.nextBoundedInt(2);
this.placeTrunk(level, x, y, z, random, this.getTreeHeight() - random.nextBoundedInt(3));
int radius = random.nextBoundedInt(2);
int maxR = 1;
int minR = 0;
for (int yy = 0; yy <= topSize; ++yy) {
int yyy = y + this.treeHeight - yy;
for (int xx = x - radius; xx <= x + radius; ++xx) {
int xOff = Math.abs(xx - x);
for (int zz = z - radius; zz <= z + radius; ++zz) {
int zOff = Math.abs(zz - z);
if (xOff == radius && zOff == radius && radius > 0) {
continue;
}
if (!Block.solid[level.getBlockIdAt(xx, yyy, zz)]) {
level.setBlockIdAt(xx, yyy, zz, this.getLeafBlock());
level.setBlockDataAt(xx, yyy, zz, this.getType());
}
}
}
if (radius >= maxR) {
radius = minR;
minR = 1;
if (++maxR > lRadius) {
maxR = lRadius;
}
} else {
++radius;
}
}
}
}
| 2,132 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
NewJungleTree.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/tree/NewJungleTree.java | package cn.nukkit.level.generator.object.tree;
import cn.nukkit.block.*;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.BlockVector3;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
/**
* Created by CreeperFace on 26. 10. 2016.
*/
public class NewJungleTree extends TreeGenerator {
/**
* The minimum height of a generated tree.
*/
private final int minTreeHeight;
/**
* The metadata value of the wood to use in tree generation.
*/
private final Block metaWood = new BlockWood(BlockWood.JUNGLE);
/**
* The metadata value of the leaves to use in tree generation.
*/
private final Block metaLeaves = new BlockLeaves(BlockLeaves.JUNGLE);
public NewJungleTree(int minTreeHeight) {
this.minTreeHeight = minTreeHeight;
}
@Override
public boolean generate(ChunkManager worldIn, NukkitRandom rand, Vector3 vectorPosition) {
BlockVector3 position = new BlockVector3(vectorPosition.getFloorX(), vectorPosition.getFloorY(), vectorPosition.getFloorZ());
int i = rand.nextBoundedInt(3) + this.minTreeHeight;
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 <= 256) {
for (int j = position.getY(); j <= position.getY() + 1 + i; ++j) {
int k = 1;
if (j == position.getY()) {
k = 0;
}
if (j >= position.getY() + 1 + i - 2) {
k = 2;
}
BlockVector3 pos2 = new BlockVector3();
for (int l = position.getX() - k; l <= position.getX() + k && flag; ++l) {
for (int i1 = position.getZ() - k; i1 <= position.getZ() + k && flag; ++i1) {
if (j >= 0 && j < 256) {
pos2.setComponents(l, j, i1);
if (!this.canGrowInto(worldIn.getBlockIdAt(pos2.x, pos2.y, pos2.z))) {
flag = false;
}
} else {
flag = false;
}
}
}
}
if (!flag) {
return false;
} else {
BlockVector3 down = position.down();
int block = worldIn.getBlockIdAt(down.x, down.y, down.z);
if ((block == Block.GRASS || block == Block.DIRT || block == Block.FARMLAND) && position.getY() < 256 - i - 1) {
this.setDirtAt(worldIn, down);
int k2 = 3;
int l2 = 0;
for (int i3 = position.getY() - 3 + i; i3 <= position.getY() + i; ++i3) {
int i4 = i3 - (position.getY() + i);
int j1 = 1 - i4 / 2;
for (int k1 = position.getX() - j1; k1 <= position.getX() + j1; ++k1) {
int l1 = k1 - position.getX();
for (int i2 = position.getZ() - j1; i2 <= position.getZ() + j1; ++i2) {
int j2 = i2 - position.getZ();
if (Math.abs(l1) != j1 || Math.abs(j2) != j1 || rand.nextBoundedInt(2) != 0 && i4 != 0) {
BlockVector3 blockpos = new BlockVector3(k1, i3, i2);
int id = worldIn.getBlockIdAt(blockpos.x, blockpos.y, blockpos.z);
if (id == Block.AIR || id == Block.LEAVES || id == Block.VINE) {
this.setBlockAndNotifyAdequately(worldIn, blockpos, this.metaLeaves);
}
}
}
}
}
for (int j3 = 0; j3 < i; ++j3) {
BlockVector3 up = position.up(j3);
int id = worldIn.getBlockIdAt(up.x, up.y, up.z);
if (id == Block.AIR || id == Block.LEAVES || id == Block.VINE) {
this.setBlockAndNotifyAdequately(worldIn, up, this.metaWood);
if (j3 > 0) {
if (rand.nextBoundedInt(3) > 0 && isAirBlock(worldIn, position.add(-1, j3, 0))) {
this.addVine(worldIn, position.add(-1, j3, 0), 8);
}
if (rand.nextBoundedInt(3) > 0 && isAirBlock(worldIn, position.add(1, j3, 0))) {
this.addVine(worldIn, position.add(1, j3, 0), 2);
}
if (rand.nextBoundedInt(3) > 0 && isAirBlock(worldIn, position.add(0, j3, -1))) {
this.addVine(worldIn, position.add(0, j3, -1), 1);
}
if (rand.nextBoundedInt(3) > 0 && isAirBlock(worldIn, position.add(0, j3, 1))) {
this.addVine(worldIn, position.add(0, j3, 1), 4);
}
}
}
}
for (int k3 = position.getY() - 3 + i; k3 <= position.getY() + i; ++k3) {
int j4 = k3 - (position.getY() + i);
int k4 = 2 - j4 / 2;
BlockVector3 pos2 = new BlockVector3();
for (int l4 = position.getX() - k4; l4 <= position.getX() + k4; ++l4) {
for (int i5 = position.getZ() - k4; i5 <= position.getZ() + k4; ++i5) {
pos2.setComponents(l4, k3, i5);
if (worldIn.getBlockIdAt(pos2.x, pos2.y, pos2.z) == Block.LEAVES) {
BlockVector3 blockpos2 = pos2.west();
BlockVector3 blockpos3 = pos2.east();
BlockVector3 blockpos4 = pos2.north();
BlockVector3 blockpos1 = pos2.south();
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos2.x, blockpos2.y, blockpos2.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos2, 8);
}
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos3.x, blockpos3.y, blockpos3.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos3, 2);
}
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos4.x, blockpos4.y, blockpos4.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos4, 1);
}
if (rand.nextBoundedInt(4) == 0 && worldIn.getBlockIdAt(blockpos1.x, blockpos1.y, blockpos1.z) == Block.AIR) {
this.addHangingVine(worldIn, blockpos1, 4);
}
}
}
}
}
if (rand.nextBoundedInt(5) == 0 && i > 5) {
for (int l3 = 0; l3 < 2; ++l3) {
for (BlockFace enumfacing : BlockFace.Plane.HORIZONTAL) {
if (rand.nextBoundedInt(4 - l3) == 0) {
BlockFace enumfacing1 = enumfacing.getOpposite();
this.placeCocoa(worldIn, rand.nextBoundedInt(3), position.add(enumfacing1.getXOffset(), i - 5 + l3, enumfacing1.getZOffset()), enumfacing);
}
}
}
}
return true;
} else {
return false;
}
}
} else {
return false;
}
}
private void placeCocoa(ChunkManager worldIn, int age, BlockVector3 pos, BlockFace side) {
int meta = getCocoaMeta(age, side.getIndex());
this.setBlockAndNotifyAdequately(worldIn, pos, new BlockUnknown(127, meta));
}
private void addVine(ChunkManager worldIn, BlockVector3 pos, int meta) {
this.setBlockAndNotifyAdequately(worldIn, pos, new BlockVine(meta));
}
private void addHangingVine(ChunkManager worldIn, BlockVector3 pos, int meta) {
this.addVine(worldIn, pos, meta);
int i = 4;
for (pos = pos.down(); i > 0 && worldIn.getBlockIdAt(pos.x, pos.y, pos.z) == Block.AIR; --i) {
this.addVine(worldIn, pos, meta);
pos = pos.down();
}
}
private boolean isAirBlock(ChunkManager level, BlockVector3 v) {
return level.getBlockIdAt(v.x, v.y, v.z) == 0;
}
private int getCocoaMeta(int age, int side) {
int meta = 0;
meta *= age;
//3 4 2 5
switch (side) {
case 4:
meta++;
break;
case 2:
meta += 2;
break;
case 5:
meta += 3;
break;
}
return meta;
}
}
| 9,535 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BigMushroom.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/mushroom/BigMushroom.java | package cn.nukkit.level.generator.object.mushroom;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockHugeMushroomBrown;
import cn.nukkit.block.BlockHugeMushroomRed;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.level.generator.object.BasicGenerator;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector3;
public class BigMushroom extends BasicGenerator {
public static final int NORTH_WEST = 1;
public static final int NORTH = 2;
public static final int NORTH_EAST = 3;
public static final int WEST = 4;
public static final int CENTER = 5;
public static final int EAST = 6;
public static final int SOUTH_WEST = 7;
public static final int SOUTH = 8;
public static final int SOUTH_EAST = 9;
public static final int STEM = 10;
public static final int ALL_INSIDE = 0;
public static final int ALL_OUTSIDE = 14;
public static final int ALL_STEM = 15;
public static final int BROWN = 0;
public static final int RED = 1;
/**
* The mushroom type. 0 for brown, 1 for red.
*/
private int mushroomType;
public BigMushroom(int mushroomType) {
this.mushroomType = mushroomType;
}
public BigMushroom() {
this.mushroomType = -1;
}
public boolean generate(ChunkManager level, NukkitRandom rand, Vector3 position) {
int block = this.mushroomType;
if (block < 0) {
block = rand.nextBoolean() ? RED : BROWN;
}
Block mushroom = block == 0 ? new BlockHugeMushroomBrown() : new BlockHugeMushroomRed();
int i = rand.nextBoundedInt(3) + 4;
if (rand.nextBoundedInt(12) == 0) {
i *= 2;
}
boolean flag = true;
if (position.getY() >= 1 && position.getY() + i + 1 < 256) {
for (int j = position.getFloorY(); j <= position.getY() + 1 + i; ++j) {
int k = 3;
if (j <= position.getY() + 3) {
k = 0;
}
Vector3 pos = new Vector3();
for (int l = position.getFloorX() - k; l <= position.getX() + k && flag; ++l) {
for (int i1 = position.getFloorZ() - k; i1 <= position.getZ() + k && flag; ++i1) {
if (j >= 0 && j < 256) {
pos.setComponents(l, j, i1);
int material = level.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ());
if (material != Block.AIR && material != Block.LEAVES) {
flag = false;
}
} else {
flag = false;
}
}
}
}
if (!flag) {
return false;
} else {
Vector3 pos2 = position.down();
int block1 = level.getBlockIdAt(pos2.getFloorX(), pos2.getFloorY(), pos2.getFloorZ());
if (block1 != Block.DIRT && block1 != Block.GRASS && block1 != Block.MYCELIUM) {
return false;
} else {
int k2 = position.getFloorY() + i;
if (block == RED) {
k2 = position.getFloorY() + i - 3;
}
for (int l2 = k2; l2 <= position.getY() + i; ++l2) {
int j3 = 1;
if (l2 < position.getY() + i) {
++j3;
}
if (block == BROWN) {
j3 = 3;
}
int k3 = position.getFloorX() - j3;
int l3 = position.getFloorX() + j3;
int j1 = position.getFloorZ() - j3;
int k1 = position.getFloorZ() + j3;
for (int l1 = k3; l1 <= l3; ++l1) {
for (int i2 = j1; i2 <= k1; ++i2) {
int j2 = 5;
if (l1 == k3) {
--j2;
} else if (l1 == l3) {
++j2;
}
if (i2 == j1) {
j2 -= 3;
} else if (i2 == k1) {
j2 += 3;
}
int meta = j2;
if (block == BROWN || l2 < position.getY() + i) {
if ((l1 == k3 || l1 == l3) && (i2 == j1 || i2 == k1)) {
continue;
}
if (l1 == position.getX() - (j3 - 1) && i2 == j1) {
meta = NORTH_WEST;
}
if (l1 == k3 && i2 == position.getZ() - (j3 - 1)) {
meta = NORTH_WEST;
}
if (l1 == position.getX() + (j3 - 1) && i2 == j1) {
meta = NORTH_EAST;
}
if (l1 == l3 && i2 == position.getZ() - (j3 - 1)) {
meta = NORTH_EAST;
}
if (l1 == position.getX() - (j3 - 1) && i2 == k1) {
meta = SOUTH_WEST;
}
if (l1 == k3 && i2 == position.getZ() + (j3 - 1)) {
meta = SOUTH_WEST;
}
if (l1 == position.getX() + (j3 - 1) && i2 == k1) {
meta = SOUTH_EAST;
}
if (l1 == l3 && i2 == position.getZ() + (j3 - 1)) {
meta = SOUTH_EAST;
}
}
if (meta == CENTER && l2 < position.getY() + i) {
meta = ALL_INSIDE;
}
if (position.getY() >= position.getY() + i - 1 || meta != ALL_INSIDE) {
Vector3 blockPos = new Vector3(l1, l2, i2);
if (!Block.solid[level.getBlockIdAt(blockPos.getFloorX(), blockPos.getFloorY(), blockPos.getFloorZ())]) {
mushroom.setDamage(meta);
this.setBlockAndNotifyAdequately(level, blockPos, mushroom);
}
}
}
}
}
for (int i3 = 0; i3 < i; ++i3) {
Vector3 pos = position.up(i3);
int id = level.getBlockIdAt(pos.getFloorX(), pos.getFloorY(), pos.getFloorZ());
if (!Block.solid[id]) {
mushroom.setDamage(STEM);
this.setBlockAndNotifyAdequately(level, pos, mushroom);
}
}
return true;
}
}
} else {
return false;
}
}
}
| 7,764 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
OreType.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/ore/OreType.java | package cn.nukkit.level.generator.object.ore;
import cn.nukkit.block.Block;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class OreType {
public final Block material;
public final int clusterCount;
public final int clusterSize;
public final int maxHeight;
public final int minHeight;
public OreType(Block material, int clusterCount, int clusterSize, int minHeight, int maxHeight) {
this.material = material;
this.clusterCount = clusterCount;
this.clusterSize = clusterSize;
this.maxHeight = maxHeight;
this.minHeight = minHeight;
}
}
| 615 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ObjectOre.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/generator/object/ore/ObjectOre.java | package cn.nukkit.level.generator.object.ore;
import cn.nukkit.block.Block;
import cn.nukkit.level.ChunkManager;
import cn.nukkit.math.NukkitRandom;
import cn.nukkit.math.Vector2;
import cn.nukkit.math.VectorMath;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ObjectOre {
private final NukkitRandom random;
public final OreType type;
private int replaceId;
public ObjectOre(NukkitRandom random, OreType type) {
this(random, type, Block.STONE);
}
public ObjectOre(NukkitRandom random, OreType type, int replaceId) {
this.type = type;
this.random = random;
this.replaceId = replaceId;
}
public OreType getType() {
return type;
}
public boolean canPlaceObject(ChunkManager level, int x, int y, int z) {
return (level.getBlockIdAt(x, y, z) == replaceId);
}
public void placeObject(ChunkManager level, int x, int y, int z) {
int clusterSize = this.type.clusterSize;
double angle = this.random.nextFloat() * Math.PI;
Vector2 offset = VectorMath.getDirection2D(angle).multiply(clusterSize).divide(8);
double x1 = x + 8 + offset.x;
double x2 = x + 8 - offset.x;
double z1 = z + 8 + offset.y;
double z2 = z + 8 - offset.y;
double y1 = y + this.random.nextBoundedInt(3) + 2;
double y2 = y + this.random.nextBoundedInt(3) + 2;
for (int count = 0; count <= clusterSize; ++count) {
double seedX = x1 + (x2 - x1) * count / clusterSize;
double seedY = y1 + (y2 - y1) * count / clusterSize;
double seedZ = z1 + (z2 - z1) * count / clusterSize;
double size = ((Math.sin(count * (Math.PI / clusterSize)) + 1) * this.random.nextFloat() * clusterSize / 16 + 1) / 2;
int startX = (int) (seedX - size);
int startY = (int) (seedY - size);
int startZ = (int) (seedZ - size);
int endX = (int) (seedX + size);
int endY = (int) (seedY + size);
int endZ = (int) (seedZ + size);
for (x = startX; x <= endX; ++x) {
double sizeX = (x + 0.5 - seedX) / size;
sizeX *= sizeX;
if (sizeX < 1) {
for (y = startY; y <= endY; ++y) {
double sizeY = (y + 0.5 - seedY) / size;
sizeY *= sizeY;
if (y > 0 && (sizeX + sizeY) < 1) {
for (z = startZ; z <= endZ; ++z) {
double sizeZ = (z + 0.5 - seedZ) / size;
sizeZ *= sizeZ;
if ((sizeX + sizeY + sizeZ) < 1 && level.getBlockIdAt(x, y, z) == replaceId) {
level.setBlockIdAt(x, y, z, this.type.material.getId());
if (this.type.material.getDamage() != 0) {
level.setBlockDataAt(x, y, z, this.type.material.getDamage());
}
}
}
}
}
}
}
}
}
}
| 3,234 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ChunkSection.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/ChunkSection.java | package cn.nukkit.level.format;
import cn.nukkit.block.Block;
/**
* author: MagicDroidX
* Nukkit Project
*/
public interface ChunkSection extends Cloneable {
int getY();
int getBlockId(int x, int y, int z);
void setBlockId(int x, int y, int z, int id);
int getBlockData(int x, int y, int z);
void setBlockData(int x, int y, int z, int data);
int getFullBlock(int x, int y, int z);
Block getAndSetBlock(int x, int y, int z, Block block);
boolean setBlock(int x, int y, int z, int blockId);
boolean setBlock(int x, int y, int z, int blockId, int meta);
int getBlockSkyLight(int x, int y, int z);
void setBlockSkyLight(int x, int y, int z, int level);
int getBlockLight(int x, int y, int z);
void setBlockLight(int x, int y, int z, int level);
byte[] getIdArray();
byte[] getDataArray();
byte[] getSkyLightArray();
byte[] getLightArray();
boolean isEmpty();
byte[] getBytes();
ChunkSection clone();
}
| 1,002 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FullChunk.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/FullChunk.java | package cn.nukkit.level.format;
import cn.nukkit.block.Block;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.entity.Entity;
import java.io.IOException;
import java.util.Map;
/**
* author: MagicDroidX
* Nukkit Project
*/
public interface FullChunk extends Cloneable {
int getX();
int getZ();
default void setPosition(int x, int z) {
setX(x);
setZ(z);
}
void setX(int x);
void setZ(int z);
long getIndex();
LevelProvider getProvider();
void setProvider(LevelProvider provider);
int getFullBlock(int x, int y, int z);
Block getAndSetBlock(int x, int y, int z, Block block);
boolean setBlock(int x, int y, int z, int blockId);
boolean setBlock(int x, int y, int z, int blockId, int meta);
int getBlockId(int x, int y, int z);
void setBlockId(int x, int y, int z, int id);
int getBlockData(int x, int y, int z);
void setBlockData(int x, int y, int z, int data);
int getBlockExtraData(int x, int y, int z);
void setBlockExtraData(int x, int y, int z, int data);
int getBlockSkyLight(int x, int y, int z);
void setBlockSkyLight(int x, int y, int z, int level);
int getBlockLight(int x, int y, int z);
void setBlockLight(int x, int y, int z, int level);
int getHighestBlockAt(int x, int z);
int getHighestBlockAt(int x, int z, boolean cache);
int getHeightMap(int x, int z);
void setHeightMap(int x, int z, int value);
void recalculateHeightMap();
void populateSkyLight();
int getBiomeId(int x, int z);
void setBiomeId(int x, int z, int biomeId);
int[] getBiomeColor(int x, int z);
void setBiomeColor(int x, int z, int r, int g, int b);
boolean isLightPopulated();
void setLightPopulated();
void setLightPopulated(boolean value);
boolean isPopulated();
void setPopulated();
void setPopulated(boolean value);
boolean isGenerated();
void setGenerated();
void setGenerated(boolean value);
void addEntity(Entity entity);
void removeEntity(Entity entity);
void addBlockEntity(BlockEntity blockEntity);
void removeBlockEntity(BlockEntity blockEntity);
Map<Long, Entity> getEntities();
Map<Long, BlockEntity> getBlockEntities();
BlockEntity getTile(int x, int y, int z);
boolean isLoaded();
boolean load() throws IOException;
boolean load(boolean generate) throws IOException;
boolean unload() throws Exception;
boolean unload(boolean save) throws Exception;
boolean unload(boolean save, boolean safe) throws Exception;
void initChunk();
byte[] getBiomeIdArray();
int[] getBiomeColorArray();
byte[] getHeightMapArray();
byte[] getBlockIdArray();
byte[] getBlockDataArray();
Map<Integer, Integer> getBlockExtraDataArray();
byte[] getBlockSkyLightArray();
byte[] getBlockLightArray();
byte[] toBinary();
byte[] toFastBinary();
boolean hasChanged();
void setChanged();
void setChanged(boolean changed);
}
| 3,068 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Chunk.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/Chunk.java | package cn.nukkit.level.format;
/**
* author: MagicDroidX
* Nukkit Project
*/
public interface Chunk extends FullChunk {
byte SECTION_COUNT = 16;
boolean isSectionEmpty(float fY);
ChunkSection getSection(float fY);
boolean setSection(float fY, ChunkSection section);
ChunkSection[] getSections();
class Entry {
public final int chunkX;
public final int chunkZ;
public Entry(int chunkX, int chunkZ) {
this.chunkX = chunkX;
this.chunkZ = chunkZ;
}
}
}
| 544 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LevelProvider.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/LevelProvider.java | package cn.nukkit.level.format;
import cn.nukkit.level.GameRules;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.math.Vector3;
import cn.nukkit.scheduler.AsyncTask;
import java.util.Map;
/**
* author: MagicDroidX
* Nukkit Project
*/
public interface LevelProvider {
byte ORDER_YZX = 0;
byte ORDER_ZXY = 1;
AsyncTask requestChunkTask(int X, int Z);
String getPath();
String getGenerator();
Map<String, Object> getGeneratorOptions();
BaseFullChunk getLoadedChunk(int X, int Z);
BaseFullChunk getLoadedChunk(long hash);
BaseFullChunk getChunk(int X, int Z);
BaseFullChunk getChunk(int X, int Z, boolean create);
void saveChunks();
void saveChunk(int X, int Z);
void saveChunk(int X, int Z, FullChunk chunk);
void unloadChunks();
boolean loadChunk(int X, int Z);
boolean loadChunk(int X, int Z, boolean create);
boolean unloadChunk(int X, int Z);
boolean unloadChunk(int X, int Z, boolean safe);
boolean isChunkGenerated(int X, int Z);
boolean isChunkPopulated(int X, int Z);
boolean isChunkLoaded(int X, int Z);
boolean isChunkLoaded(long hash);
void setChunk(int chunkX, int chunkZ, FullChunk chunk);
String getName();
boolean isRaining();
void setRaining(boolean raining);
int getRainTime();
void setRainTime(int rainTime);
boolean isThundering();
void setThundering(boolean thundering);
int getThunderTime();
void setThunderTime(int thunderTime);
long getCurrentTick();
void setCurrentTick(long currentTick);
long getTime();
void setTime(long value);
long getSeed();
void setSeed(long value);
Vector3 getSpawn();
void setSpawn(Vector3 pos);
Map<Long, ? extends FullChunk> getLoadedChunks();
void doGarbageCollection();
default void doGarbageCollection(long time) {
}
Level getLevel();
void close();
void saveLevelData();
void updateLevelName(String name);
GameRules getGamerules();
void setGameRules(GameRules rules);
}
| 2,127 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LevelProviderManager.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/LevelProviderManager.java | package cn.nukkit.level.format;
import cn.nukkit.Server;
import java.util.HashMap;
import java.util.Map;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class LevelProviderManager {
protected static final Map<String, Class<? extends LevelProvider>> providers = new HashMap<>();
public static void addProvider(Server server, Class<? extends LevelProvider> clazz) {
try {
providers.put((String) clazz.getMethod("getProviderName").invoke(null), clazz);
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
}
public static Class<? extends LevelProvider> getProvider(String path) {
for (Class<? extends LevelProvider> provider : providers.values()) {
try {
if ((boolean) provider.getMethod("isValid", String.class).invoke(null, path)) {
return provider;
}
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
}
return null;
}
public static Class<? extends LevelProvider> getProviderByName(String name) {
name = name.trim().toLowerCase();
return providers.containsKey(name) ? providers.get(name) : null;
}
}
| 1,292 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ChunkSection.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/ChunkSection.java | package cn.nukkit.level.format.anvil;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.anvil.palette.DataPalette;
import cn.nukkit.level.format.generic.EmptyChunkSection;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.utils.Binary;
import cn.nukkit.utils.ThreadCache;
import cn.nukkit.utils.Utils;
import cn.nukkit.utils.Zlib;
import java.io.IOException;
import java.util.Arrays;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ChunkSection implements cn.nukkit.level.format.ChunkSection {
private final int y;
private DataPalette palette;
protected byte[] blockLight;
protected byte[] skyLight;
protected byte[] compressedLight;
protected boolean hasBlockLight;
protected boolean hasSkyLight;
public ChunkSection(int y) {
this.y = y;
hasBlockLight = false;
hasSkyLight = false;
palette = new DataPalette();
}
public ChunkSection(CompoundTag nbt) {
this.y = nbt.getByte("Y");
byte[] blocks = nbt.getByteArray("Blocks");
byte[] data = nbt.getByteArray("Data");
char[] rawData = new char[4096];
int index = 0;
int i1, i2, i3, i4;
for (int x = 0; x < 16;) {
{
i1 = x;
for (int z = 0; z < 16; z++) {
i2 = i1 + (z << 4);
for (int y = 0; y < 16; y += 2, index += 2) {
i3 = i2 + (y << 8);
i4 = i3 + 256;
char val1 = (char) (((blocks[i3] & 0xFF) << 4) | (data[i3 >> 1] & 0xF));
char val2 = (char) (((blocks[i4] & 0xFF) << 4) | (data[i4 >> 1] & 0xF));
rawData[index] = val1;
rawData[index + 1] = val2;
}
}
}
x++;
{
i1 = x;
for (int z = 0; z < 16; z++) {
i2 = i1 + (z << 4);
for (int y = 0; y < 16; y += 2, index += 2) {
i3 = i2 + (y << 8);
i4 = i3 + 256;
char val1 = (char) (((blocks[i3] & 0xFF) << 4) | ((data[i3 >> 1] & 0xF0) >> 4));
char val2 = (char) (((blocks[i4] & 0xFF) << 4) | ((data[i4 >> 1] & 0xF0) >> 4));
rawData[index] = val1;
rawData[index + 1] = val2;
}
}
}
x++;
}
palette = new DataPalette(rawData);
this.blockLight = nbt.getByteArray("BlockLight");
this.skyLight = nbt.getByteArray("SkyLight");
}
@Override
public int getY() {
return y;
}
@Override
public int getBlockId(int x, int y, int z) {
return palette.getFullBlock(x, y, z) >> 4;
}
@Override
public void setBlockId(int x, int y, int z, int id) {
palette.setFullBlock(x, y, z, (char) (id << 4));
}
@Override
public int getBlockData(int x, int y, int z) {
return palette.getBlockData(x, y, z);
}
@Override
public void setBlockData(int x, int y, int z, int data) {
palette.setBlockData(x, y, z, data);
}
@Override
public int getFullBlock(int x, int y, int z) {
return palette.getFullBlock(x, y, z);
}
@Override
public boolean setBlock(int x, int y, int z, int blockId) {
return setBlock(x, y, z, blockId, 0);
}
public Block getAndSetBlock(int x, int y, int z, Block block) {
int fullId = palette.getAndSetFullBlock(x, y, z, block.getFullId());
return Block.fullList[fullId].clone();
}
@Override
public boolean setBlock(int x, int y, int z, int blockId, int meta) {
int newFullId = (blockId << 4) + meta;
int previousFullId = palette.getAndSetFullBlock(x, y, z, newFullId);
return (newFullId != previousFullId);
}
@Override
public int getBlockSkyLight(int x, int y, int z) {
if (this.skyLight == null && !hasSkyLight) return 0;
this.skyLight = getSkyLightArray();
int sl = this.skyLight[(y << 7) | (z << 3) | (x >> 1)] & 0xff;
if ((x & 1) == 0) {
return sl & 0x0f;
}
return sl >> 4;
}
@Override
public void setBlockSkyLight(int x, int y, int z, int level) {
if (this.skyLight == null) {
if (hasSkyLight) {
this.skyLight = getSkyLightArray();
} else if (level == 0) {
return;
} else {
this.skyLight = new byte[2048];
}
}
int i = (y << 7) | (z << 3) | (x >> 1);
int old = this.skyLight[i] & 0xff;
if ((x & 1) == 0) {
this.skyLight[i] = (byte) ((old & 0xf0) | (level & 0x0f));
} else {
this.skyLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f));
}
}
@Override
public int getBlockLight(int x, int y, int z) {
if (blockLight == null && !hasBlockLight) return 0;
this.blockLight = getLightArray();
int l = blockLight[(y << 7) | (z << 3) | (x >> 1)] & 0xff;
if ((x & 1) == 0) {
return l & 0x0f;
}
return l >> 4;
}
@Override
public void setBlockLight(int x, int y, int z, int level) {
if (this.blockLight == null) {
if (hasBlockLight) {
this.blockLight = getLightArray();
} else if (level == 0) {
return;
} else {
this.blockLight = new byte[2048];
}
}
int i = (y << 7) | (z << 3) | (x >> 1);
int old = this.blockLight[i] & 0xff;
if ((x & 1) == 0) {
this.blockLight[i] = (byte) ((old & 0xf0) | (level & 0x0f));
} else {
this.blockLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f));
}
}
@Override
public byte[] getIdArray() {
char[] raw = palette.getRaw();
byte[][] bufferLayers = ThreadCache.idArray.get();
byte[] buffer = bufferLayers[y];
if (buffer == null) buffer = bufferLayers[y] = new byte[4096];
int srcIndex = 0;
for (int x = 0; x < 16; x++) {
int destIndexX = x;
for (int z = 0; z < 16; z++) {
int destIndexZ = destIndexX + (z << 4);
for (int y = 0; y < 16; y++, srcIndex++) {
int destIndex = destIndexZ + (y << 8);
buffer[destIndex] = (byte) (raw[srcIndex] >> 4);
}
}
}
return buffer;
}
@Override
public byte[] getDataArray() {
char[] raw = palette.getRaw();
byte[][] bufferLayers = ThreadCache.dataArray.get();
byte[] buffer = bufferLayers[y];
if (buffer == null) buffer = bufferLayers[y] = new byte[2048];
int srcIndex = 0;
for (int x = 0; x < 16; x++) {
int destIndexX = x;
for (int z = 0; z < 16; z++) {
int destIndexZ = destIndexX + (z << 4);
for (int y = 0; y < 16; y += 2, srcIndex ++) {
int destIndex1 = destIndexZ + (y << 8);
int destIndex2 = destIndex1 + 256;
byte newVal = (byte) ((raw[destIndex1] & 0xF) + ((raw[destIndex2] & 0xF) << 4));
buffer[srcIndex] = newVal;
}
}
}
return buffer;
}
@Override
public byte[] getSkyLightArray() {
if (this.skyLight != null) return skyLight;
if (hasSkyLight) {
inflate();
return this.skyLight;
} else {
return EmptyChunkSection.EMPTY_LIGHT_ARR;
}
}
private void inflate() {
try {
if (compressedLight != null && compressedLight.length != 0) {
byte[] inflated = Zlib.inflate(compressedLight);
blockLight = Arrays.copyOfRange(inflated, 0, 2048);
skyLight = Arrays.copyOfRange(inflated, 2048, 4096);
compressedLight = null;
} else {
blockLight = new byte[2048];
skyLight = new byte[2048];
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public byte[] getLightArray() {
if (this.blockLight != null) return blockLight;
if (hasBlockLight) {
inflate();
return this.blockLight;
} else {
return EmptyChunkSection.EMPTY_LIGHT_ARR;
}
}
@Override
public boolean isEmpty() {
return false;
}
private byte[] toXZY(char[] raw) {
byte[] buffer = ThreadCache.byteCache6144.get();
for (int i = 0; i < 4096; i++) {
buffer[i] = (byte) (raw[i] >> 4);
}
for (int i = 0, j = 4096; i < 4096; i += 2, j++) {
buffer[j] = (byte) (((raw[i + 1] & 0xF) << 4) | (raw[i] & 0xF));
}
return buffer;
}
@Override
public byte[] getBytes() {
return toXZY(palette.getRaw());
}
public boolean compress() {
if (!palette.compress()) {
if (blockLight != null) {
byte[] arr1 = blockLight;
hasBlockLight = !Utils.isByteArrayEmpty(arr1);
byte[] arr2;
if (skyLight != null) {
arr2 = skyLight;
hasSkyLight = !Utils.isByteArrayEmpty(skyLight);
} else {
arr2 = EmptyChunkSection.EMPTY_LIGHT_ARR;
hasSkyLight = false;
}
blockLight = null;
skyLight = null;
if (hasBlockLight && hasSkyLight) {
try {
compressedLight = Zlib.deflate(Binary.appendBytes(arr1, arr2), 1);
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
return false;
}
return true;
}
@Override
public ChunkSection clone() {
ChunkSection section;
try {
section = (ChunkSection) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
if (this.blockLight != null) section.blockLight = this.blockLight.clone();
if (this.skyLight != null) section.skyLight = this.skyLight.clone();
section.hasBlockLight = this.hasBlockLight;
section.hasSkyLight = this.hasSkyLight;
if (this.compressedLight != null) section.compressedLight = this.compressedLight.clone();
section.palette = this.palette.clone();
return section;
}
}
| 10,907 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Anvil.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/Anvil.java | package cn.nukkit.level.format.anvil;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.blockentity.BlockEntitySpawnable;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.level.format.generic.BaseLevelProvider;
import cn.nukkit.level.format.generic.BaseRegionLoader;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.scheduler.AsyncTask;
import cn.nukkit.utils.BinaryStream;
import cn.nukkit.utils.ChunkException;
import cn.nukkit.utils.ThreadCache;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.*;
import java.util.regex.Pattern;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Anvil extends BaseLevelProvider {
static private final byte[] PAD_256 = new byte[256];
public Anvil(Level level, String path) throws IOException {
super(level, path);
}
public static String getProviderName() {
return "anvil";
}
public static byte getProviderOrder() {
return ORDER_YZX;
}
public static boolean usesChunkSection() {
return true;
}
public static boolean isValid(String path) {
boolean isValid = (new File(path + "/level.dat").exists()) && new File(path + "/region/").isDirectory();
if (isValid) {
for (File file : new File(path + "/region/").listFiles((dir, name) -> Pattern.matches("^.+\\.mc[r|a]$", name))) {
if (!file.getName().endsWith(".mca")) {
isValid = false;
break;
}
}
}
return isValid;
}
public static void generate(String path, String name, long seed, Class<? extends Generator> generator) throws IOException {
generate(path, name, seed, generator, new HashMap<>());
}
public static void generate(String path, String name, long seed, Class<? extends Generator> generator, Map<String, String> options) throws IOException {
if (!new File(path + "/region").exists()) {
new File(path + "/region").mkdirs();
}
CompoundTag levelData = new CompoundTag("Data")
.putCompound("GameRules", new CompoundTag())
.putLong("DayTime", 0)
.putInt("GameType", 0)
.putString("generatorName", Generator.getGeneratorName(generator))
.putString("generatorOptions", options.containsKey("preset") ? options.get("preset") : "")
.putInt("generatorVersion", 1)
.putBoolean("hardcore", false)
.putBoolean("initialized", true)
.putLong("LastPlayed", System.currentTimeMillis() / 1000)
.putString("LevelName", name)
.putBoolean("raining", false)
.putInt("rainTime", 0)
.putLong("RandomSeed", seed)
.putInt("SpawnX", 128)
.putInt("SpawnY", 70)
.putInt("SpawnZ", 128)
.putBoolean("thundering", false)
.putInt("thunderTime", 0)
.putInt("version", 19133)
.putLong("Time", 0)
.putLong("SizeOnDisk", 0);
NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", levelData), new FileOutputStream(path + "level.dat"), ByteOrder.BIG_ENDIAN);
}
public Chunk getEmptyChunk(int chunkX, int chunkZ) {
return Chunk.getEmptyChunk(chunkX, chunkZ, this);
}
@Override
public AsyncTask requestChunkTask(int x, int z) throws ChunkException {
Chunk chunk = (Chunk) this.getChunk(x, z, false);
if (chunk == null) {
throw new ChunkException("Invalid Chunk Set");
}
long timestamp = chunk.getChanges();
byte[] blockEntities = new byte[0];
if (!chunk.getBlockEntities().isEmpty()) {
List<CompoundTag> tagList = new ArrayList<>();
for (BlockEntity blockEntity : chunk.getBlockEntities().values()) {
if (blockEntity instanceof BlockEntitySpawnable) {
tagList.add(((BlockEntitySpawnable) blockEntity).getSpawnCompound());
}
}
try {
blockEntities = NBTIO.write(tagList, ByteOrder.LITTLE_ENDIAN, true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Map<Integer, Integer> extra = chunk.getBlockExtraDataArray();
BinaryStream extraData;
if (!extra.isEmpty()) {
extraData = new BinaryStream();
extraData.putVarInt(extra.size());
for (Map.Entry<Integer, Integer> entry : extra.entrySet()) {
extraData.putVarInt(entry.getKey());
extraData.putLShort(entry.getValue());
}
} else {
extraData = null;
}
BinaryStream stream = ThreadCache.binaryStream.get().reset();
int count = 0;
cn.nukkit.level.format.ChunkSection[] sections = chunk.getSections();
for (int i = sections.length - 1; i >= 0; i--) {
if (!sections[i].isEmpty()) {
count = i + 1;
break;
}
}
stream.putByte((byte) count);
for (int i = 0; i < count; i++) {
stream.putByte((byte) 0);
stream.put(sections[i].getBytes());
}
for (byte height : chunk.getHeightMapArray()) {
stream.putByte(height);
}
stream.put(PAD_256);
stream.put(chunk.getBiomeIdArray());
stream.putByte((byte) 0);
if (extraData != null) {
stream.put(extraData.getBuffer());
} else {
stream.putVarInt(0);
}
stream.put(blockEntities);
this.getLevel().chunkRequestCallback(timestamp, x, z, stream.getBuffer());
return null;
}
private int lastPosition = 0;
@Override
public void doGarbageCollection(long time) {
long start = System.currentTimeMillis();
int maxIterations = size();
if (lastPosition > maxIterations) lastPosition = 0;
ObjectIterator<BaseFullChunk> iter = getChunks();
if (lastPosition != 0) iter.skip(lastPosition);
int i;
for (i = 0; i < maxIterations; i++) {
if (!iter.hasNext()) {
iter = getChunks();
}
BaseFullChunk chunk = iter.next();
if (chunk == null) continue;
if (chunk.isGenerated() && chunk.isPopulated() && chunk instanceof Chunk) {
Chunk anvilChunk = (Chunk) chunk;
for (cn.nukkit.level.format.ChunkSection section : anvilChunk.getSections()) {
if (section instanceof ChunkSection) {
ChunkSection anvilSection = (ChunkSection) section;
if (!anvilSection.isEmpty()) {
anvilSection.compress();
}
}
}
if (System.currentTimeMillis() - start >= time) break;
}
}
lastPosition += i;
}
@Override
public void doGarbageCollection() {
int limit = (int) (System.currentTimeMillis() - 50);
for (Map.Entry<Long, BaseRegionLoader> entry : this.regions.entrySet()) {
long index = entry.getKey();
BaseRegionLoader region = entry.getValue();
if (region.lastUsed <= limit) {
try {
region.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.regions.remove(index);
}
}
}
@Override
public BaseFullChunk loadChunk(long index, int chunkX, int chunkZ, boolean create) {
int regionX = getRegionIndexX(chunkX);
int regionZ = getRegionIndexZ(chunkZ);
BaseRegionLoader region = this.loadRegion(regionX, regionZ);
this.level.timings.syncChunkLoadDataTimer.startTiming();
BaseFullChunk chunk;
try {
chunk = region.readChunk(chunkX - regionX * 32, chunkZ - regionZ * 32);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (chunk == null) {
if (create) {
chunk = this.getEmptyChunk(chunkX, chunkZ);
putChunk(index, chunk);
}
} else {
putChunk(index, chunk);
}
this.level.timings.syncChunkLoadDataTimer.stopTiming();
return chunk;
}
@Override
public void saveChunk(int X, int Z) {
BaseFullChunk chunk = this.getChunk(X, Z);
if (chunk != null) {
try {
this.loadRegion(X >> 5, Z >> 5).writeChunk(chunk);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public void saveChunk(int x, int z, FullChunk chunk) {
if (!(chunk instanceof Chunk)) {
throw new ChunkException("Invalid Chunk class");
}
int regionX = x >> 5;
int regionZ = z >> 5;
this.loadRegion(regionX, regionZ);
chunk.setX(x);
chunk.setZ(z);
try {
this.getRegion(regionX, regionZ).writeChunk(chunk);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static ChunkSection createChunkSection(int y) {
ChunkSection cs = new ChunkSection(y);
Arrays.fill(cs.getSkyLightArray(), (byte) 0xff);
return cs;
}
protected BaseRegionLoader loadRegion(int x, int z) {
BaseRegionLoader tmp = lastRegion;
if (tmp != null && x == tmp.getX() && z == tmp.getZ()) {
return tmp;
}
long index = Level.chunkHash(x, z);
BaseRegionLoader region = this.regions.get(index);
if (region == null) {
try {
region = new RegionLoader(this, x, z);
} catch (IOException e) {
throw new RuntimeException(e);
}
this.regions.put(index, region);
return lastRegion = region;
} else {
return lastRegion = region;
}
}
}
| 10,523 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ChunkRequestTask.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/ChunkRequestTask.java | package cn.nukkit.level.format.anvil;
import cn.nukkit.Server;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.blockentity.BlockEntitySpawnable;
import cn.nukkit.level.Level;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.scheduler.AsyncTask;
import cn.nukkit.utils.Binary;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ChunkRequestTask extends AsyncTask {
protected final int levelId;
protected final byte[] chunk;
protected final int chunkX;
protected final int chunkZ;
protected final long timeStamp;
protected byte[] blockEntities;
public ChunkRequestTask(Level level, Chunk chunk) {
this.timeStamp = chunk.getChanges();
this.levelId = level.getId();
this.chunk = chunk.toFastBinary();
this.chunkX = chunk.getX();
this.chunkZ = chunk.getZ();
byte[] buffer = new byte[0];
for (BlockEntity blockEntity : chunk.getBlockEntities().values()) {
if (blockEntity instanceof BlockEntitySpawnable) {
try {
buffer = Binary.appendBytes(buffer, NBTIO.write(((BlockEntitySpawnable) blockEntity).getSpawnCompound(), ByteOrder.BIG_ENDIAN, true));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
this.blockEntities = buffer;
}
@Override
public void onRun() {
Chunk chunk = Chunk.fromFastBinary(this.chunk);
byte[] ids = chunk.getBlockIdArray();
byte[] meta = chunk.getBlockDataArray();
byte[] heightMap = chunk.getHeightMapArray();
int[] biomeColors = chunk.getBiomeColorArray();
ByteBuffer buffer = ByteBuffer.allocate(
16 * 16 * (128 + 64 + 64 + 64)
+ 256
+ 256
+ this.blockEntities.length
);
ByteBuffer orderedIds = ByteBuffer.allocate(16 * 16 * 128);
ByteBuffer orderedData = ByteBuffer.allocate(16 * 16 * 64);
ByteBuffer orderedSkyLight = ByteBuffer.allocate(16 * 16 * 64);
ByteBuffer orderedLight = ByteBuffer.allocate(16 * 16 * 64);
for (int x = 0; x < 16; ++x) {
for (int z = 0; z < 16; ++z) {
orderedIds.put(this.getColumn(ids, x, z));
orderedData.put(this.getHalfColumn(meta, x, z));
}
}
ByteBuffer orderedHeightMap = ByteBuffer.wrap(heightMap);
ByteBuffer orderedBiomeColors = ByteBuffer.allocate(biomeColors.length * 4);
for (int i : biomeColors) {
orderedBiomeColors.put(Binary.writeInt(i));
}
this.setResult(
buffer
.put(orderedIds)
.put(orderedData)
.put(orderedHeightMap)
.put(orderedBiomeColors)
.put(this.blockEntities)
.array()
);
}
public byte[] getColumn(byte[] data, int x, int z) {
byte[] column = new byte[128];
int i = (z << 4) + x;
for (int y = 0; y < 128; ++y) {
column[y] = data[(y << 8) + i];
}
return column;
}
public byte[] getHalfColumn(byte[] data, int x, int z) {
byte[] column = new byte[64];
int i = (z << 3) + (x >> 1);
if ((x & 1) == 0) {
for (int y = 0; y < 128; y += 2) {
column[(y / 2)] = (byte) ((byte) (data[(y << 7) + i] & 0x0f) | (byte) (((data[((y + 1) << 7) + i] & 0x0f) & 0xff) << 4));
}
} else {
for (int y = 0; y < 128; y += 2) {
column[(y / 2)] = (byte) ((byte) (((data[(y << 7) + i] & 0xf0) & 0xff) >> 4) | (byte) (data[((y + 1) << 7) + i] & 0xf0));
}
}
return column;
}
@Override
public void onCompletion(Server server) {
Level level = server.getLevel(this.levelId);
if (level != null && this.hasResult()) {
level.chunkRequestCallback(timeStamp, this.chunkX, this.chunkZ, (byte[]) this.getResult());
}
}
}
| 4,227 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Chunk.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/Chunk.java | package cn.nukkit.level.format.anvil;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.entity.Entity;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.generic.BaseChunk;
import cn.nukkit.level.format.generic.EmptyChunkSection;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.stream.NBTInputStream;
import cn.nukkit.nbt.stream.NBTOutputStream;
import cn.nukkit.nbt.tag.*;
import cn.nukkit.utils.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.ByteOrder;
import java.util.*;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Chunk extends BaseChunk {
protected CompoundTag nbt;
@Override
public BaseChunk clone() {
Chunk chunk = (Chunk) super.clone();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
NBTOutputStream out = new NBTOutputStream(baos);
try {
nbt.write(out);
NBTInputStream in = new NBTInputStream(new ByteArrayInputStream(baos.toByteArray()));
chunk.nbt = new CompoundTag();
chunk.nbt.load(in);
} catch (IOException e) {
}
return chunk;
}
public Chunk(LevelProvider level) {
this(level, null);
}
public Chunk(Class<? extends LevelProvider> providerClass) {
this((LevelProvider) null, null);
this.providerClass = providerClass;
}
public Chunk(Class<? extends LevelProvider> providerClass, CompoundTag nbt) {
this((LevelProvider) null, nbt);
this.providerClass = providerClass;
}
public Chunk(LevelProvider level, CompoundTag nbt) {
this.provider = level;
if (level != null) {
this.providerClass = level.getClass();
}
if (nbt == null) {
this.nbt = new CompoundTag("Level");
return;
}
this.nbt = nbt;
if (!(this.nbt.contains("Entities") && (this.nbt.get("Entities") instanceof ListTag))) {
this.nbt.putList(new ListTag<CompoundTag>("Entities"));
}
if (!(this.nbt.contains("TileEntities") && (this.nbt.get("TileEntities") instanceof ListTag))) {
this.nbt.putList(new ListTag<CompoundTag>("Entities"));
}
if (!(this.nbt.contains("TileTicks") && (this.nbt.get("TileTicks") instanceof ListTag))) {
this.nbt.putList(new ListTag<CompoundTag>("TileTicks"));
}
if (!(this.nbt.contains("Sections") && (this.nbt.get("Sections") instanceof ListTag))) {
this.nbt.putList(new ListTag<CompoundTag>("Sections"));
}
if (!(this.nbt.contains("BiomeColors") && (this.nbt.get("BiomeColors") != null))) {
this.nbt.putIntArray("BiomeColors", new int[256]);
}
if (!(this.nbt.contains("HeightMap") && (this.nbt.get("HeightMap") instanceof IntArrayTag))) {
this.nbt.putIntArray("HeightMap", new int[256]);
}
cn.nukkit.level.format.ChunkSection[] sections = new cn.nukkit.level.format.ChunkSection[16];
for (Tag section : this.nbt.getList("Sections").getAll()) {
if (section instanceof CompoundTag) {
int y = ((CompoundTag) section).getByte("Y");
if (y < 16) {
sections[y] = new ChunkSection((CompoundTag) section);
}
}
}
for (int y = 0; y < 16; y++) {
if (sections[y] == null) {
sections[y] = EmptyChunkSection.EMPTY[y];
}
}
Map<Integer, Integer> extraData = new HashMap<>();
if (!this.nbt.contains("ExtraData") || !(this.nbt.get("ExtraData") instanceof ByteArrayTag)) {
this.nbt.putByteArray("ExtraData", Binary.writeInt(0));
} else {
BinaryStream stream = new BinaryStream(this.nbt.getByteArray("ExtraData"));
for (int i = 0; i < stream.getInt(); i++) {
int key = stream.getInt();
extraData.put(key, stream.getShort());
}
}
this.setPosition(this.nbt.getInt("xPos"), this.nbt.getInt("zPos"));
for (int Y = 0; Y < sections.length; ++Y) {
cn.nukkit.level.format.ChunkSection section = sections[Y];
if (section != null) {
this.sections[Y] = section;
} else {
throw new ChunkException("Received invalid ChunkSection instance");
}
if (Y >= SECTION_COUNT) {
throw new ChunkException("Invalid amount of chunks");
}
}
int[] biomeColors = this.nbt.getIntArray("BiomeColors");
if (biomeColors.length != 256) {
biomeColors = new int[256];
Arrays.fill(biomeColors, Binary.readInt(new byte[]{(byte) 0xff, (byte) 0x00, (byte) 0x00, (byte) 0x00}));
}
this.biomeColors = biomeColors;
int[] heightMap = this.nbt.getIntArray("HeightMap");
this.heightMap = new byte[256];
if (heightMap.length != 256) {
Arrays.fill(this.heightMap, (byte) 255);
} else {
for (int i = 0; i < heightMap.length; i++) {
this.heightMap[i] = (byte) heightMap[i];
}
}
this.extraData = extraData;
this.NBTentities = this.nbt.getList("Entities", CompoundTag.class).getAll();
this.NBTtiles = this.nbt.getList("TileEntities", CompoundTag.class).getAll();
ListTag<CompoundTag> updateEntries = nbt.getList("TileTicks", CompoundTag.class);
if (updateEntries != null && updateEntries.size() > 0) {
for (CompoundTag entryNBT : updateEntries.getAll()) {
Block block = null;
try {
Tag tag = entryNBT.get("i");
if (tag instanceof StringTag) {
String name = ((StringTag) tag).data;
@SuppressWarnings("unchecked")
Class<? extends Block> clazz = (Class<? extends Block>) Class.forName("cn.nukkit.block." + name);
Constructor constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
block = (Block) constructor.newInstance();
}
} catch (Throwable e) {
continue;
}
if (block == null) {
continue;
}
block.x = entryNBT.getInt("x");
block.y = entryNBT.getInt("y");
block.z = entryNBT.getInt("z");
this.provider.getLevel().scheduleUpdate(block, block, entryNBT.getInt("t"), entryNBT.getInt("p"), false);
}
}
if (this.nbt.contains("Biomes")) {
this.checkOldBiomes(this.nbt.getByteArray("Biomes"));
this.nbt.remove("Biomes");
}
this.nbt.remove("Sections");
this.nbt.remove("ExtraData");
}
@Override
public boolean isPopulated() {
return this.nbt.contains("TerrainPopulated") && this.nbt.getBoolean("TerrainPopulated");
}
@Override
public void setPopulated() {
this.setPopulated(true);
}
@Override
public void setPopulated(boolean value) {
this.nbt.putBoolean("TerrainPopulated", value);
setChanged();
}
@Override
public boolean isGenerated() {
if (this.nbt.contains("TerrainGenerated")) {
return this.nbt.getBoolean("TerrainGenerated");
} else if (this.nbt.contains("TerrainPopulated")) {
return this.nbt.getBoolean("TerrainPopulated");
}
return false;
}
@Override
public void setGenerated() {
this.setGenerated(true);
}
@Override
public void setGenerated(boolean value) {
this.nbt.putBoolean("TerrainGenerated", value);
setChanged();
}
public CompoundTag getNBT() {
return nbt;
}
public static Chunk fromBinary(byte[] data) {
return fromBinary(data, null);
}
public static Chunk fromBinary(byte[] data, LevelProvider provider) {
try {
CompoundTag chunk = NBTIO.read(new ByteArrayInputStream(Zlib.inflate(data)), ByteOrder.BIG_ENDIAN);
if (!chunk.contains("Level") || !(chunk.get("Level") instanceof CompoundTag)) {
return null;
}
return new Chunk(provider, chunk.getCompound("Level"));
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
return null;
}
}
public static Chunk fromFastBinary(byte[] data) {
return fromFastBinary(data, null);
}
public static Chunk fromFastBinary(byte[] data, LevelProvider provider) {
try {
CompoundTag chunk = NBTIO.read(new DataInputStream(new ByteArrayInputStream(data)), ByteOrder.BIG_ENDIAN);
if (!chunk.contains("Level") || !(chunk.get("Level") instanceof CompoundTag)) {
return null;
}
return new Chunk(provider, chunk.getCompound("Level"));
} catch (Exception e) {
return null;
}
}
@Override
public byte[] toFastBinary() {
CompoundTag nbt = this.getNBT().copy();
nbt.putInt("xPos", this.getX());
nbt.putInt("zPos", this.getZ());
nbt.putIntArray("BiomeColors", this.getBiomeColorArray());
int[] heightInts = new int[256];
byte[] heightBytes = this.getHeightMapArray();
for (int i = 0; i < heightInts.length; i++) {
heightInts[i] = heightBytes[i] & 0xFF;
}
for (cn.nukkit.level.format.ChunkSection section : this.getSections()) {
if (section instanceof EmptyChunkSection) {
continue;
}
CompoundTag s = new CompoundTag(null);
s.putByte("Y", section.getY());
s.putByteArray("Blocks", section.getIdArray());
s.putByteArray("Data", section.getDataArray());
s.putByteArray("BlockLight", section.getLightArray());
s.putByteArray("SkyLight", section.getSkyLightArray());
nbt.getList("Sections", CompoundTag.class).add(s);
}
ArrayList<CompoundTag> entities = new ArrayList<>();
for (Entity entity : this.getEntities().values()) {
if (!(entity instanceof Player) && !entity.closed) {
entity.saveNBT();
entities.add(entity.namedTag);
}
}
ListTag<CompoundTag> entityListTag = new ListTag<>("Entities");
entityListTag.setAll(entities);
nbt.putList(entityListTag);
ArrayList<CompoundTag> tiles = new ArrayList<>();
for (BlockEntity blockEntity : this.getBlockEntities().values()) {
blockEntity.saveNBT();
tiles.add(blockEntity.namedTag);
}
ListTag<CompoundTag> tileListTag = new ListTag<>("TileEntities");
tileListTag.setAll(tiles);
nbt.putList(tileListTag);
Set<BlockUpdateEntry> entries = this.provider.getLevel().getPendingBlockUpdates(this);
if (entries != null) {
ListTag<CompoundTag> tileTickTag = new ListTag<>("TileTicks");
long totalTime = this.provider.getLevel().getCurrentTick();
for (BlockUpdateEntry entry : entries) {
CompoundTag entryNBT = new CompoundTag()
.putString("i", entry.block.getSaveId())
.putInt("x", entry.pos.getFloorX())
.putInt("y", entry.pos.getFloorY())
.putInt("z", entry.pos.getFloorZ())
.putInt("t", (int) (entry.delay - totalTime))
.putInt("p", entry.priority);
tileTickTag.add(entryNBT);
}
nbt.putList(tileTickTag);
}
BinaryStream extraData = new BinaryStream();
Map<Integer, Integer> extraDataArray = this.getBlockExtraDataArray();
extraData.putInt(extraDataArray.size());
for (Integer key : extraDataArray.keySet()) {
extraData.putInt(key);
extraData.putShort(extraDataArray.get(key));
}
nbt.putByteArray("ExtraData", extraData.getBuffer());
CompoundTag chunk = new CompoundTag("");
chunk.putCompound("Level", nbt);
try {
return NBTIO.write(chunk, ByteOrder.BIG_ENDIAN);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public byte[] toBinary() {
CompoundTag nbt = this.getNBT().copy();
nbt.putInt("xPos", this.getX());
nbt.putInt("zPos", this.getZ());
ListTag<CompoundTag> sectionList = new ListTag<>("Sections");
for (cn.nukkit.level.format.ChunkSection section : this.getSections()) {
if (section instanceof EmptyChunkSection) {
continue;
}
CompoundTag s = new CompoundTag(null);
s.putByte("Y", (section.getY()));
s.putByteArray("Blocks", section.getIdArray());
s.putByteArray("Data", section.getDataArray());
s.putByteArray("BlockLight", section.getLightArray());
s.putByteArray("SkyLight", section.getSkyLightArray());
sectionList.add(s);
}
nbt.putList(sectionList);
nbt.putIntArray("BiomeColors", this.getBiomeColorArray());
int[] heightInts = new int[256];
byte[] heightBytes = this.getHeightMapArray();
for (int i = 0; i < heightInts.length; i++) {
heightInts[i] = heightBytes[i] & 0xFF;
}
nbt.putIntArray("HeightMap", heightInts);
ArrayList<CompoundTag> entities = new ArrayList<>();
for (Entity entity : this.getEntities().values()) {
if (!(entity instanceof Player) && !entity.closed) {
entity.saveNBT();
entities.add(entity.namedTag);
}
}
ListTag<CompoundTag> entityListTag = new ListTag<>("Entities");
entityListTag.setAll(entities);
nbt.putList(entityListTag);
ArrayList<CompoundTag> tiles = new ArrayList<>();
for (BlockEntity blockEntity : this.getBlockEntities().values()) {
blockEntity.saveNBT();
tiles.add(blockEntity.namedTag);
}
ListTag<CompoundTag> tileListTag = new ListTag<>("TileEntities");
tileListTag.setAll(tiles);
nbt.putList(tileListTag);
Set<BlockUpdateEntry> entries = this.provider.getLevel().getPendingBlockUpdates(this);
if (entries != null) {
ListTag<CompoundTag> tileTickTag = new ListTag<>("TileTicks");
long totalTime = this.provider.getLevel().getCurrentTick();
for (BlockUpdateEntry entry : entries) {
CompoundTag entryNBT = new CompoundTag()
.putString("i", entry.block.getSaveId())
.putInt("x", entry.pos.getFloorX())
.putInt("y", entry.pos.getFloorY())
.putInt("z", entry.pos.getFloorZ())
.putInt("t", (int) (entry.delay - totalTime))
.putInt("p", entry.priority);
tileTickTag.add(entryNBT);
}
nbt.putList(tileTickTag);
}
BinaryStream extraData = new BinaryStream();
Map<Integer, Integer> extraDataArray = this.getBlockExtraDataArray();
extraData.putInt(extraDataArray.size());
for (Integer key : extraDataArray.keySet()) {
extraData.putInt(key);
extraData.putShort(extraDataArray.get(key));
}
nbt.putByteArray("ExtraData", extraData.getBuffer());
CompoundTag chunk = new CompoundTag("");
chunk.putCompound("Level", nbt);
try {
return Zlib.deflate(NBTIO.write(chunk, ByteOrder.BIG_ENDIAN), RegionLoader.COMPRESSION_LEVEL);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public int getBlockSkyLight(int x, int y, int z) {
cn.nukkit.level.format.ChunkSection section = this.sections[y >> 4];
if (section instanceof cn.nukkit.level.format.anvil.ChunkSection) {
cn.nukkit.level.format.anvil.ChunkSection anvilSection = (cn.nukkit.level.format.anvil.ChunkSection) section;
if (anvilSection.skyLight != null) {
return section.getBlockSkyLight(x, y & 0x0f, z);
} else if (!anvilSection.hasSkyLight) {
return 0;
} else {
int height = getHighestBlockAt(x, z);
if (height < y) {
return 15;
} else if (height == y) {
return Block.transparent[getBlockId(x, y, z)] ? 15 : 0;
} else {
return section.getBlockSkyLight(x, y & 0x0f, z);
}
}
} else {
return section.getBlockSkyLight(x, y & 0x0f, z);
}
}
@Override
public int getBlockLight(int x, int y, int z) {
cn.nukkit.level.format.ChunkSection section = this.sections[y >> 4];
if (section instanceof cn.nukkit.level.format.anvil.ChunkSection) {
cn.nukkit.level.format.anvil.ChunkSection anvilSection = (cn.nukkit.level.format.anvil.ChunkSection) section;
if (anvilSection.blockLight != null) {
return section.getBlockLight(x, y & 0x0f, z);
} else if (!anvilSection.hasBlockLight) {
return 0;
} else {
return section.getBlockLight(x, y & 0x0f, z);
}
} else {
return section.getBlockLight(x, y & 0x0f, z);
}
}
public static Chunk getEmptyChunk(int chunkX, int chunkZ) {
return getEmptyChunk(chunkX, chunkZ, null);
}
public static Chunk getEmptyChunk(int chunkX, int chunkZ, LevelProvider provider) {
try {
Chunk chunk;
if (provider != null) {
chunk = new Chunk(provider, null);
} else {
chunk = new Chunk(Anvil.class, null);
}
chunk.setPosition(chunkX, chunkZ);
chunk.sections = new cn.nukkit.level.format.ChunkSection[16];
for (int y = 0; y < 16; ++y) {
chunk.sections[y] = EmptyChunkSection.EMPTY[y];
}
chunk.heightMap = new byte[256];
chunk.biomeColors = new int[256];
chunk.nbt.putByte("V", 1);
chunk.nbt.putLong("InhabitedTime", 0);
chunk.nbt.putBoolean("TerrainGenerated", false);
chunk.nbt.putBoolean("TerrainPopulated", false);
chunk.nbt.putBoolean("LightPopulated", false);
return chunk;
} catch (Exception e) {
return null;
}
}
}
| 19,250 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
RegionLoader.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/RegionLoader.java | package cn.nukkit.level.format.anvil;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.generic.BaseRegionLoader;
import cn.nukkit.utils.*;
import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class RegionLoader extends BaseRegionLoader {
public RegionLoader(LevelProvider level, int regionX, int regionZ) throws IOException {
super(level, regionX, regionZ, "mca");
}
@Override
protected boolean isChunkGenerated(int index) {
Integer[] array = this.locationTable.get(index);
return !(array[0] == 0 || array[1] == 0);
}
@Override
public Chunk readChunk(int x, int z) throws IOException {
int index = getChunkOffset(x, z);
if (index < 0 || index >= 4096) {
return null;
}
this.lastUsed = System.currentTimeMillis();
if (!this.isChunkGenerated(index)) {
return null;
}
try {
Integer[] table = this.locationTable.get(index);
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(table[0] << 12);
int length = raf.readInt();
byte compression = raf.readByte();
if (length <= 0 || length >= MAX_SECTOR_LENGTH) {
if (length >= MAX_SECTOR_LENGTH) {
table[0] = ++this.lastSector;
table[1] = 1;
this.locationTable.put(index, table);
MainLogger.getLogger().error("Corrupted chunk header detected");
}
return null;
}
if (length > (table[1] << 12)) {
MainLogger.getLogger().error("Corrupted bigger chunk detected");
table[1] = length >> 12;
this.locationTable.put(index, table);
this.writeLocationIndex(index);
} else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) {
MainLogger.getLogger().error("Invalid compression type");
return null;
}
byte[] data = new byte[length - 1];
raf.readFully(data);
Chunk chunk = this.unserializeChunk(data);
if (chunk != null) {
return chunk;
} else {
MainLogger.getLogger().error("Corrupted chunk detected");
return null;
}
} catch (EOFException e) {
MainLogger.getLogger().error("Your world is corrupt, because some code is bad and corrupted it. oops. ");
return null;
}
}
@Override
protected Chunk unserializeChunk(byte[] data) {
return Chunk.fromBinary(data, this.levelProvider);
}
@Override
public boolean chunkExists(int x, int z) {
return this.isChunkGenerated(getChunkOffset(x, z));
}
@Override
protected void saveChunk(int x, int z, byte[] chunkData) throws IOException {
int length = chunkData.length + 1;
if (length + 4 > MAX_SECTOR_LENGTH) {
throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH);
}
int sectors = (int) Math.ceil((length + 4) / 4096d);
int index = getChunkOffset(x, z);
boolean indexChanged = false;
Integer[] table = this.locationTable.get(index);
if (table[1] < sectors) {
table[0] = this.lastSector + 1;
this.locationTable.put(index, table);
this.lastSector += sectors;
indexChanged = true;
} else if (table[1] != sectors) {
indexChanged = true;
}
table[1] = sectors;
table[2] = (int) (System.currentTimeMillis() / 1000d);
this.locationTable.put(index, table);
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(table[0] << 12);
BinaryStream stream = new BinaryStream();
stream.put(Binary.writeInt(length));
stream.putByte(COMPRESSION_ZLIB);
stream.put(chunkData);
byte[] data = stream.getBuffer();
if (data.length < sectors << 12) {
byte[] newData = new byte[sectors << 12];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
raf.write(data);
if (indexChanged) {
this.writeLocationIndex(index);
}
}
@Override
public void removeChunk(int x, int z) {
int index = getChunkOffset(x, z);
Integer[] table = this.locationTable.get(0);
table[0] = 0;
table[1] = 0;
this.locationTable.put(index, table);
}
@Override
public void writeChunk(FullChunk chunk) throws Exception {
this.lastUsed = System.currentTimeMillis();
byte[] chunkData = chunk.toBinary();
this.saveChunk(chunk.getX() & 0x1f, chunk.getZ() & 0x1f, chunkData);
}
protected static int getChunkOffset(int x, int z) {
return x | (z << 5);
}
@Override
public void close() throws IOException {
this.writeLocationTable();
this.levelProvider = null;
super.close();
}
@Override
public int doSlowCleanUp() throws Exception {
RandomAccessFile raf = this.getRandomAccessFile();
for (int i = 0; i < 1024; i++) {
Integer[] table = this.locationTable.get(i);
if (table[0] == 0 || table[1] == 0) {
continue;
}
raf.seek(table[0] << 12);
byte[] chunk = new byte[table[1] << 12];
raf.readFully(chunk);
int length = Binary.readInt(Arrays.copyOfRange(chunk, 0, 3));
if (length <= 1) {
this.locationTable.put(i, (table = new Integer[]{0, 0, 0}));
}
try {
chunk = Zlib.inflate(Arrays.copyOf(chunk, 5));
} catch (Exception e) {
this.locationTable.put(i, new Integer[]{0, 0, 0});
continue;
}
chunk = Zlib.deflate(chunk, 9);
ByteBuffer buffer = ByteBuffer.allocate(4 + 1 + chunk.length);
buffer.put(Binary.writeInt(chunk.length + 1));
buffer.put(COMPRESSION_ZLIB);
buffer.put(chunk);
chunk = buffer.array();
int sectors = (int) Math.ceil(chunk.length / 4096d);
if (sectors > table[1]) {
table[0] = this.lastSector + 1;
this.lastSector += sectors;
this.locationTable.put(i, table);
}
raf.seek(table[0] << 12);
byte[] bytes = new byte[sectors << 12];
ByteBuffer buffer1 = ByteBuffer.wrap(bytes);
buffer1.put(chunk);
raf.write(buffer1.array());
}
this.writeLocationTable();
int n = this.cleanGarbage();
this.writeLocationTable();
return n;
}
@Override
protected void loadLocationTable() throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(0);
this.lastSector = 1;
int[] data = new int[1024 * 2]; //1024 records * 2 times
for (int i = 0; i < 1024 * 2; i++) {
data[i] = raf.readInt();
}
for (int i = 0; i < 1024; ++i) {
int index = data[i];
this.locationTable.put(i, new Integer[]{index >> 8, index & 0xff, data[1024 + i]});
int value = this.locationTable.get(i)[0] + this.locationTable.get(i)[1] - 1;
if (value > this.lastSector) {
this.lastSector = value;
}
}
}
private void writeLocationTable() throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(0);
for (int i = 0; i < 1024; ++i) {
Integer[] array = this.locationTable.get(i);
raf.writeInt((array[0] << 8) | array[1]);
}
for (int i = 0; i < 1024; ++i) {
Integer[] array = this.locationTable.get(i);
raf.writeInt(array[2]);
}
}
private int cleanGarbage() throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
Map<Integer, Integer> sectors = new TreeMap<>();
for (Map.Entry entry : this.locationTable.entrySet()) {
Integer index = (Integer) entry.getKey();
Integer[] data = (Integer[]) entry.getValue();
if (data[0] == 0 || data[1] == 0) {
this.locationTable.put(index, new Integer[]{0, 0, 0});
continue;
}
sectors.put(data[0], index);
}
if (sectors.size() == (this.lastSector - 2)) {
return 0;
}
int shift = 0;
int lastSector = 1;
raf.seek(8192);
int s = 2;
for (int sector : sectors.keySet()) {
s = sector;
int index = sectors.get(sector);
if ((sector - lastSector) > 1) {
shift += sector - lastSector - 1;
}
if (shift > 0) {
raf.seek(sector << 12);
byte[] old = new byte[4096];
raf.readFully(old);
raf.seek((sector - shift) << 12);
raf.write(old);
}
Integer[] v = this.locationTable.get(index);
v[0] -= shift;
this.locationTable.put(index, v);
this.lastSector = sector;
}
raf.setLength((s + 1) << 12);
return shift;
}
@Override
protected void writeLocationIndex(int index) throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
Integer[] array = this.locationTable.get(index);
raf.seek(index << 2);
raf.writeInt((array[0] << 8) | array[1]);
raf.seek(4096 + (index << 2));
raf.writeInt(array[2]);
}
@Override
protected void createBlank() throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(0);
raf.setLength(0);
this.lastSector = 1;
int time = (int) (System.currentTimeMillis() / 1000d);
for (int i = 0; i < 1024; ++i) {
this.locationTable.put(i, new Integer[]{0, 0, time});
raf.writeInt(0);
}
for (int i = 0; i < 1024; ++i) {
raf.writeInt(time);
}
}
@Override
public int getX() {
return x;
}
@Override
public int getZ() {
return z;
}
}
| 10,635 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
CharPalette.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/palette/CharPalette.java | package cn.nukkit.level.format.anvil.palette;
import java.util.Arrays;
/**
* @author https://github.com/boy0001/
*/
public class CharPalette {
private static char[] CHAR0 = new char[0];
private char[] keys = CHAR0;
private char lastIndex = Character.MAX_VALUE;
public void add(char key) {
keys = insert(key);
lastIndex = Character.MAX_VALUE;
}
protected void set(char[] keys) {
this.keys = keys;
lastIndex = Character.MAX_VALUE;
}
private char[] insert(char val) {
if (keys.length == 0) {
return new char[] { val };
}
else if (val < keys[0]) {
char[] s = new char[keys.length + 1];
System.arraycopy(keys, 0, s, 1, keys.length);
s[0] = val;
return s;
} else if (val > keys[keys.length - 1]) {
char[] s = Arrays.copyOf(keys, keys.length + 1);
s[keys.length] = val;
return s;
}
char[] s = Arrays.copyOf(keys, keys.length + 1);
for (int i = 0; i < s.length; i++) {
if (keys[i] < val) {
continue;
}
System.arraycopy(keys, i, s, i + 1, s.length - i - 1);
s[i] = val;
break;
}
return s;
}
public char getKey(int index) {
return keys[index];
}
public char getValue(char key) {
char lastTmp = lastIndex;
boolean hasLast = lastTmp != Character.MAX_VALUE;
int index;
if (hasLast) {
char lastKey = keys[lastTmp];
if (lastKey == key) return lastTmp;
if (lastKey > key) {
index = binarySearch0(0, lastTmp, key);
} else {
index = binarySearch0(lastTmp + 1, keys.length, key);
}
} else {
index = binarySearch0(0, keys.length, key);
}
if (index >= keys.length || index < 0) {
return lastTmp = Character.MAX_VALUE;
} else {
return lastTmp = (char) index;
}
}
private int binarySearch0(int fromIndex, int toIndex, char key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
char midVal = keys[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
}
| 2,579 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BitArray.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/palette/BitArray.java | package cn.nukkit.level.format.anvil.palette;
import cn.nukkit.utils.ThreadCache;
/**
* @author https://github.com/boy0001/
*/
public final class BitArray {
private final int bitsPerEntry;
private final int maxSeqLocIndex;
private final int maxEntryValue;
private final long[] data;
public BitArray(int bitsPerEntry) {
this.bitsPerEntry = bitsPerEntry;
this.maxSeqLocIndex = 64 - bitsPerEntry;
maxEntryValue = (1 << bitsPerEntry) - 1;
int longLen = (this.bitsPerEntry * 4096) >> 6;
this.data = new long[longLen];
}
public final void setAt(int index, int value) {
int bitIndexStart = index * bitsPerEntry;
int longIndexStart = bitIndexStart >> 6;
int localBitIndexStart = bitIndexStart & 63;
this.data[longIndexStart] = this.data[longIndexStart] & ~((long) maxEntryValue << localBitIndexStart) | ((long) value) << localBitIndexStart;
if(localBitIndexStart > maxSeqLocIndex) {
int longIndexEnd = longIndexStart + 1;
int localShiftStart = 64 - localBitIndexStart;
int localShiftEnd = bitsPerEntry - localShiftStart;
this.data[longIndexEnd] = this.data[longIndexEnd] >>> localShiftEnd << localShiftEnd | (((long) value) >> localShiftStart);
}
}
public final int getAt(int index) {
int bitIndexStart = index * bitsPerEntry;
int longIndexStart = bitIndexStart >> 6;
int localBitIndexStart = bitIndexStart & 63;
if(localBitIndexStart <= maxSeqLocIndex) {
return (int)(this.data[longIndexStart] >>> localBitIndexStart & maxEntryValue);
} else {
int localShift = 64 - localBitIndexStart;
return (int) ((this.data[longIndexStart] >>> localBitIndexStart | this.data[longIndexStart + 1] << localShift) & maxEntryValue);
}
}
public final void fromRawSlow(char[] arr) {
for (int i = 0; i < arr.length; i++) {
setAt(i, arr[i]);
}
}
public final void fromRaw(char[] arr) {
final long[] data = this.data;
final int dataLength = data.length;
final int bitsPerEntry = this.bitsPerEntry;
final int maxEntryValue = this.maxEntryValue;
final int maxSeqLocIndex = this.maxSeqLocIndex;
int localStart = 0;
char lastVal;
int arrI = 0;
long l = 0;
long nextVal;
for (int i = 0; i < dataLength; i++) {
for (; localStart <= maxSeqLocIndex; localStart += bitsPerEntry) {
lastVal = arr[arrI++];
l |= ((long) lastVal << localStart);
}
if (localStart < 64) {
if (i != dataLength - 1) {
lastVal = arr[arrI++];
int shift = 64 - localStart;
nextVal = lastVal >> shift;
l |= ((lastVal - (nextVal << shift)) << localStart);
data[i] = l;
data[i + 1] = l = nextVal;
localStart -= maxSeqLocIndex;
}
} else {
localStart = 0;
data[i] = l;
l = 0;
}
}
}
public BitArray grow(int newBitsPerEntry) {
int amtGrow = newBitsPerEntry - this.bitsPerEntry;
if (amtGrow <= 0) return this;
BitArray newBitArray = new BitArray(newBitsPerEntry);
char[] buffer = ThreadCache.charCache4096.get();
toRaw(buffer);
newBitArray.fromRaw(buffer);
return newBitArray;
}
public BitArray growSlow(int bitsPerEntry) {
BitArray newBitArray = new BitArray(bitsPerEntry);
for (int i = 0; i < 4096; i++) {
newBitArray.setAt(i, getAt(i));
}
return newBitArray;
}
public final char[] toRawSlow() {
char[] arr = new char[4096];
for (int i = 0; i < arr.length; i++) {
arr[i] = (char) getAt(i);
}
return arr;
}
public final char[] toRaw() {
return toRaw(new char[4096]);
}
protected final char[] toRaw(char[] buffer) {
final long[] data = this.data;
final int dataLength = data.length;
final int bitsPerEntry = this.bitsPerEntry;
final int maxEntryValue = this.maxEntryValue;
final int maxSeqLocIndex = this.maxSeqLocIndex;
int localStart = 0;
char lastVal;
int arrI = 0;
long l;
for (int i = 0; i < dataLength; i++) {
l = data[i];
for (; localStart <= maxSeqLocIndex; localStart += bitsPerEntry) {
lastVal = (char) (l >>> localStart & maxEntryValue);
buffer[arrI++] = lastVal;
}
if (localStart < 64) {
if (i != dataLength - 1) {
lastVal = (char) (l >>> localStart);
localStart -= maxSeqLocIndex;
l = data[i + 1];
int localShift = bitsPerEntry - localStart;
lastVal |= l << localShift;
lastVal &= maxEntryValue;
buffer[arrI++] = lastVal;
}
} else {
localStart = 0;
}
}
return buffer;
}
}
| 5,329 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DataPalette.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/anvil/palette/DataPalette.java | package cn.nukkit.level.format.anvil.palette;
import cn.nukkit.math.MathHelper;
import cn.nukkit.utils.ThreadCache;
import java.util.Arrays;
/**
* @author https://github.com/boy0001/
*/
public final class DataPalette implements Cloneable {
private char[] rawData;
private BitArray encodedData;
private CharPalette palette;
// TODO compress unused sections
// private byte[] compressedData;
public DataPalette() {
this(new char[4096]);
}
public DataPalette(char[] rawData) {
this.rawData = rawData;
}
public synchronized char[] getRaw() {
char[] raw = rawData;
if (raw == null) {
raw = encodedData.toRaw();
for (int i = 0; i < 4096; i++) {
raw[i] = palette.getKey(raw[i]);
}
}
rawData = raw;
encodedData = null;
palette = null;
return rawData;
}
private int getIndex(int x, int y, int z) {
return (x << 8) + (z << 4) + y; // XZY = Bedrock format
}
public int getBlockData(int x, int y, int z) {
return getFullBlock(x, y, z) & 0xF;
}
public int getBlockId(int x, int y, int z) {
return getFullBlock(x, y, z) >> 4;
}
public void setBlockId(int x, int y, int z, int id) {
setFullBlock(x, y, z, (char) (id << 4));
}
public void setBlockData(int x, int y, int z, int data) {
int index = getIndex(x, y, z);
char[] raw = rawData;
if (raw != null) {
int fullId = raw[index];
raw[index] = (char) ((fullId & 0xFFF0) | data);
} else {
char fullId = palette.getKey(encodedData.getAt(index));
if ((fullId & 0xF) != data) {
setPaletteFullBlock(index, (char) ((fullId & 0xFFF0) | data));
}
}
}
public int getFullBlock(int x, int y, int z) {
return getFullBlock(getIndex(x, y, z));
}
public void setFullBlock(int x, int y, int z, int value) {
this.setFullBlock(getIndex(x, y, z), (char) value);
}
public int getAndSetFullBlock(int x, int y, int z, int value) {
return getAndSetFullBlock(getIndex(x, y, z), (char) value);
}
private int getAndSetFullBlock(int index, char value) {
char[] raw = rawData;
if (raw != null) {
char result = raw[index];
raw[index] = value;
return result;
} else {
char fullId = palette.getKey(encodedData.getAt(index));
if (fullId != value) {
setPaletteFullBlock(index, value);
}
return fullId;
}
}
private int getFullBlock(int index) {
char[] raw = rawData;
if (raw != null) {
return raw[index];
}
return palette.getKey(encodedData.getAt(index));
}
private void setFullBlock(int index, char value) {
char[] raw = rawData;
if (raw != null) {
raw[index] = value;
return;
}
setPaletteFullBlock(index, value);
}
private void setPaletteFullBlock(int index, char value) {
char encodedValue = palette.getValue(value);
if (encodedValue != Character.MAX_VALUE) {
encodedData.setAt(index, encodedValue);
} else {
synchronized (this) {
char[] raw = encodedData.toRaw();
for (int i = 0; i < 4096; i++) {
raw[i] = palette.getKey(raw[i]);
}
raw[index] = value;
rawData = raw;
encodedData = null;
palette = null;
}
}
}
public boolean compress() {
char[] raw = rawData;
if (raw != null) {
synchronized (this) {
char unique = 0;
boolean[] countTable = ThreadCache.boolCache4096.get();
char[] mapFullTable = ThreadCache.charCache4096.get();
char[] mapBitTable = ThreadCache.charCache4096v2.get();
Arrays.fill(countTable, false);
for (char c : raw) {
if (!countTable[c]) {
mapBitTable[unique] = c;
countTable[c] = true;
unique++;
}
}
char[] keys = Arrays.copyOfRange(mapBitTable, 0, unique);
if (keys.length > 1) {
Arrays.sort(keys);
for (char c = 0; c < keys.length; c++) {
mapFullTable[keys[c]] = c;
}
} else {
mapFullTable[keys[0]] = 0;
}
CharPalette palette = new CharPalette();
palette.set(keys);
int bits = MathHelper.log2nlz(unique) + 1;
BitArray encodedData = new BitArray(bits);
for (int i = 0; i < raw.length; i++) {
raw[i] = mapFullTable[raw[i]];
}
encodedData.fromRaw(raw);
this.palette = palette;
this.encodedData = encodedData;
rawData = null;
return true;
}
}
return false;
}
public synchronized DataPalette clone() {
char[] raw = getRaw();
return new DataPalette(raw.clone());
}
}
| 5,463 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Chunk.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/Chunk.java | package cn.nukkit.level.format.leveldb;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.entity.Entity;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.level.format.leveldb.key.EntitiesKey;
import cn.nukkit.level.format.leveldb.key.ExtraDataKey;
import cn.nukkit.level.format.leveldb.key.TilesKey;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.stream.NBTInputStream;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.Tag;
import cn.nukkit.utils.Binary;
import cn.nukkit.utils.BinaryStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Chunk extends BaseFullChunk {
public static final int DATA_LENGTH = 16384 * (2 + 1 + 1 + 1) + 256 + 1024;
protected boolean isLightPopulated = false;
protected boolean isPopulated = false;
protected boolean isGenerated = false;
public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain) {
this(level, chunkX, chunkZ, terrain, null);
}
public Chunk(Class<? extends LevelProvider> providerClass, int chunkX, int chunkZ, byte[] terrain) {
this(null, chunkX, chunkZ, terrain, null);
this.providerClass = providerClass;
}
public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain, List<CompoundTag> entityData) {
this(level, chunkX, chunkZ, terrain, entityData, null);
}
public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain, List<CompoundTag> entityData, List<CompoundTag> tileData) {
this(level, chunkX, chunkZ, terrain, entityData, tileData, null);
}
public Chunk(LevelProvider level, int chunkX, int chunkZ, byte[] terrain, List<CompoundTag> entityData, List<CompoundTag> tileData, Map<Integer, Integer> extraData) {
ByteBuffer buffer = ByteBuffer.wrap(terrain).order(ByteOrder.BIG_ENDIAN);
byte[] blocks = new byte[32768];
buffer.get(blocks);
byte[] data = new byte[16384];
buffer.get(data);
byte[] skyLight = new byte[16384];
buffer.get(skyLight);
byte[] blockLight = new byte[16384];
buffer.get(blockLight);
byte[] heightMap = new byte[256];
for (int i = 0; i < 256; i++) {
heightMap[i] = buffer.get();
}
int[] biomeColors = new int[256];
for (int i = 0; i < 256; i++) {
biomeColors[i] = buffer.getInt();
}
this.provider = level;
if (level != null) {
this.providerClass = level.getClass();
}
this.setPosition(chunkX, chunkZ);
this.blocks = blocks;
this.data = data;
this.skyLight = skyLight;
this.blockLight = blockLight;
if (biomeColors.length == 256) {
this.biomeColors = biomeColors;
} else {
this.biomeColors = new int[256];
}
if (heightMap.length == 256) {
this.heightMap = heightMap;
} else {
byte[] bytes = new byte[256];
Arrays.fill(bytes, (byte) 256);
this.heightMap = bytes;
}
this.NBTentities = entityData == null ? new ArrayList<>() : entityData;
this.NBTtiles = tileData == null ? new ArrayList<>() : tileData;
this.extraData = extraData == null ? new HashMap<>() : extraData;
}
@Override
public int getBlockId(int x, int y, int z) {
return this.blocks[(x << 11) | (z << 7) | y] & 0xff;
}
@Override
public void setBlockId(int x, int y, int z, int id) {
this.blocks[(x << 11) | (z << 7) | y] = (byte) id;
setChanged();
}
@Override
public int getBlockData(int x, int y, int z) {
int b = this.data[(x << 10) | (z << 6) | (y >> 1)] & 0xff;
if ((y & 1) == 0) {
return b & 0x0f;
} else {
return b >> 4;
}
}
@Override
public void setBlockData(int x, int y, int z, int data) {
int i = (x << 10) | (z << 6) | (y >> 1);
int old = this.data[i] & 0xff;
if ((y & 1) == 0) {
this.data[i] = (byte) ((old & 0xf0) | (old & 0x0f));
} else {
this.data[i] = (byte) (((data & 0x0f) << 4) | (old & 0x0f));
}
setChanged();
}
@Override
public int getFullBlock(int x, int y, int z) {
int i = (x << 11) | (z << 7) | y;
int block = this.blocks[i] & 0xff;
int data = this.data[i >> 1] & 0xff;
if ((y & 1) == 0) {
return (block << 4) | (data & 0x0f);
} else {
return (block << 4) | (data >> 4);
}
}
@Override
public Block getAndSetBlock(int x, int y, int z, Block block) {
int i = (x << 11) | (z << 7) | y;
boolean changed = false;
byte id = (byte) block.getId();
byte previousId = this.blocks[i];
if (previousId != id) {
this.blocks[i] = id;
changed = true;
}
int previousData;
i >>= 1;
int old = this.data[i] & 0xff;
if ((y & 1) == 0) {
previousData = old & 0x0f;
if (Block.hasMeta[block.getId()]) {
this.data[i] = (byte) ((old & 0xf0) | (block.getDamage() & 0x0f));
if (block.getDamage() != previousData) {
changed = true;
}
}
} else {
previousData = old >> 4;
if (Block.hasMeta[block.getId()]) {
this.data[i] = (byte) (((block.getDamage() & 0x0f) << 4) | (old & 0x0f));
if (block.getDamage() != previousData) {
changed = true;
}
}
}
if (changed) {
setChanged();
}
return Block.get(previousId, previousData);
}
@Override
public boolean setBlock(int x, int y, int z, int blockId) {
return setBlock(x, y, z, blockId, 0);
}
@Override
public boolean setBlock(int x, int y, int z, int blockId, int meta) {
int i = (x << 11) | (z << 7) | y;
boolean changed = false;
byte id = (byte) blockId;
if (this.blocks[i] != id) {
this.blocks[i] = id;
changed = true;
}
if (Block.hasMeta[blockId]) {
i >>= 1;
int old = this.data[i] & 0xff;
if ((y & 1) == 0) {
this.data[i] = (byte) ((old & 0xf0) | (meta & 0x0f));
if ((old & 0x0f) != meta) {
changed = true;
}
} else {
this.data[i] = (byte) (((meta & 0x0f) << 4) | (old & 0x0f));
if (meta != (old >> 4)) {
changed = true;
}
}
}
if (changed) {
setChanged();
}
return changed;
}
@Override
public int getBlockSkyLight(int x, int y, int z) {
int sl = this.skyLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff;
if ((y & 1) == 0) {
return sl & 0x0f;
} else {
return sl >> 4;
}
}
@Override
public void setBlockSkyLight(int x, int y, int z, int level) {
int i = (x << 10) | (z << 6) | (y >> 1);
int old = this.skyLight[i] & 0xff;
if ((y & 1) == 0) {
this.skyLight[i] = (byte) ((old & 0xf0) | (level & 0x0f));
} else {
this.skyLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f));
}
setChanged();
}
@Override
public int getBlockLight(int x, int y, int z) {
int b = this.blockLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff;
if ((y & 1) == 0) {
return b & 0x0f;
} else {
return b >> 4;
}
}
@Override
public void setBlockLight(int x, int y, int z, int level) {
int i = (x << 10) | (z << 6) | (y >> 1);
int old = this.blockLight[i] & 0xff;
if ((y & 1) == 0) {
this.blockLight[i] = (byte) ((old & 0xf0) | (level & 0x0f));
} else {
this.blockLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f));
}
setChanged();
}
@Override
public boolean isLightPopulated() {
return this.isLightPopulated;
}
@Override
public void setLightPopulated() {
this.setLightPopulated(true);
}
@Override
public void setLightPopulated(boolean value) {
this.isLightPopulated = value;
}
@Override
public boolean isPopulated() {
return this.isPopulated;
}
@Override
public void setPopulated() {
this.setPopulated(true);
}
@Override
public void setPopulated(boolean value) {
this.isPopulated = true;
}
@Override
public boolean isGenerated() {
return this.isGenerated;
}
@Override
public void setGenerated() {
this.setGenerated(true);
}
@Override
public void setGenerated(boolean value) {
this.isGenerated = true;
}
public static Chunk fromBinary(byte[] data) {
return fromBinary(data, null);
}
public static Chunk fromBinary(byte[] data, LevelProvider provider) {
try {
int chunkX = Binary.readLInt(new byte[]{data[0], data[1], data[2], data[3]});
int chunkZ = Binary.readLInt(new byte[]{data[4], data[5], data[6], data[7]});
byte[] chunkData = Binary.subBytes(data, 8, data.length - 1);
int flags = data[data.length - 1];
List<CompoundTag> entities = new ArrayList<>();
List<CompoundTag> tiles = new ArrayList<>();
Map<Integer, Integer> extraDataMap = new HashMap<>();
if (provider instanceof LevelDB) {
byte[] entityData = ((LevelDB) provider).getDatabase().get(EntitiesKey.create(chunkX, chunkZ).toArray());
if (entityData != null && entityData.length > 0) {
try (NBTInputStream nbtInputStream = new NBTInputStream(new ByteArrayInputStream(entityData), ByteOrder.LITTLE_ENDIAN)) {
while (nbtInputStream.available() > 0) {
Tag tag = Tag.readNamedTag(nbtInputStream);
if (!(tag instanceof CompoundTag)) {
throw new IOException("Root tag must be a named compound tag");
}
entities.add((CompoundTag) tag);
}
}
}
byte[] tileData = ((LevelDB) provider).getDatabase().get(TilesKey.create(chunkX, chunkZ).toArray());
if (tileData != null && tileData.length > 0) {
try (NBTInputStream nbtInputStream = new NBTInputStream(new ByteArrayInputStream(tileData), ByteOrder.LITTLE_ENDIAN)) {
while (nbtInputStream.available() > 0) {
Tag tag = Tag.readNamedTag(nbtInputStream);
if (!(tag instanceof CompoundTag)) {
throw new IOException("Root tag must be a named compound tag");
}
tiles.add((CompoundTag) tag);
}
}
}
byte[] extraData = ((LevelDB) provider).getDatabase().get(ExtraDataKey.create(chunkX, chunkZ).toArray());
if (extraData != null && extraData.length > 0) {
BinaryStream stream = new BinaryStream(tileData);
int count = stream.getInt();
for (int i = 0; i < count; ++i) {
int key = stream.getInt();
int value = stream.getShort();
extraDataMap.put(key, value);
}
}
/*if (!entities.isEmpty() || !blockEntities.isEmpty()) {
CompoundTag ct = new CompoundTag();
ListTag<CompoundTag> entityList = new ListTag<>("entities");
ListTag<CompoundTag> tileList = new ListTag<>("blockEntities");
entityList.list = entities;
tileList.list = blockEntities;
ct.putList(entityList);
ct.putList(tileList);
NBTIO.write(ct, new File(Nukkit.DATA_PATH + chunkX + "_" + chunkZ + ".dat"));
}*/
Chunk chunk = new Chunk(provider, chunkX, chunkZ, chunkData, entities, tiles, extraDataMap);
if ((flags & 0x01) > 0) {
chunk.setGenerated();
}
if ((flags & 0x02) > 0) {
chunk.setPopulated();
}
if ((flags & 0x04) > 0) {
chunk.setLightPopulated();
}
return chunk;
}
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
return null;
}
public static Chunk fromFastBinary(byte[] data) {
return fromFastBinary(data, null);
}
public static Chunk fromFastBinary(byte[] data, LevelProvider provider) {
return fromBinary(data, provider);
}
@Override
public byte[] toFastBinary() {
return this.toBinary(false);
}
@Override
public byte[] toBinary() {
return this.toBinary(false);
}
public byte[] toBinary(boolean saveExtra) {
try {
LevelProvider provider = this.getProvider();
if (saveExtra && provider instanceof LevelDB) {
List<CompoundTag> entities = new ArrayList<>();
for (Entity entity : this.getEntities().values()) {
if (!(entity instanceof Player) && !entity.closed) {
entity.saveNBT();
entities.add(entity.namedTag);
}
}
EntitiesKey entitiesKey = EntitiesKey.create(this.getX(), this.getZ());
if (!entities.isEmpty()) {
((LevelDB) provider).getDatabase().put(entitiesKey.toArray(), NBTIO.write(entities));
} else {
((LevelDB) provider).getDatabase().delete(entitiesKey.toArray());
}
List<CompoundTag> tiles = new ArrayList<>();
for (BlockEntity blockEntity : this.getBlockEntities().values()) {
if (!blockEntity.closed) {
blockEntity.saveNBT();
entities.add(blockEntity.namedTag);
}
}
TilesKey tilesKey = TilesKey.create(this.getX(), this.getZ());
if (!tiles.isEmpty()) {
((LevelDB) provider).getDatabase().put(tilesKey.toArray(), NBTIO.write(tiles));
} else {
((LevelDB) provider).getDatabase().delete(tilesKey.toArray());
}
ExtraDataKey extraDataKey = ExtraDataKey.create(this.getX(), this.getZ());
if (!this.getBlockExtraDataArray().isEmpty()) {
BinaryStream extraData = new BinaryStream();
Map<Integer, Integer> extraDataArray = this.getBlockExtraDataArray();
extraData.putInt(extraDataArray.size());
for (Integer key : extraDataArray.keySet()) {
extraData.putInt(key);
extraData.putShort(extraDataArray.get(key));
}
((LevelDB) provider).getDatabase().put(extraDataKey.toArray(), extraData.getBuffer());
} else {
((LevelDB) provider).getDatabase().delete(extraDataKey.toArray());
}
}
byte[] heightMap = this.getHeightMapArray();
byte[] biomeColors = new byte[this.getBiomeColorArray().length * 4];
for (int i = 0; i < this.getBiomeColorArray().length; i++) {
byte[] bytes = Binary.writeInt(this.getBiomeColorArray()[i]);
biomeColors[i * 4] = bytes[0];
biomeColors[i * 4 + 1] = bytes[1];
biomeColors[i * 4 + 2] = bytes[2];
biomeColors[i * 4 + 3] = bytes[3];
}
return Binary.appendBytes(
Binary.writeLInt(this.getX()),
Binary.writeLInt(this.getZ()),
this.getBlockIdArray(),
this.getBlockDataArray(),
this.getBlockSkyLightArray(),
this.getBlockLightArray(),
heightMap,
biomeColors,
new byte[]{(byte) (((this.isLightPopulated ? 0x04 : 0) | (this.isPopulated() ? 0x02 : 0) | (this.isGenerated() ? 0x01 : 0)) & 0xff)}
);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Chunk getEmptyChunk(int chunkX, int chunkZ) {
return getEmptyChunk(chunkX, chunkZ, null);
}
public static Chunk getEmptyChunk(int chunkX, int chunkZ, LevelProvider provider) {
try {
Chunk chunk;
if (provider != null) {
chunk = new Chunk(provider, chunkX, chunkZ, new byte[DATA_LENGTH]);
} else {
chunk = new Chunk(LevelDB.class, chunkX, chunkZ, new byte[DATA_LENGTH]);
}
byte[] skyLight = new byte[16384];
Arrays.fill(skyLight, (byte) 0xff);
chunk.skyLight = skyLight;
return chunk;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 18,073 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LevelDB.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/LevelDB.java | package cn.nukkit.level.format.leveldb;
import cn.nukkit.Server;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.blockentity.BlockEntitySpawnable;
import cn.nukkit.level.GameRules;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.ChunkSection;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.level.format.leveldb.key.BaseKey;
import cn.nukkit.level.format.leveldb.key.FlagsKey;
import cn.nukkit.level.format.leveldb.key.TerrainKey;
import cn.nukkit.level.format.leveldb.key.VersionKey;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.scheduler.AsyncTask;
import cn.nukkit.utils.*;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.Iq80DBFactory;
import java.io.*;
import java.nio.ByteOrder;
import java.util.*;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class LevelDB implements LevelProvider {
protected Map<Long, Chunk> chunks = new HashMap<>();
protected DB db;
protected Level level;
protected final String path;
protected CompoundTag levelData;
public LevelDB(Level level, String path) {
this.level = level;
this.path = path;
File file_path = new File(this.path);
if (!file_path.exists()) {
file_path.mkdirs();
}
try (FileInputStream stream = new FileInputStream(this.getPath() + "level.dat")) {
stream.skip(8);
CompoundTag levelData = NBTIO.read(stream, ByteOrder.LITTLE_ENDIAN);
if (levelData != null) {
this.levelData = levelData;
} else {
throw new IOException("LevelData can not be null");
}
} catch (IOException e) {
throw new LevelException("Invalid level.dat");
}
if (!this.levelData.contains("generatorName")) {
this.levelData.putString("generatorName", Generator.getGenerator("DEFAULT").getSimpleName().toLowerCase());
}
if (!this.levelData.contains("generatorOptions")) {
this.levelData.putString("generatorOptions", "");
}
try {
this.db = Iq80DBFactory.factory.open(new File(this.getPath() + "/db"), new Options().createIfMissing(true));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String getProviderName() {
return "leveldb";
}
public static byte getProviderOrder() {
return ORDER_ZXY;
}
public static boolean usesChunkSection() {
return false;
}
public static boolean isValid(String path) {
return new File(path + "/level.dat").exists() && new File(path + "/db").isDirectory();
}
public static void generate(String path, String name, long seed, Class<? extends Generator> generator) throws IOException {
generate(path, name, seed, generator, new HashMap<>());
}
public static void generate(String path, String name, long seed, Class<? extends Generator> generator, Map<String, String> options) throws IOException {
if (!new File(path + "/db").exists()) {
new File(path + "/db").mkdirs();
}
CompoundTag levelData = new CompoundTag("")
.putLong("currentTick", 0)
.putInt("DayCycleStopTime", -1)
.putInt("GameType", 0)
.putInt("Generator", Generator.getGeneratorType(generator))
.putBoolean("hasBeenLoadedInCreative", false)
.putLong("LastPlayed", System.currentTimeMillis() / 1000)
.putString("LevelName", name)
.putFloat("lightningLevel", 0)
.putInt("lightningTime", new Random().nextInt())
.putInt("limitedWorldOriginX", 128)
.putInt("limitedWorldOriginY", 70)
.putInt("limitedWorldOriginZ", 128)
.putInt("Platform", 0)
.putFloat("rainLevel", 0)
.putInt("rainTime", new Random().nextInt())
.putLong("RandomSeed", seed)
.putByte("spawnMobs", 0)
.putInt("SpawnX", 128)
.putInt("SpawnY", 70)
.putInt("SpawnZ", 128)
.putInt("storageVersion", 4)
.putLong("Time", 0)
.putLong("worldStartCount", ((long) Integer.MAX_VALUE) & 0xffffffffL);
byte[] data = NBTIO.write(levelData, ByteOrder.LITTLE_ENDIAN);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(Binary.writeLInt(3));
outputStream.write(Binary.writeLInt(data.length));
outputStream.write(data);
Utils.writeFile(path + "level.dat", new ByteArrayInputStream(outputStream.toByteArray()));
DB db = Iq80DBFactory.factory.open(new File(path + "/db"), new Options().createIfMissing(true));
db.close();
}
@Override
public void saveLevelData() {
try {
byte[] data = NBTIO.write(levelData, ByteOrder.LITTLE_ENDIAN);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(Binary.writeLInt(3));
outputStream.write(Binary.writeLInt(data.length));
outputStream.write(data);
Utils.writeFile(path + "level.dat", new ByteArrayInputStream(outputStream.toByteArray()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public AsyncTask requestChunkTask(int x, int z) {
Chunk chunk = this.getChunk(x, z, false);
if (chunk == null) {
throw new ChunkException("Invalid Chunk sent");
}
long timestamp = chunk.getChanges();
byte[] tiles = new byte[0];
if (!chunk.getBlockEntities().isEmpty()) {
List<CompoundTag> tagList = new ArrayList<>();
for (BlockEntity blockEntity : chunk.getBlockEntities().values()) {
if (blockEntity instanceof BlockEntitySpawnable) {
tagList.add(((BlockEntitySpawnable) blockEntity).getSpawnCompound());
}
}
try {
tiles = NBTIO.write(tagList, ByteOrder.LITTLE_ENDIAN);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Map<Integer, Integer> extra = chunk.getBlockExtraDataArray();
BinaryStream extraData;
if (!extra.isEmpty()) {
extraData = new BinaryStream();
extraData.putLInt(extra.size());
for (Integer key : extra.values()) {
extraData.putLInt(key);
extraData.putLShort(extra.get(key));
}
} else {
extraData = null;
}
BinaryStream stream = new BinaryStream();
stream.put(chunk.getBlockIdArray());
stream.put(chunk.getBlockDataArray());
stream.put(chunk.getBlockSkyLightArray());
stream.put(chunk.getBlockLightArray());
stream.put(chunk.getHeightMapArray());
for (int color : chunk.getBiomeColorArray()) {
stream.put(Binary.writeInt(color));
}
if (extraData != null) {
stream.put(extraData.getBuffer());
} else {
stream.putLInt(0);
}
stream.put(tiles);
this.getLevel().chunkRequestCallback(timestamp, x, z, stream.getBuffer());
return null;
}
@Override
public void unloadChunks() {
for (Chunk chunk : new ArrayList<>(this.chunks.values())) {
this.unloadChunk(chunk.getX(), chunk.getZ(), false);
}
this.chunks = new HashMap<>();
}
@Override
public String getGenerator() {
return this.levelData.getString("generatorName");
}
@Override
public Map<String, Object> getGeneratorOptions() {
return new HashMap<String, Object>() {
{
put("preset", levelData.getString("generatorOptions"));
}
};
}
@Override
public BaseFullChunk getLoadedChunk(int X, int Z) {
return this.getLoadedChunk(Level.chunkHash(X, Z));
}
@Override
public BaseFullChunk getLoadedChunk(long hash) {
return this.chunks.get(hash);
}
@Override
public Map<Long, Chunk> getLoadedChunks() {
return this.chunks;
}
@Override
public boolean isChunkLoaded(int x, int z) {
return this.isChunkLoaded(Level.chunkHash(x, z));
}
@Override
public boolean isChunkLoaded(long hash) {
return this.chunks.containsKey(hash);
}
@Override
public void saveChunks() {
for (Chunk chunk : this.chunks.values()) {
this.saveChunk(chunk.getX(), chunk.getZ());
}
}
@Override
public boolean loadChunk(int x, int z) {
return this.loadChunk(x, z, false);
}
@Override
public boolean loadChunk(int x, int z, boolean create) {
long index = Level.chunkHash(x, z);
if (this.chunks.containsKey(index)) {
return true;
}
this.level.timings.syncChunkLoadDataTimer.startTiming();
Chunk chunk = this.readChunk(x, z);
if (chunk == null && create) {
chunk = Chunk.getEmptyChunk(x, z, this);
}
this.level.timings.syncChunkLoadDataTimer.stopTiming();
if (chunk != null) {
this.chunks.put(index, chunk);
return true;
}
return false;
}
public Chunk readChunk(int chunkX, int chunkZ) {
byte[] data;
if (!this.chunkExists(chunkX, chunkZ) || (data = this.db.get(TerrainKey.create(chunkX, chunkZ).toArray())) == null) {
return null;
}
byte[] flags = this.db.get(FlagsKey.create(chunkX, chunkZ).toArray());
if (flags == null) {
flags = new byte[]{0x03};
}
return Chunk.fromBinary(
Binary.appendBytes(
Binary.writeLInt(chunkX),
Binary.writeLInt(chunkZ),
data,
flags)
, this);
}
private void writeChunk(Chunk chunk) {
byte[] binary = chunk.toBinary(true);
this.db.put(TerrainKey.create(chunk.getX(), chunk.getZ()).toArray(), Binary.subBytes(binary, 8, binary.length - 1));
this.db.put(FlagsKey.create(chunk.getX(), chunk.getZ()).toArray(), Binary.subBytes(binary, binary.length - 1));
this.db.put(VersionKey.create(chunk.getX(), chunk.getZ()).toArray(), new byte[]{0x02});
}
@Override
public boolean unloadChunk(int x, int z) {
return this.unloadChunk(x, z, true);
}
@Override
public boolean unloadChunk(int x, int z, boolean safe) {
long index = Level.chunkHash(x, z);
Chunk chunk = this.chunks.containsKey(index) ? this.chunks.get(index) : null;
if (chunk != null && chunk.unload(false, safe)) {
this.chunks.remove(index);
return true;
}
return false;
}
@Override
public void saveChunk(int x, int z) {
if (this.isChunkLoaded(x, z)) {
this.writeChunk(this.getChunk(x, z));
}
}
@Override
public void saveChunk(int x, int z, FullChunk chunk) {
if (!(chunk instanceof Chunk)) {
throw new ChunkException("Invalid Chunk class");
}
this.writeChunk((Chunk) chunk);
}
@Override
public Chunk getChunk(int x, int z) {
return this.getChunk(x, z, false);
}
@Override
public Chunk getChunk(int x, int z, boolean create) {
long index = Level.chunkHash(x, z);
if (this.chunks.containsKey(index)) {
return this.chunks.get(index);
} else {
this.loadChunk(x, z, create);
return this.chunks.containsKey(index) ? this.chunks.get(index) : null;
}
}
public DB getDatabase() {
return db;
}
@Override
public void setChunk(int chunkX, int chunkZ, FullChunk chunk) {
if (!(chunk instanceof Chunk)) {
throw new ChunkException("Invalid Chunk class");
}
chunk.setProvider(this);
chunk.setPosition(chunkX, chunkZ);
long index = Level.chunkHash(chunkX, chunkZ);
if (this.chunks.containsKey(index) && !this.chunks.get(index).equals(chunk)) {
this.unloadChunk(chunkX, chunkZ, false);
}
this.chunks.put(index, (Chunk) chunk);
}
public static ChunkSection createChunkSection(int y) {
return null;
}
private boolean chunkExists(int chunkX, int chunkZ) {
return this.db.get(VersionKey.create(chunkX, chunkZ).toArray()) != null;
}
@Override
public boolean isChunkGenerated(int x, int z) {
return this.chunkExists(x, z) && this.getChunk(x, z, false) != null;
}
@Override
public boolean isChunkPopulated(int x, int z) {
return this.getChunk(x, z) != null;
}
@Override
public void close() {
this.unloadChunks();
try {
this.db.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.level = null;
}
@Override
public String getPath() {
return path;
}
public Server getServer() {
return this.level.getServer();
}
@Override
public Level getLevel() {
return level;
}
@Override
public String getName() {
return this.levelData.getString("LevelName");
}
@Override
public boolean isRaining() {
return this.levelData.getFloat("rainLevel") > 0;
}
@Override
public void setRaining(boolean raining) {
this.levelData.putFloat("rainLevel", raining ? 1.0f : 0);
}
@Override
public int getRainTime() {
return this.levelData.getInt("rainTime");
}
@Override
public void setRainTime(int rainTime) {
this.levelData.putInt("rainTime", rainTime);
}
@Override
public boolean isThundering() {
return this.levelData.getFloat("lightningLevel") > 0;
}
@Override
public void setThundering(boolean thundering) {
this.levelData.putFloat("lightningLevel", thundering ? 1.0f : 0);
}
@Override
public int getThunderTime() {
return this.levelData.getInt("lightningTime");
}
@Override
public void setThunderTime(int thunderTime) {
this.levelData.putInt("lightningTime", thunderTime);
}
@Override
public long getCurrentTick() {
return this.levelData.getLong("currentTick");
}
@Override
public void setCurrentTick(long currentTick) {
this.levelData.putLong("currentTick", currentTick);
}
@Override
public long getTime() {
return this.levelData.getLong("Time");
}
@Override
public void setTime(long value) {
this.levelData.putLong("Time", value);
}
@Override
public long getSeed() {
return this.levelData.getLong("RandomSeed");
}
@Override
public void setSeed(long value) {
this.levelData.putLong("RandomSeed", value);
}
@Override
public Vector3 getSpawn() {
return new Vector3(this.levelData.getInt("SpawnX"), this.levelData.getInt("SpawnY"), this.levelData.getInt("SpawnZ"));
}
@Override
public void setSpawn(Vector3 pos) {
this.levelData.putInt("SpawnX", (int) pos.x);
this.levelData.putInt("SpawnY", (int) pos.y);
this.levelData.putInt("SpawnZ", (int) pos.z);
}
@Override
public GameRules getGamerules() {
GameRules rules = GameRules.getDefault();
if (this.levelData.contains("GameRules"))
rules.readNBT(this.levelData.getCompound("GameRules"));
return rules;
}
@Override
public void setGameRules(GameRules rules) {
this.levelData.putCompound("GameRules", rules.writeNBT());
}
@Override
public void doGarbageCollection() {
}
public CompoundTag getLevelData() {
return levelData;
}
public void updateLevelName(String name) {
if (!this.getName().equals(name)) {
this.levelData.putString("LevelName", name);
}
}
public byte[][] getTerrainKeys() {
List<byte[]> result = new ArrayList<>();
this.db.forEach((entry) -> {
byte[] key = entry.getKey();
if (key.length > 8 && key[8] == BaseKey.DATA_TERRAIN) {
result.add(key);
}
});
return result.stream().toArray(byte[][]::new);
}
}
| 16,904 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
TilesKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/TilesKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class TilesKey extends BaseKey {
protected TilesKey(int chunkX, int chunkZ) {
super(chunkX, chunkZ, DATA_TILES);
}
public static TilesKey create(int chunkX, int chunkZ) {
return new TilesKey(chunkX, chunkZ);
}
}
| 346 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
TicksKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/TicksKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class TicksKey extends BaseKey {
protected TicksKey(int chunkX, int chunkZ) {
super(chunkX, chunkZ, DATA_TICKS);
}
public static TicksKey create(int chunkX, int chunkZ) {
return new TicksKey(chunkX, chunkZ);
}
}
| 346 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
VersionKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/VersionKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class VersionKey extends BaseKey {
protected VersionKey(int chunkX, int chunkZ) {
super(chunkX, chunkZ, DATA_VERSION);
}
public static VersionKey create(int chunkX, int chunkZ) {
return new VersionKey(chunkX, chunkZ);
}
}
| 356 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FlagsKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/FlagsKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class FlagsKey extends BaseKey {
protected FlagsKey(int chunkX, int chunkZ) {
super(chunkX, chunkZ, DATA_FLAGS);
}
public static FlagsKey create(int chunkX, int chunkZ) {
return new FlagsKey(chunkX, chunkZ);
}
}
| 346 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BaseKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/BaseKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class BaseKey {
private final int chunkX;
private final int chunkZ;
private final byte type;
public static final byte DATA_VERSION = 0x76;
public static final byte DATA_FLAGS = 0x66;
public static final byte DATA_EXTRA_DATA = 0x34;
public static final byte DATA_TICKS = 0x33;
public static final byte DATA_ENTITIES = 0x32;
public static final byte DATA_TILES = 0x31;
public static final byte DATA_TERRAIN = 0x30;
protected BaseKey(int chunkX, int chunkZ, byte type) {
this.chunkX = chunkX;
this.chunkZ = chunkZ;
this.type = type;
}
public byte[] toArray() {
return new byte[]{
(byte) (this.chunkX & 0xff),
(byte) ((this.chunkX >>> 8) & 0xff),
(byte) ((this.chunkX >>> 16) & 0xff),
(byte) ((this.chunkX >>> 24) & 0xff),
(byte) (this.chunkZ & 0xff),
(byte) ((this.chunkZ >>> 8) & 0xff),
(byte) ((this.chunkZ >>> 16) & 0xff),
(byte) ((this.chunkZ >>> 24) & 0xff),
this.type
};
}
}
| 1,222 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
EntitiesKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/EntitiesKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class EntitiesKey extends BaseKey {
protected EntitiesKey(int chunkX, int chunkZ) {
super(chunkX, chunkZ, DATA_ENTITIES);
}
public static EntitiesKey create(int chunkX, int chunkZ) {
return new EntitiesKey(chunkX, chunkZ);
}
}
| 361 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ExtraDataKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/ExtraDataKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ExtraDataKey extends BaseKey {
protected ExtraDataKey(int chunkX, int chunkZ) {
super(chunkX, chunkZ, DATA_EXTRA_DATA);
}
public static ExtraDataKey create(int chunkX, int chunkZ) {
return new ExtraDataKey(chunkX, chunkZ);
}
}
| 367 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
TerrainKey.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/leveldb/key/TerrainKey.java | package cn.nukkit.level.format.leveldb.key;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class TerrainKey extends BaseKey {
protected TerrainKey(int chunkX, int chunkZ) {
super(chunkX, chunkZ, DATA_TERRAIN);
}
public static TerrainKey create(int chunkX, int chunkZ) {
return new TerrainKey(chunkX, chunkZ);
}
}
| 356 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BaseRegionLoader.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/generic/BaseRegionLoader.java | package cn.nukkit.level.format.generic;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.nbt.stream.BufferedRandomAccessFile;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
/**
* author: MagicDroidX
* Nukkit Project
*/
abstract public class BaseRegionLoader {
public static final int VERSION = 1;
public static final byte COMPRESSION_GZIP = 1;
public static final byte COMPRESSION_ZLIB = 2;
public static final int MAX_SECTOR_LENGTH = 256 << 12;
public static final int COMPRESSION_LEVEL = 7;
protected int x;
protected int z;
protected int lastSector;
protected LevelProvider levelProvider;
private RandomAccessFile randomAccessFile;
// TODO: A simple array will perform better and use less memory
protected final Map<Integer, Integer[]> locationTable = new HashMap<>();
public long lastUsed;
public BaseRegionLoader(LevelProvider level, int regionX, int regionZ, String ext) {
try {
this.x = regionX;
this.z = regionZ;
this.levelProvider = level;
String filePath = this.levelProvider.getPath() + "region/r." + regionX + "." + regionZ + "." + ext;
File file = new File(filePath);
boolean exists = file.exists();
if (!exists) {
file.createNewFile();
}
// TODO: buffering is a temporary solution to chunk reading/writing being poorly optimized
// - need to fix the code where it reads single bytes at a time from disk
this.randomAccessFile = new BufferedRandomAccessFile(filePath, "rw", 1024);
if (!exists) {
this.createBlank();
} else {
this.loadLocationTable();
}
this.lastUsed = System.currentTimeMillis();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void compress() {
// TODO
}
public RandomAccessFile getRandomAccessFile() {
return randomAccessFile;
}
protected abstract boolean isChunkGenerated(int index);
public abstract BaseFullChunk readChunk(int x, int z) throws IOException;
protected abstract BaseFullChunk unserializeChunk(byte[] data);
public abstract boolean chunkExists(int x, int z);
protected abstract void saveChunk(int x, int z, byte[] chunkData) throws IOException;
public abstract void removeChunk(int x, int z);
public abstract void writeChunk(FullChunk chunk) throws Exception;
public void close() throws IOException {
if (randomAccessFile != null) randomAccessFile.close();
}
protected abstract void loadLocationTable() throws IOException;
public abstract int doSlowCleanUp() throws Exception;
protected abstract void writeLocationIndex(int index) throws IOException;
protected abstract void createBlank() throws IOException;
public abstract int getX();
public abstract int getZ();
public Integer[] getLocationIndexes() {
return this.locationTable.keySet().stream().toArray(Integer[]::new);
}
}
| 3,251 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BaseFullChunk.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/generic/BaseFullChunk.java | package cn.nukkit.level.format.generic;
import cn.nukkit.Player;
import cn.nukkit.block.Block;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.entity.Entity;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.generator.biome.Biome;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.nbt.tag.NumberTag;
import cn.nukkit.network.protocol.BatchPacket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class BaseFullChunk implements FullChunk {
protected final Map<Long, Entity> entities = new HashMap<>();
protected final Map<Long, BlockEntity> tiles = new HashMap<>();
protected final Map<Integer, BlockEntity> tileList = new HashMap<>();
protected int[] biomeColors;
protected byte[] blocks;
protected byte[] data;
protected byte[] skyLight;
protected byte[] blockLight;
protected byte[] heightMap;
protected List<CompoundTag> NBTtiles;
protected List<CompoundTag> NBTentities;
protected Map<Integer, Integer> extraData = new HashMap<>();
protected LevelProvider provider;
protected Class<? extends LevelProvider> providerClass;
private int x;
private int z;
private long hash;
protected long changes = 0;
protected boolean isInit = false;
protected BatchPacket chunkPacket;
@Override
public BaseFullChunk clone() {
BaseFullChunk chunk;
try {
chunk = (BaseFullChunk) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
if (this.biomeColors != null) {
chunk.biomeColors = this.getBiomeColorArray().clone();
}
if (this.blocks != null) {
chunk.blocks = this.blocks.clone();
}
if (this.data != null) {
chunk.data = this.data.clone();
}
if (this.skyLight != null) {
chunk.skyLight = this.skyLight.clone();
}
if (this.blockLight != null) {
chunk.blockLight = this.blockLight.clone();
}
if (this.heightMap != null) {
chunk.heightMap = this.getHeightMapArray().clone();
}
return chunk;
}
public void setChunkPacket(BatchPacket packet) {
this.chunkPacket = packet;
}
public BatchPacket getChunkPacket() {
return chunkPacket;
}
protected void checkOldBiomes(byte[] data) {
if (data.length != 256) {
return;
}
for (int x = 0; x < 16; ++x) {
for (int z = 0; z < 16; ++z) {
Biome biome = Biome.getBiome(data[(z << 4) | x] & 0xff);
this.setBiomeId(x, z, biome.getId());
int c = biome.getColor();
this.setBiomeColor(x, z, c >> 16, (c >> 8) & 0xff, c & 0xff);
}
}
}
public void initChunk() {
if (this.getProvider() != null && !this.isInit) {
boolean changed = false;
if (this.NBTentities != null) {
this.getProvider().getLevel().timings.syncChunkLoadEntitiesTimer.startTiming();
for (CompoundTag nbt : NBTentities) {
if (!nbt.contains("id")) {
this.setChanged();
continue;
}
ListTag pos = nbt.getList("Pos");
if ((((NumberTag) pos.get(0)).getData().intValue() >> 4) != this.getX() || ((((NumberTag) pos.get(2)).getData().intValue() >> 4) != this.getZ())) {
changed = true;
continue;
}
Entity entity = Entity.createEntity(nbt.getString("id"), this, nbt);
if (entity != null) {
changed = true;
continue;
}
}
this.getProvider().getLevel().timings.syncChunkLoadEntitiesTimer.stopTiming();
this.NBTentities = null;
}
if (this.NBTtiles != null) {
this.getProvider().getLevel().timings.syncChunkLoadBlockEntitiesTimer.startTiming();
for (CompoundTag nbt : NBTtiles) {
if (nbt != null) {
if (!nbt.contains("id")) {
changed = true;
continue;
}
if ((nbt.getInt("x") >> 4) != this.getX() || ((nbt.getInt("z") >> 4) != this.getZ())) {
changed = true;
continue;
}
BlockEntity blockEntity = BlockEntity.createBlockEntity(nbt.getString("id"), this, nbt);
if (blockEntity == null) {
changed = true;
continue;
}
}
}
this.getProvider().getLevel().timings.syncChunkLoadBlockEntitiesTimer.stopTiming();
this.NBTtiles = null;
}
this.setChanged(changed);
this.isInit = true;
}
}
@Override
public final long getIndex() {
return hash;
}
@Override
public final int getX() {
return x;
}
@Override
public final int getZ() {
return z;
}
@Override
public void setPosition(int x, int z) {
this.x = x;
this.z = z;
this.hash = Level.chunkHash(x, z);
}
public final void setX(int x) {
this.x = x;
this.hash = Level.chunkHash(x, getZ());
}
public final void setZ(int z) {
this.z = z;
this.hash = Level.chunkHash(getX(), z);
}
@Override
public LevelProvider getProvider() {
return provider;
}
@Override
public void setProvider(LevelProvider provider) {
this.provider = provider;
}
@Override
public int getBiomeId(int x, int z) {
return this.biomeColors[(z << 4) | x] >> 24;
}
@Override
public void setBiomeId(int x, int z, int biomeId) {
this.setChanged();
this.biomeColors[(z << 4) | x] = this.biomeColors[(z << 4) | x] & 0xffffff | (biomeId << 24);
}
@Override
public int[] getBiomeColor(int x, int z) {
int color = this.biomeColors[(z << 4) | x];
return new int[]{(color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff};
}
@Override
public void setBiomeColor(int x, int z, int r, int g, int b) {
this.setChanged();
this.biomeColors[(z << 4) | x] = this.biomeColors[(z << 4) | x] & 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
}
@Override
public int getHeightMap(int x, int z) {
return this.heightMap[(z << 4) | x] & 0xFF;
}
@Override
public void setHeightMap(int x, int z, int value) {
this.heightMap[(z << 4) | x] = (byte) value;
}
@Override
public void recalculateHeightMap() {
for (int z = 0; z < 16; ++z) {
for (int x = 0; x < 16; ++x) {
this.setHeightMap(x, z, this.getHighestBlockAt(x, z, false));
}
}
}
@Override
public int getBlockExtraData(int x, int y, int z) {
int index = Level.chunkBlockHash(x, y, z);
if (this.extraData.containsKey(index)) {
return this.extraData.get(index);
}
return 0;
}
@Override
public void setBlockExtraData(int x, int y, int z, int data) {
if (data == 0) {
this.extraData.remove(Level.chunkBlockHash(x, y, z));
} else {
this.extraData.put(Level.chunkBlockHash(x, y, z), data);
}
this.setChanged(true);
}
@Override
public void populateSkyLight() {
for (int z = 0; z < 16; ++z) {
for (int x = 0; x < 16; ++x) {
int top = this.getHeightMap(x, z);
for (int y = 255; y > top; --y) {
this.setBlockSkyLight(x, y, z, 15);
}
for (int y = top; y >= 0; --y) {
if (Block.solid[this.getBlockId(x, y, z)]) {
break;
}
this.setBlockSkyLight(x, y, z, 15);
}
this.setHeightMap(x, z, this.getHighestBlockAt(x, z, false));
}
}
}
@Override
public int getHighestBlockAt(int x, int z) {
return this.getHighestBlockAt(x, z, true);
}
@Override
public int getHighestBlockAt(int x, int z, boolean cache) {
if (cache) {
int h = this.getHeightMap(x, z);
if (h != 0 && h != 255) {
return h;
}
}
for (int y = 255; y >= 0; --y) {
if (getBlockId(x, y, z) != 0x00) {
this.setHeightMap(x, z, y);
return y;
}
}
return 0;
}
@Override
public void addEntity(Entity entity) {
this.entities.put(entity.getId(), entity);
if (!(entity instanceof Player) && this.isInit) {
this.setChanged();
}
}
@Override
public void removeEntity(Entity entity) {
this.entities.remove(entity.getId());
if (!(entity instanceof Player) && this.isInit) {
this.setChanged();
}
}
@Override
public void addBlockEntity(BlockEntity blockEntity) {
this.tiles.put(blockEntity.getId(), blockEntity);
int index = ((blockEntity.getFloorZ() & 0x0f) << 12) | ((blockEntity.getFloorX() & 0x0f) << 8) | (blockEntity.getFloorY() & 0xff);
if (this.tileList.containsKey(index) && !this.tileList.get(index).equals(blockEntity)) {
this.tileList.get(index).close();
}
this.tileList.put(index, blockEntity);
if (this.isInit) {
this.setChanged();
}
}
@Override
public void removeBlockEntity(BlockEntity blockEntity) {
this.tiles.remove(blockEntity.getId());
int index = ((blockEntity.getFloorZ() & 0x0f) << 12) | ((blockEntity.getFloorX() & 0x0f) << 8) | (blockEntity.getFloorY() & 0xff);
this.tileList.remove(index);
if (this.isInit) {
this.setChanged();
}
}
@Override
public Map<Long, Entity> getEntities() {
return entities;
}
@Override
public Map<Long, BlockEntity> getBlockEntities() {
return tiles;
}
@Override
public Map<Integer, Integer> getBlockExtraDataArray() {
return this.extraData;
}
@Override
public BlockEntity getTile(int x, int y, int z) {
int index = (z << 12) | (x << 8) | y;
return this.tileList.containsKey(index) ? this.tileList.get(index) : null;
}
@Override
public boolean isLoaded() {
return this.getProvider() != null && this.getProvider().isChunkLoaded(this.getX(), this.getZ());
}
@Override
public boolean load() throws IOException {
return this.load(true);
}
@Override
public boolean load(boolean generate) throws IOException {
return this.getProvider() != null && this.getProvider().getChunk(this.getX(), this.getZ(), true) != null;
}
@Override
public boolean unload() throws Exception {
return this.unload(true, true);
}
@Override
public boolean unload(boolean save) throws Exception {
return this.unload(save, true);
}
@Override
public boolean unload(boolean save, boolean safe) {
LevelProvider level = this.getProvider();
if (level == null) {
return true;
}
if (save && this.changes != 0) {
level.saveChunk(this.getX(), this.getZ());
}
if (safe) {
for (Entity entity : this.getEntities().values()) {
if (entity instanceof Player) {
return false;
}
}
}
for (Entity entity : new ArrayList<>(this.getEntities().values())) {
if (entity instanceof Player) {
continue;
}
entity.close();
}
for (BlockEntity blockEntity : new ArrayList<>(this.getBlockEntities().values())) {
blockEntity.close();
}
this.provider = null;
return true;
}
@Override
public byte[] getBlockIdArray() {
return this.blocks;
}
@Override
public byte[] getBlockDataArray() {
return this.data;
}
@Override
public byte[] getBlockSkyLightArray() {
return this.skyLight;
}
@Override
public byte[] getBlockLightArray() {
return this.blockLight;
}
@Override
public byte[] getBiomeIdArray() {
byte[] ids = new byte[this.getBiomeColorArray().length];
for (int i = 0; i < this.getBiomeColorArray().length; i++) {
int d = this.getBiomeColorArray()[i];
ids[i] = (byte) (d >> 24);
}
return ids;
}
@Override
public int[] getBiomeColorArray() {
return this.biomeColors;
}
@Override
public byte[] getHeightMapArray() {
return this.heightMap;
}
public long getChanges() {
return changes;
}
@Override
public boolean hasChanged() {
return this.changes != 0;
}
@Override
public void setChanged() {
this.changes++;
chunkPacket = null;
}
@Override
public void setChanged(boolean changed) {
if (changed) {
setChanged();
} else {
changes = 0;
}
}
@Override
public byte[] toFastBinary() {
return this.toBinary();
}
@Override
public boolean isLightPopulated() {
return true;
}
@Override
public void setLightPopulated() {
this.setLightPopulated(true);
}
@Override
public void setLightPopulated(boolean value) {
}
}
| 14,297 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
EmptyChunkSection.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/generic/EmptyChunkSection.java | package cn.nukkit.level.format.generic;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.ChunkSection;
import cn.nukkit.utils.ChunkException;
import java.util.Arrays;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class EmptyChunkSection implements ChunkSection {
public static final EmptyChunkSection[] EMPTY = new EmptyChunkSection[16];
static {
for (int y = 0; y < EMPTY.length; y++) {
EMPTY[y] = new EmptyChunkSection(y);
}
}
public static byte[] EMPTY_LIGHT_ARR = new byte[2048];
public static byte[] EMPTY_SKY_LIGHT_ARR = new byte[2048];
static {
Arrays.fill(EMPTY_SKY_LIGHT_ARR, (byte) 255);
}
private final int y;
public EmptyChunkSection(int y) {
this.y = y;
}
@Override
public int getY() {
return this.y;
}
@Override
final public int getBlockId(int x, int y, int z) {
return 0;
}
@Override
public int getFullBlock(int x, int y, int z) throws ChunkException {
return 0;
}
@Override
public Block getAndSetBlock(int x, int y, int z, Block block) {
if (block.getId() != 0) throw new ChunkException("Tried to modify an empty Chunk");
return Block.get(0);
}
@Override
public boolean setBlock(int x, int y, int z, int blockId) throws ChunkException {
if (blockId != 0) throw new ChunkException("Tried to modify an empty Chunk");
return false;
}
@Override
public boolean setBlock(int x, int y, int z, int blockId, int meta) throws ChunkException {
if (blockId != 0) throw new ChunkException("Tried to modify an empty Chunk");
return false;
}
@Override
public byte[] getIdArray() {
return new byte[4096];
}
@Override
public byte[] getDataArray() {
return new byte[2048];
}
@Override
public byte[] getSkyLightArray() {
return EMPTY_SKY_LIGHT_ARR;
}
@Override
public byte[] getLightArray() {
return EMPTY_LIGHT_ARR;
}
@Override
final public void setBlockId(int x, int y, int z, int id) throws ChunkException {
if (id != 0) throw new ChunkException("Tried to modify an empty Chunk");
}
@Override
final public int getBlockData(int x, int y, int z) {
return 0;
}
@Override
public void setBlockData(int x, int y, int z, int data) throws ChunkException {
if (data != 0) throw new ChunkException("Tried to modify an empty Chunk");
}
@Override
public int getBlockLight(int x, int y, int z) {
return 0;
}
@Override
public void setBlockLight(int x, int y, int z, int level) throws ChunkException {
if (level != 0) throw new ChunkException("Tried to modify an empty Chunk");
}
@Override
public int getBlockSkyLight(int x, int y, int z) {
return 15;
}
@Override
public void setBlockSkyLight(int x, int y, int z, int level) throws ChunkException {
if (level != 15) throw new ChunkException("Tried to modify an empty Chunk");
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public byte[] getBytes() {
return new byte[6144];
}
@Override
public ChunkSection clone() {
return this;
}
}
| 3,338 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BaseChunk.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/generic/BaseChunk.java | package cn.nukkit.level.format.generic;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.Chunk;
import cn.nukkit.level.format.ChunkSection;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.utils.ChunkException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class BaseChunk extends BaseFullChunk implements Chunk {
protected ChunkSection[] sections = new ChunkSection[SECTION_COUNT];
@Override
public BaseChunk clone() {
BaseChunk chunk = (BaseChunk) super.clone();
chunk.biomeColors = this.getBiomeColorArray().clone();
chunk.heightMap = this.getHeightMapArray().clone();
if (sections != null && sections[0] != null) {
chunk.sections = new ChunkSection[sections.length];
for (int i = 0; i < sections.length; i++) {
chunk.sections[i] = sections[i].clone();
}
}
return chunk;
}
@Override
public int getFullBlock(int x, int y, int z) {
return this.sections[y >> 4].getFullBlock(x, y & 0x0f, z);
}
@Override
public boolean setBlock(int x, int y, int z, int blockId) {
return this.setBlock(x, y, z, blockId, 0);
}
@Override
public Block getAndSetBlock(int x, int y, int z, Block block) {
int Y = y >> 4;
try {
setChanged();
return this.sections[Y].getAndSetBlock(x, y & 0x0f, z, block);
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
return this.sections[Y].getAndSetBlock(x, y & 0x0f, z, block);
}
}
@Override
public boolean setBlock(int x, int y, int z, int blockId, int meta) {
int Y = y >> 4;
try {
setChanged();
return this.sections[Y].setBlock(x, y & 0x0f, z, blockId, meta);
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
return this.sections[Y].setBlock(x, y & 0x0f, z, blockId, meta);
}
}
@Override
public void setBlockId(int x, int y, int z, int id) {
int Y = y >> 4;
try {
this.sections[Y].setBlockId(x, y & 0x0f, z, id);
setChanged();
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
this.sections[Y].setBlockId(x, y & 0x0f, z, id);
}
}
@Override
public int getBlockId(int x, int y, int z) {
return this.sections[y >> 4].getBlockId(x, y & 0x0f, z);
}
@Override
public int getBlockData(int x, int y, int z) {
return this.sections[y >> 4].getBlockData(x, y & 0x0f, z);
}
@Override
public void setBlockData(int x, int y, int z, int data) {
int Y = y >> 4;
try {
this.sections[Y].setBlockData(x, y & 0x0f, z, data);
setChanged();
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
this.sections[Y].setBlockData(x, y & 0x0f, z, data);
}
}
@Override
public int getBlockSkyLight(int x, int y, int z) {
return this.sections[y >> 4].getBlockSkyLight(x, y & 0x0f, z);
}
@Override
public void setBlockSkyLight(int x, int y, int z, int level) {
int Y = y >> 4;
try {
this.sections[Y].setBlockSkyLight(x, y & 0x0f, z, level);
setChanged();
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
this.sections[Y].setBlockSkyLight(x, y & 0x0f, z, level);
}
}
@Override
public int getBlockLight(int x, int y, int z) {
return this.sections[y >> 4].getBlockLight(x, y & 0x0f, z);
}
@Override
public void setBlockLight(int x, int y, int z, int level) {
int Y = y >> 4;
try {
this.sections[Y].setBlockLight(x, y & 0x0f, z, level);
setChanged();
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
this.sections[Y].setBlockLight(x, y & 0x0f, z, level);
}
}
@Override
public boolean isSectionEmpty(float fY) {
return this.sections[(int) fY] instanceof EmptyChunkSection;
}
@Override
public ChunkSection getSection(float fY) {
return this.sections[(int) fY];
}
@Override
public boolean setSection(float fY, ChunkSection section) {
byte[] emptyIdArray = new byte[4096];
byte[] emptyDataArray = new byte[2048];
if (Arrays.equals(emptyIdArray, section.getIdArray()) && Arrays.equals(emptyDataArray, section.getDataArray())) {
this.sections[(int) fY] = EmptyChunkSection.EMPTY[(int) fY];
} else {
this.sections[(int) fY] = section;
}
setChanged();
return true;
}
private void setInternalSection(float fY, ChunkSection section) {
this.sections[(int) fY] = section;
setChanged();
}
@Override
public boolean load() throws IOException {
return this.load(true);
}
@Override
public boolean load(boolean generate) throws IOException {
return this.getProvider() != null && this.getProvider().getChunk(this.getX(), this.getZ(), true) != null;
}
@Override
public byte[] getBlockIdArray() {
ByteBuffer buffer = ByteBuffer.allocate(4096 * SECTION_COUNT);
for (int y = 0; y < SECTION_COUNT; y++) {
buffer.put(this.sections[y].getIdArray());
}
return buffer.array();
}
@Override
public byte[] getBlockDataArray() {
ByteBuffer buffer = ByteBuffer.allocate(2048 * SECTION_COUNT);
for (int y = 0; y < SECTION_COUNT; y++) {
buffer.put(this.sections[y].getDataArray());
}
return buffer.array();
}
@Override
public byte[] getBlockSkyLightArray() {
ByteBuffer buffer = ByteBuffer.allocate(2048 * SECTION_COUNT);
for (int y = 0; y < SECTION_COUNT; y++) {
buffer.put(this.sections[y].getSkyLightArray());
}
return buffer.array();
}
@Override
public byte[] getBlockLightArray() {
ByteBuffer buffer = ByteBuffer.allocate(2048 * SECTION_COUNT);
for (int y = 0; y < SECTION_COUNT; y++) {
buffer.put(this.sections[y].getLightArray());
}
return buffer.array();
}
@Override
public ChunkSection[] getSections() {
return sections;
}
@Override
public int[] getBiomeColorArray() {
return this.biomeColors;
}
@Override
public byte[] getHeightMapArray() {
return this.heightMap;
}
@Override
public LevelProvider getProvider() {
return this.provider;
}
}
| 8,738 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ChunkConverter.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/generic/ChunkConverter.java | package cn.nukkit.level.format.generic;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.anvil.Chunk;
import cn.nukkit.level.format.anvil.ChunkSection;
import java.util.ArrayList;
public class ChunkConverter {
private BaseFullChunk chunk;
private Class<? extends FullChunk> toClass;
private LevelProvider provider;
public ChunkConverter(LevelProvider provider) {
this.provider = provider;
}
public ChunkConverter from(BaseFullChunk chunk) {
if (!(chunk instanceof cn.nukkit.level.format.mcregion.Chunk) && !(chunk instanceof cn.nukkit.level.format.leveldb.Chunk)) {
throw new IllegalArgumentException("From type can be only McRegion or LevelDB");
}
this.chunk = chunk;
return this;
}
public ChunkConverter to(Class<? extends FullChunk> toClass) {
if (toClass != Chunk.class) {
throw new IllegalArgumentException("To type can be only Anvil");
}
this.toClass = toClass;
return this;
}
public FullChunk perform() {
BaseFullChunk result;
try {
result = (BaseFullChunk) toClass.getMethod("getEmptyChunk", int.class, int.class, LevelProvider.class).invoke(null, chunk.getX(), chunk.getZ(), provider);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (toClass == Chunk.class) {
for (int Y = 0; Y < 8; Y++) {
boolean empty = true;
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
if (chunk.getBlockId(x, (Y << 4) | y, z) != 0) {
empty = false;
break;
}
}
if (!empty) break;
}
if (!empty) break;
}
if (!empty) {
ChunkSection section = new ChunkSection(Y);
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
section.setBlockId(x, y, z, chunk.getBlockId(x, (Y << 4) | y, z));
section.setBlockData(x, y, z, chunk.getBlockData(x, (Y << 4) | y, z));
section.setBlockLight(x, y, z, chunk.getBlockLight(x, (Y << 4) | y, z));
section.setBlockSkyLight(x, y, z, chunk.getBlockSkyLight(x, (Y << 4) | y, z));
}
}
}
((BaseChunk) result).sections[Y] = section;
}
}
}
System.arraycopy(chunk.getBiomeColorArray(), 0, result.biomeColors, 0, 256);
System.arraycopy(chunk.getHeightMapArray(), 0, result.heightMap, 0, 256);
result.NBTentities = new ArrayList<>();
chunk.NBTentities.forEach((nbt) -> result.NBTentities.add(nbt.copy()));
result.NBTtiles = new ArrayList<>();
chunk.NBTtiles.forEach((nbt) -> result.NBTtiles.add(nbt.copy()));
result.setGenerated();
result.setPopulated();
result.setLightPopulated();
result.initChunk();
return result;
}
}
| 3,463 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BaseLevelProvider.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/generic/BaseLevelProvider.java | package cn.nukkit.level.format.generic;
import cn.nukkit.Server;
import cn.nukkit.level.GameRules;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.utils.ChunkException;
import cn.nukkit.utils.LevelException;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class BaseLevelProvider implements LevelProvider {
protected Level level;
protected final String path;
protected CompoundTag levelData;
private Vector3 spawn;
protected BaseRegionLoader lastRegion;
protected final Map<Long, BaseRegionLoader> regions = new HashMap<>();
private final Long2ObjectOpenHashMap<BaseFullChunk> chunks = new Long2ObjectOpenHashMap<>();
public BaseLevelProvider(Level level, String path) throws IOException {
this.level = level;
this.path = path;
File file_path = new File(this.path);
if (!file_path.exists()) {
file_path.mkdirs();
}
CompoundTag levelData = NBTIO.readCompressed(new FileInputStream(new File(this.getPath() + "level.dat")), ByteOrder.BIG_ENDIAN);
if (levelData.get("Data") instanceof CompoundTag) {
this.levelData = levelData.getCompound("Data");
} else {
throw new LevelException("Invalid level.dat");
}
if (!this.levelData.contains("generatorName")) {
this.levelData.putString("generatorName", Generator.getGenerator("DEFAULT").getSimpleName().toLowerCase());
}
if (!this.levelData.contains("generatorOptions")) {
this.levelData.putString("generatorOptions", "");
}
this.spawn = new Vector3(this.levelData.getInt("SpawnX"), this.levelData.getInt("SpawnY"), this.levelData.getInt("SpawnZ"));
}
public abstract BaseFullChunk loadChunk(long index, int chunkX, int chunkZ, boolean create);
public int size() {
return this.chunks.size();
}
public ObjectIterator<BaseFullChunk> getChunks() {
return chunks.values().iterator();
}
protected void putChunk(long index, BaseFullChunk chunk) {
this.chunks.put(index, chunk);
}
@Override
public void unloadChunks() {
Iterator<Map.Entry<Long, BaseFullChunk>> iter = chunks.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Long, BaseFullChunk> entry = iter.next();
long index = entry.getKey();
BaseFullChunk chunk = entry.getValue();
chunk.unload(true, false);
iter.remove();
}
}
@Override
public String getGenerator() {
return this.levelData.getString("generatorName");
}
@Override
public Map<String, Object> getGeneratorOptions() {
return new HashMap<String, Object>() {
{
put("preset", levelData.getString("generatorOptions"));
}
};
}
@Override
public Map<Long, BaseFullChunk> getLoadedChunks() {
return this.chunks;
}
@Override
public boolean isChunkLoaded(int X, int Z) {
return this.chunks.containsKey(Level.chunkHash(X, Z));
}
@Override
public boolean isChunkLoaded(long hash) {
return this.chunks.containsKey(hash);
}
public BaseRegionLoader getRegion(int x, int z) {
long index = Level.chunkHash(x, z);
return this.regions.get(index);
}
protected static int getRegionIndexX(int chunkX) {
return chunkX >> 5;
}
protected static int getRegionIndexZ(int chunkZ) {
return chunkZ >> 5;
}
@Override
public String getPath() {
return path;
}
public Server getServer() {
return this.level.getServer();
}
@Override
public Level getLevel() {
return level;
}
@Override
public String getName() {
return this.levelData.getString("LevelName");
}
@Override
public boolean isRaining() {
return this.levelData.getBoolean("raining");
}
@Override
public void setRaining(boolean raining) {
this.levelData.putBoolean("raining", raining);
}
@Override
public int getRainTime() {
return this.levelData.getInt("rainTime");
}
@Override
public void setRainTime(int rainTime) {
this.levelData.putInt("rainTime", rainTime);
}
@Override
public boolean isThundering() {
return this.levelData.getBoolean("thundering");
}
@Override
public void setThundering(boolean thundering) {
this.levelData.putBoolean("thundering", thundering);
}
@Override
public int getThunderTime() {
return this.levelData.getInt("thunderTime");
}
@Override
public void setThunderTime(int thunderTime) {
this.levelData.putInt("thunderTime", thunderTime);
}
@Override
public long getCurrentTick() {
return this.levelData.getLong("Time");
}
@Override
public void setCurrentTick(long currentTick) {
this.levelData.putLong("Time", currentTick);
}
@Override
public long getTime() {
return this.levelData.getLong("DayTime");
}
@Override
public void setTime(long value) {
this.levelData.putLong("DayTime", value);
}
@Override
public long getSeed() {
return this.levelData.getLong("RandomSeed");
}
@Override
public void setSeed(long value) {
this.levelData.putLong("RandomSeed", value);
}
@Override
public Vector3 getSpawn() {
return spawn;
}
@Override
public void setSpawn(Vector3 pos) {
this.levelData.putInt("SpawnX", (int) pos.x);
this.levelData.putInt("SpawnY", (int) pos.y);
this.levelData.putInt("SpawnZ", (int) pos.z);
spawn = pos;
}
@Override
public GameRules getGamerules() {
GameRules rules = GameRules.getDefault();
if (this.levelData.contains("GameRules"))
rules.readNBT(this.levelData.getCompound("GameRules"));
return rules;
}
@Override
public void setGameRules(GameRules rules) {
this.levelData.putCompound("GameRules", rules.writeNBT());
}
@Override
public void doGarbageCollection() {
int limit = (int) (System.currentTimeMillis() - 50);
for (Map.Entry<Long, BaseRegionLoader> entry : this.regions.entrySet()) {
long index = entry.getKey();
BaseRegionLoader region = entry.getValue();
if (region.lastUsed <= limit) {
try {
region.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
lastRegion = null;
this.regions.remove(index);
}
}
}
@Override
public void saveChunks() {
for (BaseFullChunk chunk : this.chunks.values()) {
if (chunk.getChanges() != 0) {
chunk.setChanged(false);
this.saveChunk(chunk.getX(), chunk.getZ());
}
}
}
public CompoundTag getLevelData() {
return levelData;
}
@Override
public void saveLevelData() {
try {
NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", this.levelData), new FileOutputStream(this.getPath() + "level.dat"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void updateLevelName(String name) {
if (!this.getName().equals(name)) {
this.levelData.putString("LevelName", name);
}
}
@Override
public boolean loadChunk(int chunkX, int chunkZ) {
return this.loadChunk(chunkX, chunkZ, false);
}
@Override
public boolean loadChunk(int chunkX, int chunkZ, boolean create) {
long index = Level.chunkHash(chunkX, chunkZ);
if (this.chunks.containsKey(index)) {
return true;
}
return loadChunk(index, chunkX, chunkZ, create) != null;
}
@Override
public boolean unloadChunk(int X, int Z) {
return this.unloadChunk(X, Z, true);
}
@Override
public boolean unloadChunk(int X, int Z, boolean safe) {
long index = Level.chunkHash(X, Z);
BaseFullChunk chunk = this.chunks.get(index);
if (chunk != null && chunk.unload(false, safe)) {
lastChunk = null;
this.chunks.remove(index, chunk);
return true;
}
return false;
}
@Override
public BaseFullChunk getChunk(int chunkX, int chunkZ) {
return this.getChunk(chunkX, chunkZ, false);
}
private volatile BaseFullChunk lastChunk;
@Override
public BaseFullChunk getLoadedChunk(int chunkX, int chunkZ) {
BaseFullChunk tmp = lastChunk;
if (tmp != null && tmp.getX() == chunkX && tmp.getZ() == chunkZ) {
return tmp;
}
long index = Level.chunkHash(chunkX, chunkZ);
lastChunk = tmp = chunks.get(index);
return tmp;
}
@Override
public BaseFullChunk getLoadedChunk(long hash) {
BaseFullChunk tmp = lastChunk;
if (tmp != null && tmp.getIndex() == hash) {
return tmp;
}
lastChunk = tmp = chunks.get(hash);
return tmp;
}
@Override
public BaseFullChunk getChunk(int chunkX, int chunkZ, boolean create) {
BaseFullChunk tmp = lastChunk;
if (tmp != null && tmp.getX() == chunkX && tmp.getZ() == chunkZ) {
return tmp;
}
long index = Level.chunkHash(chunkX, chunkZ);
lastChunk = tmp = chunks.get(index);
if (tmp != null) {
return tmp;
} else {
tmp = this.loadChunk(index, chunkX, chunkZ, create);
lastChunk = tmp;
return tmp;
}
}
@Override
public void setChunk(int chunkX, int chunkZ, FullChunk chunk) {
if (!(chunk instanceof BaseFullChunk)) {
throw new ChunkException("Invalid Chunk class");
}
chunk.setProvider(this);
chunk.setPosition(chunkX, chunkZ);
long index = Level.chunkHash(chunkX, chunkZ);
if (this.chunks.containsKey(index) && !this.chunks.get(index).equals(chunk)) {
this.unloadChunk(chunkX, chunkZ, false);
}
this.chunks.put(index, (BaseFullChunk) chunk);
}
@Override
public boolean isChunkPopulated(int chunkX, int chunkZ) {
BaseFullChunk chunk = this.getChunk(chunkX, chunkZ);
return chunk != null && chunk.isPopulated();
}
@Override
public synchronized void close() {
this.unloadChunks();
Iterator<Map.Entry<Long, BaseRegionLoader>> iter = this.regions.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Long, BaseRegionLoader> entry = iter.next();
long index = entry.getKey();
BaseRegionLoader region = entry.getValue();
try {
region.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
lastRegion = null;
iter.remove();
}
this.level = null;
}
@Override
public boolean isChunkGenerated(int chunkX, int chunkZ) {
BaseRegionLoader region = this.getRegion(chunkX >> 5, chunkZ >> 5);
return region != null && region.chunkExists(chunkX - region.getX() * 32, chunkZ - region.getZ() * 32) && this.getChunk(chunkX - region.getX() * 32, chunkZ - region.getZ() * 32, true).isGenerated();
}
}
| 12,124 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Chunk.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/mcregion/Chunk.java | package cn.nukkit.level.format.mcregion;
import cn.nukkit.Player;
import cn.nukkit.block.Block;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.entity.Entity;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.ByteArrayTag;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.IntArrayTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.utils.Binary;
import cn.nukkit.utils.BinaryStream;
import cn.nukkit.utils.Zlib;
import java.io.ByteArrayInputStream;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Chunk extends BaseFullChunk {
protected final CompoundTag nbt;
public Chunk(LevelProvider level) {
this(level, null);
}
public Chunk(Class<? extends LevelProvider> providerClass) {
this((LevelProvider) null, null);
this.providerClass = providerClass;
}
public Chunk(Class<? extends LevelProvider> providerClass, CompoundTag nbt) {
this((LevelProvider) null, nbt);
this.providerClass = providerClass;
}
public Chunk(LevelProvider level, CompoundTag nbt) {
this.provider = level;
if (level != null) {
this.providerClass = level.getClass();
}
if (nbt == null) {
this.nbt = new CompoundTag("Level");
return;
}
this.nbt = nbt;
if (!(this.nbt.contains("Entities") && (this.nbt.get("Entities") instanceof ListTag))) {
this.nbt.putList(new ListTag<CompoundTag>("Entities"));
}
if (!(this.nbt.contains("TileEntities") && (this.nbt.get("TileEntities") instanceof ListTag))) {
this.nbt.putList(new ListTag<CompoundTag>("TileEntities"));
}
if (!(this.nbt.contains("TileTicks") && (this.nbt.get("TileTicks") instanceof ListTag))) {
this.nbt.putList(new ListTag<CompoundTag>("TileTicks"));
}
if (!(this.nbt.contains("BiomeColors") && (this.nbt.get("BiomeColors") instanceof IntArrayTag))) {
this.nbt.putIntArray("BiomeColors", new int[256]);
}
if (!(this.nbt.contains("HeightMap") && (this.nbt.get("HeightMap") instanceof IntArrayTag))) {
this.nbt.putIntArray("HeightMap", new int[256]);
}
if (!(this.nbt.contains("Blocks"))) {
this.nbt.putByteArray("Blocks", new byte[32768]);
}
if (!(this.nbt.contains("Data"))) {
this.nbt.putByteArray("Data", new byte[16384]);
this.nbt.putByteArray("SkyLight", new byte[16384]);
this.nbt.putByteArray("BlockLight", new byte[16384]);
}
Map<Integer, Integer> extraData = new HashMap<>();
if (!this.nbt.contains("ExtraData") || !(this.nbt.get("ExtraData") instanceof ByteArrayTag)) {
this.nbt.putByteArray("ExtraData", Binary.writeInt(0));
} else {
BinaryStream stream = new BinaryStream(this.nbt.getByteArray("ExtraData"));
for (int i = 0; i < stream.getInt(); i++) {
int key = stream.getInt();
extraData.put(key, stream.getShort());
}
}
this.setPosition(this.nbt.getInt("xPos"), this.nbt.getInt("zPos"));
this.blocks = this.nbt.getByteArray("Blocks");
this.data = this.nbt.getByteArray("Data");
this.skyLight = this.nbt.getByteArray("SkyLight");
this.blockLight = this.nbt.getByteArray("BlockLight");
int[] biomeColors = this.nbt.getIntArray("BiomeColors");
if (biomeColors.length != 256) {
biomeColors = new int[256];
Arrays.fill(biomeColors, Binary.readInt(new byte[]{(byte) 0xff, (byte) 0x00, (byte) 0x00, (byte) 0x00}));
}
this.biomeColors = biomeColors;
int[] heightMap = this.nbt.getIntArray("HeightMap");
this.heightMap = new byte[256];
if (heightMap.length != 256) {
Arrays.fill(this.heightMap, (byte) 255);
} else {
for (int i = 0; i < heightMap.length; i++) {
this.heightMap[i] = (byte) heightMap[i];
}
}
this.extraData = extraData;
this.NBTentities = ((ListTag<CompoundTag>) this.nbt.getList("Entities")).getAll();
this.NBTtiles = ((ListTag<CompoundTag>) this.nbt.getList("TileEntities")).getAll();
if (this.nbt.contains("Biomes")) {
this.checkOldBiomes(this.nbt.getByteArray("Biomes"));
this.nbt.remove("Biomes");
}
this.nbt.remove("Blocks");
this.nbt.remove("Data");
this.nbt.remove("SkyLight");
this.nbt.remove("BlockLight");
this.nbt.remove("BiomeColors");
this.nbt.remove("HeightMap");
this.nbt.remove("Biomes");
}
@Override
public int getBlockId(int x, int y, int z) {
return this.blocks[(x << 11) | (z << 7) | y] & 0xff;
}
@Override
public void setBlockId(int x, int y, int z, int id) {
this.blocks[(x << 11) | (z << 7) | y] = (byte) id;
setChanged();
}
@Override
public int getBlockData(int x, int y, int z) {
int b = this.data[(x << 10) | (z << 6) | (y >> 1)] & 0xff;
if ((y & 1) == 0) {
return b & 0x0f;
} else {
return b >> 4;
}
}
@Override
public void setBlockData(int x, int y, int z, int data) {
int i = (x << 10) | (z << 6) | (y >> 1);
int old = this.data[i] & 0xff;
if ((y & 1) == 0) {
this.data[i] = (byte) ((old & 0xf0) | (data & 0x0f));
} else {
this.data[i] = (byte) (((data & 0x0f) << 4) | (old & 0x0f));
}
setChanged();
}
@Override
public int getFullBlock(int x, int y, int z) {
int i = (x << 11) | (z << 7) | y;
int block = this.blocks[i] & 0xff;
int data = this.data[i >> 1] & 0xff;
if ((y & 1) == 0) {
return (block << 4) | (data & 0x0f);
} else {
return (block << 4) | (data >> 4);
}
}
@Override
public boolean setBlock(int x, int y, int z, int blockId) {
return setBlock(x, y, z, blockId, 0);
}
@Override
public boolean setBlock(int x, int y, int z, int blockId, int meta) {
int i = (x << 11) | (z << 7) | y;
boolean changed = false;
byte id = (byte) blockId;
if (this.blocks[i] != id) {
this.blocks[i] = id;
changed = true;
}
if (Block.hasMeta[blockId]) {
i >>= 1;
int old = this.data[i] & 0xff;
if ((y & 1) == 0) {
this.data[i] = (byte) ((old & 0xf0) | (meta & 0x0f));
if ((old & 0x0f) != meta) {
changed = true;
}
} else {
this.data[i] = (byte) (((meta & 0x0f) << 4) | (old & 0x0f));
if (meta != (old >> 4)) {
changed = true;
}
}
}
if (changed) {
setChanged();
}
return changed;
}
@Override
public Block getAndSetBlock(int x, int y, int z, Block block) {
int i = (x << 11) | (z << 7) | y;
boolean changed = false;
byte id = (byte) block.getId();
byte previousId = this.blocks[i];
if (previousId != id) {
this.blocks[i] = id;
changed = true;
}
int previousData;
i >>= 1;
int old = this.data[i] & 0xff;
if ((y & 1) == 0) {
previousData = old & 0x0f;
if (Block.hasMeta[block.getId()]) {
this.data[i] = (byte) ((old & 0xf0) | (block.getDamage() & 0x0f));
if (block.getDamage() != previousData) {
changed = true;
}
}
} else {
previousData = old >> 4;
if (Block.hasMeta[block.getId()]) {
this.data[i] = (byte) (((block.getDamage() & 0x0f) << 4) | (old & 0x0f));
if (block.getDamage() != previousData) {
changed = true;
}
}
}
if (changed) {
setChanged();
}
return Block.get(previousId, previousData);
}
@Override
public int getBlockSkyLight(int x, int y, int z) {
int sl = this.skyLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff;
if ((y & 1) == 0) {
return sl & 0x0f;
} else {
return sl >> 4;
}
}
@Override
public void setBlockSkyLight(int x, int y, int z, int level) {
int i = (x << 10) | (z << 6) | (y >> 1);
int old = this.skyLight[i] & 0xff;
if ((y & 1) == 0) {
this.skyLight[i] = (byte) ((old & 0xf0) | (level & 0x0f));
} else {
this.skyLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f));
}
setChanged();
}
@Override
public int getBlockLight(int x, int y, int z) {
int b = this.blockLight[(x << 10) | (z << 6) | (y >> 1)] & 0xff;
if ((y & 1) == 0) {
return b & 0x0f;
} else {
return b >> 4;
}
}
@Override
public void setBlockLight(int x, int y, int z, int level) {
int i = (x << 10) | (z << 6) | (y >> 1);
int old = this.blockLight[i] & 0xff;
if ((y & 1) == 0) {
this.blockLight[i] = (byte) ((old & 0xf0) | (level & 0x0f));
} else {
this.blockLight[i] = (byte) (((level & 0x0f) << 4) | (old & 0x0f));
}
setChanged();
}
@Override
public boolean isLightPopulated() {
return this.nbt.getBoolean("LightPopulated");
}
@Override
public void setLightPopulated() {
this.setLightPopulated(true);
}
@Override
public void setLightPopulated(boolean value) {
this.nbt.putBoolean("LightPopulated", value);
setChanged();
}
@Override
public boolean isPopulated() {
return this.nbt.contains("TerrainPopulated") && this.nbt.getBoolean("TerrainPopulated");
}
@Override
public void setPopulated() {
this.setPopulated(true);
}
@Override
public void setPopulated(boolean value) {
this.nbt.putBoolean("TerrainPopulated", value);
setChanged();
}
@Override
public boolean isGenerated() {
if (this.nbt.contains("TerrainGenerated")) {
return this.nbt.getBoolean("TerrainGenerated");
} else if (this.nbt.contains("TerrainPopulated")) {
return this.nbt.getBoolean("TerrainPopulated");
}
return false;
}
@Override
public void setGenerated() {
this.setGenerated(true);
}
@Override
public void setGenerated(boolean value) {
this.nbt.putBoolean("TerrainGenerated", value);
setChanged();
}
public static Chunk fromBinary(byte[] data) {
return fromBinary(data, null);
}
public static Chunk fromBinary(byte[] data, LevelProvider provider) {
try {
CompoundTag chunk = NBTIO.read(new ByteArrayInputStream(Zlib.inflate(data)), ByteOrder.BIG_ENDIAN);
if (!chunk.contains("Level") || !(chunk.get("Level") instanceof CompoundTag)) {
return null;
}
return new Chunk(provider != null ? provider : McRegion.class.newInstance(), chunk.getCompound("Level"));
} catch (Exception e) {
return null;
}
}
public static Chunk fromFastBinary(byte[] data) {
return fromFastBinary(data, null);
}
public static Chunk fromFastBinary(byte[] data, LevelProvider provider) {
try {
int offset = 0;
Chunk chunk = new Chunk(provider != null ? provider : McRegion.class.newInstance(), null);
chunk.provider = provider;
int chunkX = (Binary.readInt(Arrays.copyOfRange(data, offset, offset + 3)));
offset += 4;
int chunkZ = (Binary.readInt(Arrays.copyOfRange(data, offset, offset + 3)));
chunk.setPosition(chunkX, chunkZ);
offset += 4;
chunk.blocks = Arrays.copyOfRange(data, offset, offset + 32767);
offset += 32768;
chunk.data = Arrays.copyOfRange(data, offset, offset + 16383);
offset += 16384;
chunk.skyLight = Arrays.copyOfRange(data, offset, offset + 16383);
offset += 16384;
chunk.blockLight = Arrays.copyOfRange(data, offset, offset + 16383);
offset += 16384;
chunk.heightMap = Arrays.copyOfRange(data, offset, offset + 256);
offset += 256;
chunk.biomeColors = new int[256];
for (int i = 0; i < 256; i++) {
chunk.biomeColors[i] = Binary.readInt(Arrays.copyOfRange(data, offset, offset + 3));
offset += 4;
}
byte flags = data[offset++];
chunk.nbt.putByte("TerrainGenerated", (flags & 0b1));
chunk.nbt.putByte("TerrainPopulated", ((flags >> 1) & 0b1));
chunk.nbt.putByte("LightPopulated", ((flags >> 2) & 0b1));
return chunk;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public byte[] toFastBinary() {
BinaryStream stream = new BinaryStream(new byte[65536]);
stream.put(Binary.writeInt(this.getX()));
stream.put(Binary.writeInt(this.getZ()));
stream.put(this.getBlockIdArray());
stream.put(this.getBlockDataArray());
stream.put(this.getBlockSkyLightArray());
stream.put(this.getBlockLightArray());
stream.put(this.getHeightMapArray());
for (int color : this.getBiomeColorArray()) {
stream.put(Binary.writeInt(color));
}
stream.putByte((byte) ((this.isLightPopulated() ? 1 << 2 : 0) + (this.isPopulated() ? 1 << 2 : 0) + (this.isGenerated() ? 1 : 0)));
return stream.getBuffer();
}
@Override
public byte[] toBinary() {
CompoundTag nbt = this.getNBT().copy();
nbt.putInt("xPos", this.getX());
nbt.putInt("zPos", this.getZ());
if (this.isGenerated()) {
nbt.putByteArray("Blocks", this.getBlockIdArray());
nbt.putByteArray("Data", this.getBlockDataArray());
nbt.putByteArray("SkyLight", this.getBlockSkyLightArray());
nbt.putByteArray("BlockLight", this.getBlockLightArray());
nbt.putIntArray("BiomeColors", this.getBiomeColorArray());
int[] heightInts = new int[256];
byte[] heightBytes = this.getHeightMapArray();
for (int i = 0; i < heightInts.length; i++) {
heightInts[i] = heightBytes[i] & 0xFF;
}
nbt.putIntArray("HeightMap", heightInts);
}
ArrayList<CompoundTag> entities = new ArrayList<>();
for (Entity entity : this.getEntities().values()) {
if (!(entity instanceof Player) && !entity.closed) {
entity.saveNBT();
entities.add(entity.namedTag);
}
}
ListTag<CompoundTag> entityListTag = new ListTag<>("Entities");
entityListTag.setAll(entities);
nbt.putList(entityListTag);
ArrayList<CompoundTag> tiles = new ArrayList<>();
for (BlockEntity blockEntity : this.getBlockEntities().values()) {
blockEntity.saveNBT();
tiles.add(blockEntity.namedTag);
}
ListTag<CompoundTag> tileListTag = new ListTag<>("TileEntities");
tileListTag.setAll(tiles);
nbt.putList(tileListTag);
BinaryStream extraData = new BinaryStream();
Map<Integer, Integer> extraDataArray = this.getBlockExtraDataArray();
extraData.putInt(extraDataArray.size());
for (Integer key : extraDataArray.keySet()) {
extraData.putInt(key);
extraData.putShort(extraDataArray.get(key));
}
nbt.putByteArray("ExtraData", extraData.getBuffer());
CompoundTag chunk = new CompoundTag("");
chunk.putCompound("Level", nbt);
try {
return Zlib.deflate(NBTIO.write(chunk, ByteOrder.BIG_ENDIAN), RegionLoader.COMPRESSION_LEVEL);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public CompoundTag getNBT() {
return nbt;
}
public static Chunk getEmptyChunk(int chunkX, int chunkZ) {
return getEmptyChunk(chunkX, chunkZ, null);
}
public static Chunk getEmptyChunk(int chunkX, int chunkZ, LevelProvider provider) {
try {
Chunk chunk;
if (provider != null) {
chunk = new Chunk(provider, null);
} else {
chunk = new Chunk(McRegion.class, null);
}
chunk.setPosition(chunkX, chunkZ);
chunk.data = new byte[16384];
chunk.blocks = new byte[32768];
byte[] skyLight = new byte[16384];
Arrays.fill(skyLight, (byte) 0xff);
chunk.skyLight = skyLight;
chunk.blockLight = chunk.data;
chunk.heightMap = new byte[256];
chunk.biomeColors = new int[256];
chunk.nbt.putByte("V", 1);
chunk.nbt.putLong("InhabitedTime", 0);
chunk.nbt.putBoolean("TerrainGenerated", false);
chunk.nbt.putBoolean("TerrainPopulated", false);
chunk.nbt.putBoolean("LightPopulated", false);
return chunk;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 17,892 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
RegionLoader.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/mcregion/RegionLoader.java | package cn.nukkit.level.format.mcregion;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.LevelProvider;
import cn.nukkit.level.format.generic.BaseRegionLoader;
import cn.nukkit.utils.*;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class RegionLoader extends BaseRegionLoader {
public RegionLoader(LevelProvider level, int regionX, int regionZ) {
super(level, regionX, regionZ, "mcr");
}
@Override
protected boolean isChunkGenerated(int index) {
Integer[] array = this.locationTable.get(index);
return !(array[0] == 0 || array[1] == 0);
}
public Chunk readChunk(int x, int z) throws IOException {
int index = getChunkOffset(x, z);
if (index < 0 || index >= 4096) {
return null;
}
this.lastUsed = System.currentTimeMillis();
if (!this.isChunkGenerated(index)) {
return null;
}
Integer[] table = this.locationTable.get(index);
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(table[0] << 12);
int length = raf.readInt();
if (length <= 0 || length >= MAX_SECTOR_LENGTH) {
if (length >= MAX_SECTOR_LENGTH) {
table[0] = ++this.lastSector;
table[1] = 1;
this.locationTable.put(index, table);
MainLogger.getLogger().error("Corrupted chunk header detected");
}
return null;
}
byte compression = raf.readByte();
if (length > (table[1] << 12)) {
MainLogger.getLogger().error("Corrupted bigger chunk detected");
table[1] = length >> 12;
this.locationTable.put(index, table);
this.writeLocationIndex(index);
} else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) {
MainLogger.getLogger().error("Invalid compression type");
return null;
}
byte[] data = new byte[length - 1];
raf.readFully(data);
Chunk chunk = this.unserializeChunk(data);
if (chunk != null) {
return chunk;
} else {
MainLogger.getLogger().error("Corrupted chunk detected");
return null;
}
}
@Override
protected Chunk unserializeChunk(byte[] data) {
return Chunk.fromBinary(data, this.levelProvider);
}
@Override
public boolean chunkExists(int x, int z) {
return this.isChunkGenerated(getChunkOffset(x, z));
}
@Override
protected void saveChunk(int x, int z, byte[] chunkData) throws IOException {
int length = chunkData.length + 1;
if (length + 4 > MAX_SECTOR_LENGTH) {
throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH);
}
int sectors = (int) Math.ceil((length + 4) / 4096d);
int index = getChunkOffset(x, z);
boolean indexChanged = false;
Integer[] table = this.locationTable.get(index);
if (table[1] < sectors) {
table[0] = this.lastSector + 1;
this.locationTable.put(index, table);
this.lastSector += sectors;
indexChanged = true;
} else if (table[1] != sectors) {
indexChanged = true;
}
table[1] = sectors;
table[2] = (int) (System.currentTimeMillis() / 1000d);
this.locationTable.put(index, table);
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(table[0] << 12);
BinaryStream stream = new BinaryStream();
stream.put(Binary.writeInt(length));
stream.putByte(COMPRESSION_ZLIB);
stream.put(chunkData);
byte[] data = stream.getBuffer();
if (data.length < sectors << 12) {
byte[] newData = new byte[sectors << 12];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
raf.write(data);
if (indexChanged) {
this.writeLocationIndex(index);
}
}
@Override
public void removeChunk(int x, int z) {
int index = getChunkOffset(x, z);
Integer[] table = this.locationTable.get(0);
table[0] = 0;
table[1] = 0;
this.locationTable.put(index, table);
}
@Override
public void writeChunk(FullChunk chunk) throws Exception {
this.lastUsed = System.currentTimeMillis();
byte[] chunkData = chunk.toBinary();
this.saveChunk(chunk.getX() & 0x1f, chunk.getZ() & 0x1f, chunkData);
}
protected static int getChunkOffset(int x, int z) {
return x | (z << 5);
}
@Override
public void close() throws IOException {
this.writeLocationTable();
this.levelProvider = null;
super.close();
}
@Override
public int doSlowCleanUp() throws Exception {
RandomAccessFile raf = this.getRandomAccessFile();
for (int i = 0; i < 1024; i++) {
Integer[] table = this.locationTable.get(i);
if (table[0] == 0 || table[1] == 0) {
continue;
}
raf.seek(table[0] << 12);
byte[] chunk = new byte[table[1] << 12];
raf.readFully(chunk);
int length = Binary.readInt(Arrays.copyOfRange(chunk, 0, 3));
if (length <= 1) {
this.locationTable.put(i, (table = new Integer[]{0, 0, 0}));
}
try {
chunk = Zlib.inflate(Arrays.copyOf(chunk, 5));
} catch (Exception e) {
this.locationTable.put(i, new Integer[]{0, 0, 0});
continue;
}
chunk = Zlib.deflate(chunk, 9);
ByteBuffer buffer = ByteBuffer.allocate(4 + 1 + chunk.length);
buffer.put(Binary.writeInt(chunk.length + 1));
buffer.put(COMPRESSION_ZLIB);
buffer.put(chunk);
chunk = buffer.array();
int sectors = (int) Math.ceil(chunk.length / 4096d);
if (sectors > table[1]) {
table[0] = this.lastSector + 1;
this.lastSector += sectors;
this.locationTable.put(i, table);
}
raf.seek(table[0] << 12);
byte[] bytes = new byte[sectors << 12];
ByteBuffer buffer1 = ByteBuffer.wrap(bytes);
buffer1.put(chunk);
raf.write(buffer1.array());
}
this.writeLocationTable();
int n = this.cleanGarbage();
this.writeLocationTable();
return n;
}
@Override
protected void loadLocationTable() throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(0);
this.lastSector = 1;
int[] data = new int[1024 * 2]; //1024 records * 2 times
for (int i = 0; i < 1024 * 2; i++) {
data[i] = raf.readInt();
}
for (int i = 0; i < 1024; ++i) {
int index = data[i];
this.locationTable.put(i, new Integer[]{index >> 8, index & 0xff, data[1024 + i]});
int value = this.locationTable.get(i)[0] + this.locationTable.get(i)[1] - 1;
if (value > this.lastSector) {
this.lastSector = value;
}
}
}
private void writeLocationTable() throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(0);
for (int i = 0; i < 1024; ++i) {
Integer[] array = this.locationTable.get(i);
raf.writeInt((array[0] << 8) | array[1]);
}
for (int i = 0; i < 1024; ++i) {
Integer[] array = this.locationTable.get(i);
raf.writeInt(array[2]);
}
}
private int cleanGarbage() throws IOException {
Map<Integer, Integer> sectors = new TreeMap<>();
for (int index : new ArrayList<>(this.locationTable.keySet())) {
Integer[] data = this.locationTable.get(index);
if (data[0] == 0 || data[1] == 0) {
this.locationTable.put(index, new Integer[]{0, 0, 0});
continue;
}
sectors.put(data[0], index);
}
if (sectors.size() == (this.lastSector - 2)) {
return 0;
}
int shift = 0;
int lastSector = 1;
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(8192);
int s = 2;
for (int sector : sectors.keySet()) {
s = sector;
int index = sectors.get(sector);
if ((sector - lastSector) > 1) {
shift += sector - lastSector - 1;
}
if (shift > 0) {
raf.seek(sector << 12);
byte[] old = new byte[4096];
raf.readFully(old);
raf.seek((sector - shift) << 12);
raf.write(old);
}
Integer[] v = this.locationTable.get(index);
v[0] -= shift;
this.locationTable.put(index, v);
this.lastSector = sector;
}
raf.setLength((s + 1) << 12);
return shift;
}
@Override
protected void writeLocationIndex(int index) throws IOException {
Integer[] array = this.locationTable.get(index);
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(index << 2);
raf.writeInt((array[0] << 8) | array[1]);
raf.seek(4096 + (index << 2));
raf.writeInt(array[2]);
}
@Override
protected void createBlank() throws IOException {
RandomAccessFile raf = this.getRandomAccessFile();
raf.seek(0);
raf.setLength(0);
this.lastSector = 1;
int time = (int) (System.currentTimeMillis() / 1000d);
for (int i = 0; i < 1024; ++i) {
this.locationTable.put(i, new Integer[]{0, 0, time});
raf.writeInt(0);
}
for (int i = 0; i < 1024; ++i) {
raf.writeInt(time);
}
}
@Override
public int getX() {
return x;
}
@Override
public int getZ() {
return z;
}
}
| 10,366 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
McRegion.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/level/format/mcregion/McRegion.java | package cn.nukkit.level.format.mcregion;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.blockentity.BlockEntitySpawnable;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.ChunkSection;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.level.format.generic.BaseFullChunk;
import cn.nukkit.level.format.generic.BaseLevelProvider;
import cn.nukkit.level.format.generic.BaseRegionLoader;
import cn.nukkit.level.generator.Generator;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.scheduler.AsyncTask;
import cn.nukkit.utils.Binary;
import cn.nukkit.utils.BinaryStream;
import cn.nukkit.utils.ChunkException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class McRegion extends BaseLevelProvider {
public McRegion(Level level, String path) throws IOException {
super(level, path);
}
public static String getProviderName() {
return "mcregion";
}
public static byte getProviderOrder() {
return ORDER_ZXY;
}
public static boolean usesChunkSection() {
return false;
}
public static boolean isValid(String path) {
boolean isValid = (new File(path + "/level.dat").exists()) && new File(path + "/region/").isDirectory();
if (isValid) {
for (File file : new File(path + "/region/").listFiles((dir, name) -> Pattern.matches("^.+\\.mc[r|a]$", name))) {
if (!file.getName().endsWith(".mcr")) {
isValid = false;
break;
}
}
}
return isValid;
}
public static void generate(String path, String name, long seed, Class<? extends Generator> generator) throws IOException {
generate(path, name, seed, generator, new HashMap<>());
}
public static void generate(String path, String name, long seed, Class<? extends Generator> generator, Map<String, String> options) throws IOException {
if (!new File(path + "/region").exists()) {
new File(path + "/region").mkdirs();
}
CompoundTag levelData = new CompoundTag("Data")
.putCompound("GameRules", new CompoundTag())
.putLong("DayTime", 0)
.putInt("GameType", 0)
.putString("generatorName", Generator.getGeneratorName(generator))
.putString("generatorOptions", options.containsKey("preset") ? options.get("preset") : "")
.putInt("generatorVersion", 1)
.putBoolean("hardcore", false)
.putBoolean("initialized", true)
.putLong("LastPlayed", System.currentTimeMillis() / 1000)
.putString("LevelName", name)
.putBoolean("raining", false)
.putInt("rainTime", 0)
.putLong("RandomSeed", seed)
.putInt("SpawnX", 128)
.putInt("SpawnY", 70)
.putInt("SpawnZ", 128)
.putBoolean("thundering", false)
.putInt("thunderTime", 0)
.putInt("version", 19133)
.putLong("Time", 0)
.putLong("SizeOnDisk", 0);
NBTIO.writeGZIPCompressed(new CompoundTag().putCompound("Data", levelData), new FileOutputStream(path + "level.dat"), ByteOrder.BIG_ENDIAN);
}
@Override
public AsyncTask requestChunkTask(int x, int z) throws ChunkException {
BaseFullChunk chunk = this.getChunk(x, z, false);
if (chunk == null) {
throw new ChunkException("Invalid Chunk Sent");
}
long timestamp = chunk.getChanges();
byte[] tiles = new byte[0];
if (!chunk.getBlockEntities().isEmpty()) {
List<CompoundTag> tagList = new ArrayList<>();
for (BlockEntity blockEntity : chunk.getBlockEntities().values()) {
if (blockEntity instanceof BlockEntitySpawnable) {
tagList.add(((BlockEntitySpawnable) blockEntity).getSpawnCompound());
}
}
try {
tiles = NBTIO.write(tagList, ByteOrder.LITTLE_ENDIAN, true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Map<Integer, Integer> extra = chunk.getBlockExtraDataArray();
BinaryStream extraData;
if (!extra.isEmpty()) {
extraData = new BinaryStream();
extraData.putLInt(extra.size());
for (Map.Entry<Integer, Integer> entry : extra.entrySet()) {
extraData.putLInt(entry.getKey());
extraData.putLShort(entry.getValue());
}
} else {
extraData = null;
}
BinaryStream stream = new BinaryStream();
stream.put(chunk.getBlockIdArray());
stream.put(chunk.getBlockDataArray());
stream.put(chunk.getBlockSkyLightArray());
stream.put(chunk.getBlockLightArray());
stream.put(chunk.getHeightMapArray());
for (int color : chunk.getBiomeColorArray()) {
stream.put(Binary.writeInt(color));
}
if (extraData != null) {
stream.put(extraData.getBuffer());
} else {
stream.putLInt(0);
}
stream.put(tiles);
this.getLevel().chunkRequestCallback(timestamp, x, z, stream.getBuffer());
return null;
}
@Override
public BaseFullChunk loadChunk(long index, int chunkX, int chunkZ, boolean create) {
int regionX = getRegionIndexX(chunkX);
int regionZ = getRegionIndexZ(chunkZ);
BaseRegionLoader region = this.loadRegion(regionX, regionZ);
this.level.timings.syncChunkLoadDataTimer.startTiming();
BaseFullChunk chunk;
try {
chunk = region.readChunk(chunkX - regionX * 32, chunkZ - regionZ * 32);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (chunk == null) {
if (create) {
chunk = this.getEmptyChunk(chunkX, chunkZ);
putChunk(index, chunk);
}
} else {
putChunk(index, chunk);
}
this.level.timings.syncChunkLoadDataTimer.stopTiming();
return chunk;
}
public Chunk getEmptyChunk(int chunkX, int chunkZ) {
return Chunk.getEmptyChunk(chunkX, chunkZ, this);
}
@Override
public void saveChunk(int x, int z) {
if (this.isChunkLoaded(x, z)) {
try {
this.getRegion(x >> 5, z >> 5).writeChunk(this.getChunk(x, z));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public void saveChunk(int x, int z, FullChunk chunk) {
if (!(chunk instanceof Chunk)) {
throw new ChunkException("Invalid Chunk class");
}
this.loadRegion(x >> 5, z >> 5);
chunk.setPosition(x, z);
try {
this.getRegion(x >> 5, z >> 5).writeChunk(chunk);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static ChunkSection createChunkSection(int y) {
return null;
}
protected BaseRegionLoader loadRegion(int x, int z) {
BaseRegionLoader tmp = lastRegion;
if (tmp != null && x == tmp.getX() && z == tmp.getZ()) {
return tmp;
}
long index = Level.chunkHash(x, z);
BaseRegionLoader region = this.regions.get(index);
if (region == null) {
region = new RegionLoader(this, x, z);
this.regions.put(index, region);
return lastRegion = region;
} else {
return lastRegion = region;
}
}
}
| 8,010 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
AbstractResourcePack.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/resourcepacks/AbstractResourcePack.java | package cn.nukkit.resourcepacks;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public abstract class AbstractResourcePack implements ResourcePack {
protected JsonObject manifest;
protected boolean verifyManifest() {
if (this.manifest.has("format_version") && this.manifest.has("header") && this.manifest.has("modules")) {
JsonObject header = this.manifest.getAsJsonObject("header");
return header.has("description") &&
header.has("name") &&
header.has("uuid") &&
header.has("version") &&
header.getAsJsonArray("version").size() == 3;
} else {
return false;
}
}
@Override
public String getPackName() {
return this.manifest.getAsJsonObject("header")
.get("name").getAsString();
}
@Override
public String getPackId() {
return this.manifest.getAsJsonObject("header")
.get("uuid").getAsString();
}
@Override
public String getPackVersion() {
JsonArray version = this.manifest.getAsJsonObject("header")
.get("version").getAsJsonArray();
return String.join(".", version.get(0).getAsString(),
version.get(1).getAsString(),
version.get(2).getAsString());
}
}
| 1,379 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ZippedResourcePack.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/resourcepacks/ZippedResourcePack.java | package cn.nukkit.resourcepacks;
import cn.nukkit.Server;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZippedResourcePack extends AbstractResourcePack {
private File file;
private byte[] sha256 = null;
public ZippedResourcePack(File file) {
if (!file.exists()) {
throw new IllegalArgumentException(Server.getInstance().getLanguage()
.translateString("nukkit.resources.zip.not-found", file.getName()));
}
this.file = file;
try (ZipFile zip = new ZipFile(file)) {
ZipEntry entry = zip.getEntry("manifest.json");
if (entry == null) {
throw new IllegalArgumentException(Server.getInstance().getLanguage()
.translateString("nukkit.resources.zip.no-manifest"));
} else {
this.manifest = new JsonParser()
.parse(new InputStreamReader(zip.getInputStream(entry), StandardCharsets.UTF_8))
.getAsJsonObject();
}
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
if (!this.verifyManifest()) {
throw new IllegalArgumentException(Server.getInstance().getLanguage()
.translateString("nukkit.resources.zip.invalid-manifest"));
}
}
@Override
public int getPackSize() {
return (int) this.file.length();
}
@Override
public byte[] getSha256() {
if (this.sha256 == null) {
try {
this.sha256 = MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(this.file.toPath()));
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
}
return this.sha256;
}
@Override
public byte[] getPackChunk(int off, int len) {
byte[] chunk;
if (this.getPackSize() - off > len) {
chunk = new byte[len];
} else {
chunk = new byte[this.getPackSize() - off];
}
try (FileInputStream fis = new FileInputStream(this.file)) {
fis.skip(off);
fis.read(chunk);
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
return chunk;
}
}
| 2,625 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ResourcePack.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/resourcepacks/ResourcePack.java | package cn.nukkit.resourcepacks;
public interface ResourcePack {
String getPackName();
String getPackId();
String getPackVersion();
int getPackSize();
byte[] getSha256();
byte[] getPackChunk(int off, int len);
}
| 242 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ResourcePackManager.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/resourcepacks/ResourcePackManager.java | package cn.nukkit.resourcepacks;
import cn.nukkit.Server;
import com.google.common.io.Files;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResourcePackManager {
private ResourcePack[] resourcePacks;
private Map<String, ResourcePack> resourcePacksById = new HashMap<>();
public ResourcePackManager(File path) {
if (!path.exists()) {
path.mkdirs();
} else if (!path.isDirectory()) {
throw new IllegalArgumentException(Server.getInstance().getLanguage()
.translateString("nukkit.resources.invalid-path", path.getName()));
}
List<ResourcePack> loadedResourcePacks = new ArrayList<>();
for (File pack : path.listFiles()) {
try {
ResourcePack resourcePack = null;
if (!pack.isDirectory()) { //directory resource packs temporarily unsupported
switch (Files.getFileExtension(pack.getName())) {
case "zip":
case "mcpack":
resourcePack = new ZippedResourcePack(pack);
break;
default:
Server.getInstance().getLogger().warning(Server.getInstance().getLanguage()
.translateString("nukkit.resources.unknown-format", pack.getName()));
break;
}
}
if (resourcePack != null) {
loadedResourcePacks.add(resourcePack);
this.resourcePacksById.put(resourcePack.getPackId(), resourcePack);
}
} catch (IllegalArgumentException e) {
Server.getInstance().getLogger().warning(Server.getInstance().getLanguage()
.translateString("nukkit.resources.fail", pack.getName(), e.getMessage()));
}
}
this.resourcePacks = loadedResourcePacks.toArray(new ResourcePack[loadedResourcePacks.size()]);
Server.getInstance().getLogger().info(Server.getInstance().getLanguage()
.translateString("nukkit.resources.success", String.valueOf(this.resourcePacks.length)));
}
public ResourcePack[] getResourceStack() {
return this.resourcePacks;
}
public ResourcePack getPackById(String id) {
return this.resourcePacksById.get(id);
}
}
| 2,509 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockIterator.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/BlockIterator.java | package cn.nukkit.utils;
import cn.nukkit.block.Block;
import cn.nukkit.level.Level;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.Vector3;
import java.util.Iterator;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class BlockIterator implements Iterator<Block> {
private final Level level;
private final int maxDistance;
private static final int gridSize = 1 << 24;
private boolean end = false;
private final Block[] blockQueue;
private int currentBlock = 0;
private Block currentBlockObject = null;
private int currentDistance;
private int maxDistanceInt = 0;
private int secondError;
private int thirdError;
private final int secondStep;
private final int thirdStep;
private BlockFace mainFace;
private BlockFace secondFace;
private BlockFace thirdFace;
public BlockIterator(Level level, Vector3 start, Vector3 direction) {
this(level, start, direction, 0);
}
public BlockIterator(Level level, Vector3 start, Vector3 direction, double yOffset) {
this(level, start, direction, yOffset, 0);
}
public BlockIterator(Level level, Vector3 start, Vector3 direction, double yOffset, int maxDistance) {
this.level = level;
this.maxDistance = maxDistance;
this.blockQueue = new Block[3];
Vector3 startClone = new Vector3(start.x, start.y, start.z);
startClone.y += yOffset;
this.currentDistance = 0;
double mainDirection = 0;
double secondDirection = 0;
double thirdDirection = 0;
double mainPosition = 0;
double secondPosition = 0;
double thirdPosition = 0;
Vector3 pos = new Vector3(startClone.x, startClone.y, startClone.z);
Block startBlock = this.level.getBlock(new Vector3(Math.floor(pos.x), Math.floor(pos.y), Math.floor(pos.z)));
if (this.getXLength(direction) > mainDirection) {
this.mainFace = this.getXFace(direction);
mainDirection = this.getXLength(direction);
mainPosition = this.getXPosition(direction, startClone, startBlock);
this.secondFace = this.getYFace(direction);
secondDirection = this.getYLength(direction);
secondPosition = this.getYPosition(direction, startClone, startBlock);
this.thirdFace = this.getZFace(direction);
thirdDirection = this.getZLength(direction);
thirdPosition = this.getZPosition(direction, startClone, startBlock);
}
if (this.getYLength(direction) > mainDirection) {
this.mainFace = this.getYFace(direction);
mainDirection = this.getYLength(direction);
mainPosition = this.getYPosition(direction, startClone, startBlock);
this.secondFace = this.getZFace(direction);
secondDirection = this.getZLength(direction);
secondPosition = this.getZPosition(direction, startClone, startBlock);
this.thirdFace = this.getXFace(direction);
thirdDirection = this.getXLength(direction);
thirdPosition = this.getXPosition(direction, startClone, startBlock);
}
if (this.getZLength(direction) > mainDirection) {
this.mainFace = this.getZFace(direction);
mainDirection = this.getZLength(direction);
mainPosition = this.getZPosition(direction, startClone, startBlock);
this.secondFace = this.getXFace(direction);
secondDirection = this.getXLength(direction);
secondPosition = this.getXPosition(direction, startClone, startBlock);
this.thirdFace = this.getYFace(direction);
thirdDirection = this.getYLength(direction);
thirdPosition = this.getYPosition(direction, startClone, startBlock);
}
double d = mainPosition / mainDirection;
double secondd = secondPosition - secondDirection * d;
double thirdd = thirdPosition - thirdDirection * d;
this.secondError = (int) Math.floor(secondd * gridSize);
this.secondStep = (int) Math.round(secondDirection / mainDirection * gridSize);
this.thirdError = (int) Math.floor(thirdd * gridSize);
this.thirdStep = (int) Math.round(thirdDirection / mainDirection * gridSize);
if (this.secondError + this.secondStep <= 0) {
this.secondError = -this.secondStep + 1;
}
if (this.thirdError + this.thirdStep <= 0) {
this.thirdError = -this.thirdStep + 1;
}
Block lastBlock = startBlock.getSide(this.mainFace.getOpposite());
if (this.secondError < 0) {
this.secondError += gridSize;
lastBlock = lastBlock.getSide(this.secondFace.getOpposite());
}
if (this.thirdError < 0) {
this.thirdError += gridSize;
lastBlock = lastBlock.getSide(this.thirdFace.getOpposite());
}
this.secondError -= gridSize;
this.thirdError -= gridSize;
this.blockQueue[0] = lastBlock;
this.currentBlock = -1;
this.scan();
boolean startBlockFound = false;
for (int cnt = this.currentBlock; cnt >= 0; --cnt) {
if (this.blockEquals(this.blockQueue[cnt], startBlock)) {
this.currentBlock = cnt;
startBlockFound = true;
break;
}
}
if (!startBlockFound) {
throw new IllegalStateException("Start block missed in BlockIterator");
}
this.maxDistanceInt = (int) Math.round(maxDistance / (Math.sqrt(mainDirection * mainDirection + secondDirection * secondDirection + thirdDirection * thirdDirection) / mainDirection));
}
private boolean blockEquals(Block a, Block b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
private BlockFace getXFace(Vector3 direction) {
return ((direction.x) > 0) ? BlockFace.EAST : BlockFace.WEST;
}
private BlockFace getYFace(Vector3 direction) {
return ((direction.y) > 0) ? BlockFace.UP : BlockFace.DOWN;
}
private BlockFace getZFace(Vector3 direction) {
return ((direction.z) > 0) ? BlockFace.SOUTH : BlockFace.NORTH;
}
private double getXLength(Vector3 direction) {
return Math.abs(direction.x);
}
private double getYLength(Vector3 direction) {
return Math.abs(direction.y);
}
private double getZLength(Vector3 direction) {
return Math.abs(direction.z);
}
private double getPosition(double direction, double position, double blockPosition) {
return direction > 0 ? (position - blockPosition) : (blockPosition + 1 - position);
}
private double getXPosition(Vector3 direction, Vector3 position, Block block) {
return this.getPosition(direction.x, position.x, block.x);
}
private double getYPosition(Vector3 direction, Vector3 position, Block block) {
return this.getPosition(direction.y, position.y, block.y);
}
private double getZPosition(Vector3 direction, Vector3 position, Block block) {
return this.getPosition(direction.z, position.z, block.z);
}
@Override
public Block next() {
this.scan();
if (this.currentBlock <= -1) {
throw new IndexOutOfBoundsException();
} else {
this.currentBlockObject = this.blockQueue[this.currentBlock--];
}
return this.currentBlockObject;
}
@Override
public boolean hasNext() {
this.scan();
return this.currentBlock != -1;
}
private void scan() {
if (this.currentBlock >= 0) {
return;
}
if (this.maxDistance != 0 && this.currentDistance > this.maxDistanceInt) {
this.end = true;
return;
}
if (this.end) {
return;
}
++this.currentDistance;
this.secondError += this.secondStep;
this.thirdError += this.thirdStep;
if (this.secondError > 0 && this.thirdError > 0) {
this.blockQueue[2] = this.blockQueue[0].getSide(this.mainFace);
if ((this.secondStep * this.thirdError) < (this.thirdStep * this.secondError)) {
this.blockQueue[1] = this.blockQueue[2].getSide(this.secondFace);
this.blockQueue[0] = this.blockQueue[1].getSide(this.thirdFace);
} else {
this.blockQueue[1] = this.blockQueue[2].getSide(this.thirdFace);
this.blockQueue[0] = this.blockQueue[1].getSide(this.secondFace);
}
this.thirdError -= gridSize;
this.secondError -= gridSize;
this.currentBlock = 2;
} else if (this.secondError > 0) {
this.blockQueue[1] = this.blockQueue[0].getSide(this.mainFace);
this.blockQueue[0] = this.blockQueue[1].getSide(this.secondFace);
this.secondError -= gridSize;
this.currentBlock = 1;
} else if (this.thirdError > 0) {
this.blockQueue[1] = this.blockQueue[0].getSide(this.mainFace);
this.blockQueue[0] = this.blockQueue[1].getSide(this.thirdFace);
this.thirdError -= gridSize;
this.currentBlock = 1;
} else {
this.blockQueue[0] = this.blockQueue[0].getSide(this.mainFace);
this.currentBlock = 0;
}
}
}
| 9,427 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockUpdateEntry.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/BlockUpdateEntry.java | package cn.nukkit.utils;
import cn.nukkit.block.Block;
import cn.nukkit.math.Vector3;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class BlockUpdateEntry implements Comparable<BlockUpdateEntry> {
private static long entryID = 0;
public int priority;
public long delay;
public final Vector3 pos;
public final Block block;
public final long id;
public BlockUpdateEntry(Vector3 pos, Block block) {
this.pos = pos;
this.block = block;
this.id = entryID++;
}
public BlockUpdateEntry(Vector3 pos, Block block, long delay, int priority) {
this.id = entryID++;
this.pos = pos;
this.priority = priority;
this.delay = delay;
this.block = block;
}
@Override
public int compareTo(BlockUpdateEntry entry) {
return this.delay < entry.delay ? -1 : (this.delay > entry.delay ? 1 : (this.priority != entry.priority ? this.priority - entry.priority : (this.id < entry.id ? -1 : (this.id > entry.id ? 1 : 0))));
}
@Override
public boolean equals(Object object) {
if (!(object instanceof BlockUpdateEntry)) {
if (object instanceof Vector3) {
return pos.equals(object);
}
return false;
} else {
BlockUpdateEntry entry = (BlockUpdateEntry) object;
return this.pos.equals(entry.pos) && Block.equals(this.block, entry.block, false);
}
}
@Override
public int hashCode() {
return this.pos.hashCode();
}
} | 1,555 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ThreadedLogger.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ThreadedLogger.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class ThreadedLogger extends Thread implements Logger {
}
| 149 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DummyBossBar.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/DummyBossBar.java | package cn.nukkit.utils;
import cn.nukkit.Player;
import cn.nukkit.entity.Attribute;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.data.EntityMetadata;
import cn.nukkit.entity.mob.EntityCreeper;
import cn.nukkit.network.protocol.*;
import java.awt.*;
import java.util.concurrent.ThreadLocalRandom;
/**
* DummyBossBar
* ===============
* author: boybook
* Nukkit Project
* ===============
*/
public class DummyBossBar {
private final Player player;
private final long bossBarId;
private String text;
private float length;
private Color color;
private DummyBossBar(Builder builder) {
this.player = builder.player;
this.bossBarId = builder.bossBarId;
this.text = builder.text;
this.length = builder.length;
this.color = builder.color;
}
public static class Builder {
private final Player player;
private final long bossBarId;
private String text = "";
private float length = 100;
private Color color = null;
public Builder(Player player) {
this.player = player;
this.bossBarId = 1095216660480L + ThreadLocalRandom.current().nextLong(0, 0x7fffffffL);
}
public Builder text(String text) {
this.text = text;
return this;
}
public Builder length(float length) {
if (length >= 0 && length <= 100) this.length = length;
return this;
}
public Builder color(Color color) {
this.color = color;
return this;
}
public Builder color(int red, int green, int blue) {
return color(new Color(red, green, blue));
}
public DummyBossBar build() {
return new DummyBossBar(this);
}
}
public Player getPlayer() {
return player;
}
public long getBossBarId() {
return bossBarId;
}
public String getText() {
return text;
}
public void setText(String text) {
if (!this.text.equals(text)) {
this.text = text;
this.updateBossEntityNameTag();
this.sendSetBossBarTitle();
}
}
public float getLength() {
return length;
}
public void setLength(float length) {
if (this.length != length) {
this.length = length;
this.sendAttributes();
}
}
/**
* Color is not working in the current version. We are keep waiting for client support.
* @param color the boss bar color
*/
public void setColor(Color color) {
if (this.color == null || !this.color.equals(color)) {
this.color = color;
this.sendSetBossBarTexture();
}
}
public void setColor(int red, int green, int blue) {
this.setColor(new Color(red, green, blue));
}
public int getMixedColor() {
return this.color.getRGB();//(this.color.getRed() << 16 | this.color.getGreen() << 8 | this.color.getBlue()) & 0xffffff;
}
public Color getColor() {
return this.color;
}
private void createBossEntity() {
AddEntityPacket pkAdd = new AddEntityPacket();
pkAdd.type = EntityCreeper.NETWORK_ID;
pkAdd.entityUniqueId = bossBarId;
pkAdd.entityRuntimeId = bossBarId;
pkAdd.x = (float) player.x;
pkAdd.y = (float) -10; // Below the bedrock
pkAdd.z = (float) player.z;
pkAdd.speedX = 0;
pkAdd.speedY = 0;
pkAdd.speedZ = 0;
pkAdd.metadata = new EntityMetadata()
// Default Metadata tags
.putLong(Entity.DATA_FLAGS, 0)
.putShort(Entity.DATA_AIR, 400)
.putShort(Entity.DATA_MAX_AIR, 400)
.putLong(Entity.DATA_LEAD_HOLDER_EID, -1)
.putString(Entity.DATA_NAMETAG, text) // Set the entity name
.putFloat(Entity.DATA_SCALE, 0); // And make it invisible
player.dataPacket(pkAdd);
}
private void sendAttributes() {
UpdateAttributesPacket pkAttributes = new UpdateAttributesPacket();
pkAttributes.entityId = bossBarId;
Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH);
attr.setMaxValue(100); // Max value - We need to change the max value first, or else the "setValue" will return a IllegalArgumentException
attr.setValue(length); // Entity health
pkAttributes.entries = new Attribute[]{attr};
player.dataPacket(pkAttributes);
}
private void sendShowBossBar() {
BossEventPacket pkBoss = new BossEventPacket();
pkBoss.bossEid = bossBarId;
pkBoss.type = BossEventPacket.TYPE_SHOW;
pkBoss.title = text;
pkBoss.healthPercent = this.length;
player.dataPacket(pkBoss);
}
private void sendHideBossBar() {
BossEventPacket pkBoss = new BossEventPacket();
pkBoss.bossEid = bossBarId;
pkBoss.type = BossEventPacket.TYPE_HIDE;
player.dataPacket(pkBoss);
}
private void sendSetBossBarTexture() {
BossEventPacket pk = new BossEventPacket();
pk.bossEid = this.bossBarId;
pk.type = BossEventPacket.TYPE_TEXTURE;
pk.color = this.getMixedColor();
player.dataPacket(pk);
}
private void sendSetBossBarTitle() {
BossEventPacket pkBoss = new BossEventPacket();
pkBoss.bossEid = bossBarId;
pkBoss.type = BossEventPacket.TYPE_TITLE;
pkBoss.title = text;
pkBoss.healthPercent = this.length;
player.dataPacket(pkBoss);
}
/**
* Don't let the entity go too far from the player, or the BossBar will disappear.
* Update boss entity's position when teleport and each 5s.
*/
public void updateBossEntityPosition() {
MoveEntityPacket pk = new MoveEntityPacket();
pk.eid = this.bossBarId;
pk.x = this.player.x;
pk.y = -10;
pk.z = this.player.z;
pk.headYaw = 0;
pk.yaw = 0;
pk.pitch = 0;
player.dataPacket(pk);
}
private void updateBossEntityNameTag() {
SetEntityDataPacket pk = new SetEntityDataPacket();
pk.eid = this.bossBarId;
pk.metadata = new EntityMetadata().putString(Entity.DATA_NAMETAG, this.text);
player.dataPacket(pk);
}
private void removeBossEntity() {
RemoveEntityPacket pkRemove = new RemoveEntityPacket();
pkRemove.eid = bossBarId;
player.dataPacket(pkRemove);
}
public void create() {
createBossEntity();
sendAttributes();
sendShowBossBar();
if (color != null) this.sendSetBossBarTexture();
}
/**
* Once the player has teleported, resend Show BossBar
*/
public void reshow() {
updateBossEntityPosition();
sendShowBossBar();
}
public void destroy() {
sendHideBossBar();
removeBossEntity();
}
}
| 7,000 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ZlibThreadLocal.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ZlibThreadLocal.java | package cn.nukkit.utils;
import cn.nukkit.nbt.stream.FastByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
public final class ZlibThreadLocal implements ZlibProvider {
@Override
public byte[] deflate(byte[][] datas, int level) throws Exception {
Deflater deflater = getDef(level);
if (deflater == null) throw new IllegalArgumentException("No deflate for level " + level + " !");
deflater.reset();
FastByteArrayOutputStream bos = ThreadCache.fbaos.get();
bos.reset();
byte[] buffer = buf.get();
for (byte[] data : datas) {
deflater.setInput(data);
while (!deflater.needsInput()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
}
deflater.finish();
while (!deflater.finished()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
//Deflater::end is called the time when the process exits.
return bos.toByteArray();
}
@Override
public byte[] deflate(byte[] data, int level) throws Exception {
Deflater deflater = getDef(level);
if (deflater == null) throw new IllegalArgumentException("No deflate for level " + level + " !");
deflater.reset();
deflater.setInput(data);
deflater.finish();
FastByteArrayOutputStream bos = ThreadCache.fbaos.get();
bos.reset();
byte[] buffer = buf.get();
while (!deflater.finished()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
//Deflater::end is called the time when the process exits.
return bos.toByteArray();
}
/* -=-=-=-=-=- Internal -=-=-=-=-=- Do NOT attempt to use in production -=-=-=-=-=- */
public static final IterableThreadLocal<byte[]> buf = new IterableThreadLocal<byte[]>() {
@Override
public byte[] init() {
return new byte[8192];
}
};
public static final IterableThreadLocal<Deflater> def = new IterableThreadLocal<Deflater>() {
@Override
public Deflater init() {
return new Deflater();
}
};
private static Deflater getDef(int level) {
def.get().setLevel(level);
return def.get();
}
@Override
public byte[] inflate(InputStream stream) throws IOException {
InflaterInputStream inputStream = new InflaterInputStream(stream);
FastByteArrayOutputStream outputStream = ThreadCache.fbaos.get();
outputStream.reset();
int length;
byte[] result;
byte[] buffer = buf.get();
try {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
result = outputStream.toByteArray();
outputStream.flush();
outputStream.close();
inputStream.close();
}
return result;
}
}
| 3,139 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Config.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/Config.java | package cn.nukkit.utils;
import cn.nukkit.Server;
import cn.nukkit.scheduler.FileWriteTask;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
/**
* author: MagicDroidX
* Nukkit
*/
public class Config {
public static final int DETECT = -1; //Detect by file extension
public static final int PROPERTIES = 0; // .properties
public static final int CNF = Config.PROPERTIES; // .cnf
public static final int JSON = 1; // .js, .json
public static final int YAML = 2; // .yml, .yaml
//public static final int EXPORT = 3; // .export, .xport
//public static final int SERIALIZED = 4; // .sl
public static final int ENUM = 5; // .txt, .list, .enum
public static final int ENUMERATION = Config.ENUM;
//private LinkedHashMap<String, Object> config = new LinkedHashMap<>();
private ConfigSection config = new ConfigSection();
private File file;
private boolean correct = false;
private int type = Config.DETECT;
public static final Map<String, Integer> format = new TreeMap<>();
static {
format.put("properties", Config.PROPERTIES);
format.put("con", Config.PROPERTIES);
format.put("conf", Config.PROPERTIES);
format.put("config", Config.PROPERTIES);
format.put("js", Config.JSON);
format.put("json", Config.JSON);
format.put("yml", Config.YAML);
format.put("yaml", Config.YAML);
//format.put("sl", Config.SERIALIZED);
//format.put("serialize", Config.SERIALIZED);
format.put("txt", Config.ENUM);
format.put("list", Config.ENUM);
format.put("enum", Config.ENUM);
}
/**
* Constructor for Config instance with undefined file object
*
* @param type - Config type
*/
public Config(int type) {
this.type = type;
this.correct = true;
this.config = new ConfigSection();
}
/**
* Constructor for Config (YAML) instance with undefined file object
*/
public Config() {
this(Config.YAML);
}
public Config(String file) {
this(file, Config.DETECT);
}
public Config(File file) {
this(file.toString(), Config.DETECT);
}
public Config(String file, int type) {
this(file, type, new ConfigSection());
}
public Config(File file, int type) {
this(file.toString(), type, new ConfigSection());
}
@Deprecated
public Config(String file, int type, LinkedHashMap<String, Object> defaultMap) {
this.load(file, type, new ConfigSection(defaultMap));
}
public Config(String file, int type, ConfigSection defaultMap) {
this.load(file, type, defaultMap);
}
public Config(File file, int type, ConfigSection defaultMap) {
this.load(file.toString(), type, defaultMap);
}
@Deprecated
public Config(File file, int type, LinkedHashMap<String, Object> defaultMap) {
this(file.toString(), type, new ConfigSection(defaultMap));
}
public void reload() {
this.config.clear();
this.correct = false;
//this.load(this.file.toString());
if (this.file == null) throw new IllegalStateException("Failed to reload Config. File object is undefined.");
this.load(this.file.toString(), this.type);
}
public boolean load(String file) {
return this.load(file, Config.DETECT);
}
public boolean load(String file, int type) {
return this.load(file, type, new ConfigSection());
}
@SuppressWarnings("unchecked")
public boolean load(String file, int type, ConfigSection defaultMap) {
this.correct = true;
this.type = type;
this.file = new File(file);
if (!this.file.exists()) {
try {
this.file.getParentFile().mkdirs();
this.file.createNewFile();
} catch (IOException e) {
MainLogger.getLogger().error("Could not create Config " + this.file.toString(), e);
}
this.config = defaultMap;
this.save();
} else {
if (this.type == Config.DETECT) {
String extension = "";
if (this.file.getName().lastIndexOf(".") != -1 && this.file.getName().lastIndexOf(".") != 0) {
extension = this.file.getName().substring(this.file.getName().lastIndexOf(".") + 1);
}
if (format.containsKey(extension)) {
this.type = format.get(extension);
} else {
this.correct = false;
}
}
if (this.correct) {
String content = "";
try {
content = Utils.readFile(this.file);
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
this.parseContent(content);
if (!this.correct) return false;
if (this.setDefault(defaultMap) > 0) {
this.save();
}
} else {
return false;
}
}
return true;
}
public boolean load(InputStream inputStream) {
if (inputStream == null) return false;
if (this.correct) {
String content;
try {
content = Utils.readFile(inputStream);
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
return false;
}
this.parseContent(content);
}
return correct;
}
public boolean check() {
return this.correct;
}
public boolean isCorrect() {
return correct;
}
/**
* Save configuration into provided file. Internal file object will be set to new file.
*
* @param file
* @param async
* @return
*/
public boolean save(File file, boolean async) {
this.file = file;
return save(async);
}
public boolean save(File file) {
this.file = file;
return save();
}
public boolean save() {
return this.save(false);
}
public boolean save(Boolean async) {
if (this.file == null) throw new IllegalStateException("Failed to save Config. File object is undefined.");
if (this.correct) {
String content = "";
switch (this.type) {
case Config.PROPERTIES:
content = this.writeProperties();
break;
case Config.JSON:
content = new GsonBuilder().setPrettyPrinting().create().toJson(this.config);
break;
case Config.YAML:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
content = yaml.dump(this.config);
break;
case Config.ENUM:
for (Object o : this.config.entrySet()) {
Map.Entry entry = (Map.Entry) o;
content += String.valueOf(entry.getKey()) + "\r\n";
}
break;
}
if (async) {
Server.getInstance().getScheduler().scheduleAsyncTask(new FileWriteTask(this.file, content));
} else {
try {
Utils.writeFile(this.file, content);
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
return true;
} else {
return false;
}
}
public void set(final String key, Object value) {
this.config.set(key, value);
}
public Object get(String key) {
return this.get(key, null);
}
@SuppressWarnings("unchecked")
public <T> T get(String key, T defaultValue) {
return this.correct ? this.config.get(key, defaultValue) : defaultValue;
}
public ConfigSection getSection(String key) {
return this.correct ? this.config.getSection(key) : new ConfigSection();
}
public boolean isSection(String key) {
return config.isSection(key);
}
public ConfigSection getSections(String key) {
return this.correct ? this.config.getSections(key) : new ConfigSection();
}
public ConfigSection getSections() {
return this.correct ? this.config.getSections() : new ConfigSection();
}
public int getInt(String key) {
return this.getInt(key, 0);
}
public int getInt(String key, int defaultValue) {
return this.correct ? this.config.getInt(key, defaultValue) : defaultValue;
}
public boolean isInt(String key) {
return config.isInt(key);
}
public long getLong(String key) {
return this.getLong(key, 0);
}
public long getLong(String key, long defaultValue) {
return this.correct ? this.config.getLong(key, defaultValue) : defaultValue;
}
public boolean isLong(String key) {
return config.isLong(key);
}
public double getDouble(String key) {
return this.getDouble(key, 0);
}
public double getDouble(String key, double defaultValue) {
return this.correct ? this.config.getDouble(key, defaultValue) : defaultValue;
}
public boolean isDouble(String key) {
return config.isDouble(key);
}
public String getString(String key) {
return this.getString(key, "");
}
public String getString(String key, String defaultValue) {
return this.correct ? this.config.getString(key, defaultValue) : defaultValue;
}
public boolean isString(String key) {
return config.isString(key);
}
public boolean getBoolean(String key) {
return this.getBoolean(key, false);
}
public boolean getBoolean(String key, boolean defaultValue) {
return this.correct ? this.config.getBoolean(key, defaultValue) : defaultValue;
}
public boolean isBoolean(String key) {
return config.isBoolean(key);
}
public List getList(String key) {
return this.getList(key, null);
}
public List getList(String key, List defaultList) {
return this.correct ? this.config.getList(key, defaultList) : defaultList;
}
public boolean isList(String key) {
return config.isList(key);
}
public List<String> getStringList(String key) {
return config.getStringList(key);
}
public List<Integer> getIntegerList(String key) {
return config.getIntegerList(key);
}
public List<Boolean> getBooleanList(String key) {
return config.getBooleanList(key);
}
public List<Double> getDoubleList(String key) {
return config.getDoubleList(key);
}
public List<Float> getFloatList(String key) {
return config.getFloatList(key);
}
public List<Long> getLongList(String key) {
return config.getLongList(key);
}
public List<Byte> getByteList(String key) {
return config.getByteList(key);
}
public List<Character> getCharacterList(String key) {
return config.getCharacterList(key);
}
public List<Short> getShortList(String key) {
return config.getShortList(key);
}
public List<Map> getMapList(String key) {
return config.getMapList(key);
}
public void setAll(LinkedHashMap<String, Object> map) {
this.config = new ConfigSection(map);
}
public void setAll(ConfigSection section) {
this.config = section;
}
public boolean exists(String key) {
return config.exists(key);
}
public boolean exists(String key, boolean ignoreCase) {
return config.exists(key, ignoreCase);
}
public void remove(String key) {
config.remove(key);
}
public Map<String, Object> getAll() {
return this.config.getAllMap();
}
/**
* Get root (main) config section of the Config
*
* @return
*/
public ConfigSection getRootSection() {
return config;
}
public int setDefault(LinkedHashMap<String, Object> map) {
return setDefault(new ConfigSection(map));
}
public int setDefault(ConfigSection map) {
int size = this.config.size();
this.config = this.fillDefaults(map, this.config);
return this.config.size() - size;
}
private ConfigSection fillDefaults(ConfigSection defaultMap, ConfigSection data) {
for (String key : defaultMap.keySet()) {
if (!data.containsKey(key)) {
data.put(key, defaultMap.get(key));
}
}
return data;
}
private void parseList(String content) {
content = content.replace("\r\n", "\n");
for (String v : content.split("\n")) {
if (v.trim().isEmpty()) {
continue;
}
config.put(v, true);
}
}
private String writeProperties() {
String content = "#Properties Config file\r\n#" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "\r\n";
for (Object o : this.config.entrySet()) {
Map.Entry entry = (Map.Entry) o;
Object v = entry.getValue();
Object k = entry.getKey();
if (v instanceof Boolean) {
v = (Boolean) v ? "on" : "off";
}
content += String.valueOf(k) + "=" + String.valueOf(v) + "\r\n";
}
return content;
}
private void parseProperties(String content) {
for (String line : content.split("\n")) {
if (Pattern.compile("[a-zA-Z0-9\\-_\\.]*+=+[^\\r\\n]*").matcher(line).matches()) {
String[] b = line.split("=", -1);
String k = b[0];
String v = b[1].trim();
String v_lower = v.toLowerCase();
if (this.config.containsKey(k)) {
MainLogger.getLogger().debug("[Config] Repeated property " + k + " on file " + this.file.toString());
}
switch (v_lower) {
case "on":
case "true":
case "yes":
this.config.put(k, true);
break;
case "off":
case "false":
case "no":
this.config.put(k, false);
break;
default:
this.config.put(k, v);
break;
}
}
}
}
/**
* @deprecated use {@link #get(String)} instead
*/
@Deprecated
public Object getNested(String key) {
return get(key);
}
/**
* @deprecated use {@link #get(String, T)} instead
*/
@Deprecated
public <T> T getNested(String key, T defaultValue) {
return get(key, defaultValue);
}
/**
* @deprecated use {@link #get(String)} instead
*/
@Deprecated
@SuppressWarnings("unchecked")
public <T> T getNestedAs(String key, Class<T> type) {
return (T) get(key);
}
/**
* @deprecated use {@link #remove(String)} instead
*/
@Deprecated
public void removeNested(String key) {
remove(key);
}
private void parseContent(String content) {
switch (this.type) {
case Config.PROPERTIES:
this.parseProperties(content);
break;
case Config.JSON:
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
this.config = new ConfigSection(gson.fromJson(content, new TypeToken<LinkedHashMap<String, Object>>() {
}.getType()));
break;
case Config.YAML:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
this.config = new ConfigSection(yaml.loadAs(content, LinkedHashMap.class));
break;
// case Config.SERIALIZED
case Config.ENUM:
this.parseList(content);
break;
default:
this.correct = false;
}
}
public Set<String> getKeys() {
if (this.correct) return config.getKeys();
return new HashSet<>();
}
public Set<String> getKeys(boolean child) {
if (this.correct) return config.getKeys(child);
return new HashSet<>();
}
}
| 17,200 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
EventException.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/EventException.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class EventException extends RuntimeException {
private final Throwable cause;
/**
* Constructs a new EventException based on the given Exception
*
* @param throwable Exception that triggered this Exception
*/
public EventException(Throwable throwable) {
cause = throwable;
}
/**
* Constructs a new EventException
*/
public EventException() {
cause = null;
}
/**
* Constructs a new EventException with the given message
*
* @param cause The exception that caused this
* @param message The message
*/
public EventException(Throwable cause, String message) {
super(message);
this.cause = cause;
}
/**
* Constructs a new EventException with the given message
*
* @param message The message
*/
public EventException(String message) {
super(message);
cause = null;
}
/**
* If applicable, returns the Exception that triggered this Exception
*
* @return Inner exception, or null if one does not exist
*/
@Override
public Throwable getCause() {
return cause;
}
}
| 1,263 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ZlibSingleThreadLowMem.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ZlibSingleThreadLowMem.java | package cn.nukkit.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
public class ZlibSingleThreadLowMem implements ZlibProvider {
static final int BUFFER_SIZE = 8192;
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
byte[] buffer = new byte[BUFFER_SIZE];
@Override
public synchronized byte[] deflate(byte[][] datas, int level) throws Exception {
Deflater deflater = this.deflater;
if (deflater == null) throw new IllegalArgumentException("No deflate for level " + level + " !");
deflater.reset();
ByteArrayOutputStream bos = new ByteArrayOutputStream(datas.length);;
for (byte[] data : datas) {
deflater.setInput(data);
while (!deflater.needsInput()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
}
deflater.finish();
while (!deflater.finished()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
//Deflater::end is called the time when the process exits.
return bos.toByteArray();
}
@Override
synchronized public byte[] deflate(byte[] data, int level) throws Exception {
deflater.reset();
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
try {
while (!deflater.finished()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
} finally {
//deflater.end();
}
return bos.toByteArray();
}
@Override
synchronized public byte[] inflate(InputStream stream) throws IOException {
InflaterInputStream inputStream = new InflaterInputStream(stream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] bufferOut;
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
outputStream.flush();
bufferOut = outputStream.toByteArray();
outputStream.close();
inputStream.close();
}
return bufferOut;
}
}
| 2,445 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Binary.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/Binary.java | package cn.nukkit.utils;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.data.*;
import cn.nukkit.item.Item;
import cn.nukkit.math.BlockVector3;
import cn.nukkit.math.NukkitMath;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Binary {
public static int signByte(int value) {
return value << 56 >> 56;
}
public static int unsignByte(int value) {
return value & 0xff;
}
public static int signShort(int value) {
return value << 48 >> 48;
}
public int unsignShort(int value) {
return value & 0xffff;
}
public static int signInt(int value) {
return value << 32 >> 32;
}
public static int unsignInt(int value) {
return value;
}
//Triad: {0x00,0x00,0x01}<=>1
public static int readTriad(byte[] bytes) {
return readInt(new byte[]{
(byte) 0x00,
bytes[0],
bytes[1],
bytes[2]
});
}
public static byte[] writeTriad(int value) {
return new byte[]{
(byte) ((value >>> 16) & 0xFF),
(byte) ((value >>> 8) & 0xFF),
(byte) (value & 0xFF)
};
}
//LTriad: {0x01,0x00,0x00}<=>1
public static int readLTriad(byte[] bytes) {
return readLInt(new byte[]{
bytes[0],
bytes[1],
bytes[2],
(byte) 0x00
});
}
public static byte[] writeLTriad(int value) {
return new byte[]{
(byte) (value & 0xFF),
(byte) ((value >>> 8) & 0xFF),
(byte) ((value >>> 16) & 0xFF)
};
}
public static UUID readUUID(byte[] bytes) {
return new UUID(readLLong(bytes), readLLong(new byte[]{
bytes[8],
bytes[9],
bytes[10],
bytes[11],
bytes[12],
bytes[13],
bytes[14],
bytes[15]
}));
}
public static byte[] writeUUID(UUID uuid) {
return appendBytes(writeLLong(uuid.getMostSignificantBits()), writeLLong(uuid.getLeastSignificantBits()));
}
public static byte[] writeMetadata(EntityMetadata metadata) {
BinaryStream stream = new BinaryStream();
Map<Integer, EntityData> map = metadata.getMap();
stream.putUnsignedVarInt(map.size());
for (int id : map.keySet()) {
EntityData d = map.get(id);
stream.putUnsignedVarInt(id);
stream.putUnsignedVarInt(d.getType());
switch (d.getType()) {
case Entity.DATA_TYPE_BYTE:
stream.putByte(((ByteEntityData) d).getData().byteValue());
break;
case Entity.DATA_TYPE_SHORT:
stream.putLShort(((ShortEntityData) d).getData());
break;
case Entity.DATA_TYPE_INT:
stream.putVarInt(((IntEntityData) d).getData());
break;
case Entity.DATA_TYPE_FLOAT:
stream.putLFloat(((FloatEntityData) d).getData());
break;
case Entity.DATA_TYPE_STRING:
String s = ((StringEntityData) d).getData();
stream.putUnsignedVarInt(s.getBytes(StandardCharsets.UTF_8).length);
stream.put(s.getBytes(StandardCharsets.UTF_8));
break;
case Entity.DATA_TYPE_SLOT:
SlotEntityData slot = (SlotEntityData) d;
stream.putSlot(slot.getData());
break;
case Entity.DATA_TYPE_POS:
IntPositionEntityData pos = (IntPositionEntityData) d;
stream.putVarInt(pos.x);
stream.putVarInt(pos.y);
stream.putVarInt(pos.z);
break;
case Entity.DATA_TYPE_LONG:
stream.putVarLong(((LongEntityData) d).getData());
break;
case Entity.DATA_TYPE_VECTOR3F:
Vector3fEntityData v3data = (Vector3fEntityData) d;
stream.putLFloat(v3data.x);
stream.putLFloat(v3data.y);
stream.putLFloat(v3data.z);
break;
}
}
return stream.getBuffer();
}
public static EntityMetadata readMetadata(byte[] payload) {
BinaryStream stream = new BinaryStream();
stream.setBuffer(payload);
long count = stream.getUnsignedVarInt();
EntityMetadata m = new EntityMetadata();
for (int i = 0; i < count; i++) {
int key = (int) stream.getUnsignedVarInt();
int type = (int) stream.getUnsignedVarInt();
EntityData value = null;
switch (type) {
case Entity.DATA_TYPE_BYTE:
value = new ByteEntityData(key, stream.getByte());
break;
case Entity.DATA_TYPE_SHORT:
value = new ShortEntityData(key, stream.getLShort());
break;
case Entity.DATA_TYPE_INT:
value = new IntEntityData(key, stream.getVarInt());
break;
case Entity.DATA_TYPE_FLOAT:
value = new FloatEntityData(key, stream.getLFloat());
break;
case Entity.DATA_TYPE_STRING:
value = new StringEntityData(key, stream.getString());
break;
case Entity.DATA_TYPE_SLOT:
Item item = stream.getSlot();
value = new SlotEntityData(key, item.getId(), item.getDamage(), item.getCount());
break;
case Entity.DATA_TYPE_POS:
BlockVector3 v3 = stream.getSignedBlockPosition();
value = new IntPositionEntityData(key, v3.x, v3.y, v3.z);
break;
case Entity.DATA_TYPE_LONG:
value = new LongEntityData(key, stream.getVarLong());
break;
case Entity.DATA_TYPE_VECTOR3F:
value = new Vector3fEntityData(key, stream.getVector3f());
break;
}
if (value != null) m.put(value);
}
return m;
}
public static boolean readBool(byte b) {
return b == 0;
}
public static byte writeBool(boolean b) {
return (byte) (b ? 0x01 : 0x00);
}
public static int readSignedByte(byte b) {
return b & 0xFF;
}
public static byte writeByte(byte b) {
return b;
}
public static int readShort(byte[] bytes) {
return ((bytes[0] & 0xFF) << 8) + (bytes[1] & 0xFF);
}
public static short readSignedShort(byte[] bytes) {
return (short) readShort(bytes);
}
public static byte[] writeShort(int s) {
return new byte[]{
(byte) ((s >>> 8) & 0xFF),
(byte) (s & 0xFF)
};
}
public static int readLShort(byte[] bytes) {
return ((bytes[1] & 0xFF) << 8) + (bytes[0] & 0xFF);
}
public static short readSignedLShort(byte[] bytes) {
return (short) readLShort(bytes);
}
public static byte[] writeLShort(int s) {
s &= 0xffff;
return new byte[]{
(byte) (s & 0xFF),
(byte) ((s >>> 8) & 0xFF)
};
}
public static int readInt(byte[] bytes) {
return ((bytes[0] & 0xff) << 24) +
((bytes[1] & 0xff) << 16) +
((bytes[2] & 0xff) << 8) +
(bytes[3] & 0xff);
}
public static byte[] writeInt(int i) {
return new byte[]{
(byte) ((i >>> 24) & 0xFF),
(byte) ((i >>> 16) & 0xFF),
(byte) ((i >>> 8) & 0xFF),
(byte) (i & 0xFF)
};
}
public static int readLInt(byte[] bytes) {
return ((bytes[3] & 0xff) << 24) +
((bytes[2] & 0xff) << 16) +
((bytes[1] & 0xff) << 8) +
(bytes[0] & 0xff);
}
public static byte[] writeLInt(int i) {
return new byte[]{
(byte) (i & 0xFF),
(byte) ((i >>> 8) & 0xFF),
(byte) ((i >>> 16) & 0xFF),
(byte) ((i >>> 24) & 0xFF)
};
}
public static float readFloat(byte[] bytes) {
return readFloat(bytes, -1);
}
public static float readFloat(byte[] bytes, int accuracy) {
float val = Float.intBitsToFloat(readInt(bytes));
if (accuracy > -1) {
return (float) NukkitMath.round(val, accuracy);
} else {
return val;
}
}
public static byte[] writeFloat(float f) {
return writeInt(Float.floatToIntBits(f));
}
public static float readLFloat(byte[] bytes) {
return readLFloat(bytes, -1);
}
public static float readLFloat(byte[] bytes, int accuracy) {
float val = Float.intBitsToFloat(readLInt(bytes));
if (accuracy > -1) {
return (float) NukkitMath.round(val, accuracy);
} else {
return val;
}
}
public static byte[] writeLFloat(float f) {
return writeLInt(Float.floatToIntBits(f));
}
public static double readDouble(byte[] bytes) {
return Double.longBitsToDouble(readLong(bytes));
}
public static byte[] writeDouble(double d) {
return writeLong(Double.doubleToLongBits(d));
}
public static double readLDouble(byte[] bytes) {
return Double.longBitsToDouble(readLLong(bytes));
}
public static byte[] writeLDouble(double d) {
return writeLLong(Double.doubleToLongBits(d));
}
public static long readLong(byte[] bytes) {
return (((long) bytes[0] << 56) +
((long) (bytes[1] & 0xFF) << 48) +
((long) (bytes[2] & 0xFF) << 40) +
((long) (bytes[3] & 0xFF) << 32) +
((long) (bytes[4] & 0xFF) << 24) +
((bytes[5] & 0xFF) << 16) +
((bytes[6] & 0xFF) << 8) +
((bytes[7] & 0xFF)));
}
public static byte[] writeLong(long l) {
return new byte[]{
(byte) (l >>> 56),
(byte) (l >>> 48),
(byte) (l >>> 40),
(byte) (l >>> 32),
(byte) (l >>> 24),
(byte) (l >>> 16),
(byte) (l >>> 8),
(byte) (l)
};
}
public static long readLLong(byte[] bytes) {
return (((long) bytes[7] << 56) +
((long) (bytes[6] & 0xFF) << 48) +
((long) (bytes[5] & 0xFF) << 40) +
((long) (bytes[4] & 0xFF) << 32) +
((long) (bytes[3] & 0xFF) << 24) +
((bytes[2] & 0xFF) << 16) +
((bytes[1] & 0xFF) << 8) +
((bytes[0] & 0xFF)));
}
public static byte[] writeLLong(long l) {
return new byte[]{
(byte) (l),
(byte) (l >>> 8),
(byte) (l >>> 16),
(byte) (l >>> 24),
(byte) (l >>> 32),
(byte) (l >>> 40),
(byte) (l >>> 48),
(byte) (l >>> 56),
};
}
public static byte[] writeVarInt(int v) {
BinaryStream stream = new BinaryStream();
stream.putVarInt(v);
return stream.getBuffer();
}
public static byte[] writeUnsignedVarInt(long v) {
BinaryStream stream = new BinaryStream();
stream.putUnsignedVarInt(v);
return stream.getBuffer();
}
public static byte[] reserveBytes(byte[] bytes) {
byte[] newBytes = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
newBytes[bytes.length - 1 - i] = bytes[i];
}
return newBytes;
}
public static String bytesToHexString(byte[] src) {
return bytesToHexString(src, false);
}
public static String bytesToHexString(byte[] src, boolean blank) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (byte b : src) {
if (!(stringBuilder.length() == 0) && blank) {
stringBuilder.append(" ");
}
int v = b & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
String str = "0123456789ABCDEF";
hexString = hexString.toUpperCase().replace(" ", "");
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (((byte) str.indexOf(hexChars[pos]) << 4) | ((byte) str.indexOf(hexChars[pos + 1])));
}
return d;
}
public static byte[] subBytes(byte[] bytes, int start, int length) {
int len = Math.min(bytes.length, start + length);
return Arrays.copyOfRange(bytes, start, len);
}
public static byte[] subBytes(byte[] bytes, int start) {
return subBytes(bytes, start, bytes.length - start);
}
public static byte[][] splitBytes(byte[] bytes, int chunkSize) {
byte[][] splits = new byte[(bytes.length + chunkSize - 1) / chunkSize][chunkSize];
int chunks = 0;
for (int i = 0; i < bytes.length; i += chunkSize) {
if ((bytes.length - i) > chunkSize) {
splits[chunks] = Arrays.copyOfRange(bytes, i, i + chunkSize);
} else {
splits[chunks] = Arrays.copyOfRange(bytes, i, bytes.length);
}
chunks++;
}
return splits;
}
public static byte[] appendBytes(byte[][] bytes) {
int length = 0;
for (byte[] b : bytes) {
length += b.length;
}
ByteBuffer buffer = ByteBuffer.allocate(length);
for (byte[] b : bytes) {
buffer.put(b);
}
return buffer.array();
}
public static byte[] appendBytes(byte byte1, byte[]... bytes2) {
int length = 1;
for (byte[] bytes : bytes2) {
length += bytes.length;
}
ByteBuffer buffer = ByteBuffer.allocate(length);
buffer.put(byte1);
for (byte[] bytes : bytes2) {
buffer.put(bytes);
}
return buffer.array();
}
public static byte[] appendBytes(byte[] bytes1, byte[]... bytes2) {
int length = bytes1.length;
for (byte[] bytes : bytes2) {
length += bytes.length;
}
ByteBuffer buffer = ByteBuffer.allocate(length);
buffer.put(bytes1);
for (byte[] bytes : bytes2) {
buffer.put(bytes);
}
return buffer.array();
}
}
| 15,585 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LoginChainData.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/LoginChainData.java | package cn.nukkit.utils;
import java.util.UUID;
/**
* @author CreeperFace
*/
public interface LoginChainData {
String getUsername();
UUID getClientUUID();
String getIdentityPublicKey();
long getClientId();
String getServerAddress();
String getDeviceModel();
int getDeviceOS();
String getGameVersion();
int getGuiScale();
String getLanguageCode();
String getXUID();
boolean isXboxAuthed();
int getCurrentInputMode();
int getDefaultInputMode();
String getCapeData();
int getUIProfile();
}
| 571 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
IterableThreadLocal.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/IterableThreadLocal.java | package cn.nukkit.utils;
import java.lang.ref.Reference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;
public abstract class IterableThreadLocal<T> extends ThreadLocal<T> implements Iterable<T> {
private ThreadLocal<T> flag;
private ConcurrentLinkedDeque<T> allValues = new ConcurrentLinkedDeque<T>();
public IterableThreadLocal() {
}
@Override
protected final T initialValue() {
T value = init();
if (value != null) {
allValues.add(value);
}
return value;
}
@Override
public final Iterator<T> iterator() {
return getAll().iterator();
}
public T init() {
return null;
}
public void clean() {
IterableThreadLocal.clean(this);
}
public static void clean(ThreadLocal instance) {
try {
ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( );
ThreadGroup parentGroup;
while ( ( parentGroup = rootGroup.getParent() ) != null ) {
rootGroup = parentGroup;
}
Thread[] threads = new Thread[ rootGroup.activeCount() ];
if (threads.length != 0) {
while (rootGroup.enumerate(threads, true) == threads.length) {
threads = new Thread[threads.length * 2];
}
}
Field tl = Thread.class.getDeclaredField("threadLocals");
tl.setAccessible(true);
Method methodRemove = null;
for (Thread thread : threads) {
if (thread != null) {
Object tlm = tl.get(thread);
if (tlm != null) {
if (methodRemove == null) {
methodRemove = tlm.getClass().getDeclaredMethod("remove", ThreadLocal.class);
methodRemove.setAccessible(true);
}
if (methodRemove != null) {
try {
methodRemove.invoke(tlm, instance);
} catch (Throwable ignore) {}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void cleanAll() {
try {
// Get a reference to the thread locals table of the current thread
Thread thread = Thread.currentThread();
Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
Object threadLocalTable = threadLocalsField.get(thread);
// Get a reference to the array holding the thread local variables inside the
// ThreadLocalMap of the current thread
Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
Field tableField = threadLocalMapClass.getDeclaredField("table");
tableField.setAccessible(true);
Object table = tableField.get(threadLocalTable);
// The key to the ThreadLocalMap is a WeakReference object. The referent field of this object
// is a reference to the actual ThreadLocal variable
Field referentField = Reference.class.getDeclaredField("referent");
referentField.setAccessible(true);
for (int i = 0; i < Array.getLength(table); i++) {
// Each entry in the table array of ThreadLocalMap is an Entry object
// representing the thread local reference and its value
Object entry = Array.get(table, i);
if (entry != null) {
// Get a reference to the thread local object and remove it from the table
ThreadLocal threadLocal = (ThreadLocal)referentField.get(entry);
clean(threadLocal);
}
}
} catch(Exception e) {
// We will tolerate an exception here and just log it
throw new IllegalStateException(e);
}
}
public final Collection<T> getAll() {
return Collections.unmodifiableCollection(allValues);
}
@Override
protected void finalize() throws Throwable {
clean(this);
super.finalize();
}
}
| 4,537 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
MainLogger.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/MainLogger.java | package cn.nukkit.utils;
import cn.nukkit.Nukkit;
import cn.nukkit.command.CommandReader;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* author: MagicDroidX
* Nukkit
*/
public class MainLogger extends ThreadedLogger {
protected final String logPath;
protected final ConcurrentLinkedQueue<String> logBuffer = new ConcurrentLinkedQueue<>();
protected boolean shutdown;
protected LogLevel logLevel = LogLevel.DEFAULT_LEVEL;
private final Map<TextFormat, String> replacements = new EnumMap<>(TextFormat.class);
private final TextFormat[] colors = TextFormat.values();
protected static MainLogger logger;
public MainLogger(String logFile) {
this(logFile, LogLevel.DEFAULT_LEVEL);
}
public MainLogger(String logFile, LogLevel logLevel) {
if (logger != null) {
throw new RuntimeException("MainLogger has been already created");
}
logger = this;
this.logPath = logFile;
this.start();
}
public MainLogger(String logFile, boolean logDebug) {
this(logFile, logDebug ? LogLevel.DEBUG : LogLevel.INFO);
}
public static MainLogger getLogger() {
return logger;
}
@Override
public void emergency(String message) {
if (LogLevel.EMERGENCY.getLevel() <= logLevel.getLevel())
this.send(TextFormat.RED + "[EMERGENCY] " + message);
}
@Override
public void alert(String message) {
if (LogLevel.ALERT.getLevel() <= logLevel.getLevel())
this.send(TextFormat.RED + "[ALERT] " + message);
}
@Override
public void critical(String message) {
if (LogLevel.CRITICAL.getLevel() <= logLevel.getLevel())
this.send(TextFormat.RED + "[CRITICAL] " + message);
}
@Override
public void error(String message) {
if (LogLevel.ERROR.getLevel() <= logLevel.getLevel())
this.send(TextFormat.DARK_RED + "[ERROR] " + message);
}
@Override
public void warning(String message) {
if (LogLevel.WARNING.getLevel() <= logLevel.getLevel())
this.send(TextFormat.YELLOW + "[WARNING] " + message);
}
@Override
public void notice(String message) {
if (LogLevel.NOTICE.getLevel() <= logLevel.getLevel())
this.send(TextFormat.AQUA + "[NOTICE] " + message);
}
@Override
public void info(String message) {
if (LogLevel.INFO.getLevel() <= logLevel.getLevel())
this.send(TextFormat.WHITE + "[INFO] " + message);
}
@Override
public void debug(String message) {
if (LogLevel.DEBUG.getLevel() <= logLevel.getLevel())
this.send(TextFormat.GRAY + "[DEBUG] " + message);
}
public void setLogDebug(Boolean logDebug) {
this.logLevel = logDebug ? LogLevel.DEBUG : LogLevel.INFO;
}
public void logException(Exception e) {
this.alert(Utils.getExceptionMessage(e));
}
@Override
public void log(LogLevel level, String message) {
switch (level) {
case EMERGENCY:
this.emergency(message);
break;
case ALERT:
this.alert(message);
break;
case CRITICAL:
this.critical(message);
break;
case ERROR:
this.error(message);
break;
case WARNING:
this.warning(message);
break;
case NOTICE:
this.notice(message);
break;
case INFO:
this.info(message);
break;
case DEBUG:
this.debug(message);
break;
}
}
public void shutdown() {
this.shutdown = true;
}
protected void send(String message) {
this.send(message, -1);
synchronized (this) {
this.notify();
}
}
protected void send(String message, int level) {
logBuffer.add(message);
}
private String colorize(String string) {
if (string.indexOf(TextFormat.ESCAPE) < 0) {
return string;
} else if (Nukkit.ANSI) {
for (TextFormat color : colors) {
if (replacements.containsKey(color)) {
string = string.replaceAll("(?i)" + color, replacements.get(color));
} else {
string = string.replaceAll("(?i)" + color, "");
}
}
} else {
return TextFormat.clean(string);
}
return string + Ansi.ansi().reset();
}
@Override
public void run() {
AnsiConsole.systemInstall();
File logFile = new File(logPath);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
this.logException(e);
}
} else {
long date = logFile.lastModified();
String newName = new SimpleDateFormat("Y-M-d HH.mm.ss").format(new Date(date)) + ".log";
File oldLogs = new File(Nukkit.DATA_PATH, "logs");
if (!oldLogs.exists()) {
oldLogs.mkdirs();
}
logFile.renameTo(new File(oldLogs, newName));
logFile = new File(logPath);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
this.logException(e);
}
}
}
replacements.put(TextFormat.BLACK, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString());
replacements.put(TextFormat.DARK_BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString());
replacements.put(TextFormat.DARK_GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString());
replacements.put(TextFormat.DARK_AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString());
replacements.put(TextFormat.DARK_RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString());
replacements.put(TextFormat.DARK_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString());
replacements.put(TextFormat.GOLD, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString());
replacements.put(TextFormat.GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString());
replacements.put(TextFormat.DARK_GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString());
replacements.put(TextFormat.BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString());
replacements.put(TextFormat.GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString());
replacements.put(TextFormat.AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString());
replacements.put(TextFormat.RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString());
replacements.put(TextFormat.LIGHT_PURPLE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString());
replacements.put(TextFormat.YELLOW, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString());
replacements.put(TextFormat.WHITE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString());
replacements.put(TextFormat.BOLD, Ansi.ansi().a(Ansi.Attribute.UNDERLINE_DOUBLE).toString());
replacements.put(TextFormat.STRIKETHROUGH, Ansi.ansi().a(Ansi.Attribute.STRIKETHROUGH_ON).toString());
replacements.put(TextFormat.UNDERLINE, Ansi.ansi().a(Ansi.Attribute.UNDERLINE).toString());
replacements.put(TextFormat.ITALIC, Ansi.ansi().a(Ansi.Attribute.ITALIC).toString());
replacements.put(TextFormat.RESET, Ansi.ansi().a(Ansi.Attribute.RESET).toString());
this.shutdown = false;
do {
flushBuffer(logFile);
} while (!this.shutdown);
flushBuffer(logFile);
}
private void flushBuffer(File logFile) {
if (logBuffer.isEmpty()) {
try {
synchronized (this) {
wait(25000); // Wait for next message
}
Thread.sleep(5); // Buffer for 5ms to reduce back and forth between disk
} catch (InterruptedException ignore) {
}
}
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile, true), StandardCharsets.UTF_8), 1024);
Date now = new Date();
String consoleDateFormat = new SimpleDateFormat("HH:mm:ss ").format(now);
String fileDateFormat = new SimpleDateFormat("Y-M-d HH:mm:ss ").format(now);
int count = 0;
while (!logBuffer.isEmpty()) {
String message = logBuffer.poll();
if (message != null) {
writer.write(fileDateFormat);
writer.write(TextFormat.clean(message));
writer.write("\r\n");
CommandReader.getInstance().stashLine();
System.out.println(colorize(TextFormat.AQUA + consoleDateFormat + TextFormat.RESET + message + TextFormat.RESET));
CommandReader.getInstance().unstashLine();
}
}
writer.flush();
writer.close();
} catch (Exception e) {
this.logException(e);
}
}
@Override
public void emergency(String message, Throwable t) {
this.emergency(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void alert(String message, Throwable t) {
this.alert(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void critical(String message, Throwable t) {
this.critical(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void error(String message, Throwable t) {
this.error(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void warning(String message, Throwable t) {
this.warning(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void notice(String message, Throwable t) {
this.notice(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void info(String message, Throwable t) {
this.info(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void debug(String message, Throwable t) {
this.debug(message + "\r\n" + Utils.getExceptionMessage(t));
}
@Override
public void log(LogLevel level, String message, Throwable t) {
this.log(level, message + "\r\n" + Utils.getExceptionMessage(t));
}
}
| 11,265 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ClientChainData.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ClientChainData.java | package cn.nukkit.utils;
import cn.nukkit.network.protocol.LoginPacket;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory;
import net.minidev.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
/**
* ClientChainData is a container of chain data sent from clients.
* <p>
* Device information such as client UUID, xuid and serverAddress, can be
* read from instances of this object.
* <p>
* To get chain data, you can use player.getLoginChainData() or read(loginPacket)
* <p>
* ===============
* author: boybook
* Nukkit Project
* ===============
*/
public final class ClientChainData implements LoginChainData {
private static final String MOJANG_PUBLIC_KEY_BASE64 =
"MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V";
private static final PublicKey MOJANG_PUBLIC_KEY;
static {
try {
MOJANG_PUBLIC_KEY = generateKey(MOJANG_PUBLIC_KEY_BASE64);
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public static ClientChainData of(byte[] buffer) {
return new ClientChainData(buffer);
}
public static ClientChainData read(LoginPacket pk) {
return of(pk.getBuffer());
}
@Override
public String getUsername() {
return username;
}
@Override
public UUID getClientUUID() {
return clientUUID;
}
@Override
public String getIdentityPublicKey() {
return identityPublicKey;
}
@Override
public long getClientId() {
return clientId;
}
@Override
public String getServerAddress() {
return serverAddress;
}
@Override
public String getDeviceModel() {
return deviceModel;
}
@Override
public int getDeviceOS() {
return deviceOS;
}
@Override
public String getGameVersion() {
return gameVersion;
}
@Override
public int getGuiScale() {
return guiScale;
}
@Override
public String getLanguageCode() {
return languageCode;
}
@Override
public String getXUID() {
return xuid;
}
private boolean xboxAuthed;
@Override
public int getCurrentInputMode() {
return currentInputMode;
}
@Override
public int getDefaultInputMode() {
return defaultInputMode;
}
@Override
public String getCapeData() {
return capeData;
}
public final static int UI_PROFILE_CLASSIC = 0;
public final static int UI_PROFILE_POCKET = 1;
@Override
public int getUIProfile() {
return UIProfile;
}
///////////////////////////////////////////////////////////////////////////
// Override
///////////////////////////////////////////////////////////////////////////
@Override
public boolean equals(Object obj) {
return obj instanceof ClientChainData && Objects.equals(bs, ((ClientChainData) obj).bs);
}
@Override
public int hashCode() {
return bs.hashCode();
}
///////////////////////////////////////////////////////////////////////////
// Internal
///////////////////////////////////////////////////////////////////////////
private String username;
private UUID clientUUID;
private String xuid;
private static PublicKey generateKey(String base64) throws NoSuchAlgorithmException, InvalidKeySpecException {
return KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(base64)));
}
private String identityPublicKey;
private long clientId;
private String serverAddress;
private String deviceModel;
private int deviceOS;
private String gameVersion;
private int guiScale;
private String languageCode;
private int currentInputMode;
private int defaultInputMode;
private int UIProfile;
private String capeData;
private BinaryStream bs = new BinaryStream();
private ClientChainData(byte[] buffer) {
bs.setBuffer(buffer, 0);
decodeChainData();
decodeSkinData();
}
@Override
public boolean isXboxAuthed() {
return xboxAuthed;
}
private void decodeSkinData() {
JsonObject skinToken = decodeToken(new String(bs.get(bs.getLInt())));
if (skinToken == null) return;
if (skinToken.has("ClientRandomId")) this.clientId = skinToken.get("ClientRandomId").getAsLong();
if (skinToken.has("ServerAddress")) this.serverAddress = skinToken.get("ServerAddress").getAsString();
if (skinToken.has("DeviceModel")) this.deviceModel = skinToken.get("DeviceModel").getAsString();
if (skinToken.has("DeviceOS")) this.deviceOS = skinToken.get("DeviceOS").getAsInt();
if (skinToken.has("GameVersion")) this.gameVersion = skinToken.get("GameVersion").getAsString();
if (skinToken.has("GuiScale")) this.guiScale = skinToken.get("GuiScale").getAsInt();
if (skinToken.has("LanguageCode")) this.languageCode = skinToken.get("LanguageCode").getAsString();
if (skinToken.has("CurrentInputMode")) this.currentInputMode = skinToken.get("CurrentInputMode").getAsInt();
if (skinToken.has("DefaultInputMode")) this.defaultInputMode = skinToken.get("DefaultInputMode").getAsInt();
if (skinToken.has("UIProfile")) this.UIProfile = skinToken.get("UIProfile").getAsInt();
if (skinToken.has("CapeData")) this.capeData = skinToken.get("CapeData").getAsString();
}
private JsonObject decodeToken(String token) {
String[] base = token.split("\\.");
if (base.length < 2) return null;
String json = new String(Base64.getDecoder().decode(base[1]), StandardCharsets.UTF_8);
//Server.getInstance().getLogger().debug(json);
return new Gson().fromJson(json, JsonObject.class);
}
private void decodeChainData() {
Map<String, List<String>> map = new Gson().fromJson(new String(bs.get(bs.getLInt()), StandardCharsets.UTF_8),
new TypeToken<Map<String, List<String>>>() {
}.getType());
if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty()) return;
List<String> chains = map.get("chain");
// Validate keys
try {
xboxAuthed = verifyChain(chains);
} catch (Exception e) {
xboxAuthed = false;
}
for (String c : chains) {
JsonObject chainMap = decodeToken(c);
if (chainMap == null) continue;
if (chainMap.has("extraData")) {
JsonObject extra = chainMap.get("extraData").getAsJsonObject();
if (extra.has("displayName")) this.username = extra.get("displayName").getAsString();
if (extra.has("identity")) this.clientUUID = UUID.fromString(extra.get("identity").getAsString());
if (extra.has("XUID")) this.xuid = extra.get("XUID").getAsString();
}
if (chainMap.has("identityPublicKey"))
this.identityPublicKey = chainMap.get("identityPublicKey").getAsString();
}
if (!xboxAuthed) {
xuid = null;
}
}
private boolean verifyChain(List<String> chains) throws Exception {
PublicKey lastKey = null;
boolean mojangKeyVerified = false;
for (String chain: chains) {
JWSObject jws = JWSObject.parse(chain);
if (!mojangKeyVerified) {
// First chain should be signed using Mojang's private key. We'd be in big trouble if it leaked...
mojangKeyVerified = verify(MOJANG_PUBLIC_KEY, jws);
}
if (lastKey != null) {
if (!verify(lastKey, jws)) {
throw new JOSEException("Unable to verify key in chain.");
}
}
JSONObject payload = jws.getPayload().toJSONObject();
String base64key = payload.getAsString("identityPublicKey");
if (base64key == null) {
throw new RuntimeException("No key found");
}
lastKey = generateKey(base64key);
}
return mojangKeyVerified;
}
private boolean verify(PublicKey key, JWSObject object) throws JOSEException {
JWSVerifier verifier = new DefaultJWSVerifierFactory().createJWSVerifier(object.getHeader(), key);
return object.verify(verifier);
}
}
| 9,037 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
MinecartType.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/MinecartType.java | package cn.nukkit.utils;
import cn.nukkit.api.API;
import java.util.HashMap;
import java.util.Map;
/**
* Helper class of Minecart variants
* <p>
* By Adam Matthew
* Creation time: 2017/7/17 19:55.
*/
@API(usage = API.Usage.STABLE, definition = API.Definition.INTERNAL)
public enum MinecartType {
/**
* Represents an empty vehicle.
*/
MINECART_EMPTY(0, false, "Minecart"),
/**
* Represents a chest holder.
*/
MINECART_CHEST(1, true, "Minecart with Chest"),
/**
* Represents a furnace minecart.
*/
MINECART_FURNACE(2, true, "Minecart with Furnace"),
/**
* Represents a TNT minecart.
*/
MINECART_TNT(3, true, "Minecart with TNT"),
/**
* Represents a mob spawner minecart.
*/
MINECART_MOB_SPAWNER(4, true, "Minecart with Mob Spawner"),
/**
* Represents a hopper minecart.
*/
MINECART_HOPPER(5, true, "Minecart with Hopper"),
/**
* Represents a command block minecart.
*/
MINECART_COMMAND_BLOCK(6, true, "Minecart with Command Block"),
/**
* Represents an unknown minecart.
*/
MINECART_UNKNOWN(-1, false, "Unknown Minecart");
private final int type;
private final boolean hasBlockInside;
private final String realName;
private static final Map<Integer, MinecartType> TYPES = new HashMap<>();
static {
MinecartType[] types = values();
int var1 = types.length;
for (int var2 = 0; var2 < var1; var2++) {
MinecartType var3 = types[var2];
TYPES.put(var3.getId(), var3);
}
}
MinecartType(int number, boolean hasBlockInside, String name) {
type = number;
this.hasBlockInside = hasBlockInside;
realName = name;
}
/**
* Get the variants of the current minecart
*
* @return Integer
*/
public int getId() {
return type;
}
/**
* Get the name of the minecart variants
*
* @return String
*/
public String getName() {
return realName;
}
/**
* Gets if the minecart contains block
*
* @return Boolean
*/
public boolean hasBlockInside() {
return hasBlockInside;
}
/**
* Returns of an instance of Minecart-variants
*
* @param types The number of minecart
* @return Integer
*/
public static MinecartType valueOf(int types) {
MinecartType what = TYPES.get(types);
return what == null ? MINECART_UNKNOWN : what;
}
}
| 2,533 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ThreadStore.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ThreadStore.java | package cn.nukkit.utils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ThreadStore {
public static final Map<String, Object> store = new ConcurrentHashMap<>();
}
| 253 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
TextFormat.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/TextFormat.java | package cn.nukkit.utils;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* All supported formatting values for chat and console.
*/
public enum TextFormat {
/**
* Represents black.
*/
BLACK('0', 0x00),
/**
* Represents dark blue.
*/
DARK_BLUE('1', 0x1),
/**
* Represents dark green.
*/
DARK_GREEN('2', 0x2),
/**
* Represents dark blue (aqua).
*/
DARK_AQUA('3', 0x3),
/**
* Represents dark red.
*/
DARK_RED('4', 0x4),
/**
* Represents dark purple.
*/
DARK_PURPLE('5', 0x5),
/**
* Represents gold.
*/
GOLD('6', 0x6),
/**
* Represents gray.
*/
GRAY('7', 0x7),
/**
* Represents dark gray.
*/
DARK_GRAY('8', 0x8),
/**
* Represents blue.
*/
BLUE('9', 0x9),
/**
* Represents green.
*/
GREEN('a', 0xA),
/**
* Represents aqua.
*/
AQUA('b', 0xB),
/**
* Represents red.
*/
RED('c', 0xC),
/**
* Represents light purple.
*/
LIGHT_PURPLE('d', 0xD),
/**
* Represents yellow.
*/
YELLOW('e', 0xE),
/**
* Represents white.
*/
WHITE('f', 0xF),
/**
* Makes the text obfuscated.
*/
OBFUSCATED('k', 0x10, true),
/**
* Makes the text bold.
*/
BOLD('l', 0x11, true),
/**
* Makes a line appear through the text.
*/
STRIKETHROUGH('m', 0x12, true),
/**
* Makes the text appear underlined.
*/
UNDERLINE('n', 0x13, true),
/**
* Makes the text italic.
*/
ITALIC('o', 0x14, true),
/**
* Resets all previous chat colors or formats.
*/
RESET('r', 0x15);
/**
* The special character which prefixes all format codes. Use this if
* you need to dynamically convert format codes from your custom format.
*/
public static final char ESCAPE = '\u00A7';
private static final Pattern CLEAN_PATTERN = Pattern.compile("(?i)" + String.valueOf(ESCAPE) + "[0-9A-FK-OR]");
private final static Map<Integer, TextFormat> BY_ID = Maps.newTreeMap();
private final static Map<Character, TextFormat> BY_CHAR = new HashMap<>();
static {
for (TextFormat color : values()) {
BY_ID.put(color.intCode, color);
BY_CHAR.put(color.code, color);
}
}
private final int intCode;
private final char code;
private final boolean isFormat;
private final String toString;
TextFormat(char code, int intCode) {
this(code, intCode, false);
}
TextFormat(char code, int intCode, boolean isFormat) {
this.code = code;
this.intCode = intCode;
this.isFormat = isFormat;
this.toString = new String(new char[]{ESCAPE, code});
}
/**
* Gets the TextFormat represented by the specified format code.
*
* @param code Code to check
* @return Associative {@link TextFormat} with the given code,
* or null if it doesn't exist
*/
public static TextFormat getByChar(char code) {
return BY_CHAR.get(code);
}
/**
* Gets the TextFormat represented by the specified format code.
*
* @param code Code to check
* @return Associative {@link TextFormat} with the given code,
* or null if it doesn't exist
*/
public static TextFormat getByChar(String code) {
if (code == null || code.length() <= 1) {
return null;
}
return BY_CHAR.get(code.charAt(0));
}
/**
* Cleans the given message of all format codes.
*
* @param input String to clean.
* @return A copy of the input string, without any formatting.
*/
public static String clean(final String input) {
if (input == null) {
return null;
}
return CLEAN_PATTERN.matcher(input).replaceAll("");
}
/**
* Translates a string using an alternate format code character into a
* string that uses the internal TextFormat.ESCAPE format code
* character. The alternate format code character will only be replaced if
* it is immediately followed by 0-9, A-F, a-f, K-O, k-o, R or r.
*
* @param altFormatChar The alternate format code character to replace. Ex: &
* @param textToTranslate Text containing the alternate format code character.
* @return Text containing the TextFormat.ESCAPE format code character.
*/
public static String colorize(char altFormatChar, String textToTranslate) {
char[] b = textToTranslate.toCharArray();
for (int i = 0; i < b.length - 1; i++) {
if (b[i] == altFormatChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) {
b[i] = TextFormat.ESCAPE;
b[i + 1] = Character.toLowerCase(b[i + 1]);
}
}
return new String(b);
}
/**
* Translates a string, using an ampersand (&) as an alternate format code
* character, into a string that uses the internal TextFormat.ESCAPE format
* code character. The alternate format code character will only be replaced if
* it is immediately followed by 0-9, A-F, a-f, K-O, k-o, R or r.
*
* @param textToTranslate Text containing the alternate format code character.
* @return Text containing the TextFormat.ESCAPE format code character.
*/
public static String colorize(String textToTranslate) {
return colorize('&', textToTranslate);
}
/**
* Gets the chat color used at the end of the given input string.
*
* @param input Input string to retrieve the colors from.
* @return Any remaining chat color to pass onto the next line.
*/
public static String getLastColors(String input) {
String result = "";
int length = input.length();
// Search backwards from the end as it is faster
for (int index = length - 1; index > -1; index--) {
char section = input.charAt(index);
if (section == ESCAPE && index < length - 1) {
char c = input.charAt(index + 1);
TextFormat color = getByChar(c);
if (color != null) {
result = color.toString() + result;
// Once we find a color or reset we can stop searching
if (color.isColor() || color.equals(RESET)) {
break;
}
}
}
}
return result;
}
/**
* Gets the char value associated with this color
*
* @return A char value of this color code
*/
public char getChar() {
return code;
}
@Override
public String toString() {
return toString;
}
/**
* Checks if this code is a format code as opposed to a color code.
*/
public boolean isFormat() {
return isFormat;
}
/**
* Checks if this code is a color code as opposed to a format code.
*/
public boolean isColor() {
return !isFormat && this != RESET;
}
} | 7,208 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Watchdog.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/Watchdog.java | package cn.nukkit.utils;
import cn.nukkit.Server;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
public class Watchdog extends Thread {
private final Server server;
private final long time;
public boolean running = true;
private boolean responding = true;
public Watchdog(Server server, long time) {
this.server = server;
this.time = time;
this.running = true;
}
public void kill() {
running = false;
synchronized (this) {
this.notifyAll();
}
}
@Override
public void run() {
while (this.running && server.isRunning()) {
long current = server.getNextTick();
if (current != 0) {
long diff = System.currentTimeMillis() - current;
if (diff > time) {
if (responding) {
MainLogger logger = this.server.getLogger();
logger.emergency("--------- Server stopped responding --------- (" + (diff / 1000d) + "s)");
logger.emergency("Please report this to nukkit:");
logger.emergency(" - https://github.com/NukkitX/Nukkit/issues/new");
logger.emergency("---------------- Main thread ----------------");
dumpThread(ManagementFactory.getThreadMXBean().getThreadInfo(this.server.getPrimaryThread().getId(), Integer.MAX_VALUE), logger);
logger.emergency("---------------- All threads ----------------");
ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
for (int i = 0; i < threads.length; i++) {
if (i != 0) logger.emergency("------------------------------");
dumpThread(threads[i], logger);
}
logger.emergency("---------------------------------------------");
responding = false;
}
} else {
responding = true;
}
}
try {
synchronized (this) {
this.wait(Math.max(time / 4, 1000));
}
} catch (InterruptedException ignore) {}
}
}
private static void dumpThread(ThreadInfo thread, Logger logger) {
logger.emergency("Current Thread: " + thread.getThreadName());
logger.emergency("\tPID: " + thread.getThreadId() + " | Suspended: " + thread.isSuspended() + " | Native: " + thread.isInNative() + " | State: " + thread.getThreadState());
// Monitors
if (thread.getLockedMonitors().length != 0) {
logger.emergency("\tThread is waiting on monitor(s):");
for (MonitorInfo monitor : thread.getLockedMonitors()) {
logger.emergency("\t\tLocked on:" + monitor.getLockedStackFrame());
}
}
logger.emergency("\tStack:");
for (StackTraceElement stack : thread.getStackTrace()) {
logger.emergency("\t\t" + stack);
}
}
} | 3,245 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LevelException.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/LevelException.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class LevelException extends ServerException {
public LevelException(String message) {
super(message);
}
}
| 205 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ConfigSection.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ConfigSection.java | package cn.nukkit.utils;
import java.util.*;
/**
* Created by fromgate on 26.04.2016.
*/
public class ConfigSection extends LinkedHashMap<String, Object> {
/**
* Empty ConfigSection constructor
*/
public ConfigSection() {
super();
}
/**
* Constructor of ConfigSection that contains initial key/value data
*
* @param key
* @param value
*/
public ConfigSection(String key, Object value) {
this();
this.set(key, value);
}
/**
* Constructor of ConfigSection, based on values stored in map.
*
* @param map
*/
public ConfigSection(LinkedHashMap<String, Object> map) {
this();
if (map == null || map.isEmpty()) return;
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof LinkedHashMap) {
super.put(entry.getKey(), new ConfigSection((LinkedHashMap) entry.getValue()));
} else if (entry.getValue() instanceof List) {
super.put(entry.getKey(), parseList((List) entry.getValue()));
} else {
super.put(entry.getKey(), entry.getValue());
}
}
}
private List parseList(List list) {
List<Object> newList = new ArrayList<>();
for (Object o : list) {
if (o instanceof LinkedHashMap) {
newList.add(new ConfigSection((LinkedHashMap) o));
} else {
newList.add(o);
}
}
return newList;
}
/**
* Get root section as LinkedHashMap
*
* @return
*/
public Map<String, Object> getAllMap() {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.putAll(this);
return map;
}
/**
* Get new instance of config section
*
* @return
*/
public ConfigSection getAll() {
return new ConfigSection(this);
}
/**
* Get object by key. If section does not contain value, return null
*/
public Object get(String key) {
return this.get(key, null);
}
/**
* Get object by key. If section does not contain value, return default value
*
* @param key
* @param defaultValue
* @return
*/
public <T> T get(String key, T defaultValue) {
if (key == null || key.isEmpty()) return defaultValue;
if (super.containsKey(key)) return (T) super.get(key);
String[] keys = key.split("\\.", 2);
if (!super.containsKey(keys[0])) return defaultValue;
Object value = super.get(keys[0]);
if (value != null && value instanceof ConfigSection) {
ConfigSection section = (ConfigSection) value;
return section.get(keys[1], defaultValue);
}
return defaultValue;
}
/**
* Store value into config section
*
* @param key
* @param value
*/
public void set(String key, Object value) {
String[] subKeys = key.split("\\.", 2);
if (subKeys.length > 1) {
ConfigSection childSection = new ConfigSection();
if (this.containsKey(subKeys[0]) && super.get(subKeys[0]) instanceof ConfigSection)
childSection = (ConfigSection) super.get(subKeys[0]);
childSection.set(subKeys[1], value);
super.put(subKeys[0], childSection);
} else super.put(subKeys[0], value);
}
/**
* Check type of section element defined by key. Return true this element is ConfigSection
*
* @param key
* @return
*/
public boolean isSection(String key) {
Object value = this.get(key);
return value instanceof ConfigSection;
}
/**
* Get config section element defined by key
*
* @param key
* @return
*/
public ConfigSection getSection(String key) {
return this.get(key, new ConfigSection());
}
//@formatter:off
/**
* Get all ConfigSections in root path.
* Example config:
* a1:
* b1:
* c1:
* c2:
* a2:
* b2:
* c3:
* c4:
* a3: true
* a4: "hello"
* a5: 100
* <p>
* getSections() will return new ConfigSection, that contains sections a1 and a2 only.
*
* @return
*/
//@formatter:on
public ConfigSection getSections() {
return getSections(null);
}
/**
* Get sections (and only sections) from provided path
*
* @param key - config section path, if null or empty root path will used.
* @return
*/
public ConfigSection getSections(String key) {
ConfigSection sections = new ConfigSection();
ConfigSection parent = key == null || key.isEmpty() ? this.getAll() : getSection(key);
if (parent == null) return sections;
parent.entrySet().forEach(e -> {
if (e.getValue() instanceof ConfigSection)
sections.put(e.getKey(), e.getValue());
});
return sections;
}
/**
* Get int value of config section element
*
* @param key - key (inside) current section (default value equals to 0)
* @return
*/
public int getInt(String key) {
return this.getInt(key, 0);
}
/**
* Get int value of config section element
*
* @param key - key (inside) current section
* @param defaultValue - default value that will returned if section element is not exists
* @return
*/
public int getInt(String key, int defaultValue) {
return this.get(key, ((Number) defaultValue)).intValue();
}
/**
* Check type of section element defined by key. Return true this element is Integer
*
* @param key
* @return
*/
public boolean isInt(String key) {
Object val = get(key);
return val instanceof Integer;
}
/**
* Get long value of config section element
*
* @param key - key (inside) current section
* @return
*/
public long getLong(String key) {
return this.getLong(key, 0);
}
/**
* Get long value of config section element
*
* @param key - key (inside) current section
* @param defaultValue - default value that will returned if section element is not exists
* @return
*/
public long getLong(String key, long defaultValue) {
return this.get(key, ((Number) defaultValue)).longValue();
}
/**
* Check type of section element defined by key. Return true this element is Long
*
* @param key
* @return
*/
public boolean isLong(String key) {
Object val = get(key);
return val instanceof Long;
}
/**
* Get double value of config section element
*
* @param key - key (inside) current section
* @return
*/
public double getDouble(String key) {
return this.getDouble(key, 0);
}
/**
* Get double value of config section element
*
* @param key - key (inside) current section
* @param defaultValue - default value that will returned if section element is not exists
* @return
*/
public double getDouble(String key, double defaultValue) {
return this.get(key, ((Number) defaultValue)).doubleValue();
}
/**
* Check type of section element defined by key. Return true this element is Double
*
* @param key
* @return
*/
public boolean isDouble(String key) {
Object val = get(key);
return val instanceof Double;
}
/**
* Get String value of config section element
*
* @param key - key (inside) current section
* @return
*/
public String getString(String key) {
return this.getString(key, "");
}
/**
* Get String value of config section element
*
* @param key - key (inside) current section
* @param defaultValue - default value that will returned if section element is not exists
* @return
*/
public String getString(String key, String defaultValue) {
Object result = this.get(key, defaultValue);
return String.valueOf(result);
}
/**
* Check type of section element defined by key. Return true this element is String
*
* @param key
* @return
*/
public boolean isString(String key) {
Object val = get(key);
return val instanceof String;
}
/**
* Get boolean value of config section element
*
* @param key - key (inside) current section
* @return
*/
public boolean getBoolean(String key) {
return this.getBoolean(key, false);
}
/**
* Get boolean value of config section element
*
* @param key - key (inside) current section
* @param defaultValue - default value that will returned if section element is not exists
* @return
*/
public boolean getBoolean(String key, boolean defaultValue) {
return this.get(key, defaultValue);
}
/**
* Check type of section element defined by key. Return true this element is Integer
*
* @param key
* @return
*/
public boolean isBoolean(String key) {
Object val = get(key);
return val instanceof Boolean;
}
/**
* Get List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List getList(String key) {
return this.getList(key, null);
}
/**
* Get List value of config section element
*
* @param key - key (inside) current section
* @param defaultList - default value that will returned if section element is not exists
* @return
*/
public List getList(String key, List defaultList) {
return this.get(key, defaultList);
}
/**
* Check type of section element defined by key. Return true this element is List
*
* @param key
* @return
*/
public boolean isList(String key) {
Object val = get(key);
return val instanceof List;
}
/**
* Get String List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<String> getStringList(String key) {
List value = this.getList(key);
if (value == null) {
return new ArrayList<>(0);
}
List<String> result = new ArrayList<>();
for (Object o : value) {
if (o instanceof String || o instanceof Number || o instanceof Boolean || o instanceof Character) {
result.add(String.valueOf(o));
}
}
return result;
}
/**
* Get Integer List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Integer> getIntegerList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Integer> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Integer) {
result.add((Integer) object);
} else if (object instanceof String) {
try {
result.add(Integer.valueOf((String) object));
} catch (Exception ex) {
//ignore
}
} else if (object instanceof Character) {
result.add((int) (Character) object);
} else if (object instanceof Number) {
result.add(((Number) object).intValue());
}
}
return result;
}
/**
* Get Boolean List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Boolean> getBooleanList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Boolean> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Boolean) {
result.add((Boolean) object);
} else if (object instanceof String) {
if (Boolean.TRUE.toString().equals(object)) {
result.add(true);
} else if (Boolean.FALSE.toString().equals(object)) {
result.add(false);
}
}
}
return result;
}
/**
* Get Double List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Double> getDoubleList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Double> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Double) {
result.add((Double) object);
} else if (object instanceof String) {
try {
result.add(Double.valueOf((String) object));
} catch (Exception ex) {
//ignore
}
} else if (object instanceof Character) {
result.add((double) (Character) object);
} else if (object instanceof Number) {
result.add(((Number) object).doubleValue());
}
}
return result;
}
/**
* Get Float List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Float> getFloatList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Float> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Float) {
result.add((Float) object);
} else if (object instanceof String) {
try {
result.add(Float.valueOf((String) object));
} catch (Exception ex) {
//ignore
}
} else if (object instanceof Character) {
result.add((float) (Character) object);
} else if (object instanceof Number) {
result.add(((Number) object).floatValue());
}
}
return result;
}
/**
* Get Long List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Long> getLongList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Long> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Long) {
result.add((Long) object);
} else if (object instanceof String) {
try {
result.add(Long.valueOf((String) object));
} catch (Exception ex) {
//ignore
}
} else if (object instanceof Character) {
result.add((long) (Character) object);
} else if (object instanceof Number) {
result.add(((Number) object).longValue());
}
}
return result;
}
/**
* Get Byte List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Byte> getByteList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Byte> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Byte) {
result.add((Byte) object);
} else if (object instanceof String) {
try {
result.add(Byte.valueOf((String) object));
} catch (Exception ex) {
//ignore
}
} else if (object instanceof Character) {
result.add((byte) ((Character) object).charValue());
} else if (object instanceof Number) {
result.add(((Number) object).byteValue());
}
}
return result;
}
/**
* Get Character List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Character> getCharacterList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Character> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Character) {
result.add((Character) object);
} else if (object instanceof String) {
String str = (String) object;
if (str.length() == 1) {
result.add(str.charAt(0));
}
} else if (object instanceof Number) {
result.add((char) ((Number) object).intValue());
}
}
return result;
}
/**
* Get Short List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Short> getShortList(String key) {
List<?> list = getList(key);
if (list == null) {
return new ArrayList<>(0);
}
List<Short> result = new ArrayList<>();
for (Object object : list) {
if (object instanceof Short) {
result.add((Short) object);
} else if (object instanceof String) {
try {
result.add(Short.valueOf((String) object));
} catch (Exception ex) {
//ignore
}
} else if (object instanceof Character) {
result.add((short) ((Character) object).charValue());
} else if (object instanceof Number) {
result.add(((Number) object).shortValue());
}
}
return result;
}
/**
* Get Map List value of config section element
*
* @param key - key (inside) current section
* @return
*/
public List<Map> getMapList(String key) {
List<Map> list = getList(key);
List<Map> result = new ArrayList<>();
if (list == null) {
return result;
}
for (Object object : list) {
if (object instanceof Map) {
result.add((Map) object);
}
}
return result;
}
/**
* Check existence of config section element
*
* @param key
* @param ignoreCase
* @return
*/
public boolean exists(String key, boolean ignoreCase) {
if (ignoreCase) key = key.toLowerCase();
for (String existKey : this.getKeys(true)) {
if (ignoreCase) existKey = existKey.toLowerCase();
if (existKey.equals(key)) return true;
}
return false;
}
/**
* Check existence of config section element
*
* @param key
* @return
*/
public boolean exists(String key) {
return exists(key, false);
}
/**
* Remove config section element
*
* @param key
*/
public void remove(String key) {
if (key == null || key.isEmpty()) return;
if (super.containsKey(key)) super.remove(key);
else if (this.containsKey(".")) {
String[] keys = key.split("\\.", 2);
if (super.get(keys[0]) instanceof ConfigSection) {
ConfigSection section = (ConfigSection) super.get(keys[0]);
section.remove(keys[1]);
}
}
}
/**
* Get all keys
*
* @param child - true = include child keys
* @return
*/
public Set<String> getKeys(boolean child) {
Set<String> keys = new LinkedHashSet<>();
this.entrySet().forEach(entry -> {
keys.add(entry.getKey());
if (entry.getValue() instanceof ConfigSection) {
if (child)
((ConfigSection) entry.getValue()).getKeys(true).forEach(childKey -> keys.add(entry.getKey() + "." + childKey));
}
});
return keys;
}
/**
* Get all keys
*
* @return
*/
public Set<String> getKeys() {
return this.getKeys(true);
}
} | 20,791 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Rail.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/Rail.java | package cn.nukkit.utils;
import cn.nukkit.api.API;
import cn.nukkit.block.Block;
import cn.nukkit.math.BlockFace;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import static cn.nukkit.math.BlockFace.*;
import static cn.nukkit.utils.Rail.Orientation.State.*;
/**
* INTERNAL helper class of railway
* <p>
* By lmlstarqaq http://snake1999.com/
* Creation time: 2017/7/1 17:42.
*/
@API(usage = API.Usage.BLEEDING, definition = API.Definition.INTERNAL)
public final class Rail {
public static boolean isRailBlock(Block block) {
Objects.requireNonNull(block, "Rail block predicate can not accept null block");
return isRailBlock(block.getId());
}
public enum Orientation {
STRAIGHT_NORTH_SOUTH(0, STRAIGHT, NORTH, SOUTH, null),
STRAIGHT_EAST_WEST(1, STRAIGHT, EAST, WEST, null),
ASCENDING_EAST(2, ASCENDING, EAST, WEST, EAST),
ASCENDING_WEST(3, ASCENDING, EAST, WEST, WEST),
ASCENDING_NORTH(4, ASCENDING, NORTH, SOUTH, NORTH),
ASCENDING_SOUTH(5, ASCENDING, NORTH, SOUTH, SOUTH),
CURVED_SOUTH_EAST(6, CURVED, SOUTH, EAST, null),
CURVED_SOUTH_WEST(7, CURVED, SOUTH, WEST, null),
CURVED_NORTH_WEST(8, CURVED, NORTH, WEST, null),
CURVED_NORTH_EAST(9, CURVED, NORTH, EAST, null);
private static final Orientation[] META_LOOKUP = new Orientation[values().length];
private final int meta;
private final State state;
private final List<BlockFace> connectingDirections;
private final BlockFace ascendingDirection;
Orientation(int meta, State state, BlockFace from, BlockFace to, BlockFace ascendingDirection) {
this.meta = meta;
this.state = state;
this.connectingDirections = Arrays.asList(from, to);
this.ascendingDirection = ascendingDirection;
}
public static Orientation byMetadata(int meta) {
if (meta < 0 || meta >= META_LOOKUP.length) {
meta = 0;
}
return META_LOOKUP[meta];
}
public static Orientation straight(BlockFace face) {
switch (face) {
case NORTH:
case SOUTH:
return STRAIGHT_NORTH_SOUTH;
case EAST:
case WEST:
return STRAIGHT_EAST_WEST;
}
return STRAIGHT_NORTH_SOUTH;
}
public static Orientation ascending(BlockFace face) {
switch (face) {
case NORTH:
return ASCENDING_NORTH;
case SOUTH:
return ASCENDING_SOUTH;
case EAST:
return ASCENDING_EAST;
case WEST:
return ASCENDING_WEST;
}
return ASCENDING_EAST;
}
public static Orientation curved(BlockFace f1, BlockFace f2) {
for (Orientation o : new Orientation[]{CURVED_SOUTH_EAST, CURVED_SOUTH_WEST, CURVED_NORTH_WEST, CURVED_NORTH_EAST}) {
if (o.connectingDirections.contains(f1) && o.connectingDirections.contains(f2)) {
return o;
}
}
return CURVED_SOUTH_EAST;
}
public static Orientation straightOrCurved(BlockFace f1, BlockFace f2) {
for (Orientation o : new Orientation[]{STRAIGHT_NORTH_SOUTH, STRAIGHT_EAST_WEST, CURVED_SOUTH_EAST, CURVED_SOUTH_WEST, CURVED_NORTH_WEST, CURVED_NORTH_EAST}) {
if (o.connectingDirections.contains(f1) && o.connectingDirections.contains(f2)) {
return o;
}
}
return STRAIGHT_NORTH_SOUTH;
}
public int metadata() {
return meta;
}
public boolean hasConnectingDirections(BlockFace... faces) {
return Stream.of(faces).allMatch(connectingDirections::contains);
}
public List<BlockFace> connectingDirections() {
return connectingDirections;
}
public Optional<BlockFace> ascendingDirection() {
return Optional.ofNullable(ascendingDirection);
}
public enum State {
STRAIGHT, ASCENDING, CURVED
}
public boolean isStraight() {
return state == STRAIGHT;
}
public boolean isAscending() {
return state == ASCENDING;
}
public boolean isCurved() {
return state == CURVED;
}
static {
for (Orientation o : values()) {
META_LOOKUP[o.meta] = o;
}
}
}
public static boolean isRailBlock(int blockId) {
switch (blockId) {
case Block.RAIL:
case Block.POWERED_RAIL:
case Block.ACTIVATOR_RAIL:
case Block.DETECTOR_RAIL:
return true;
default:
return false;
}
}
private Rail() {
//no instance
}
}
| 5,129 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
HastebinUtility.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/HastebinUtility.java | package cn.nukkit.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HastebinUtility {
public static final String BIN_URL = "https://hastebin.com/documents", USER_AGENT = "Mozilla/5.0";
public static final Pattern PATTERN = Pattern.compile("\\{\"key\":\"([\\S\\s]*)\"\\}");
public static String upload(final String string) throws IOException {
final URL url = new URL(BIN_URL);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(string.getBytes());
outputStream.flush();
}
StringBuilder response;
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
Matcher matcher = PATTERN.matcher(response.toString());
if (matcher.matches()) {
return "https://hastebin.com/" + matcher.group(1);
} else {
throw new RuntimeException("Couldn't read response!");
}
}
public static String upload(final File file) throws IOException {
final StringBuilder content = new StringBuilder();
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) {
content.append(lines.get(i)).append("\n");
}
return upload(content.toString());
}
} | 2,210 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
VarInt.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/VarInt.java | package cn.nukkit.utils;
import cn.nukkit.api.API;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static cn.nukkit.api.API.Definition.UNIVERSAL;
import static cn.nukkit.api.API.Usage.EXPERIMENTAL;
/**
* Tool class for VarInt or VarLong operations.
* <p>
* Some code from http://wiki.vg/Protocol.
*
* @author MagicDroidX
* @author lmlstarqaq
*/
@API(usage = EXPERIMENTAL, definition = UNIVERSAL)
public final class VarInt {
private VarInt() {
//no instance
}
/**
* @param v Signed int
* @return Unsigned encoded int
*/
public static long encodeZigZag32(int v) {
// Note: the right-shift must be arithmetic
return (long) ((v << 1) ^ (v >> 31));
}
/**
* @param v Unsigned encoded int
* @return Signed decoded int
*/
public static int decodeZigZag32(long v) {
return (int) (v >> 1) ^ -(int) (v & 1);
}
/**
* @param v Signed long
* @return Unsigned encoded long
*/
public static long encodeZigZag64(long v) {
return (v << 1) ^ (v >> 63);
}
/**
* @param v Signed encoded long
* @return Unsigned decoded long
*/
public static long decodeZigZag64(long v) {
return (v >>> 1) ^ -(v & 1);
}
private static long read(BinaryStream stream, int maxSize) {
long value = 0;
int size = 0;
int b;
while (((b = stream.getByte()) & 0x80) == 0x80) {
value |= (long) (b & 0x7F) << (size++ * 7);
if (size >= maxSize) {
throw new IllegalArgumentException("VarLong too big");
}
}
return value | ((long) (b & 0x7F) << (size * 7));
}
private static long read(InputStream stream, int maxSize) throws IOException {
long value = 0;
int size = 0;
int b;
while (((b = stream.read()) & 0x80) == 0x80) {
value |= (long) (b & 0x7F) << (size++ * 7);
if (size >= maxSize) {
throw new IllegalArgumentException("VarLong too big");
}
}
return value | ((long) (b & 0x7F) << (size * 7));
}
/**
* @param stream BinaryStream
* @return Signed int
*/
public static int readVarInt(BinaryStream stream) {
return decodeZigZag32(readUnsignedVarInt(stream));
}
/**
* @param stream InputStream
* @return Signed int
*/
public static int readVarInt(InputStream stream) throws IOException {
return decodeZigZag32(readUnsignedVarInt(stream));
}
/**
* @param stream BinaryStream
* @return Unsigned int
*/
public static long readUnsignedVarInt(BinaryStream stream) {
return read(stream, 5);
}
/**
* @param stream InputStream
* @return Unsigned int
*/
public static long readUnsignedVarInt(InputStream stream) throws IOException {
return read(stream, 5);
}
/**
* @param stream BinaryStream
* @return Signed long
*/
public static long readVarLong(BinaryStream stream) {
return decodeZigZag64(readUnsignedVarLong(stream));
}
/**
* @param stream InputStream
* @return Signed long
*/
public static long readVarLong(InputStream stream) throws IOException {
return decodeZigZag64(readUnsignedVarLong(stream));
}
/**
* @param stream BinaryStream
* @return Unsigned long
*/
public static long readUnsignedVarLong(BinaryStream stream) {
return read(stream, 10);
}
/**
* @param stream InputStream
* @return Unsigned long
*/
public static long readUnsignedVarLong(InputStream stream) throws IOException {
return read(stream, 10);
}
private static void write(BinaryStream stream, long value) {
do {
byte temp = (byte) (value & 0b01111111);
// Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone
value >>>= 7;
if (value != 0) {
temp |= 0b10000000;
}
stream.putByte(temp);
} while (value != 0);
}
private static void write(OutputStream stream, long value) throws IOException {
do {
byte temp = (byte) (value & 0b01111111);
// Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone
value >>>= 7;
if (value != 0) {
temp |= 0b10000000;
}
stream.write(temp);
} while (value != 0);
}
/**
* @param stream BinaryStream
* @param value Signed int
*/
public static void writeVarInt(BinaryStream stream, int value) {
writeUnsignedVarInt(stream, encodeZigZag32(value));
}
/**
* @param stream OutputStream
* @param value Signed int
*/
public static void writeVarInt(OutputStream stream, int value) throws IOException {
writeUnsignedVarInt(stream, encodeZigZag32(value));
}
/**
* @param stream BinaryStream
* @param value Unsigned int
*/
public static void writeUnsignedVarInt(BinaryStream stream, long value) {
write(stream, value);
}
/**
* @param stream OutputStream
* @param value Unsigned int
*/
public static void writeUnsignedVarInt(OutputStream stream, long value) throws IOException {
write(stream, value);
}
/**
* @param stream BinaryStream
* @param value Signed long
*/
public static void writeVarLong(BinaryStream stream, long value) {
writeUnsignedVarLong(stream, encodeZigZag64(value));
}
/**
* @param stream OutputStream
* @param value Signed long
*/
public static void writeVarLong(OutputStream stream, long value) throws IOException {
writeUnsignedVarLong(stream, encodeZigZag64(value));
}
/**
* @param stream BinaryStream
* @param value Unsigned long
*/
public static void writeUnsignedVarLong(BinaryStream stream, long value) {
write(stream, value);
}
/**
* @param stream OutputStream
* @param value Unsigned long
*/
public static void writeUnsignedVarLong(OutputStream stream, long value) throws IOException {
write(stream, value);
}
} | 6,419 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DyeColor.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/DyeColor.java | package cn.nukkit.utils;
public enum DyeColor {
BLACK(0, 15, "Black", BlockColor.BLACK_BLOCK_COLOR),
RED(1, 14, "Red", BlockColor.RED_BLOCK_COLOR),
GREEN(2, 13, "Green", BlockColor.GREEN_BLOCK_COLOR),
BROWN(3, 12, "Brown", BlockColor.BROWN_BLOCK_COLOR),
BLUE(4, 11, "Blue", BlockColor.BLUE_BLOCK_COLOR),
PURPLE(5, 10, "Purple", BlockColor.PURPLE_BLOCK_COLOR),
CYAN(6, 9, "Cyan", BlockColor.CYAN_BLOCK_COLOR),
LIGHT_GRAY(7, 8, "Light Gray", BlockColor.LIGHT_GRAY_BLOCK_COLOR),
GRAY(8, 7, "Gray", BlockColor.GRAY_BLOCK_COLOR),
PINK(9, 6, "Pink", BlockColor.PINK_BLOCK_COLOR),
LIME(10, 5, "Lime", BlockColor.LIME_BLOCK_COLOR),
YELLOW(11, 4, "Yellow", BlockColor.YELLOW_BLOCK_COLOR),
LIGHT_BLUE(12, 3, "Light Blue", BlockColor.LIGHT_BLUE_BLOCK_COLOR),
MAGENTA(13, 2, "Magenta", BlockColor.MAGENTA_BLOCK_COLOR),
ORANGE(14, 1, "Orange", BlockColor.ORANGE_BLOCK_COLOR),
WHITE(15, 0, "White", BlockColor.WHITE_BLOCK_COLOR);
private int dyeColorMeta;
private int woolColorMeta;
private String colorName;
private BlockColor blockColor;
private final static DyeColor[] BY_WOOL_DATA;
private final static DyeColor[] BY_DYE_DATA;
DyeColor(int dyeColorMeta, int woolColorMeta, String colorName, BlockColor blockColor) {
this.dyeColorMeta = dyeColorMeta;
this.woolColorMeta = woolColorMeta;
this.colorName = colorName;
this.blockColor = blockColor;
}
public BlockColor getColor() {
return this.blockColor;
}
public int getDyeData() {
return this.dyeColorMeta;
}
public int getWoolData() {
return this.woolColorMeta;
}
public String getName() {
return this.colorName;
}
static {
BY_DYE_DATA = values();
BY_WOOL_DATA = values();
for (DyeColor color : values()) {
BY_WOOL_DATA[color.woolColorMeta & 0x0f] = color;
BY_DYE_DATA[color.dyeColorMeta & 0x0f] = color;
}
}
public static DyeColor getByDyeData(int dyeColorMeta) {
return BY_DYE_DATA[dyeColorMeta & 0x0f];
}
public static DyeColor getByWoolData(int woolColorMeta) {
return BY_WOOL_DATA[woolColorMeta & 0x0f];
}
}
| 2,258 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockColor.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/BlockColor.java | package cn.nukkit.utils;
/**
* Created by Snake1999 on 2016/1/10.
* Package cn.nukkit.utils in project nukkit
*/
public class BlockColor extends java.awt.Color {
public static final BlockColor TRANSPARENT_BLOCK_COLOR = new BlockColor(0x00, 0x00, 0x00, 0x00);
public static final BlockColor VOID_BLOCK_COLOR = new BlockColor(0x00, 0x00, 0x00, 0x00);
public static final BlockColor AIR_BLOCK_COLOR = new BlockColor(0x00, 0x00, 0x00);
public static final BlockColor GRASS_BLOCK_COLOR = new BlockColor(0x7f, 0xb2, 0x38);
public static final BlockColor SAND_BLOCK_COLOR = new BlockColor(0xf1, 0xe9, 0xa3);
public static final BlockColor CLOTH_BLOCK_COLOR = new BlockColor(0xa7, 0xa7, 0xa7);
public static final BlockColor TNT_BLOCK_COLOR = new BlockColor(0xff, 0x00, 0x00);
public static final BlockColor ICE_BLOCK_COLOR = new BlockColor(0xa0, 0xa0, 0xff);
public static final BlockColor IRON_BLOCK_COLOR = new BlockColor(0xa7, 0xa7, 0xa7);
public static final BlockColor FOLIAGE_BLOCK_COLOR = new BlockColor(0x00, 0x7c, 0x00);
public static final BlockColor SNOW_BLOCK_COLOR = new BlockColor(0xff, 0xff, 0xff);
public static final BlockColor CLAY_BLOCK_COLOR = new BlockColor(0xa4, 0xa8, 0xb8);
public static final BlockColor DIRT_BLOCK_COLOR = new BlockColor(0xb7, 0x6a, 0x2f);
public static final BlockColor STONE_BLOCK_COLOR = new BlockColor(0x70, 0x70, 0x70);
public static final BlockColor WATER_BLOCK_COLOR = new BlockColor(0x40, 0x40, 0xff);
public static final BlockColor LAVA_BLOCK_COLOR = TNT_BLOCK_COLOR;
public static final BlockColor WOOD_BLOCK_COLOR = new BlockColor(0x68, 0x53, 0x32);
public static final BlockColor QUARTZ_BLOCK_COLOR = new BlockColor(0xff, 0xfc, 0xf5);
public static final BlockColor ADOBE_BLOCK_COLOR = new BlockColor(0xd8, 0x7f, 0x33);
public static final BlockColor WHITE_BLOCK_COLOR = SNOW_BLOCK_COLOR;
public static final BlockColor ORANGE_BLOCK_COLOR = ADOBE_BLOCK_COLOR;
public static final BlockColor MAGENTA_BLOCK_COLOR = new BlockColor(0xb2, 0x4c, 0xd8);
public static final BlockColor LIGHT_BLUE_BLOCK_COLOR = new BlockColor(0x66, 0x99, 0xd8);
public static final BlockColor YELLOW_BLOCK_COLOR = new BlockColor(0xe5, 0xe5, 0x33);
public static final BlockColor LIME_BLOCK_COLOR = new BlockColor(0x7f, 0xcc, 0x19);
public static final BlockColor PINK_BLOCK_COLOR = new BlockColor(0xf2, 0x7f, 0xa5);
public static final BlockColor GRAY_BLOCK_COLOR = new BlockColor(0x4c, 0x4c, 0x4c);
public static final BlockColor LIGHT_GRAY_BLOCK_COLOR = new BlockColor(0x99, 0x99, 0x99);
public static final BlockColor CYAN_BLOCK_COLOR = new BlockColor(0x4c, 0x7f, 0x99);
public static final BlockColor PURPLE_BLOCK_COLOR = new BlockColor(0x7f, 0x3f, 0xb2);
public static final BlockColor BLUE_BLOCK_COLOR = new BlockColor(0x33, 0x4c, 0xb2);
public static final BlockColor BROWN_BLOCK_COLOR = new BlockColor(0x66, 0x4c, 0x33);
public static final BlockColor GREEN_BLOCK_COLOR = new BlockColor(0x66, 0x7f, 0x33);
public static final BlockColor RED_BLOCK_COLOR = new BlockColor(0x99, 0x33, 0x33);
public static final BlockColor BLACK_BLOCK_COLOR = new BlockColor(0x19, 0x19, 0x19);
public static final BlockColor GOLD_BLOCK_COLOR = new BlockColor(0xfa, 0xee, 0x4d);
public static final BlockColor DIAMOND_BLOCK_COLOR = new BlockColor(0x5c, 0xdb, 0xd5);
public static final BlockColor LAPIS_BLOCK_COLOR = new BlockColor(0x4a, 0x80, 0xff);
public static final BlockColor EMERALD_BLOCK_COLOR = new BlockColor(0x00, 0xd9, 0x3a);
public static final BlockColor OBSIDIAN_BLOCK_COLOR = new BlockColor(0x15, 0x14, 0x1f);
public static final BlockColor NETHERRACK_BLOCK_COLOR = new BlockColor(0x70, 0x02, 0x00);
public static final BlockColor REDSTONE_BLOCK_COLOR = TNT_BLOCK_COLOR;
public BlockColor(float r, float g, float b, float a) {
super(r, g, b, a);
}
public BlockColor(float r, float g, float b) {
super(r, g, b);
}
public BlockColor(int rgba, boolean hasAlpha) {
super(rgba, hasAlpha);
}
public BlockColor(int r, int g, int b, int a) {
super(r, g, b, a);
}
public BlockColor(int rgb) {
super(rgb);
}
public BlockColor(int r, int g, int b) {
super(r, g, b);
}
@Deprecated
public static BlockColor getDyeColor(int dyeColorMeta) {
return DyeColor.getByDyeData(dyeColorMeta).getColor();
}
}
| 4,509 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LogLevel.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/LogLevel.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public enum LogLevel implements Comparable<LogLevel> {
NONE,
EMERGENCY,
ALERT,
CRITICAL,
ERROR,
WARNING,
NOTICE,
INFO,
DEBUG;
public static final LogLevel DEFAULT_LEVEL = INFO;
int getLevel() {
return ordinal();
}
}
| 348 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Logger.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/Logger.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public interface Logger {
void emergency(String message);
void alert(String message);
void critical(String message);
void error(String message);
void warning(String message);
void notice(String message);
void info(String message);
void debug(String message);
void log(LogLevel level, String message);
void emergency(String message, Throwable t);
void alert(String message, Throwable t);
void critical(String message, Throwable t);
void error(String message, Throwable t);
void warning(String message, Throwable t);
void notice(String message, Throwable t);
void info(String message, Throwable t);
void debug(String message, Throwable t);
void log(LogLevel level, String message, Throwable t);
}
| 860 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Utils.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/Utils.java | package cn.nukkit.utils;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Utils {
public static void writeFile(String fileName, String content) throws IOException {
writeFile(fileName, new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
}
public static void writeFile(String fileName, InputStream content) throws IOException {
writeFile(new File(fileName), content);
}
public static void writeFile(File file, String content) throws IOException {
writeFile(file, new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
}
public static void writeFile(File file, InputStream content) throws IOException {
if (content == null) {
throw new IllegalArgumentException("content must not be null");
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = content.read(buffer)) != -1) {
stream.write(buffer, 0, length);
}
stream.close();
content.close();
}
public static String readFile(File file) throws IOException {
if (!file.exists() || file.isDirectory()) {
throw new FileNotFoundException();
}
return readFile(new FileInputStream(file));
}
public static String readFile(String filename) throws IOException {
File file = new File(filename);
if (!file.exists() || file.isDirectory()) {
throw new FileNotFoundException();
}
return readFile(new FileInputStream(file));
}
public static String readFile(InputStream inputStream) throws IOException {
return readFile(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
}
private static String readFile(Reader reader) throws IOException {
BufferedReader br = new BufferedReader(reader);
String temp;
StringBuilder stringBuilder = new StringBuilder();
temp = br.readLine();
while (temp != null) {
if (stringBuilder.length() != 0) {
stringBuilder.append("\n");
}
stringBuilder.append(temp);
temp = br.readLine();
}
br.close();
reader.close();
return stringBuilder.toString();
}
public static void copyFile(File from, File to) throws IOException {
if (!from.exists()) {
throw new FileNotFoundException();
}
if (from.isDirectory() || to.isDirectory()) {
throw new FileNotFoundException();
}
FileInputStream fi = null;
FileChannel in = null;
FileOutputStream fo = null;
FileChannel out = null;
try {
if (!to.exists()) {
to.createNewFile();
}
fi = new FileInputStream(from);
in = fi.getChannel();
fo = new FileOutputStream(to);
out = fo.getChannel();
in.transferTo(0, in.size(), out);
} finally {
if (fi != null) fi.close();
if (in != null) in.close();
if (fo != null) fo.close();
if (out != null) out.close();
}
}
public static String getAllThreadDumps() {
ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
StringBuilder builder = new StringBuilder();
for (ThreadInfo info : threads) {
builder.append('\n').append(info);
}
return builder.toString();
}
public static String getExceptionMessage(Throwable e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
public static UUID dataToUUID(String... params) {
StringBuilder builder = new StringBuilder();
for (String param : params) {
builder.append(param);
}
return UUID.nameUUIDFromBytes(builder.toString().getBytes(StandardCharsets.UTF_8));
}
public static UUID dataToUUID(byte[]... params) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
for (byte[] param : params) {
try {
stream.write(param);
} catch (IOException e) {
break;
}
}
return UUID.nameUUIDFromBytes(stream.toByteArray());
}
public static String rtrim(String s, char character) {
int i = s.length() - 1;
while (i >= 0 && (s.charAt(i)) == character) {
i--;
}
return s.substring(0, i + 1);
}
public static boolean isByteArrayEmpty(final byte[] array) {
for (byte b : array) {
if (b != 0) {
return false;
}
}
return true;
}
public static long toRGB(byte r, byte g, byte b, byte a) {
long result = (int) r & 0xff;
result |= ((int) g & 0xff) << 8;
result |= ((int) b & 0xff) << 16;
result |= ((int) a & 0xff) << 24;
return result & 0xFFFFFFFFL;
}
public static Object[][] splitArray(Object[] arrayToSplit, int chunkSize) {
if (chunkSize <= 0) {
return null;
}
int rest = arrayToSplit.length % chunkSize;
int chunks = arrayToSplit.length / chunkSize + (rest > 0 ? 1 : 0);
Object[][] arrays = new Object[chunks][];
for (int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++) {
arrays[i] = Arrays.copyOfRange(arrayToSplit, i * chunkSize, i * chunkSize + chunkSize);
}
if (rest > 0) {
arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) * chunkSize, (chunks - 1) * chunkSize + rest);
}
return arrays;
}
public static void reverseArray(Object[] data) {
reverseArray(data, false);
}
public static Object[] reverseArray(Object[] array, boolean copy) {
Object[] data = array;
if (copy) {
data = new Object[array.length];
System.arraycopy(array, 0, data, 0, data.length);
}
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
Object temp = data[left];
data[left] = data[right];
data[right] = temp;
}
return data;
}
@SuppressWarnings("unchecked")
public static <T> T[][] clone2dArray(T[][] array) {
T[][] newArray = (T[][]) new Object[array.length][];
for (int i = 0; i < newArray.length; i++) {
T[] old = array[i];
T[] n = (T[]) new Object[old.length];
System.arraycopy(old, 0, n, 0, n.length);
newArray[i] = n;
}
return newArray;
}
public static <T,U,V> Map<U,V> getOrCreate(Map<T, Map<U, V>> map, T key) {
Map<U, V> existing = map.get(key);
if (existing == null) {
ConcurrentHashMap<U, V> toPut = new ConcurrentHashMap<U, V>();
existing = map.putIfAbsent(key, toPut);
if (existing == null) {
existing = toPut;
}
}
return existing;
}
public static <T, U, V extends U> U getOrCreate(Map<T, U> map, Class<V> clazz, T key) {
U existing = map.get(key);
if (existing != null) {
return existing;
}
try {
U toPut = clazz.newInstance();
existing = map.putIfAbsent(key, toPut);
if (existing == null) {
return toPut;
}
return existing;
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static int toInt(Object number) {
if (number instanceof Integer) {
return (Integer) number;
}
return (int) Math.round((double) number);
}
public static byte[] parseHexBinary(String s) {
final int len = s.length();
// "111" is not a valid hex encoding.
if(len % 2 != 0)
throw new IllegalArgumentException("hexBinary needs to be even-length: " + s);
byte[] out = new byte[len / 2];
for(int i = 0; i < len; i += 2) {
int h = hexToBin(s.charAt(i));
int l = hexToBin(s.charAt(i + 1));
if(h == -1 || l == -1)
throw new IllegalArgumentException("contains illegal character for hexBinary: " + s);
out[i / 2] = (byte)(h * 16 + l);
}
return out;
}
private static int hexToBin( char ch ) {
if('0' <= ch && ch <= '9') return ch - '0';
if('A' <= ch && ch <= 'F') return ch - 'A' + 10;
if('a' <= ch && ch <= 'f') return ch - 'a' + 10;
return -1;
}
}
| 9,348 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
SimpleConfig.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/SimpleConfig.java | package cn.nukkit.utils;
import cn.nukkit.Server;
import cn.nukkit.plugin.Plugin;
import java.io.File;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
/**
* SimpleConfig for Nukkit
* added 11/02/2016 by fromgate
*/
public abstract class SimpleConfig {
private final File configFile;
public SimpleConfig(Plugin plugin) {
this(plugin, "config.yml");
}
public SimpleConfig(Plugin plugin, String fileName) {
this(new File(plugin.getDataFolder() + File.separator + fileName));
}
public SimpleConfig(File file) {
this.configFile = file;
configFile.getParentFile().mkdirs();
}
public boolean save() {
return save(false);
}
public boolean save(boolean async) {
if (configFile.exists()) try {
configFile.createNewFile();
} catch (Exception e) {
return false;
}
Config cfg = new Config(configFile, Config.YAML);
for (Field field : this.getClass().getDeclaredFields()) {
if (skipSave(field)) continue;
String path = getPath(field);
try {
if (path != null) cfg.set(path, field.get(this));
} catch (Exception e) {
return false;
}
}
cfg.save(async);
return true;
}
public boolean load() {
if (!this.configFile.exists()) return false;
Config cfg = new Config(configFile, Config.YAML);
for (Field field : this.getClass().getDeclaredFields()) {
if (field.getName().equals("configFile")) continue;
if (skipSave(field)) continue;
String path = getPath(field);
if (path == null) continue;
if (path.isEmpty()) continue;
field.setAccessible(true);
try {
if (field.getType() == int.class || field.getType() == Integer.class)
field.set(this, cfg.getInt(path, field.getInt(this)));
else if (field.getType() == boolean.class || field.getType() == Boolean.class)
field.set(this, cfg.getBoolean(path, field.getBoolean(this)));
else if (field.getType() == long.class || field.getType() == Long.class)
field.set(this, cfg.getLong(path, field.getLong(this)));
else if (field.getType() == double.class || field.getType() == Double.class)
field.set(this, cfg.getDouble(path, field.getDouble(this)));
else if (field.getType() == String.class)
field.set(this, cfg.getString(path, (String) field.get(this)));
else if (field.getType() == ConfigSection.class)
field.set(this, cfg.getSection(path));
else if (field.getType() == List.class) {
Type genericFieldType = field.getGenericType();
if (genericFieldType instanceof ParameterizedType) {
ParameterizedType aType = (ParameterizedType) genericFieldType;
Class fieldArgClass = (Class) aType.getActualTypeArguments()[0];
if (fieldArgClass == Integer.class) field.set(this, cfg.getIntegerList(path));
else if (fieldArgClass == Boolean.class) field.set(this, cfg.getBooleanList(path));
else if (fieldArgClass == Double.class) field.set(this, cfg.getDoubleList(path));
else if (fieldArgClass == Character.class) field.set(this, cfg.getCharacterList(path));
else if (fieldArgClass == Byte.class) field.set(this, cfg.getByteList(path));
else if (fieldArgClass == Float.class) field.set(this, cfg.getFloatList(path));
else if (fieldArgClass == Short.class) field.set(this, cfg.getFloatList(path));
else if (fieldArgClass == String.class) field.set(this, cfg.getStringList(path));
} else field.set(this, cfg.getList(path)); // Hell knows what's kind of List was found :)
} else
throw new IllegalStateException("SimpleConfig did not supports class: " + field.getType().getName() + " for config field " + configFile.getName());
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
return false;
}
}
return true;
}
private String getPath(Field field) {
String path = null;
if (field.isAnnotationPresent(Path.class)) {
Path pathDefine = field.getAnnotation(Path.class);
path = pathDefine.value();
}
if (path == null || path.isEmpty()) path = field.getName().replaceAll("_", ".");
if (Modifier.isFinal(field.getModifiers())) return null;
if (Modifier.isPrivate(field.getModifiers())) field.setAccessible(true);
return path;
}
private boolean skipSave(Field field) {
if (!field.isAnnotationPresent(Skip.class)) return false;
return field.getAnnotation(Skip.class).skipSave();
}
private boolean skipLoad(Field field) {
if (!field.isAnnotationPresent(Skip.class)) return false;
return field.getAnnotation(Skip.class).skipLoad();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Path {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Skip {
boolean skipSave() default true;
boolean skipLoad() default true;
}
}
| 5,933 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ThreadCache.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ThreadCache.java | package cn.nukkit.utils;
import cn.nukkit.nbt.stream.FastByteArrayOutputStream;
public class ThreadCache {
public static void clean() {
idArray.clean();
dataArray.clean();
byteCache6144.clean();
boolCache4096.clean();
charCache4096.clean();
charCache4096v2.clean();
fbaos.clean();
binaryStream.clean();
ZlibThreadLocal.def.clean();
ZlibThreadLocal.buf.clean();
}
public static final IterableThreadLocal<byte[][]> idArray = new IterableThreadLocal<byte[][]>() {
@Override
public byte[][] init() {
return new byte[16][];
}
};
public static final IterableThreadLocal<byte[][]> dataArray = new IterableThreadLocal<byte[][]>() {
@Override
public byte[][] init() {
return new byte[16][];
}
};
public static final IterableThreadLocal<byte[]> byteCache6144 = new IterableThreadLocal<byte[]>() {
@Override
public byte[] init() {
return new byte[6144];
}
};
public static final IterableThreadLocal<boolean[]> boolCache4096 = new IterableThreadLocal<boolean[]>() {
@Override
public boolean[] init() {
return new boolean[4096];
}
};
public static final IterableThreadLocal<char[]> charCache4096v2 = new IterableThreadLocal<char[]>() {
@Override
public char[] init() {
return new char[4096];
}
};
public static final IterableThreadLocal<char[]> charCache4096 = new IterableThreadLocal<char[]>() {
@Override
public char[] init() {
return new char[4096];
}
};
public static final IterableThreadLocal<FastByteArrayOutputStream> fbaos = new IterableThreadLocal<FastByteArrayOutputStream>() {
@Override
public FastByteArrayOutputStream init() {
return new FastByteArrayOutputStream(1024);
}
};
public static final IterableThreadLocal<BinaryStream> binaryStream = new IterableThreadLocal<BinaryStream>() {
@Override
public BinaryStream init() {
return new BinaryStream();
}
};
}
| 2,210 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ServerException.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ServerException.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ServerException extends RuntimeException {
public ServerException(String message) {
super(message);
}
}
| 208 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ZlibProvider.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ZlibProvider.java | package cn.nukkit.utils;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author ScraMTeam
*/
interface ZlibProvider {
public byte[] deflate(byte[][] data, int level) throws Exception;
public byte[] deflate(byte[] data, int level) throws Exception;
public byte[] inflate(InputStream stream) throws IOException;
}
| 346 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Zlib.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/Zlib.java | package cn.nukkit.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Deflater;
public abstract class Zlib {
private static ZlibProvider[] providers;
private static ZlibProvider provider;
static {
providers = new ZlibProvider[3];
providers[2] = new ZlibThreadLocal();
provider = providers[2];
}
public static void setProvider(int providerIndex) {
MainLogger.getLogger().info("Selected Zlib Provider: " + providerIndex + " (" + provider.getClass().getCanonicalName() + ")");
switch (providerIndex) {
case 0:
if (providers[providerIndex] == null)
providers[providerIndex] = new ZlibOriginal();
break;
case 1:
if (providers[providerIndex] == null)
providers[providerIndex] = new ZlibSingleThreadLowMem();
break;
case 2:
if (providers[providerIndex] == null)
providers[providerIndex] = new ZlibThreadLocal();
break;
default:
throw new UnsupportedOperationException("Invalid provider: " + providerIndex);
}
if (providerIndex != 2) {
MainLogger.getLogger().warning(" - This Zlib will negatively affect performance");
}
provider = providers[providerIndex];
}
public static byte[] deflate(byte[] data) throws Exception {
return deflate(data, Deflater.DEFAULT_COMPRESSION);
}
public static byte[] deflate(byte[] data, int level) throws Exception {
return provider.deflate(data, level);
}
public static byte[] deflate(byte[][] data, int level) throws Exception {
return provider.deflate(data, level);
}
public static byte[] inflate(InputStream stream) throws IOException {
return provider.inflate(stream);
}
public static byte[] inflate(byte[] data) throws IOException {
return inflate(new ByteArrayInputStream(data));
}
public static byte[] inflate(byte[] data, int maxSize) throws IOException {
return inflate(new ByteArrayInputStream(data, 0, maxSize));
}
}
| 2,255 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ZlibOriginal.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ZlibOriginal.java | package cn.nukkit.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
public class ZlibOriginal implements ZlibProvider {
@Override
public byte[] deflate(byte[][] datas, int level) throws Exception {
Deflater deflater = new Deflater(level);
deflater.reset();
byte[] buffer = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream(datas.length);
try {
for (byte[] data : datas) {
deflater.setInput(data);
while (!deflater.needsInput()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
}
deflater.finish();
while (!deflater.finished()) {
int i = deflater.deflate(buffer);
bos.write(buffer, 0, i);
}
} finally {
deflater.end();
}
return bos.toByteArray();
}
@Override
public byte[] deflate(byte[] data, int level) throws Exception {
Deflater deflater = new Deflater(level);
deflater.reset();
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
byte[] buf = new byte[1024];
try {
while (!deflater.finished()) {
int i = deflater.deflate(buf);
bos.write(buf, 0, i);
}
} finally {
deflater.end();
}
return bos.toByteArray();
}
@Override
public byte[] inflate(InputStream stream) throws IOException {
InflaterInputStream inputStream = new InflaterInputStream(stream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
buffer = outputStream.toByteArray();
outputStream.flush();
outputStream.close();
inputStream.close();
}
return buffer;
}
}
| 2,322 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ChunkException.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ChunkException.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ChunkException extends RuntimeException {
public ChunkException(String message) {
super(message);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
| 290 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ServerKiller.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/ServerKiller.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ServerKiller extends Thread {
public final int time;
public ServerKiller() {
this(15);
}
public ServerKiller(int time) {
this.time = time;
this.setName("Server Killer");
}
@Override
public void run() {
try {
sleep(this.time * 1000);
} catch (InterruptedException e) {
// ignore
}
System.out.println("\nTook too long to stop, server was killed forcefully!\n");
System.exit(1);
}
}
| 593 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BinaryStream.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/BinaryStream.java | package cn.nukkit.utils;
import cn.nukkit.entity.Attribute;
import cn.nukkit.entity.data.Skin;
import cn.nukkit.item.Item;
import cn.nukkit.level.GameRule;
import cn.nukkit.level.GameRules;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.BlockVector3;
import cn.nukkit.math.Vector3f;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class BinaryStream {
public int offset;
private byte[] buffer;
private int count;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public BinaryStream() {
this.buffer = new byte[32];
this.offset = 0;
this.count = 0;
}
public BinaryStream(byte[] buffer) {
this(buffer, 0);
}
public BinaryStream(byte[] buffer, int offset) {
this.buffer = buffer;
this.offset = offset;
this.count = buffer.length;
}
public BinaryStream reset() {
this.offset = 0;
this.count = 0;
return this;
}
public void setBuffer(byte[] buffer) {
this.buffer = buffer;
this.count = buffer == null ? -1 : buffer.length;
}
public void setBuffer(byte[] buffer, int offset) {
this.setBuffer(buffer);
this.setOffset(offset);
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public byte[] getBuffer() {
return Arrays.copyOf(buffer, count);
}
public int getCount() {
return count;
}
public byte[] get() {
return this.get(this.count - this.offset);
}
public byte[] get(int len) {
if (len < 0) {
this.offset = this.count - 1;
return new byte[0];
}
len = Math.min(len, this.getCount() - this.offset);
this.offset += len;
return Arrays.copyOfRange(this.buffer, this.offset - len, this.offset);
}
public void put(byte[] bytes) {
if (bytes == null) {
return;
}
this.ensureCapacity(this.count + bytes.length);
System.arraycopy(bytes, 0, this.buffer, this.count, bytes.length);
this.count += bytes.length;
}
public long getLong() {
return Binary.readLong(this.get(8));
}
public void putLong(long l) {
this.put(Binary.writeLong(l));
}
public int getInt() {
return Binary.readInt(this.get(4));
}
public void putInt(int i) {
this.put(Binary.writeInt(i));
}
public long getLLong() {
return Binary.readLLong(this.get(8));
}
public void putLLong(long l) {
this.put(Binary.writeLLong(l));
}
public int getLInt() {
return Binary.readLInt(this.get(4));
}
public void putLInt(int i) {
this.put(Binary.writeLInt(i));
}
public int getShort() {
return Binary.readShort(this.get(2));
}
public void putShort(int s) {
this.put(Binary.writeShort(s));
}
public int getLShort() {
return Binary.readLShort(this.get(2));
}
public void putLShort(int s) {
this.put(Binary.writeLShort(s));
}
public float getFloat() {
return getFloat(-1);
}
public float getFloat(int accuracy) {
return Binary.readFloat(this.get(4), accuracy);
}
public void putFloat(float v) {
this.put(Binary.writeFloat(v));
}
public float getLFloat() {
return getLFloat(-1);
}
public float getLFloat(int accuracy) {
return Binary.readLFloat(this.get(4), accuracy);
}
public void putLFloat(float v) {
this.put(Binary.writeLFloat(v));
}
public int getTriad() {
return Binary.readTriad(this.get(3));
}
public void putTriad(int triad) {
this.put(Binary.writeTriad(triad));
}
public int getLTriad() {
return Binary.readLTriad(this.get(3));
}
public void putLTriad(int triad) {
this.put(Binary.writeLTriad(triad));
}
public boolean getBoolean() {
return this.getByte() == 0x01;
}
public void putBoolean(boolean bool) {
this.putByte((byte) (bool ? 1 : 0));
}
public int getByte() {
return this.buffer[this.offset++] & 0xff;
}
public void putByte(byte b) {
this.put(new byte[]{b});
}
/**
* Reads a list of Attributes from the stream.
*
* @return Attribute[]
*/
public Attribute[] getAttributeList() throws Exception {
List<Attribute> list = new ArrayList<>();
long count = this.getUnsignedVarInt();
for (int i = 0; i < count; ++i) {
String name = this.getString();
Attribute attr = Attribute.getAttributeByName(name);
if (attr != null) {
attr.setMinValue(this.getLFloat());
attr.setValue(this.getLFloat());
attr.setMaxValue(this.getLFloat());
list.add(attr);
} else {
throw new Exception("Unknown attribute type \"" + name + "\"");
}
}
return list.stream().toArray(Attribute[]::new);
}
/**
* Writes a list of Attributes to the packet buffer using the standard format.
*/
public void putAttributeList(Attribute[] attributes) {
this.putUnsignedVarInt(attributes.length);
for (Attribute attribute : attributes) {
this.putString(attribute.getName());
this.putLFloat(attribute.getMinValue());
this.putLFloat(attribute.getValue());
this.putLFloat(attribute.getMaxValue());
}
}
public void putUUID(UUID uuid) {
this.put(Binary.writeUUID(uuid));
}
public UUID getUUID() {
return Binary.readUUID(this.get(16));
}
public void putSkin(Skin skin) {
this.putString(skin.getModel());
this.putByteArray(skin.getData());
}
public Skin getSkin() {
String modelId = this.getString();
byte[] skinData = this.getByteArray();
return new Skin(skinData, modelId);
}
public Item getSlot() {
int id = this.getVarInt();
if (id <= 0) {
return Item.get(0, 0, 0);
}
int auxValue = this.getVarInt();
int data = auxValue >> 8;
if (data == Short.MAX_VALUE) {
data = -1;
}
int cnt = auxValue & 0xff;
int nbtLen = this.getLShort();
byte[] nbt = new byte[0];
if (nbtLen > 0) {
nbt = this.get(nbtLen);
}
//TODO
int canPlaceOn = this.getVarInt();
if (canPlaceOn > 0) {
for (int i = 0; i < canPlaceOn; ++i) {
this.getString();
}
}
//TODO
int canDestroy = this.getVarInt();
if (canDestroy > 0) {
for (int i = 0; i < canDestroy; ++i) {
this.getString();
}
}
return Item.get(
id, data, cnt, nbt
);
}
public void putSlot(Item item) {
if (item == null || item.getId() == 0) {
this.putVarInt(0);
return;
}
this.putVarInt(item.getId());
int auxValue = (((item.hasMeta() ? item.getDamage() : -1) & 0x7fff) << 8) | item.getCount();
this.putVarInt(auxValue);
byte[] nbt = item.getCompoundTag();
this.putLShort(nbt.length);
this.put(nbt);
this.putVarInt(0); //TODO CanPlaceOn entry count
this.putVarInt(0); //TODO CanDestroy entry count
}
public byte[] getByteArray() {
return this.get((int) this.getUnsignedVarInt());
}
public void putByteArray(byte[] b) {
this.putUnsignedVarInt(b.length);
this.put(b);
}
public String getString() {
return new String(this.getByteArray(), StandardCharsets.UTF_8);
}
public void putString(String string) {
byte[] b = string.getBytes(StandardCharsets.UTF_8);
this.putByteArray(b);
}
public long getUnsignedVarInt() {
return VarInt.readUnsignedVarInt(this);
}
public void putUnsignedVarInt(long v) {
VarInt.writeUnsignedVarInt(this, v);
}
public int getVarInt() {
return VarInt.readVarInt(this);
}
public void putVarInt(int v) {
VarInt.writeVarInt(this, v);
}
public long getVarLong() {
return VarInt.readVarLong(this);
}
public void putVarLong(long v) {
VarInt.writeVarLong(this, v);
}
public long getUnsignedVarLong() {
return VarInt.readUnsignedVarLong(this);
}
public void putUnsignedVarLong(long v) {
VarInt.writeUnsignedVarLong(this, v);
}
public BlockVector3 getBlockVector3() {
return new BlockVector3(this.getVarInt(), (int) this.getUnsignedVarInt(), this.getVarInt());
}
public BlockVector3 getSignedBlockPosition() {
return new BlockVector3(getVarInt(), getVarInt(), getVarInt());
}
public void putSignedBlockPosition(BlockVector3 v) {
putVarInt(v.x);
putVarInt(v.y);
putVarInt(v.z);
}
public void putBlockVector3(BlockVector3 v) {
this.putBlockVector3(v.x, v.y, v.z);
}
public void putBlockVector3(int x, int y, int z) {
this.putVarInt(x);
this.putUnsignedVarInt(y);
this.putVarInt(z);
}
public Vector3f getVector3f() {
return new Vector3f(this.getLFloat(4), this.getLFloat(4), this.getLFloat(4));
}
public void putVector3f(Vector3f v) {
this.putVector3f(v.x, v.y, v.z);
}
public void putVector3f(float x, float y, float z) {
this.putLFloat(x);
this.putLFloat(y);
this.putLFloat(z);
}
public void putGameRules(GameRules gameRules) {
Map<GameRule, GameRules.Value> rules = gameRules.getGameRules();
this.putUnsignedVarInt(rules.size());
rules.forEach((gameRule, value) -> {
putString(gameRule.getName().toLowerCase());
value.write(this);
});
}
/**
* Reads and returns an EntityUniqueID
*
* @return int
*/
public long getEntityUniqueId() {
return this.getVarLong();
}
/**
* Writes an EntityUniqueID
*/
public void putEntityUniqueId(long eid) {
this.putVarLong(eid);
}
/**
* Reads and returns an EntityRuntimeID
*/
public long getEntityRuntimeId() {
return this.getUnsignedVarLong();
}
/**
* Writes an EntityUniqueID
*/
public void putEntityRuntimeId(long eid) {
this.putUnsignedVarLong(eid);
}
public BlockFace getBlockFace() {
return BlockFace.fromIndex(this.getVarInt());
}
public void putBlockFace(BlockFace face) {
this.putVarInt(face.getIndex());
}
public boolean feof() {
return this.offset < 0 || this.offset >= this.buffer.length;
}
private void ensureCapacity(int minCapacity) {
// overflow-conscious code
if (minCapacity - buffer.length > 0) {
grow(minCapacity);
}
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = buffer.length;
int newCapacity = oldCapacity << 1;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
if (newCapacity - MAX_ARRAY_SIZE > 0) {
newCapacity = hugeCapacity(minCapacity);
}
this.buffer = Arrays.copyOf(buffer, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
}
| 12,420 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginException.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/PluginException.java | package cn.nukkit.utils;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class PluginException extends ServerException {
public PluginException(String message) {
super(message);
}
}
| 207 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BugReportGenerator.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/bugreport/BugReportGenerator.java | package cn.nukkit.utils.bugreport;
import cn.nukkit.Nukkit;
import cn.nukkit.Server;
import cn.nukkit.lang.BaseLang;
import cn.nukkit.utils.Utils;
import oshi.SystemInfo;
import oshi.hardware.HWDiskStore;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
/**
* Project nukkit
*/
public class BugReportGenerator extends Thread {
private Throwable throwable;
BugReportGenerator(Throwable throwable) {
this.throwable = throwable;
}
@Override
public void run() {
BaseLang baseLang = Server.getInstance().getLanguage();
try {
Server.getInstance().getLogger().info("[BugReport] " + baseLang.translateString("nukkit.bugreport.create"));
String path = generate();
Server.getInstance().getLogger().info("[BugReport] " + baseLang.translateString("nukkit.bugreport.archive", path));
} catch (Exception e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
Server.getInstance().getLogger().info("[BugReport] " + baseLang.translateString("nukkit.bugreport.error", stringWriter.toString()));
}
}
private String generate() throws IOException {
File reports = new File(Nukkit.DATA_PATH, "logs/bug_reports");
if (!reports.isDirectory()) {
reports.mkdirs();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmSS");
String date = simpleDateFormat.format(new Date());
SystemInfo systemInfo = new SystemInfo();
long totalDiskSize = 0;
StringBuilder model = new StringBuilder();
for (HWDiskStore hwDiskStore : systemInfo.getHardware().getDiskStores()) {
totalDiskSize += hwDiskStore.getSize();
if (!model.toString().contains(hwDiskStore.getModel())) {
model.append(hwDiskStore.getModel()).append(" ");
}
}
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
File mdReport = new File(reports, date + "_" + throwable.getClass().getSimpleName() + ".md");
mdReport.createNewFile();
String content = Utils.readFile(this.getClass().getClassLoader().getResourceAsStream("report_template.md"));
Properties properties = getGitRepositoryState();
System.out.println(properties.getProperty("git.commit.id.abbrev"));
String abbrev = properties.getProperty("git.commit.id.abbrev");
content = content.replace("${NUKKIT_VERSION}", Nukkit.VERSION);
content = content.replace("${GIT_COMMIT_ABBREV}", abbrev);
content = content.replace("${JAVA_VERSION}", System.getProperty("java.vm.name") + " (" + System.getProperty("java.runtime.version") + ")");
content = content.replace("${HOSTOS}", systemInfo.getOperatingSystem().getFamily() + " [" + systemInfo.getOperatingSystem().getVersion().getVersion() + "]");
content = content.replace("${MEMORY}", getCount(systemInfo.getHardware().getMemory().getTotal(), true));
content = content.replace("${STORAGE_SIZE}", getCount(totalDiskSize, true));
content = content.replace("${CPU_TYPE}", systemInfo.getHardware().getProcessor().getName());
content = content.replace("${PHYSICAL_CORE}", String.valueOf(systemInfo.getHardware().getProcessor().getPhysicalProcessorCount()));
content = content.replace("${LOGICAL_CORE}", String.valueOf(systemInfo.getHardware().getProcessor().getLogicalProcessorCount()));
content = content.replace("${STACKTRACE}", stringWriter.toString());
content = content.replace("${PLUGIN_ERROR}", String.valueOf(!throwable.getStackTrace()[0].getClassName().startsWith("cn.nukkit")).toUpperCase());
content = content.replace("${STORAGE_TYPE}", model.toString());
Utils.writeFile(mdReport, content);
return mdReport.getAbsolutePath();
}
public Properties getGitRepositoryState() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("git.properties"));
return properties;
}
//Code section from SOF
public static String getCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
| 4,749 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ExceptionHandler.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/bugreport/ExceptionHandler.java | package cn.nukkit.utils.bugreport;
/**
* Project nukkit
*/
public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
public static void registerExceptionHandler() {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
handle(thread, throwable);
}
public void handle(Thread thread, Throwable throwable) {
throwable.printStackTrace();
try {
new BugReportGenerator(throwable).start();
} catch (Exception exception) {
// Fail Safe
}
}
} | 651 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
CommandsCompleter.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/completers/CommandsCompleter.java | package cn.nukkit.utils.completers;
import cn.nukkit.Server;
import jline.console.completer.Completer;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import static jline.internal.Preconditions.checkNotNull;
public class CommandsCompleter implements Completer {
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
// buffer could be null
checkNotNull(candidates);
if (buffer == null) {
Server.getInstance().getCommandMap().getCommands().keySet().forEach((cmd) -> candidates.add(cmd));
} else {
SortedSet<String> names = new TreeSet<String>();
Server.getInstance().getCommandMap().getCommands().keySet().forEach((cmd) -> names.add(cmd));
for (String match : names) {
if (!match.toLowerCase().startsWith(buffer.toLowerCase())) {
continue;
}
candidates.add(match);
}
}
return candidates.isEmpty() ? -1 : 0;
}
}
| 1,072 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PlayersCompleter.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/utils/completers/PlayersCompleter.java | package cn.nukkit.utils.completers;
import cn.nukkit.Server;
import jline.console.completer.Completer;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import static jline.internal.Preconditions.checkNotNull;
public class PlayersCompleter implements Completer {
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
// buffer could be null
checkNotNull(candidates);
if (buffer == null) {
Server.getInstance().getOnlinePlayers().values().forEach((p) -> candidates.add(p.getName()));
} else {
// We are auto completing player names, so 99% of the times we are doing this, it will be something like
// "say John*TAB*"
// however the buffer will be "say John", but we don't want that, the buffer must be the player's name
String[] split = buffer.split(" ");
buffer = split[split.length - 1]; // So we split and get the last value
split[split.length - 1] = ""; // And now clear the last value
String cmd = String.join(" ", split);
SortedSet<String> names = new TreeSet<String>();
Server.getInstance().getOnlinePlayers().values().forEach((p) -> names.add(p.getName()));
for (String match : names) {
if (!match.toLowerCase().startsWith(buffer.toLowerCase())) {
continue;
}
candidates.add(cmd + match);
}
}
return candidates.isEmpty() ? -1 : 0;
}
}
| 1,586 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
JsonUtil.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/timings/JsonUtil.java | package cn.nukkit.timings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.*;
import java.util.function.Function;
/**
* @author Tee7even
* <p>
* Various methods for more compact JSON object constructing
*/
@SuppressWarnings("unchecked")
public class JsonUtil {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static JsonArray toArray(Object... objects) {
List array = new ArrayList();
Collections.addAll(array, objects);
return GSON.toJsonTree(array).getAsJsonArray();
}
public static JsonObject toObject(Object object) {
return GSON.toJsonTree(object).getAsJsonObject();
}
public static <E> JsonObject mapToObject(Iterable<E> collection, Function<E, JSONPair> mapper) {
Map object = new LinkedHashMap();
for (E e : collection) {
JSONPair pair = mapper.apply(e);
if (pair != null) {
object.put(pair.key, pair.value);
}
}
return GSON.toJsonTree(object).getAsJsonObject();
}
public static <E> JsonArray mapToArray(E[] elements, Function<E, Object> mapper) {
ArrayList array = new ArrayList();
Collections.addAll(array, elements);
return mapToArray(array, mapper);
}
public static <E> JsonArray mapToArray(Iterable<E> collection, Function<E, Object> mapper) {
List array = new ArrayList();
for (E e : collection) {
Object obj = mapper.apply(e);
if (obj != null) {
array.add(obj);
}
}
return GSON.toJsonTree(array).getAsJsonArray();
}
public static class JSONPair {
public final String key;
public final Object value;
public JSONPair(String key, Object value) {
this.key = key;
this.value = value;
}
public JSONPair(int key, Object value) {
this.key = String.valueOf(key);
this.value = value;
}
}
}
| 2,141 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LevelTimings.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/timings/LevelTimings.java | package cn.nukkit.timings;
import cn.nukkit.level.Level;
import co.aikar.timings.Timing;
import co.aikar.timings.TimingsManager;
/**
* @author Pub4Game
* @author Tee7even
*/
public class LevelTimings {
public final Timing doChunkUnload;
public final Timing doTickPending;
public final Timing doChunkGC;
public final Timing doTick;
public final Timing tickChunks;
public final Timing entityTick;
public final Timing blockEntityTick;
public final Timing syncChunkSendTimer;
public final Timing syncChunkSendPrepareTimer;
public final Timing syncChunkLoadTimer;
public final Timing syncChunkLoadDataTimer;
public final Timing syncChunkLoadEntitiesTimer;
public final Timing syncChunkLoadBlockEntitiesTimer;
public LevelTimings(Level level) {
String name = level.getFolderName() + " - ";
this.doChunkUnload = TimingsManager.getTiming(name + "doChunkUnload");
this.doTickPending = TimingsManager.getTiming(name + "doTickPending");
this.doChunkGC = TimingsManager.getTiming(name + "doChunkGC");
this.doTick = TimingsManager.getTiming(name + "doTick");
this.tickChunks = TimingsManager.getTiming(name + "tickChunks");
this.entityTick = TimingsManager.getTiming(name + "entityTick");
this.blockEntityTick = TimingsManager.getTiming(name + "blockEntityTick");
this.syncChunkSendTimer = TimingsManager.getTiming(name + "syncChunkSend");
this.syncChunkSendPrepareTimer = TimingsManager.getTiming(name + "syncChunkSendPrepare");
this.syncChunkLoadTimer = TimingsManager.getTiming(name + "syncChunkLoad");
this.syncChunkLoadDataTimer = TimingsManager.getTiming(name + "syncChunkLoad - Data");
this.syncChunkLoadEntitiesTimer = TimingsManager.getTiming(name + "syncChunkLoad - Entities");
this.syncChunkLoadBlockEntitiesTimer = TimingsManager.getTiming(name + "syncChunkLoad - BlockEntities");
}
}
| 1,967 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
CacheEncapsulatedPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/network/CacheEncapsulatedPacket.java | package cn.nukkit.network;
import cn.nukkit.raknet.protocol.EncapsulatedPacket;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class CacheEncapsulatedPacket extends EncapsulatedPacket {
private byte[] internalData = null;
@Override
public byte[] toBinary() {
return this.toBinary(false);
}
@Override
public byte[] toBinary(boolean internal) {
if (this.internalData == null) {
this.internalData = super.toBinary(internal);
}
return this.internalData;
}
}
| 540 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
AdvancedSourceInterface.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/network/AdvancedSourceInterface.java | package cn.nukkit.network;
/**
* author: MagicDroidX
* Nukkit Project
*/
public interface AdvancedSourceInterface extends SourceInterface {
void blockAddress(String address);
void blockAddress(String address, int timeout);
void unblockAddress(String address);
void setNetwork(Network network);
void sendRawPacket(String address, int port, byte[] payload);
}
| 387 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.