Merge pull request #1 from gameherobrine2/0.9.5

rebase
This commit is contained in:
GameHerobrine 2023-12-10 00:23:32 +03:00 • committed by GitHub
commit 0c367a1558
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
86 changed files with 2365 additions and 662 deletions

View file

@ -13,13 +13,10 @@ You should not use it now.
<h3> Download Stable NostalgiaCore</h3>
https://github.com/kotyaralih/NostalgiaCore/releases/
<h3> PHP binaries download</h3>
* https://sourceforge.net/projects/pocketmine/files/builds/ - PHP for old PocketMine
* https://owouwu.ru/NCArm_bin.tar.gz - PHP binaries for ARM
* https://jenkins.pmmp.io/job/PHP-8.0-Aggregate/ PHP8(core should have php8 support as of now)
* https://github.com/pmmp/PHP-Binaries/releases/tag/php-8.0-latest PHP8 (Use PM4 version)
* https://github.com/DaisukeDaisuke/AndroidPHP/releases/tag/8.0.28 PHP8 for ARMv8
<h3> How to use auto-restart?</h3>
Simply start your server using ./start.sh -l

View file

@ -81,7 +81,9 @@ class BlockAPI{
[ICE, 0],
[SNOW_BLOCK, 0],
[BROWN_MUSHROOM_BLOCK, 0],
[RED_MUSHROOM_BLOCK, 0],
[BROWN_MUSHROOM_BLOCK, 14],
[BROWN_MUSHROOM_BLOCK, 15],
[RED_MUSHROOM_BLOCK, 14],
[MYCELIUM, 0],
[PODZOL, 0],
[STAINED_CLAY, 0],
@ -268,8 +270,13 @@ class BlockAPI{
[DYE, 11],
[DYE, 10],
[DYE, 9],
[DYE, 8]
[DYE, 8],
[DOUBLE_PLANT, 0],
[DOUBLE_PLANT, 1],
[DOUBLE_PLANT, 2],
[DOUBLE_PLANT, 3],
[DOUBLE_PLANT, 4],
[DOUBLE_PLANT, 5],
];
private $server;
private $scheduledUpdates = [];

View file

@ -275,6 +275,9 @@ class ConsoleAPI{
public static function debug($msg){
console("[DEBUG] ".$msg, true, true, 2);
}
public static function notice($msg){
console("[NOTICE] ".$msg);
}
public static function info($msg){
console("[INFO] ".$msg);
}

View file

@ -262,9 +262,9 @@ class EntityAPI{
"y" => $pos->y + 0.19,
"z" => $pos->z + mt_rand(-10, 10) / 50,
"level" => $pos->level,
"speedX" => Utils::randomFloat() * 0.2 - 0.1,
"speedX" => lcg_value() * 0.2 - 0.1,
"speedY" => 0.2,
"speedZ" => Utils::randomFloat() * 0.2 - 0.1,
"speedZ" => lcg_value() * 0.2 - 0.1,
"item" => $item,
];
if($this->server->api->handle("item.drop", $data) !== false){

View file

@ -6,7 +6,9 @@ class LevelAPI{
*/
public $levels;
private $server, $default;
public static $defaultLevelType = "DEFAULT";
public function __construct(){
$this->server = ServerAPI::request();
$this->levels = [];
@ -118,7 +120,17 @@ class LevelAPI{
}
return true;
}
public static function createGenerator($type, $options = []){
return match($type){
"FLAT" => new SuperflatGenerator(),
"EXPERIMENTAL" => new ExperimentalGenerator($options),
"HELL", "NETHER" => new HellGenerator($options),
"END" => new EndGenerator($options),
default => new NormalGenerator($options)
};
}
public function generateLevel($name, $seed = false, $generator = false){
if($this->levelExists($name)){
return false;
@ -132,24 +144,7 @@ class LevelAPI{
$generator = new $generator($options);
}else{
$type = strtoupper($this->server->api->getProperty("level-type"));
switch($type){
case "FLAT":
$generator = new SuperflatGenerator($options);
break;
case "EXPERIMENTAL":
$generator = new ExperimentalGenerator($options);
break;
case "HELL":
case "NETHER":
$generator = new HellGenerator($options);
break;
case "END":
$generator = new EndGenerator($options);
break;
default:
$generator = new NormalGenerator($options);
break;
}
$generator = $this->createGenerator($type, $options);
}
$gen = new WorldGenerator($generator, $name, $seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)) : (int) $seed);
$gen->generate();

View file

@ -138,10 +138,12 @@ class ServerAPI{
"enable-rcon" => false,
"rcon.password" => substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10),
"auto-save" => true,
"chunk-send-delay-ticks" => 5,
]);
Biome::init();
$this->parseProperties();
MobSpawner::$MOB_LIMIT = $this->getProperty("mobs-amount", 50);
LevelAPI::$defaultLevelType = $this->getProperty("level-type");
//Load advanced properties
define("DEBUG", $this->getProperty("debug", 1));
define("ADVANCED_CACHE", $this->getProperty("enable-advanced-cache", false));
@ -151,6 +153,7 @@ class ServerAPI{
}
MobSpawner::$spawnAnimals = $this->getProperty("spawn-animals");
MobSpawner::$spawnMobs = $this->getProperty("spawn-mobs");
PocketMinecraftServer::$chukSendDelay = $this->getProperty("chunk-send-delay-ticks");
if($this->getProperty("upnp-forwarding") == true){
console("[INFO] [UPnP] Trying to port forward...");
UPnP_PortForward($this->getProperty("server-port"));

View file

@ -49,11 +49,11 @@ class Player{
private $ip;
private $port;
private $counter = [0, 0, 0, 0];
private $username;
private $iusername;
public $username;
public $iusername;
private $eid = false;
private $startAction = false;
private $isSleeping = false;
public $isSleeping = false;
private $chunksOrder = [];
private $lastMeasure = 0;
private $bandwidthRaw = 0;
@ -68,6 +68,10 @@ class Player{
private $chunkCount = [];
private $received = [];
public $cratingItems;
public $sleepingTime = 0;
public $blockSendQueue;
public $blockSendQueueLength = 0;
/**
* @param integer $clientID
* @param string $ip
@ -94,7 +98,9 @@ class Player{
$this->packetStats = [0, 0];
$this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->buffer->data = [];
$this->server->schedule(2, [$this, "handlePacketQueues"], [], true);
$this->blockSendQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->blockSendQueue->data = [];
$this->server->schedule(1, [$this, "handlePacketQueues"], [], true);
$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true);
$this->evid[] = $this->server->event("server.close", [$this, "close"]);
console("[DEBUG] New Session started with " . $ip . ":" . $port . ". MTU " . $this->MTU . ", Client ID " . $this->clientID, true, true, 2);
@ -130,7 +136,7 @@ class Player{
$this->entity->updateMetadata();
}
$this->setSpawn($pos);
$this->server->schedule(60, [$this, "checkSleep"]);
return true;
}
@ -245,7 +251,23 @@ class Player{
$pk->teleport = true;
$this->dataPacket($pk);
}
public function addToBlockSendQueue(RakNetDataPacket $packet){
if($this->connected === false) return false;
$packet->encode();
$len = strlen($packet->buffer) + 1;
$MTU = $this->MTU - 24;
if(($this->blockSendQueueLength + $len) >= $MTU){
$this->sendBlockUpdateQueue();
}
$packet->messageIndex = $this->counter[3]++;
$packet->reliability = 2;
@$this->blockSendQueue->data[] = $packet;
$this->blockSendQueueLength += 6 + $len;
}
/**
* @param integer $id
* @param array $data
@ -321,7 +343,17 @@ class Player{
$this->bandwidthRaw += $this->server->send($packet);
}
}
public function sendBlockUpdateQueue(){
if($this->blockSendQueueLength > 0 and $this->blockSendQueue instanceof RakNetPacket){
$this->blockSendQueue->seqNumber = $this->counter[0]++;
$this->send($this->blockSendQueue);
}
$this->blockSendQueueLength = 0;
$this->blockSendQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->blockSendQueue->data = [];
}
public function sendBuffer(){
if($this->bufferLen > 0 and $this->buffer instanceof RakNetPacket){
$this->buffer->seqNumber = $this->counter[0]++;
@ -330,7 +362,7 @@ class Player{
$this->bufferLen = 0;
$this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->buffer->data = [];
$this->nextBuffer = microtime(true) + 0.1;
$this->nextBuffer = microtime(true) + 0.05;
}
/**
@ -459,7 +491,7 @@ class Player{
}
}
$tiles = $this->server->query("SELECT ID FROM tiles WHERE spawnable = 1 AND level = '" . $this->level->getName() . "' AND x >= " . (($X << 4) - 1) . " AND x < " . (($X << 4) + 17) . " AND z >= " . (($Z << 4) - 1) . " AND z < " . (($Z << 4) + 17) . ";");
/*$tiles = $this->server->query("SELECT ID FROM tiles WHERE spawnable = 1 AND level = '" . $this->level->getName() . "' AND x >= " . (($X << 4) - 1) . " AND x < " . (($X << 4) + 17) . " AND z >= " . (($Z << 4) - 1) . " AND z < " . (($Z << 4) + 17) . ";");
$this->lastChunk = false;
if($tiles !== false and $tiles !== true){
while(($tile = $tiles->fetchArray(SQLITE3_ASSOC)) !== false){
@ -468,8 +500,8 @@ class Player{
$tile->spawn($this);
}
}
}
$this->stopUsingChunk($X, $Z); //just in case
}*/
//$this->stopUsingChunk($X, $Z); //just in case
$pk = new FullChunkDataPacket;
$pk->chunkX = $X;
$pk->chunkZ = $Z;
@ -479,13 +511,18 @@ class Player{
return false;
}
}
public $chunkTicker = 0;
public function entityTick(){
//ConsoleAPI::debug("{$this->username}, cl: ".count($this->chunksLoaded).", oc: ".count($this->chunksOrder));
if(count($this->chunksOrder) <= 0 && $this->level->generatorType != 0){
$this->orderChunks();
}
$this->getNextChunk($this->level);
if($this->isSleeping) ++$this->sleepingTime;
if($this->chunkTicker++ > PocketMinecraftServer::$chukSendDelay){
$this->getNextChunk($this->level);
$this->chunkTicker = 0;
}
}
public function getNextChunk($world){
@ -502,7 +539,7 @@ class Player{
}
}
if(is_array($this->lastChunk)){
/*if(is_array($this->lastChunk)){
$tiles = $this->server->query("SELECT ID FROM tiles WHERE spawnable = 1 AND level = '" . $this->level->getName() . "' AND x >= " . ($this->lastChunk[0] - 1) . " AND x < " . ($this->lastChunk[0] + 17) . " AND z >= " . ($this->lastChunk[1] - 1) . " AND z < " . ($this->lastChunk[1] + 17) . ";");
$this->lastChunk = false;
if($tiles !== false and $tiles !== true){
@ -513,7 +550,7 @@ class Player{
}
}
}
}
}*/
$c = key($this->chunksOrder);
$d = $c != null ? $this->chunksOrder[$c] : null;
@ -531,6 +568,7 @@ class Player{
$z = $Z << 4;
$this->level->useChunk($X, $Z, $this);
$this->chunksLoaded["$X:$Z"] = true;
$pk = new FullChunkDataPacket;
$pk->chunkX = $X;
$pk->chunkZ = $Z;
@ -603,22 +641,6 @@ class Player{
$this->dataPacket($pk);
}
public function checkSleep(){
if($this->isSleeping !== false){
if($this->server->api->time->getPhase($this->level) === "night"){
foreach($this->server->api->player->getAll($this->level) as $p){
if($p->isSleeping === false){
return false;
}
}
$this->server->api->time->set("day", $this->level);
foreach($this->server->api->player->getAll($this->level) as $p){
$p->stopSleep();
}
}
}
}
/**
* @param $type
* @param $damage
@ -788,9 +810,6 @@ class Player{
$pk = new SetEntityMotionPacket; //TODO one packet for all entities if possible
$pk->entities = [[$data->eid, $data->speedX, $data->speedY, $data->speedZ]];
$this->dataPacket($pk);
$data->lastSpeedZ = $data->speedZ;
$data->lastSpeedY = $data->speedY;
$data->lastSpeedX = $data->speedX;
break;
case "entity.animate":
@ -1113,16 +1132,6 @@ class Player{
if(isset($this->received[$p->messageIndex])){
continue;
}
switch($p->pid()){
case 0x01:
case ProtocolInfo::PING_PACKET:
case ProtocolInfo::PONG_PACKET:
case ProtocolInfo::MOVE_PLAYER_PACKET:
case ProtocolInfo::REQUEST_CHUNK_PACKET:
case ProtocolInfo::ANIMATE_PACKET:
case ProtocolInfo::SET_HEALTH_PACKET:
break;
}
}
$this->received[$p->messageIndex] = true;
}
@ -1532,9 +1541,11 @@ class Player{
$this->spawned = true;
$this->server->handle("player.spawn", $this);
$this->server->api->chat->broadcast($this->username." joined the game");
//console("Current position: {$this->entity}");
$this->server->api->player->spawnAllPlayers($this);
$this->server->api->player->spawnToAllPlayers($this);
}
if($this->isSleeping) break;
if(($this->entity instanceof Entity) and $packet->messageIndex > $this->lastMovement){
$this->lastMovement = $packet->messageIndex;
$newPos = new Vector3($packet->x, $packet->y, $packet->z);
@ -1542,15 +1553,18 @@ class Player{
if($this->forceMovement->distance($newPos) <= 0.7){
$this->forceMovement = false;
}else{
//console("force");
$this->teleport($this->forceMovement, $this->entity->yaw, $this->entity->pitch, false);
}
}
$speed = $this->entity->getSpeedMeasure();
if($this->blocked === true or ($this->server->api->getProperty("allow-flight") !== true and (($speed > 9 and ($this->gamemode & 0x01) === 0x00) or $speed > 20 or $this->entity->distance($newPos) > 7)) or $this->server->api->handle("player.move", $this->entity) === false){
if($this->lastCorrect instanceof Vector3){
//console("last");
$this->teleport($this->lastCorrect, $this->entity->yaw, $this->entity->pitch, false);
}
}else{
//console("New Pos: $newPos");
$this->entity->setPosition($newPos, $packet->yaw, $packet->pitch);
}
$this->entity->updateAABB();
@ -1627,10 +1641,7 @@ class Player{
//$this->lastChunk = [$packet->chunkX, $packet->chunkZ];
break;
case ProtocolInfo::UPDATE_BLOCK_PACKET:
if($this->gamemode & 0x01 === 0){
$this->level->setBlock(new Vector3($packet->x, $packet->y, $packet->z), BlockAPI::get($packet->block, $packet->meta));
}
$this->level->resendBlocksToPlayers[$this->CID]["{$packet->x}.{$packet->y}.{$packet->z}"] = true;
break;
case ProtocolInfo::USE_ITEM_PACKET:
if(!($this->entity instanceof Entity)){
@ -2216,6 +2227,7 @@ class Player{
public function stopSleep(){
$this->isSleeping = false;
$this->sleepingTime = 0;
if($this->entity instanceof Entity){
$this->entity->updateMetadata();
}

View file

@ -1,7 +1,7 @@
<?php
class PocketMinecraftServer{
public static $chukSendDelay = 5;
public $tCnt, $ticks;
public $extraprops, $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $clients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled;
/**
@ -33,6 +33,8 @@ class PocketMinecraftServer{
console("[INFO] Starting Minecraft PE server on " . ($this->serverip === "0.0.0.0" ? "*" : $this->serverip) . ":" . $this->port);
EntityRegistry::registerEntities();
Structures::initialize();
Feature::init();
StaticBlock::init();
define("BOOTUP_RANDOM", Utils::getRandomBytes(16));
$this->serverID = $this->serverID === false ? Utils::readLong(substr(Utils::getUniqueID(true, $this->serverip . $this->port), 8)) : $this->serverID;
$this->seed = $this->seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)) : $this->seed;
@ -86,8 +88,8 @@ class PocketMinecraftServer{
"discord-bot-name" => "NostalgiaCore Logger",
"despawn-mobs" => true,
"mob-despawn-ticks" => 18000,
]);
Living::$despawnMobs = $this->extraprops->get("despawn-mobs");
Living::$despawnTimer = $this->extraprops->get("mob-despawn-ticks");
Entity::$allowedAI = $this->extraprops->get("enable-mob-ai");
@ -225,7 +227,7 @@ class PocketMinecraftServer{
"url" => $url,
"data" => [
"username" => $name,
"content" => $this->extraprops->get("discord-ru-smiles") ? str_replace("@", " ", str_replace("Ы", "<:imp_cool:1151085500396998719>", str_replace("Ь", "<:imp_badphp5:1151085478410457120>", str_replace("Ъ", "<:imp_gudjava:1151085431962742784>", str_replace("Ё", "<:imp_wut:1151085524241621012>", $msg))))) : str_replace("@", "", $msg)
"content" => $this->extraprops->get("discord-ru-smiles") ? str_replace("@", " ", str_replace("<EFBFBD>", "<:imp_cool:1151085500396998719>", str_replace("<EFBFBD>", "<:imp_badphp5:1151085478410457120>", str_replace("<EFBFBD>", "<:imp_gudjava:1151085431962742784>", str_replace("<EFBFBD>", "<:imp_wut:1151085524241621012>", $msg))))) : str_replace("@", "", $msg)
],
], null);
}

View file

@ -86,6 +86,7 @@ define("BLACK_WOOL", "35:15");
define("DANDELION", 37);
define("YELLOW_FLOWER", 37);
define("ROSE", 38);
define("MULTIFLOWER", 38);
define("CYAN_FLOWER", 38); //NO
define("RED_FLOWER", 38);
define("BLUE_ORCHID", "38:1");
@ -111,6 +112,7 @@ define("BRICKS_BLOCK", 45);
define("TNT", 46);
define("BOOKSHELF", 47);
define("MOSS_STONE", 48);
define("MOSSY_COBBLESTONE", 48);
define("MOSSY_STONE", 48);
define("OBSIDIAN", 49);
define("TORCH", 50);

View file

@ -22,4 +22,12 @@ define("BLOCK_UPDATE_NORMAL", 1);
define("BLOCK_UPDATE_RANDOM", 2);
define("BLOCK_UPDATE_SCHEDULED", 3);
define("BLOCK_UPDATE_WEAK", 4);
define("BLOCK_UPDATE_TOUCH", 5);
define("BLOCK_UPDATE_TOUCH", 5);
//Block Sides
define("SIDE_DOWN", 0);
define("SIDE_UP", 1);
define("SIDE_ZNEG", 2);
define("SIDE_ZPOS", 3);
define("SIDE_XNEG", 4);
define("SIDE_XPOS", 5);

View file

@ -22,6 +22,8 @@ if(version_compare("8.0.0", PHP_VERSION) > 0){
++$errors;
}
define("USE_NATIVE_RANDOM", version_compare("8.2.0", PHP_VERSION) <= 0);
if(php_sapi_name() !== "cli"){
console("[ERROR] You must run NostalgiaCore using the CLI.", true, true, 0);
++$errors;
@ -123,7 +125,11 @@ require_once(FILE_PATH . "/src/material/item/base/ItemSword.php");
require_once(FILE_PATH . "/src/material/item/armor/ArmorItem.php");
require_once(FILE_PATH . "/src/structure/Structure.php");
require_once(FILE_PATH . "/src/world/generator/Populator.php");
require_once(FILE_PATH . "/src/world/generator/LevelGenerator.php");
require_once(FILE_PATH . "/src/world/generator/structure/StructureBase.php");
require_once(FILE_PATH . "/src/world/generator/structure/StructureGenerator.php");
require_once(FILE_PATH . "/src/plugin/Plugin.php");
require_once(FILE_PATH . "/src/plugin/OtherPluginRequirement.php");
require_once(FILE_PATH . "/src/plugin/DummyPlugin.php");
@ -132,13 +138,23 @@ require_once(FILE_PATH . "/src/plugin/phar/PharUtils.php");
require_once(FILE_PATH . "/src/world/generator/LevelGenerator.php");
require_once(FILE_PATH . "/src/world/generator/NewLevelGenerator.php");
require_once(FILE_PATH . "/src/world/generator/biome/BiomeDecorator.php");
require_once(FILE_PATH . "/src/world/generator/biome/Biome.php");
require_once(FILE_PATH . "/src/world/generator/biome/BiomeSelector.php");
require_once(FILE_PATH . "/src/world/generator/biome/NormalGeneratorBiomeSelector.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeWithGrass.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeWithSand.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeWithSnow.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeExtremeHills.php");
require_once(FILE_PATH . "/src/world/generator/populator/TreePopulator.php");
require_all(FILE_PATH . "src/");

View file

@ -60,9 +60,9 @@ abstract class Animal extends Creature implements Ageable, Breedable{
public function spawnChild()
{
return $this->server->api->entity->add($this->level, $this->class, $this->type, [
"x" => $this->x + Utils::randomFloat() * mt_rand(-1, 1),
"x" => $this->x + lcg_value() * mt_rand(-1, 1),
"y" => $this->y,
"z" => $this->z + Utils::randomFloat() * mt_rand(-1, 1),
"z" => $this->z + lcg_value() * mt_rand(-1, 1),
"IsBaby" => true,
"Age" => -24000,
]);

View file

@ -5,6 +5,7 @@ class Entity extends Position
const TYPE = - 1;
const CLASS_TYPE = - 1;
const MIN_POSSIBLE_SPEED = 1/8000; //anything below will send 0 to player
public $counter = 0;
public $invincible, $status, $health, $fire, $crouched, $position, $meta, $stack;
@ -207,11 +208,11 @@ class Entity extends Position
}
public function isMovingHorizontally()
{
return ($this->speedX > 0.01 || $this->speedX < - 0.01) || ($this->speedZ > 0.01 || $this->speedZ < - 0.01);
return ($this->speedX >= self::MIN_POSSIBLE_SPEED || $this->speedX <= -self::MIN_POSSIBLE_SPEED) || ($this->speedZ >= self::MIN_POSSIBLE_SPEED || $this->speedZ <= -self::MIN_POSSIBLE_SPEED);
}
public function isMoving()
{
return $this->isMovingHorizontally() || ($this->speedY > 0.007 || $this->speedY < - 0.007);
return $this->isMovingHorizontally() || ($this->speedY > self::MIN_POSSIBLE_SPEED || $this->speedY < -self::MIN_POSSIBLE_SPEED);
}
public function setVelocity($vX, $vY = 0, $vZ = 0)
@ -407,8 +408,8 @@ class Entity extends Position
} else{
$hasUpdate = true;
}
if(($this->player instanceof Player) and ($this->player->gamemode & 0x01) === CREATIVE){ // Remove fire effects in next tick
$this->fire = 1;
if(($this->player instanceof Player) and ($this->player->gamemode & 0x01) === CREATIVE){
$this->fire = 0;
}
}
@ -418,20 +419,21 @@ class Entity extends Position
$endX = ceil($this->boundingBox->maxX);
$endY = ceil($this->boundingBox->maxY);
$endZ = ceil($this->boundingBox->maxZ);
for($i = 0; $i < 8; ++$i){
$x = ((($i >> 0) % 2) - 0.5) * $this->width * 0.8;
$y= ((($i >> 1) % 2) - 0.5) * 0.1;
$z = ((($i >> 2) % 2) - 0.5) * $this->width * 0.8;
if(!($this instanceof Painting) && !($this->isPlayer() && $this->player->isSleeping !== false)){
for($i = 0; $i < 8; ++$i){
$x = ((($i >> 0) % 2) - 0.5) * $this->width * 0.8;
$y= ((($i >> 1) % 2) - 0.5) * 0.1;
$z = ((($i >> 2) % 2) - 0.5) * $this->width * 0.8;
$blockX = floor($this->x + $x);
$blockY = floor($this->y + $this->getEyeHeight() + $y);
$blockZ = floor($this->z + $z);
$blockX = floor($this->x + $x);
$blockY = floor($this->y + $this->getEyeHeight() + $y);
$blockZ = floor($this->z + $z);
if($this->level->getBlockWithoutVector($blockX, $blockY, $blockZ)->isSolid){
$this->harm(1, "suffocation"); // Suffocation
$hasUpdate = true;
break;
if(StaticBlock::getIsSolid($this->level->level->getBlockID($blockX, $blockY, $blockZ))){
$this->harm(1, "suffocation"); // Suffocation
$hasUpdate = true;
break;
}
}
}
@ -570,15 +572,34 @@ class Entity extends Position
}
if(!$this->isPlayer()){
$update = false;
if(Utils::in_range($this->speedX, -0.01, 0.01)){
if($this->speedX > -self::MIN_POSSIBLE_SPEED && $this->speedX < self::MIN_POSSIBLE_SPEED){
$this->speedX = 0;
}
if(Utils::in_range($this->speedZ, -0.01, 0.01)){
if($this->speedZ > -self::MIN_POSSIBLE_SPEED && $this->speedZ < self::MIN_POSSIBLE_SPEED){
$this->speedZ = 0;
}
if(Utils::in_range($this->speedY, -0.007, 0.007)){
if($this->speedY > -self::MIN_POSSIBLE_SPEED && $this->speedY < self::MIN_POSSIBLE_SPEED){
$this->speedY = 0;
}
$horizontalMultiplyFactor = 0.91;
if($this->onGround){
$horizontalMultiplyFactor = 0.54;
$b = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minX) - 1, floor($this->z));
if($b > 0){
$horizontalMultiplyFactor = StaticBlock::getSlipperiness($b) * 0.91;
}
}
if($this->inWater){
$this->speedX *= 0.8;
$this->speedY *= 0.8;
$this->speedZ *= 0.8;
}else{
$this->speedX *= $horizontalMultiplyFactor;
$this->speedY *= 0.98;
$this->speedZ *= $horizontalMultiplyFactor;
}
$savedSpeedY = $this->speedY;
if($this->class === ENTITY_MOB || $this->class === ENTITY_ITEM || ($this->class === ENTITY_OBJECT && $this->type === OBJECT_PRIMEDTNT)){
$water = false;
@ -613,24 +634,7 @@ class Entity extends Position
}
$support = $savedSpeedY != $this->speedY && $savedSpeedY < 0;
$horizontalMultiplyFactor = 0.91;
if($support){
$horizontalMultiplyFactor = 0.54;
$b = $this->level->getBlockWithoutVector(floor($this->x), floor($this->boundingBox->minX) - 1, floor($this->z));
if($b instanceof Block){
$horizontalMultiplyFactor = $b->slipperiness * 0.91;
}
}
if($this->inWater){
$this->speedX *= 0.8;
$this->speedY *= 0.8;
$this->speedZ *= 0.8;
}else{
$this->speedX *= $horizontalMultiplyFactor;
$this->speedY *= 0.98;
$this->speedZ *= $horizontalMultiplyFactor;
}
if($this->speedX != 0){
$this->x += $this->speedX;
$update = true;
@ -669,7 +673,7 @@ class Entity extends Position
$this->onGround = $support;
if($this->hasGravity){
$this->speedY -= $this->inWater ? 0.02 : $this->gravity; // TODO: replace with $gravity
$this->speedY -= $this->inWater ? 0.02 : $this->gravity; // TODO: fix packet spam
$update = true;
} elseif($this->lastX != $this->x || $this->lastZ != $this->z || $this->lastY != $this->z){
// $this->speedX = 0;
@ -685,6 +689,9 @@ class Entity extends Position
$hasUpdate = true;
if(($this->server->ticks % 4 === 0 && $this->class === ENTITY_ITEM) || $this->class != ENTITY_ITEM){ //update item speed every 4 ticks
$this->server->api->handle("entity.motion", $this);
$this->lastSpeedZ = $this->speedZ;
$this->lastSpeedY = $this->speedY;
$this->lastSpeedX = $this->speedX;
}
}
} elseif($this->player instanceof Player){
@ -766,6 +773,7 @@ class Entity extends Position
$this->updateLast();
$players = $this->server->api->player->getAll($this->level);
if($this->player instanceof Player){
//console("gujnbguib");
unset($players[$this->player->CID]);
$pk = new MovePlayerPacket();
$pk->eid = $this->eid;
@ -831,7 +839,7 @@ class Entity extends Position
public function getDirection()
{
$rotation = ($this->yaw - 90) % 360;
$rotation = ((int)($this->yaw - 90)) % 360;
if($rotation < 0){
$rotation += 360.0;
}
@ -1236,8 +1244,8 @@ class Entity extends Position
if ($ret != false && $this->hasKnockback && is_numeric($cause) && ($entity = $this->server->api->entity->get($cause)) != false) {
$d = $entity->x - $this->x;
for ($d1 = $entity->z - $this->z; $d * $d + $d1 * $d1 < 0.0001; $d1 = (Utils::randomFloat() - Utils::randomFloat()) * 0.01) {
$d = (Utils::randomFloat() - Utils::randomFloat()) * 0.01;
for ($d1 = $entity->z - $this->z; $d * $d + $d1 * $d1 < 0.0001; $d1 = (lcg_value() - lcg_value()) * 0.01) {
$d = (lcg_value() - lcg_value()) * 0.01;
}
// attackedAtYaw = (float)((Math.atan2($d1, $d) * 180D) / 3.1415927410125732D) >
$this->knockBack($d, $d1);
@ -1384,6 +1392,7 @@ class Entity extends Position
}
public function makeDead($cause){
if($this->server->api->dhandle("entity.death", ["entity" => $this, "cause" => $cause]) === false) return false;
$this->spawnDrops();
$this->air = 200;
$this->fire = 0;

View file

@ -22,14 +22,17 @@ abstract class Living extends Entity implements Damageable, Pathfindable{
return $this->path != null;
}
public function __destruct()
{
parent::__destruct();
public function close(){
parent::close();
unset($this->pathFollower->entity);
unset($this->ai->entity);
unset($this->ai->mobController->entity);
unset($this->ai);
unset($this->parent);
}
public function update(){
if($this->closed) return;
if(!$this->dead && Entity::$allowedAI && $this->idleTime <= 0) {
$this->ai->updateTasks();
}

View file

@ -16,7 +16,7 @@ class TaskLookAround extends TaskBase
public function canBeExecuted(EntityAI $ai)
{
return !$ai->entity->inPanic && !$ai->entity->isMoving() && Utils::randomFloat() < 0.02 && !$ai->isStarted("TaskLookAtPlayer") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath(); /*Vanilla value*/
return !$ai->entity->inPanic && !$ai->entity->isMoving() && lcg_value() < 0.02 && !$ai->isStarted("TaskLookAtPlayer") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath(); /*Vanilla value*/
}
public function onUpdate(EntityAI $ai)

View file

@ -4,7 +4,7 @@ class TaskLookAtPlayer extends TaskBase{
public $target = false;
private $state, $yaw, $pitch;
public function canBeExecuted(EntityAI $ai){
return !$ai->entity->inPanic && Utils::randomFloat() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath();
return !$ai->entity->inPanic && lcg_value() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath();
}
protected function findTarget($e, $r){

View file

@ -18,7 +18,7 @@ class TaskSwimming extends TaskBase
$this->reset();
}
if(Utils::randomFloat() < 0.8){ #1.5.2 method
if(lcg_value() < 0.8){ #1.5.2 method
$ai->entity->speedY = 0.42;
}

View file

@ -37,7 +37,7 @@ class Sheep extends Animal{
$pk->event = EntityEventPacket::ENTITY_ANIM_10;
$this->server->api->player->broadcastPacket($this->level->players, $pk);
$this->server->schedule(38, [$this, "setSheared"], false);
$this->level->setblock(new Position($this->x, $this->y-1, $this->z, $this->level), new DirtBlock());
$this->level->setBlock(new Position($this->x, $this->y-1, $this->z, $this->level), new DirtBlock());
}
public function setSheared($v = null){

View file

@ -15,11 +15,8 @@ class Minecart extends Vehicle{
$this->z = isset($this->data["TileZ"]) ? $this->data["TileZ"]:$this->z;
$this->setHealth(3, "generic");
//$this->setName((isset($objects[$this->type]) ? $objects[$this->type]:$this->type));
$this->width = 1;
/*$this->moveVector[Entity::NORTH] = new Vector3(-1, 0, 0);
$this->moveVector[Entity::SOUTH] = new Vector3(1, 0, 0);
$this->moveVector[Entity::EAST] = new Vector3(0, 0, -1);
$this->moveVector[Entity::WEST] = new Vector3(0, 0, 1);*/
$this->width = 0.98;
$this->height = 0.7;
$this->update();
}

View file

@ -10,7 +10,15 @@ if(!function_exists("cli_set_process_title")){
}
}
}
function copydir($src, $dest){
if(!is_dir($dest)) mkdir($dest);
foreach(scandir($src) as $f){
if($f != "." && $f != ".."){
if(is_dir("$src/$f")) copydir("$src/$f", "$dest/$f");
else copy("$src/$f", "$dest/$f");
}
}
}
function dummy(){
}

View file

@ -143,14 +143,15 @@ abstract class Block extends Position{
LEAVES2 => "Leaves2Block",
END_PORTAL_FRAME => "EndPortalFrameBlock",
COCOA => "CocoaBlock",
RED_MUSHROOM_BLOCK => "RedMushroomBlock",
BROWN_MUSHROOM_BLOCK => "BrownMushroomBlock",
RED_MUSHROOM_BLOCK => "RedMushroomSolidBlock",
BROWN_MUSHROOM_BLOCK => "BrownMushroomSolidBlock",
MONSTER_SPAWNER => "MonsterSpawnerBlock",
VINES => "VinesBlock",
MYCELIUM => "MyceliumBlock",
PODZOL => "PodzolBlock",
STAINED_CLAY => "StainedClayBlock",
LILY_PAD => "LilypadBlock",
DOUBLE_PLANT => "DoubleTallGrass",
SPRUCE_FENCE_GATE => "SpruceFenceGateBlock",
BIRCH_FENCE_GATE => "BirchFenceGateBlock",
JUNGLE_FENCE_GATE => "JungleFenceGateBlock",

View file

@ -61,7 +61,7 @@ class NetherReactorBlock extends SolidBlock{
for($a = $aOne; $a < $aTwo; $a += $aThree) { //wth those cycles are? TODO simplify if possible(makes server lag)
for($b = $bOne; $b < $bTwo; $b += $bThree) {
for($c = $cOne; $c < $cTwo; $c += $cThree) {
if ($this->level->getBlock(new Vector3($x+$a, $y+$b, $z+$c))->getID() === 87 && Utils::randomFloat() > 0.75){
if ($this->level->getBlock(new Vector3($x+$a, $y+$b, $z+$c))->getID() === 87 && lcg_value() > 0.75){
$this->level->setBlock(new Vector3($x+$a, $y+$b, $z+$c), new AirBlock());
}
}
@ -91,23 +91,23 @@ class NetherReactorBlock extends SolidBlock{
$forceAmount = $data[3];
$server = ServerAPI::request();
if(!$forceAmount){
$spawnNumber = $minAmount + floor(Utils::randomFloat()*($maxAmount-$minAmount+1));
$spawnNumber = $minAmount + floor(lcg_value()*($maxAmount-$minAmount+1));
}
else{
$spawnNumber = $maxAmount;
}
for($i = 0; $i < $spawnNumber; $i++) {
$randomRange = floor(Utils::randomFloat()*5+3);
$shiftX = cos(floor(Utils::randomFloat()*360)*(pi()/180));
$shiftZ = sin(floor(Utils::randomFloat()*360)*(pi()/180));
$randomRange = floor(lcg_value()*5+3);
$shiftX = cos(floor(lcg_value()*360)*(pi()/180));
$shiftZ = sin(floor(lcg_value()*360)*(pi()/180));
if(Utils::chance(5)) $randomID = $this->rarePossibleLoot[array_rand($this->rarePossibleLoot)];
else $randomID = $this->possibleLoot[array_rand($this->possibleLoot)];
$server->api->entity->drop(new Position($x+($shiftX*$randomRange)+0.5, $y, $z+($shiftZ*$randomRange)+0.5, $this->level), BlockAPI::getItem($randomID, 0, 1));
}
for($i = 0; $i < $pigmen; $i++) {
$randomRange = floor(Utils::randomFloat()*5+3);
$shiftX = cos(floor(Utils::randomFloat()*360)*(pi()/180));
$shiftZ = sin(floor(Utils::randomFloat()*360)*(pi()/180));
$randomRange = floor(lcg_value()*5+3);
$shiftX = cos(floor(lcg_value()*360)*(pi()/180));
$shiftZ = sin(floor(lcg_value()*360)*(pi()/180));
$data = array(
"x" => $x+($shiftX*$randomRange)+0.5,
"y" => $y,

View file

@ -1,31 +1,11 @@
<?php
class PoweredRailBlock extends FlowableBlock{
require_once("RailBaseBlock.php");
class PoweredRailBlock extends RailBaseBlock{
public function __construct($meta = 0){
parent::__construct(POWERED_RAIL, 0, "PoweredRailBlock");
$this->hardness = 0.7;
$this->isFullBlock = false;
$this->isSolid = true;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$down = $this->getSide(0);
if($down->getID() !== AIR and $down instanceof SolidBlock){
$this->level->setBlock($block, $this, true, false, true);
return true;
}
return false;
}
public function onUpdate($type){
if($type === BLOCK_UPDATE_NORMAL){
if($this->getSide(0)->getID() === AIR){ //Replace with common break method
ServerAPI::request()->api->entity->drop($this, BlockAPI::getItem($this->id, $this->meta, 1));
$this->level->setBlock($this, new AirBlock(), true, false, true);
return BLOCK_UPDATE_NORMAL;
}
}
return false;
$this->isFullBlock = false;
$this->isSolid = false;
}
}

View file

@ -0,0 +1,56 @@
<?php
abstract class RailBaseBlock extends FlowableBlock //TODO move some methods here
{
public static function isRailBlock(Level $l, $x, $y, $z){
$id = $l->level->getBlockID($x, $y, $z);
return $id === POWERED_RAIL || $id === RAIL;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$down = $this->getSide(0);
if($down->getID() !== AIR and $down instanceof SolidBlock){
$this->level->setBlock($block, $this, true, false, true);
$logic = new RailLogic($this);
$logic->place(false, true);
return true;
}
return false;
}
public function updateState(){}
public function onUpdate($type){
if($type === BLOCK_UPDATE_NORMAL){
$meta = $this->getMetadata();
if($this->id === POWERED_RAIL){
$meta &= 7;
}
$x = $this->x;
$y = $this->y;
$z = $this->z;
if(
($this->level->level->getBlockID($x, $y - 1, $z) == 0) ||
(($meta == 2) && $this->level->level->getBlockID($x + 1, $y, $z) == 0) ||
(($meta == 3) && $this->level->level->getBlockID($x - 1, $y, $z) == 0) ||
(($meta == 4) && $this->level->level->getBlockID($x, $y, $z - 1) == 0) ||
(($meta == 5) && $this->level->level->getBlockID($x, $y, $z + 1) == 0)
){
$this->level->setBlock($this, new AirBlock(), true, false, true);
ServerAPI::request()->api->entity->drop($this, BlockAPI::getItem($this->id, $this->meta, 1));
}else{
$this->updateState();
}
//if($this->getSide(0)->getID() === AIR){//Replace with common break method
// ServerAPI::request()->api->entity->drop($this, BlockAPI::getItem($this->id, $this->meta, 1));
// $this->level->setBlock($this, new AirBlock(), true, false, true);
//}
}
}
}

View file

@ -1,173 +1,21 @@
<?php
class RailBlock extends FlowableBlock{
require_once("RailBaseBlock.php");
class RailBlock extends RailBaseBlock{
public static $shouldconnectrails = true;
public function __construct($meta = 0){
parent::__construct(RAIL, $meta, "Rail");
$this->hardness = 0.7;
$this->isFullBlock = false;
$this->isFullBlock = false;
$this->isSolid = false;
}
public static $shouldconnectrails = false;
private function isRailBlock($id){
return $id === RAIL || $id === POWERED_RAIL;
}
private function isValidRailMeta($meta){
return !($meta < 0 || $meta > 10);
}
private function canConnectRail($block) {
if(!($block instanceof RailBlock)) return null;
if($this->distanceSquared($block) > 2) return null;
$result = $this->checkRail($this);
if(count($result) === 2) return null;
return $result;
}
private function checkRail($rail){//fixed
if(!($rail instanceof RailBlock)) return null;
$damage = $rail->meta;
if ($damage < 0 || $damage > 10) return null;
$delta = array( //TODO make static
array(array(0, 1), array(0, -1)),
array(array(1, 0), array(-1, 0)),
array(array(1, 0), array(-1, 0)),
array(array(1, 0), array(-1, 0)),
array(array(0, 1), array(0, -1)),
array(array(0, 1), array(0, -1)),
array(array(1, 0), array(0, 1)),
array(array(0, 1), array(-1, 0)),
array(array(-1, 0), array(0, -1)),
array(array(0, -1), array(1, 0))
);
$deltaY = array(0, 1, -1);
$blocks = $delta[$damage];
$connected = array();
foreach($deltaY as $y){
$v3 = new Vector3(
$rail->getFloorX() + $blocks[0][0],
$rail->getFloorY() + $y,
$rail->getFloorZ() + $blocks[0][1]
);
$railBlock = $rail->level->getBlock($v3);
$idToConnect = $railBlock->getID();
$metaToConnect = $railBlock->getMetadata();
if (!$this->isRailBlock($idToConnect) || !$this->isValidRailMeta($metaToConnect)) continue;
$xDiff = $this->getFloorX() - $v3->getFloorX();
$zDiff = $this->getFloorZ() - $v3->getFloorZ();
foreach($blocks as $xz) {
if($xz[0] !== $xDiff || $xz[1] !== $zDiff) continue;
$connected[] = $v3;
}
}
foreach($deltaY as $y){
$v3 = new Vector3(
$rail->getFloorX() + $blocks[1][0],
$rail->getFloorY() + $y,
$rail->getFloorZ() + $blocks[1][1]
);
$railBlock = $rail->level->getBlock($v3);
$idToConnect = $railBlock->getID();
$metaToConnect = $railBlock->getMetadata();
if(!$this->isRailBlock($idToConnect) || !$this->isValidRailMeta($metaToConnect)) continue;
$xDiff = $this->getFloorX() - $v3->getFloorX();
$zDiff = $this->getFloorZ() - $v3->getFloorZ();
foreach($blocks as $xz){
if ($xz[0] !== $xDiff || $xz[1] !== $zDiff) continue;
$connected[] = $v3;
}
}
return $connected;
}
private function connectRail($rail){
$connected = $this->canConnectRail($rail);
if ($connected === null || count($connected) === 0) return;
if(count($connected) === 1){
$v3 = $connected[0]->subtract($this);
$this->meta = ($v3->y !== 1) ? ($v3->x === 0 ? 0 : 1) : (int) ($v3->z === 0 ? ($v3->x / -2) + 2.5 : ($v3->z / 2) + 4.5);
}elseif(count(connected) === 2){
$subtract = array(new Vector3(0, 0, 0),new Vector3(0, 0, 0));
for ($i = 0; $i < count($connected); $i++) {
$subtract[$i] = $connected[$i]->subtract($this);
}
if (abs($subtract[0]->x) === abs($subtract[1]->z) && abs($subtract[1]->x) === abs($subtract[0]->z)){
$v3 = $connected[0]->subtract($this)->add($connected[1]->subtract($this));
$this->meta = $v3->x === 1 ? ($v3->z === 1 ? 6 : 9) : ($v3->z === 1 ? 7 : 8);
}elseif ($subtract[0]->y === 1 || $subtract[1]->y === 1){
$v3 = $subtract[0]->y === 1 ? $subtract[0] : $subtract[1];
$this->meta = $v3->x === 0 ? ($v3->z === -1 ? 4 : 5) : ($v3->x === 1 ? 2 : 3);
}else{
$this->meta = $subtract[0]->x === 0 ? 0 : 1;
}
}
$this->level->setBlock($rail, new RailBlock($this->meta), true, true);
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$down = $this->getSide(0);
if($down->getID() !== AIR and $down instanceof SolidBlock){
//Rail connection(ported from nukkit)
if(RailBlock::$shouldconnectrails){
$arrayXZ = array(array(1, 0),array(0, 1),array(-1, 0),array(0, -1));
$arrayY = array(0, 1, -1);
$connected = array();
foreach($arrayXZ as $xz) {
$x = $xz[0];
$z = $xz[1];
foreach($arrayY as $y){
$v3c = new Vector3($x, $y, $z);
$v3 = $v3c->add($this);
$v3block = $this->level->getBlock($v3);
if ($v3block === null) continue;
if (!$this->isRailBlock($v3block->id) || !$this->isValidRailMeta($v3block->meta)) continue;
if (!($v3block instanceof RailBlock)) continue;
$this->connectRail($v3block);
array_push($connected, $v3block);
}
if(count($connected) >= 2) break;
}
if(count($connected) === 1) {
$v3 = $connected[0]->subtract($this);
$this->meta = ($v3->y !== 1) ? ($v3->x === 0 ? 0 : 1) : (int) ($v3->z === 0 ? ($v3->x / -2) + 2.5 : ($v3->z / 2) + 4.5);
}elseif(count($connected) === 2){
$subtract = array(new Vector3(0, 0, 0),new Vector3(0, 0, 0));
for($i = 0; $i < count($connected); $i++){
$subtract[$i] = $connected[$i]->subtract($this);
}
if(abs($subtract[0]->x) === abs($subtract[1]->z) && abs($subtract[1]->x) === abs($subtract[0]->z)) {
$v3 = $connected[0]->subtract($this)->add($connected[1]->subtract($this));
$this->meta = $v3->x === 1 ? ($v3->z === 1 ? 6 : 9) : ($v3->z === 1 ? 7 : 8);
}elseif($subtract[0]->y === 1 || $subtract[1]->y === 1) {
$v3 = $subtract[0]->y == 1 ? $subtract[0] : $subtract[1];
$this->meta = $v3->x === 0 ? ($v3->z === -1 ? 4 : 5) : ($v3->x === 1 ? 2 : 3);
}else{
$this->meta = $subtract[0]->x === 0 ? 0 : 1;
}
}
}
//End of Logic
$this->level->setBlock($block, $this, true, false, true);
return true;
}
return false;
}
public function onUpdate($type){
if($type === BLOCK_UPDATE_NORMAL){
if($this->getSide(0)->getID() === AIR){//Replace with common break method
ServerAPI::request()->api->entity->drop($this, BlockAPI::getItem($this->id, $this->meta, 1));
$this->level->setBlock($this, new AirBlock(), true, false, true);
return BLOCK_UPDATE_NORMAL;
}
}
return false;
public function updateState(){
//$logic = (new RailLogic($this));
//if($logic->countPotentialConnections() == 3){
// $logic->place(false, false);
//}
}
}

View file

@ -0,0 +1,44 @@
<?php
class DoubleTallGrass extends FlowableBlock
{
public static $NAMES = [
0 => "Sunflower",
1 => "Lilac",
2 => "Tall Grass",
3 => "Tall Fern",
4 => "Rose Bush",
5 => "Peony",
];
public function __construct($meta = 1){
parent::__construct(DOUBLE_PLANT, $meta, "Tall Grass");
$this->name = self::$NAMES[$this->meta] ?? "Tall Grass";
$this->hardness = 0;
}
public function onUpdate($type){
if($type === BLOCK_UPDATE_NORMAL){ //TODO destroy if 2nd block occupied
//if($this->meta & 0x8 == 0 && $this->getSide(0)->isTransparent === true){ //Replace with common break method
///$this->level->setBlock($this, new AirBlock(), false, false, true);
//return BLOCK_UPDATE_NORMAL;
//} //TODO fix
}
return false;
}
public function getDrops(Item $item, Player $player){ //TODO vanilla?
return [];
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$down = $this->getSide(0);
if($down->getID() == 2 or $down->getID() == 3){ //TODO destroy the block above(tested only in creative)
$this->level->setBlock($block, $this, true, false, true);
$this->level->setBlock($block->add(0, 1, 0), new DoubleTallGrass($this->meta ^ 0x8), true, false, true);
return true;
}
return false;
}
}

View file

@ -2,11 +2,11 @@
class TallGrassBlock extends FlowableBlock{
public function __construct($meta = 1){
parent::__construct(TALL_GRASS, $meta, "Tall Grass");
parent::__construct(TALL_GRASS, $meta, "Grass");
$this->isReplaceable = true;
$names = array(
0 => "Dead Shrub",
1 => "Tall Grass",
1 => "Grass",
2 => "Fern",
);
$this->name = $names[$this->meta & 0x02];
@ -15,7 +15,7 @@ class TallGrassBlock extends FlowableBlock{
public function onUpdate($type){
if($type === BLOCK_UPDATE_NORMAL){
if($this->getSide(0)->isTransparent === true){//Replace with common break method
if($this->getSide(0)->isTransparent === true){ //Replace with common break method
$this->level->setBlock($this, new AirBlock(), false, false, true);
if(Utils::chance(15)) ServerAPI::request()->api->entity->drop(new Position($this->x + 0.5, $this->y, $this->z + 0.5, $this->level), BlockAPI::getItem(WHEAT_SEEDS));
return BLOCK_UPDATE_NORMAL;

View file

@ -1,19 +0,0 @@
<?php
class BrownMushroomSolidBlock extends SolidBlock{
public function __construct($meta = 0){
parent::__construct(BROWN_MUSHROOM_BLOCK, $meta, "Mushroom");
$this->hardness = 0.2;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
//todo
$this->level->setBlock($this, $this, true, false, true);
}
public function getDrops(Item $item, Player $player){
return [
[BROWN_MUSHROOM, 0, mt_rand(0, 2)]
];
}
}

View file

@ -0,0 +1,14 @@
<?php
class BrownMushroomSolidBlock extends SolidBlock{
public function __construct($meta = 0){
parent::__construct(BROWN_MUSHROOM_BLOCK, $meta, "Mushroom");
}
public function getDrops(Item $item, Player $player){
return [
[BROWN_MUSHROOM, 0, mt_rand(0, 2)]
];
}
}

View file

@ -5,7 +5,16 @@ class MonsterSpawnerBlock extends SolidBlock{
parent::__construct(MONSTER_SPAWNER, $meta, "Monster Spawner");
$this->hardness = 5;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
parent::place($item, $player, $block, $target, $face, $fx, $fy, $fz);
ServerAPI::request()->api->tile->add($this->level, TILE_MOB_SPAWNER, $this->x, $this->y, $this->z, [
"EntityId" => 0,
"id" => TILE_MOB_SPAWNER,
"x" => $this->x,
"y" => $this->y,
"z" => $this->z,
]);
}
public function getDrops(Item $item, Player $player){
return [];
}

View file

@ -1,19 +0,0 @@
<?php
class RedMushroomSolidBlock extends SolidBlock{
public function __construct($meta = 0){
parent::__construct(RED_MUSHROOM_BLOCK, $meta, "Mushroom");
$this->hardness = 0.2;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
//todo
$this->level->setBlock($this, $this, true, false, true);
}
public function getDrops(Item $item, Player $player){
return [
[RED_MUSHROOM, 0, mt_rand(0, 2)]
];
}
}

View file

@ -0,0 +1,14 @@
<?php
class RedMushroomSolidBlock extends SolidBlock{
public function __construct($meta = 0){
parent::__construct(RED_MUSHROOM_BLOCK, $meta, "Mushroom");
}
public function getDrops(Item $item, Player $player){
return [
[RED_MUSHROOM, 0, mt_rand(0, 2)]
];
}
}

View file

@ -40,7 +40,7 @@ class StoneBlock extends SolidBlock{
public function getDrops(Item $item, Player $player){
if($item->getPickaxeLevel() >= 1){
return array(
array(COBBLESTONE, 0, 1),
array($this->meta == 0 ? COBBLESTONE : $this->id, $this->meta, 1),
);
}else{
return array();

View file

@ -12,10 +12,10 @@ class MinecartItem extends Item{
}
$server = ServerAPI::request();
$data = [
"x" => $target->getX(),
"y" => $target->getY() + 0.8,
"z" => $target->getZ(),
];
"x" => $target->getX() + 0.5,
"y" => $target->getY() + 0.8,
"z" => $target->getZ() + 0.5,
];
$e = $server->api->entity->add($level, ENTITY_OBJECT, OBJECT_MINECART, $data);
$server->api->entity->spawnToAll($e);
if(($player->gamemode & 0x01) === 0x00){

View file

@ -8,6 +8,18 @@ class SpawnEggItem extends Item{
}
public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if($target instanceof MonsterSpawnerBlock){
$tile = ServerAPI::request()->api->tile->get($target);
if($tile instanceof Tile){
$tile->data["EntityId"] = $this->meta;
//TODO update tile somehow
}else{
ConsoleAPI::warn("No tile was found at $target!");
}
return false;
}
$ageable = $this->meta === MOB_CHICKEN || $this->meta === MOB_COW || $this->meta === MOB_SHEEP || $this->meta === MOB_PIG;
$data = array(
"x" => $block->x + 0.5,

View file

@ -60,7 +60,7 @@ class AxisAlignedBB{
public function grow($x, $y, $z){
return new AxisAlignedBB($this->minX - $x, $this->minY - $y, $this->minZ - $z, $this->maxX + $x, $this->maxY + $y, $this->maxZ + $z);
}
public function expand($x, $y, $z){
$this->minX -= $x;
$this->minY -= $y;
@ -71,7 +71,8 @@ class AxisAlignedBB{
return $this;
}
public function offset($x, $y, $z){
$this->minX += $x;
$this->minY += $y;
@ -305,6 +306,28 @@ class AxisAlignedBB{
return MovingObjectPosition::fromBlock(0, 0, 0, $f, $vector);
}
public function expandTo(AxisAlignedBB $bb){
$this->minX = min($this->minX, $bb->minX);
$this->minY = min($this->minY, $bb->minY);
$this->minZ = min($this->minZ, $bb->minZ);
$this->maxX = max($this->maxX, $bb->maxX);
$this->maxY = max($this->maxY, $bb->maxY);
$this->maxZ = max($this->maxZ, $bb->maxZ);
}
public function getXSize(){
return $this->maxX - $this->minX + 1;
}
public function getYSize(){
return $this->maxY - $this->minY + 1;
}
public function getZSize(){
return $this->maxZ - $this->minZ + 1;
}
public function __toString(){
return "min: {$this->minX}, {$this->minY}, {$this->minZ}, max: {$this->maxX}, {$this->maxY}, {$this->maxZ}";
}

View file

@ -0,0 +1,18 @@
<?php
class StructureAABB extends \AxisAlignedBB
{
public function __construct($minX, $minY, $minZ, $maxX, $maxY = 0, $maxZ = 0){
if(func_num_args() == 4) parent::__construct($minX, 1, $minY, $minZ, 512, $maxX); //why no overloading
else parent::__construct($minX, $minY, $minZ, $maxX, $maxY, $maxZ);
}
public function intersectsWith($bb, $minZ = 0, $maxX = 0, $maxZ = 0){
if($bb instanceof AxisAlignedBB){
return $this->intersectsWith($bb->minX, $bb->minZ, $bb->maxX, $bb->maxZ);
}
return $this->maxX >= $bb && $this->minX <= $maxX && $this->maxZ >= $minZ && $this->minZ <= $maxZ;
}
}

View file

@ -36,4 +36,4 @@ class MovePlayerPacket extends RakNetDataPacket{
$this->putByte($this->teleport ? 0x80 : 0x00);
}
}
}

View file

@ -12,6 +12,11 @@ class UpdateBlockPacket extends RakNetDataPacket{
}
public function decode(){
$this->x = $this->getInt();
$this->z = $this->getInt();
$this->y = $this->getByte();
$this->block = $this->getByte();
$this->meta = $this->getByte();
}
public function encode(){

View file

@ -1,10 +1,13 @@
<?php
define("PMF_CURRENT_LEVEL_VERSION", 0x01);
define("PMF_CURRENT_LEVEL_VERSION", 0x02);
class PMFLevel extends PMF{
public $isLoaded = true;
/**
* @var $level Level
*/
public $level;
public $levelData = [];
private $locationTable = [];
@ -13,8 +16,8 @@ class PMFLevel extends PMF{
private $chunks = [];
private $chunkChange = [];
public $chunkInfo = [];
public $placeBlocksOnNextGen = [];
public $populated = [];
public $fakeLoaded = [];
public function __construct($file, $blank = false){
if(is_array($blank)){
$this->create($file, 0);
@ -25,7 +28,7 @@ class PMFLevel extends PMF{
}else{
if($this->load($file) !== false){
$this->parseInfo();
if($this->parseLevel() === false){
if($this->parseLevel($file) === false){
$this->isLoaded = false;
}else{
$this->isLoaded = true;
@ -36,7 +39,11 @@ class PMFLevel extends PMF{
}
}
}
public function setPopulated($X, $Z, $bool = true){
$this->populated[self::getIndex($X, $Z)] = $bool;
}
private function createBlank(){
$this->saveData(false);
$this->locationTable = [];
@ -112,16 +119,244 @@ class PMFLevel extends PMF{
private function getChunkPath($X, $Z){
return dirname($this->file) . "/chunks/" . $Z . "." . $X . ".pmc";
}
protected function parseLevel(){
public function loadNCPMF0Chunk($X, $Z){
$index = $this->getIndex($X, $Z);
if($this->isChunkLoaded($X, $Z)){
return true;
}elseif(!isset($this->locationTable[$index])){
return false;
}
$info = $this->locationTable[$index];
//$this->seek($info[0]);
$chunk = @gzopen($this->getChunkPath($X, $Z), "rb");
if($chunk === false){
return false;
}
$this->chunks[$index] = [];
$this->chunkChange[$index] = [-1 => false];
$this->chunkInfo[$index][0] = str_repeat(ord(BIOME_PLAINS), 256);
$this->setPopulated($X, $Z);
for($Y = 0; $Y < $this->levelData["height"]; ++$Y){
$t = 1 << $Y;
if(($info[0] & $t) === $t){
// 4096 + 2048 + 2048, Block Data, Meta, Light
if(strlen($chunkDataHere = gzread($chunk, 8192)) < 8192){
console("[NOTICE] Empty corrupt chunk detected [$X,$Z,:$Y], recovering contents", true, true, 2);
$this->fillMiniChunk($X, $Z, $Y);
}else{
$this->chunks[$index][$Y] = str_repeat("\x00", 16384);
$this->chunkChange[$index][-1] = true;
$this->chunkChange[$index][$Y] = 16384;
$this->chunkInfo[$index][0] = str_repeat("\x00", 256);
//Convert id-meta to id-meta-light-light
for($x = 0; $x < 16; ++$x){
for($z = 0; $z < 16; ++$z){
for($y = 0; $y < 16; ++$y){
$id = $chunkDataHere[($y + ($x << 5) + ($z << 9))] ?? "\x00";
$meta = $chunkDataHere[(($y >> 1) + 16 + ($x << 5) + ($z << 9))] ?? "\x00";
$bindex = (int) ($y + ($x << 6) + ($z << 10));
$mindex = (int) (($y >> 1) + 16 + ($x << 6) + ($z << 10));
$this->chunks[$index][$Y][$bindex] = $id;
$this->chunks[$index][$Y][$mindex] = $meta;
}
}
}
}
}else{
$this->chunks[$index][$Y] = false;
}
}
@gzclose($chunk);
return true;
}
public function loadNCPMF1Chunk($X, $Z){
$index = $this->getIndex($X, $Z);
if($this->isChunkLoaded($X, $Z)){
return true;
}
$cp = $this->getChunkPath($X, $Z);
if(!is_file($cp)) return false;
$chunk = file_get_contents($cp);
if($chunk === false){
return false;
}
$chunk = zlib_decode($chunk);
$offset = 0;
if(strlen($chunk) === 0) return false;
$info = [0 => Utils::readShort(substr($chunk, $offset, 2))];
$offset+=2;
$this->chunks[$index] = [];
$this->chunkChange[$index] = [-1 => false];
$this->chunkInfo[$index][0] = substr($chunk, $offset, 256); //Biome data
$offset += 256;
for($Y = 0; $Y < $this->levelData["height"]; ++$Y){
$t = 1 << $Y;
if(($info[0] & $t) === $t){
// 4096 + 4096 + 4096 + 4096, Id, Meta, BlockLight, Skylight
if(strlen($this->chunks[$index][$Y] = substr($chunk, $offset, 16384)) < 16384){
console("[NOTICE] Empty corrupt chunk detected [$X,$Z,:$Y], recovering contents", true, true, 2);
$this->fillMiniChunk($X, $Z, $Y);
}
$offset += 16384;
}else{
$this->chunks[$index][$Y] = false;
}
}
$this->setPopulated($X, $Z, true);
$this->chunkChange[$index][-1] = true; //force save
return true;
}
protected function parseLevel($worldFile){
if($this->getType() !== 0x00){
return false;
}
$this->seek(5);
$this->levelData["version"] = ord($this->read(1));
if($this->levelData["version"] > PMF_CURRENT_LEVEL_VERSION){ //TODO old worlds support
if($this->levelData["version"] != PMF_CURRENT_LEVEL_VERSION){
$cv = PMF_CURRENT_LEVEL_VERSION;
ConsoleAPI::warn("The level version does not match current. ({$this->levelData["version"]} != {$cv})");
switch($this->levelData["version"]){
case 0:
ConsoleAPI::notice("Converting the world from NCPMF-{$this->levelData["version"]} to NCPMF-$cv...");
$worldDir = substr($worldFile, 0, -strlen("/level.pmf"));
$backupDir = "auto-world-backup-".microtime(true);
ConsoleAPI::info("Creating backup in $backupDir...");
copydir($worldDir, $backupDir);
ConsoleAPI::info("Starting converting...");
$this->levelData["name"] = $this->read(Utils::readShort($this->read(2), false));
$this->levelData["seed"] = Utils::readInt($this->read(4));
$this->levelData["time"] = Utils::readInt($this->read(4));
$this->levelData["spawnX"] = Utils::readFloat($this->read(4));
$this->levelData["spawnY"] = Utils::readFloat($this->read(4));
$this->levelData["spawnZ"] = Utils::readFloat($this->read(4));
$this->levelData["width"] = ord($this->read(1));
$this->levelData["height"] = ord($this->read(1));
ConsoleAPI::notice("Choosing ".LevelAPI::$defaultLevelType." generator.");
$generator = LevelAPI::createGenerator(LevelAPI::$defaultLevelType);
$this->levelData["generator"] = get_class($generator);
$lastseek = ftell($this->fp);
if(($len = $this->read(2)) === false or ($this->levelData["extra"] = @gzinflate($this->read(Utils::readShort($len, false)))) === false){ //Corruption protection
console("[NOTICE] Empty/corrupt location table detected, forcing recovery");
fseek($this->fp, $lastseek);
$c = gzdeflate("");
$this->write(Utils::writeShort(strlen($c)) . $c);
$this->payloadOffset = ftell($this->fp);
$this->levelData["extra"] = "";
//$cnt = pow($this->levelData["width"], 2);
for($X = 0; $X < 16; ++$X){
for($Z = 0; $Z < 16; ++$Z){
$this->write("\x00\xFF"); //Force index recreation
}
}
fseek($this->fp, $this->payloadOffset);
}else{
$this->payloadOffset = ftell($this->fp);
}
$this->locationTable = [];
$this->seek($this->payloadOffset);
for($Z = 0; $Z < 16; ++$Z){
for($X = 0; $X < 16; ++$X){
$index = $this->getIndex($X, $Z);
$this->chunks[$index] = false;
$this->chunkChange[$index] = false;
$this->locationTable[$index] = [
0 => Utils::readShort($this->read(2)), //16 bit flags
];
}
}
foreach(scandir("$worldDir/chunks/") as $f){
if($f != "." && $f != ".."){
$xz = explode(".", $f);
$X = (int) $xz[0];
$Z = (int) $xz[1];
ConsoleAPI::info("Converting $X-$Z...");
$this->loadNCPMF0Chunk($X, $Z);
$this->unloadChunk($X, $Z);
}
}
ConsoleAPI::notice("Modifying level.pmf...");
$this->saveData(false);
ConsoleAPI::notice("World converted. Reloading...");
break;
case 1:
ConsoleAPI::notice("Converting the world from NCPMF-{$this->levelData["version"]} to NCPMF-$cv...");
$worldDir = substr($worldFile, 0, -strlen("/level.pmf"));
$backupDir = "auto-world-backup-".microtime(true);
ConsoleAPI::info("Creating backup in $backupDir...");
copydir($worldDir, $backupDir);
ConsoleAPI::info("Starting converting...");
$this->levelData["name"] = $this->read(Utils::readShort($this->read(2), false));
$this->levelData["seed"] = Utils::readInt($this->read(4));
$this->levelData["time"] = Utils::readInt($this->read(4));
$this->levelData["spawnX"] = Utils::readFloat($this->read(4));
$this->levelData["spawnY"] = Utils::readFloat($this->read(4));
$this->levelData["spawnZ"] = Utils::readFloat($this->read(4));
$this->levelData["width"] = ord($this->read(1));
$this->levelData["height"] = ord($this->read(1));
$this->levelData["generator"] = $this->read(Utils::readShort($this->read(2), false));
$lastseek = ftell($this->fp);
if(($len = $this->read(2)) === false or ($this->levelData["extra"] = @gzinflate($this->read(Utils::readShort($len, false)))) === false){ //Corruption protection
console("[NOTICE] Empty/corrupt location table detected, forcing recovery");
fseek($this->fp, $lastseek);
$c = gzdeflate("");
$this->write(Utils::writeShort(strlen($c)) . $c);
$this->payloadOffset = ftell($this->fp);
$this->levelData["extra"] = "";
for($Z = 0; $X < 16; ++$Z){
for($X = 0; $X < 16; ++$X){
$this->write("\x00\xFF"); //Force index recreation
}
}
fseek($this->fp, $this->payloadOffset);
}else{
$this->payloadOffset = ftell($this->fp);
}
foreach(scandir("$worldDir/chunks/") as $f){
if($f != "." && $f != ".."){
$xz = explode(".", $f);
$X = (int) $xz[0];
$Z = (int) $xz[1];
ConsoleAPI::info("Converting $X-$Z...");
$this->loadNCPMF1Chunk($X, $Z);
$this->unloadChunk($X, $Z);
}
}
ConsoleAPI::notice("Modifying level.pmf...");
$this->saveData(false);
ConsoleAPI::notice("World converted. Reloading...");
break;
}
return false;
}
$this->levelData["name"] = $this->read(Utils::readShort($this->read(2), false));
$this->levelData["seed"] = Utils::readInt($this->read(4));
$this->levelData["time"] = Utils::readInt($this->read(4));
@ -159,8 +394,8 @@ class PMFLevel extends PMF{
//$this->locationTable = [];
//$cnt = pow($this->levelData["width"], 2);
//$this->seek($this->payloadOffset);
for($X = 0; $X < 16; ++$X){
for($Z = 0; $Z < 16; ++$Z){
for($Z = 0; $Z < 16; ++$Z){
for($X = 0; $X < 16; ++$X){
$index = $this->getIndex($X, $Z);
$this->chunks[$index] = false;
$this->chunkChange[$index] = false;
@ -275,7 +510,8 @@ class PMFLevel extends PMF{
for($Y = 0; $Y < 8; ++$Y){
$bitmap |= ($this->chunks[$index][$Y] !== false and ((isset($this->chunkChange[$index][$Y]) and $this->chunkChange[$index][$Y] === 0) or !$this->isMiniChunkEmpty($X, $Z, $Y))) << $Y;
}
gzwrite($chunk, Utils::writeShort($bitmap), 2); //2 bytes locmap
gzwrite($chunk, Utils::writeShort($bitmap), 2); //2 bytes locmap(actually it should be only 1)
gzwrite($chunk, chr($this->populated[$index]), 1); //isPopulated
$biomedata = $this->chunkInfo[$index][0];
if(strlen($biomedata) < 256){
$biomedata = str_repeat("\x01", 256);
@ -335,7 +571,7 @@ class PMFLevel extends PMF{
}
}
public function loadChunk($X, $Z){
public function loadChunk($X, $Z, $populate = false){
$index = $this->getIndex($X, $Z);
@ -359,6 +595,8 @@ class PMFLevel extends PMF{
if(strlen($chunk) === 0) return false;
$info = [0 => Utils::readShort(substr($chunk, $offset, 2))];
$offset+=2;
$populated = ord($chunk[$offset]) > 0;
++$offset;
$this->chunks[$index] = [];
$this->chunkChange[$index] = [-1 => false];
$this->chunkInfo[$index][0] = substr($chunk, $offset, 256); //Biome data
@ -376,6 +614,10 @@ class PMFLevel extends PMF{
$this->chunks[$index][$Y] = false;
}
}
$this->setPopulated($X, $Z, $populated);
if($populate && !$populated){
$this->level->generator->populateChunk($X, $Z);
}
return true;
}
@ -420,6 +662,7 @@ class PMFLevel extends PMF{
0 => str_repeat("\x00", 256)
);
$this->locationTable[$index] = array(0);
$this->setPopulated($X, $Z, false);
}
}
public function setMiniChunk($X, $Z, $Y, $data){
@ -479,6 +722,15 @@ class PMFLevel extends PMF{
$Y = $y >> 4;
$block &= 0xFF;
$index = $this->getIndex($X, $Z);
if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){
if($this->loadChunk($X, $Z, false) === false){
$this->createUnpopulatedChunk($X, $Z);
}
}
if($this->chunks[$index][$Y] === false){
$this->fillMiniChunk($X, $Z, $Y);
}
$aX = $x & 0xf;
$aZ = $z & 0xf;
$aY = $y & 0xf;
@ -588,7 +840,13 @@ class PMFLevel extends PMF{
}
return [$b, $m];
}
public function createUnpopulatedChunk($X, $Z){
$this->initCleanChunk($X, $Z);
$this->level->generator->generateChunk($X, $Z);
$this->fakeLoaded[self::getIndex($X, $Z)] = "$X.$Z"; //TODO do not use string
}
public function setBlock($x, $y, $z, $block, $meta = 0){
$X = $x >> 4;
$Z = $z >> 4;
@ -598,13 +856,14 @@ class PMFLevel extends PMF{
if($Y >= 128 or $y < 0){
return false;
}
$index = $this->getIndex($X, $Z);
if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){
if($this->loadChunk($X, $Z) === false){
return false;
if($this->loadChunk($X, $Z, false) === false){
$this->createUnpopulatedChunk($X, $Z);
}
}else
if($this->chunks[$index][$Y] === false){
}
if(!isset($this->chunks[$index][$Y]) || $this->chunks[$index][$Y] === false){
$this->fillMiniChunk($X, $Z, $Y);
}
$aX = $x - ($X << 4);
@ -612,8 +871,8 @@ class PMFLevel extends PMF{
$aY = $y - ($Y << 4);
$bindex = (int) ($aY + ($aX << 6) + ($aZ << 10));
$mindex = (int) (($aY >> 1) + 16 + ($aX << 6) + ($aZ << 10));
$old_b = ord($this->chunks[$index][$Y][$bindex]);
$old_m = ord($this->chunks[$index][$Y][$mindex]);
$old_b = ord($this->chunks[$index][$Y][$bindex] ?? '\x00');
$old_m = ord($this->chunks[$index][$Y][$mindex] ?? '\x00');
if(($y & 1) === 0){
$m = ($old_m & 0xF0) | $meta;
}else{

View file

@ -48,7 +48,7 @@ class SmallFarmStructure extends Structure{
protected function getMappingFor($char){
if($char === "R"){
$f = Utils::randomFloat();
$f = lcg_value();
if($f <= 0.5){
return [WHEAT_BLOCK, 0];

View file

@ -1,48 +0,0 @@
<?php
//TODO remove
class Java_String{
private $value = "", $count = 0, $hash = 0;
public function __construct($string = false){
if($string !== false){
$this->value = (string) $string;
$this->count = strlen($this->value);
}
}
public function __toString(){
return $this->value;
}
public function lenght(){
return $this->count;
}
public function isEmpty(){
return $this->count === 0;
}
public function hashCode(){
$h = $this->hash;
if($h === 0 and $this->count > 0){
for($i = 0; $i < $this->count; ++$i){
$h = (($h << 5) - $h) + ord($this->charAt($i));
$h = $h & 0xFFFFFFFF;
$this->hash = $h;
}
$this->hash = $h;
}
return $h;
}
public function charAt($index){
$index = (int) $index;
if($index < 0 or $index >= $this->count){
trigger_error("Undefined offset $index", E_USER_WARNING);
return false;
}
return $this->value[$index];
}
}

83
src/utils/MTRandom.php Normal file
View file

@ -0,0 +1,83 @@
<?php
if(USE_NATIVE_RANDOM){
eval('
class MTRandom
{
public $native;
public function __construct($seed = null){
$this->native = new \Random\Randomizer(new \Random\Engine\Mt19937($seed));
}
public function setSeed($seed){
$this->native = new \Random\Randomizer(new \Random\Engine\Mt19937($seed));
}
public function genRandInt(){
return $this->native->getInt(0, 0x7fffffff);
}
public function nextInt($bound = null){
return $bound == null ? $this->native->nextInt() : $this->native->getInt(0, $bound - 1);
}
public function nextFloat(){
return $this->native->getInt(0, 0x7fffffff) / 0x7fffffff;
}
}
');
}else{
eval('
class MTRandom
{
const MAG = [0, 0x9908b0df];
public $mt;
public $index = 0;
public function __construct($seed = null){
$this->setSeed($seed == null ? (int)microtime(1) : $seed);
}
public function setSeed($seed){
$this->mt[0] = $seed & 0xffffffff;
for($this->index = 1; $this->index < 624; ++$this->index){
$this->mt[$this->index] = (0x6c078965 * ($this->mt[$this->index-1] >> 30 ^ $this->mt[$this->index - 1]) + $this->index) & 0xffffffff;
}
}
public function genRandInt(){
if($this->index >= 624 || $this->index < 0){
if($this->index >= 625 || $this->index < 0) $this->setSeed(4357);
for($kk = 0; $kk < 227; ++$kk){
$y = ($this->mt[$kk] & 0x80000000) | ($this->mt[$kk + 1] & 0x7fffffff);
$this->mt[$kk] = $this->mt[$kk+397] ^ ($y >> 1) ^ MTRandom::MAG[$y & 0x1];
}
for(;$kk < 623; ++$kk){
$y = ($this->mt[$kk] & 0x80000000) | ($this->mt[$kk + 1] & 0x7fffffff);
$this->mt[$kk] = $this->mt[$kk-227] ^ ($y >> 1) ^ MTRandom::MAG[$y & 0x1];
}
$y = ($this->mt[623] & 0x80000000) | ($this->mt[0] & 0x7fffffff);
$this->mt[623] = $this->mt[396] ^ ($y >> 1) ^ MTRandom::MAG[$y & 0x1];
$this->index = 0;
}
$y = $this->mt[$this->index++];
$y ^= ($y >> 11);
$y ^= ($y << 7) & 0x9d2c5680;
$y ^= ($y << 15) & 0xefc60000;
$y ^= ($y >> 18);
return $y;
}
public function nextInt($bound = null){
return $bound == null ? $this->genRandInt() >> 1 : $this->genRandInt() % $bound;
}
public function nextFloat(){
return $this->genRandInt() / 0xffffffff;
}
}
');
}

View file

@ -44,29 +44,22 @@ define("MASK32", $val);
class MersenneTwister{
public $mt;
public $mti = 0;
static $MAG_01 = [0, MATRIX_A];
const N = N;
//the class constant is not used anywhere in this namespace,
//but it makes the API cleaner.
//^^ u probably wanted to say makes code look weirder
function __construct(){
$this->bits32 = PHP_INT_MAX == 2147483647;
if(func_num_args() == 1){
$this->init_with_integer(func_get_arg(0));
}
public function __construct($seed = null){
$this->init_with_integer($seed == null ? ((int)microtime(1) & 0xffffffff) : $seed);
}
function init_with_integer($integer_seed){
$integer_seed = force_32_bit_int($integer_seed);
$this->mt = array_fill(0, N, 0);
$this->mt[0] = $integer_seed;
for($this->mti = 1; $this->mti < N; ++$this->mti){
for($this->mti = 1; $this->mti < 624; ++$this->mti){
$this->mt[$this->mti] = add_2(mul(1812433253, ($this->mt[$this->mti - 1] ^ (($this->mt[$this->mti - 1] >> 30) & 3))), $this->mti);
}
}

248
src/utils/RailLogic.php Normal file
View file

@ -0,0 +1,248 @@
<?php
class RailLogic
{
public $x, $y, $z;
public $level;
/**
* @var Vector3[]
*/
public $railPositions = [];
public $isStraight;
public function __construct(RailBaseBlock $rail){
$id = $rail->getID();
$meta = $rail->getMetadata();
$this->level = $rail->level;
$this->x = $rail->x;
$this->y = $rail->y;
$this->z = $rail->z;
$this->isStraight = $id === POWERED_RAIL;
$this->updateConnections($meta);
}
public function getRail($v){
if(($b = $this->level->getBlock($v)) instanceof RailBaseBlock){
return new RailLogic($b);
}elseif(($b = $this->level->getBlockWithoutVector($v->x, $v->y + 1, $v->z)) instanceof RailBaseBlock){
return new RailLogic($b);
}elseif(($b = $this->level->getBlockWithoutVector($v->x, $v->y - 1, $v->z)) instanceof RailBaseBlock){
return new RailLogic($b);
}
return null;
}
public function hasRail($x, $y, $z){
return RailBaseBlock::isRailBlock($this->level, $x, $y, $z) || RailBaseBlock::isRailBlock($this->level, $x, $y + 1, $z) || RailBaseBlock::isRailBlock($this->level, $x, $y - 1, $z);
}
public function countPotentialConnections(){
return $this->hasRail($this->x, $this->y, $this->z - 1) + $this->hasRail($this->x, $this->y, $this->z + 1) + $this->hasRail($this->x - 1, $this->y, $this->z) + $this->hasRail($this->x + 1, $this->y, $this->z);
}
public function removeSoftConnections(){
for($ind = 0; $ind < count($this->railPositions); ++$ind){
$logic = $this->getRail($this->railPositions[$ind]);
if($logic != null && $this->connectsTo($logic)){
$this->railPositions[$ind] = new Vector3($logic->x, $logic->y, $logic->z);
}else{
unset($this->railPositions[$ind--]); //TODO check?
$this->railPositions = array_values($this->railPositions); //reindexing
}
}
}
public function connectsTo(RailLogic $logic){
foreach($this->railPositions as $rpos){
if(($rpos->x === $logic->x) && ($rpos->z === $logic->z)){
return true;
}
}
return false;
}
public function canConnectTo(RailLogic $rail){
//return this.isRailChunkPositionCorrect(par1BlockBaseRailLogic) ? true : (this.railChunkPosition.size() == 2 ? false : (this.railChunkPosition.isEmpty() ? true : true));
return $this->connectsTo($rail) ? true : (count($this->railPositions) == 2 ? false : (empty($this->railPositions) ? true : true));
}
public function hasNeighborRail($x, $y, $z){
$logic = $this->getRail(new Vector3($x, $y, $z));
if($logic === null){
return false;
}else{
$logic->removeSoftConnections(); //i place $this here and was searching why isnt it working correctly for 2 hours
return $logic->canConnectTo($this);
}
}
public function place($b, $b1){
$hasZneg = $this->hasNeighborRail($this->x, $this->y, $this->z - 1);
$hasZpos = $this->hasNeighborRail($this->x, $this->y, $this->z + 1);
$hasXneg = $this->hasNeighborRail($this->x - 1, $this->y, $this->z);
$hasXpos = $this->hasNeighborRail($this->x + 1, $this->y, $this->z);
$state = -1;
if(($hasZneg || $hasZpos) && !($hasXneg && $hasXpos)){
$state = 0;
}
if(($hasXneg || $hasXpos) && !($hasZneg && $hasZpos)){
$state = 1;
}
if(!$this->isStraight){
if($hasZpos && $hasXpos && !($hasZneg && $hasXneg)) $state = 6;
if($hasZpos && $hasXneg && !($hasZneg && $hasXpos)) $state = 7;
if($hasZneg && $hasXneg && !($hasZpos && $hasXpos)) $state = 8;
if($hasZneg && $hasXpos && !($hasZpos && $hasXneg)) $state = 9;
}
if($state === -1){
if($hasZneg || $hasZpos) $state = 0;
if($hasXneg || $hasXpos) $state = 1;
if(!$this->isStraight){
if($b){
if($hasZpos && $hasXpos) $state = 6;
if($hasXneg && $hasZpos) $state = 7;
if($hasXpos && $hasZneg) $state = 9;
if($hasZneg && $hasXneg) $state = 8;
}else{
if($hasZneg && $hasXneg) $state = 8;
if($hasXpos && $hasZneg) $state = 9;
if($hasXneg && $hasZpos) $state = 7;
if($hasZpos && $hasXpos) $state = 6;
}
}
}
if($state === 0){
if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z - 1)) $state = 4;
if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z + 1)) $state = 5;
}elseif($state === 1){
if(RailBaseBlock::isRailBlock($this->level, $this->x + 1, $this->y + 1, $this->z)) $state = 2;
if(RailBaseBlock::isRailBlock($this->level, $this->x - 1, $this->y + 1, $this->z)) $state = 3;
}elseif($state < 0) $state = 0;
$this->updateConnections($state);
$meta = $state;
if($this->isStraight){
$meta = $this->level->level->getBlockDamage($this->x, $this->x, $this->z) & 8 | $state;
}
if($b1 || $this->level->level->getBlockDamage($this->x, $this->y, $this->z)){
//this.logicWorld.setBlockMetadataWithNotify(this.railX, this.railY, this.railZ, var8, 3);
$bl = $this->level->getBlockWithoutVector($this->x, $this->y, $this->z);
$bl->setMetadata($meta);
$this->level->setBlock(new Vector3($this->x, $this->y, $this->z), $bl, true, false, true);
foreach($this->railPositions as $rpos){
$logic = $this->getRail($rpos);
if($logic !== null){
$logic->removeSoftConnections();
if($logic->canConnectTo($this)){
$logic->connectTo($this);
}
}
}
}
}
public function hasConnection($x, $y, $z){
foreach($this->railPositions as $rpos){
if($rpos->x === $x && $rpos->z === $z) return true;
}
return false;
}
public function connectTo(RailLogic $logic){
$this->railPositions[] = new Vector3($logic->x, $logic->y, $logic->z);
$hasZneg = $this->hasConnection($this->x, $this->y, $this->z - 1);
$hasZpos = $this->hasConnection($this->x, $this->y, $this->z + 1);
$hasXneg = $this->hasConnection($this->x - 1, $this->y, $this->z);
$hasXpos = $this->hasConnection($this->x + 1, $this->y, $this->z);
$state = -1;
if($hasZneg || $hasZpos) $state = 0;
if($hasXneg || $hasXpos) $state = 1;
if(!$this->isStraight){
if($hasZpos && $hasXpos && !($hasZneg && $hasXneg)) $state = 6;
if($hasZpos && $hasXneg && !($hasZneg && $hasXpos)) $state = 7;
if($hasZneg && $hasXneg && !($hasZpos && $hasXpos)) $state = 8;
if($hasZneg && $hasXpos && !($hasZpos && $hasXneg)) $state = 9;
}
if($state == 0){
if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z - 1)) $state = 4;
if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z + 1)) $state = 5;
}elseif($state == 1){
if(RailBaseBlock::isRailBlock($this->level, $this->x + 1, $this->y + 1, $this->z)) $state = 2;
if(RailBaseBlock::isRailBlock($this->level, $this->x - 1, $this->y + 1, $this->z)) $state = 3;
}elseif($state < 0) $state = 0;
$meta = $state;
if($this->isStraight){
$meta = $this->level->level->getBlockDamage($this->x, $this->x, $this->z) & 8 | $state;
}
//$b = $this->level->getBlockWithoutVector($this->x, $this->y, $this->z);
//$b->setMetadata($meta);
//$this->level->setBlock(new Vector3($this->x, $this->y, $this->z), $b, true, false, true);
$this->level->fastSetBlockUpdateMeta($this->x, $this->y, $this->z, $meta, true);
}
public function updateConnections($meta){
$this->railPositions = [];
switch($meta){
case 0:
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z - 1);
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z + 1);
break;
case 1:
$this->railPositions[] = new Vector3($this->x - 1, $this->y, $this->z);
$this->railPositions[] = new Vector3($this->x + 1, $this->y, $this->z);
break;
case 2:
$this->railPositions[] = new Vector3($this->x - 1, $this->y, $this->z);
$this->railPositions[] = new Vector3($this->x + 1, $this->y + 1, $this->z);
break;
case 3:
$this->railPositions[] = new Vector3($this->x - 1, $this->y + 1, $this->z);
$this->railPositions[] = new Vector3($this->x + 1, $this->y, $this->z);
break;
case 4:
$this->railPositions[] = new Vector3($this->x, $this->y + 1, $this->z - 1);
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z + 1);
break;
case 5:
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z - 1);
$this->railPositions[] = new Vector3($this->x, $this->y + 1, $this->z + 1);
break;
case 6:
$this->railPositions[] = new Vector3($this->x + 1, $this->y, $this->z);
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z + 1);
break;
case 7:
$this->railPositions[] = new Vector3($this->x - 1, $this->y, $this->z);
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z + 1);
break;
case 8:
$this->railPositions[] = new Vector3($this->x - 1, $this->y, $this->z);
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z - 1);
break;
case 9:
$this->railPositions[] = new Vector3($this->x + 1, $this->y, $this->z);
$this->railPositions[] = new Vector3($this->x, $this->y, $this->z - 1);
break;
}
}
}

View file

@ -49,7 +49,14 @@ class Random{
public function nextFloat(){
return $this->nextInt() / 0x7FFFFFFF;
}
public function nextLong($n = -1){
if($n > 0){
return Utils::readLong($this->nextBytes(8)) & 0x7FFFFFFF % $n;
}
return Utils::readLong($this->nextBytes(8)) & 0x7FFFFFFF;
}
public function nextInt($n = -1){
if($n > 0){
return Utils::readInt($this->nextBytes(4)) & 0x7FFFFFFF % $n;

View file

@ -45,6 +45,10 @@ class Utils{
return $angle < 0 ? $angle + 360 : $angle;
}
public static function chunkPos2Int($x, $z){
return ($x & 0xFFFFFFFF) | (($z & 0xFFFFFFFF) << 32);
}
public static function wrapAngleTo180($angle)
{
$angle = fmod($angle+180, 360);
@ -456,107 +460,17 @@ class Utils{
}
public static function getRandomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0){
static $lastRandom = "";
$output = b"";
$length = abs((int) $length);
$secureValue = "";
$rounds = 0;
$drop = 0;
while(!isset($output[$length - 1])){
//some entropy, but works ^^
$weakEntropy = [
is_array($startEntropy) ? implode($startEntropy) : $startEntropy,
serialize(@stat(__FILE__)),
__DIR__,
PHP_OS,
microtime(),
(string) lcg_value(),
(string) PHP_MAXPATHLEN,
PHP_SAPI,
(string) PHP_INT_MAX . "." . PHP_INT_SIZE,
serialize($_SERVER),
serialize(get_defined_constants()),
get_current_user(),
serialize(ini_get_all()),
(string) memory_get_usage() . "." . memory_get_peak_usage(),
php_uname(),
phpversion(),
//extension_loaded("gmp") ? gmp_strval(gmp_random(4)):microtime(),
zend_version(),
(string) getmypid(),
(string) getmyuid(),
(string) mt_rand(),
(string) getmyinode(),
(string) getmygid(),
(string) rand(),
function_exists("zend_thread_id") ? ((string) zend_thread_id()) : microtime(),
function_exists("getrusage") ? @implode(getrusage()) : microtime(),
function_exists("sys_getloadavg") ? @implode(sys_getloadavg()) : microtime(),
serialize(get_loaded_extensions()),
sys_get_temp_dir(),
(string) disk_free_space("."),
(string) disk_total_space("."),
uniqid(microtime(), true),
file_exists("/proc/cpuinfo") ? file_get_contents("/proc/cpuinfo") : microtime(),
];
shuffle($weakEntropy);
$value = hash("sha512", implode($weakEntropy), true);
$lastRandom .= $value;
foreach($weakEntropy as $k => $c){ //mixing entropy values with XOR and hash randomness extractor
$value ^= hash("sha256", $c . microtime() . $k, true) . hash("sha256", mt_rand() . microtime() . $k . $c, true);
$value ^= hash("sha512", ((string) lcg_value()) . $c . microtime() . $k, true);
}
unset($weakEntropy);
if($secure === true){
$strongEntropyValues = [
is_array($startEntropy) ? hash("sha512", $startEntropy[($rounds + $drop) % count($startEntropy)], true) : hash("sha512", $startEntropy, true), //Get a random index of the startEntropy, or just read it
file_exists("/dev/urandom") ? fread(fopen("/dev/urandom", "rb"), 64) : str_repeat("\x00", 64),
(function_exists("openssl_random_pseudo_bytes") and version_compare(PHP_VERSION, "5.3.4", ">=")) ? openssl_random_pseudo_bytes(64) : str_repeat("\x00", 64),
function_exists("mcrypt_create_iv") ? mcrypt_create_iv(64, MCRYPT_DEV_URANDOM) : str_repeat("\x00", 64),
$value,
];
$strongEntropy = array_pop($strongEntropyValues);
foreach($strongEntropyValues as $value){
$strongEntropy = $strongEntropy ^ $value;
}
$value = "";
//Von Neumann randomness extractor, increases entropy
$bitcnt = 0;
for($j = 0; $j < 64; ++$j){
$a = ord($strongEntropy[$j]);
for($i = 0; $i < 8; $i += 2){
$b = ($a & (1 << $i)) > 0 ? 1 : 0;
if($b != (($a & (1 << ($i + 1))) > 0 ? 1 : 0)){
$secureValue = $b << $bitcnt;
if($bitcnt == 7){
$value .= chr($secureValue);
$secureValue = 0;
$bitcnt = 0;
}else{
++$bitcnt;
}
++$drop;
}else{
$drop += 2;
}
}
}
}
$output .= substr($value, 0, min($length - strlen($output), $length));
unset($value);
++$rounds;
}
$lastRandom = hash("sha512", $lastRandom, true);
return $raw === false ? bin2hex($output) : $output;
return $raw ? random_bytes($length) : bin2hex(random_bytes($length)); //nobody would ever notice other parameters
}
public static function chance($i){//GameHerobrine's code
return self::randomFloat() <= $i / 100;
public static function chance($i){
return lcg_value() <= $i / 100;
}
public static function randomFloat(){//GameHerobrine's code
/**
* @deprecated use lcg_value() instead.
* @return number
*/
public static function randomFloat(){
return rand() / getrandmax();
}

View file

@ -20,8 +20,8 @@ class Level{
public $entityList;
public $tiles, $blockUpdates, $nextSave, $players = [], $level, $mobSpawner;
public $time, $startCheck, $startTime, $server, $name, $usedChunks, $changedBlocks, $changedCount, $stopTime;
private $generator;
public $resendBlocksToPlayers = [];
public $generator;
public function __construct(PMFLevel $level, Config $entities, Config $tiles, Config $blockUpdates, $name){
$this->server = ServerAPI::request();
$this->level = $level;
@ -85,19 +85,22 @@ class Level{
}
public function fastSetBlockUpdate($x, $y, $z, $id, $meta, $updateBlocksAround = false){
$x = (int)$x;
$y = (int)$y;
$z = (int)$z;
$this->level->setBlock($x, $y, $z, $id, $meta);
$pk = new UpdateBlockPacket;
$pk->x = $x;
$pk->y = $y;
$pk->z = $z;
$pk->block = $id;
$pk->meta = $meta;
$this->server->api->player->broadcastPacket($this->players, $pk);
$this->sendBlockToAll($x, $y, $z);
if($updateBlocksAround){
$this->server->api->block->blockUpdateAround(new Position($x, $y, $z, $this), BLOCK_UPDATE_NORMAL, 1);
}
}
public function sendBlockToAll($x, $y, $z){
foreach($this->players as $p){
$this->resendBlocksToPlayers[$p->CID]["$x.$y.$z"] = true;
}
}
public function __destruct(){
if(isset($this->level)){
$this->save(false, false);
@ -107,7 +110,35 @@ class Level{
unset($this->mobSpawner->level);
}
public function checkSleep(){ //TODO events?
if(count($this->players) == 0) return false;
if($this->server->api->time->getPhase($this->level) === "night"){ //TODO vanilla
foreach($this->players as $p){
if($p->isSleeping == false || $p->sleepingTime < 100){
return false;
}
}
$this->server->api->time->set("day", $this->level);
}
foreach($this->players as $p){
$p->stopSleep();
}
}
public function fastSetBlockUpdateMeta($x, $y, $z, $meta, $updateBlock = false){
$this->level->setBlockDamage($x, $y, $z, $meta);
$pk = new UpdateBlockPacket;
$pk->x = $x;
$pk->y = $y;
$pk->z = $z;
$pk->block = $this->level->getBlockID($x, $y, $z);
$pk->meta = $meta;
$this->server->api->player->broadcastPacket($this->players, $pk);
if($updateBlock){
$this->server->api->block->blockUpdateAround(new Position($x, $y, $z, $this), BLOCK_UPDATE_NORMAL, 1);
}
}
public function getOrderedFullChunk($X, $Z){
$X = (int)$X;
$Z = (int)$Z;
@ -126,7 +157,7 @@ class Level{
$tileEntities = "";
if($gen) $this->level->generateChunk($X, $Z, $this->generator);
if(!$this->level->isChunkLoaded($X, $Z)){
$this->level->loadChunk($X, $Z);
$this->level->loadChunk($X, $Z, true);
}
$miniChunks = [];
@ -158,33 +189,54 @@ class Level{
}
$nbt = new NBT_new(NBT_new::LITTLE_ENDIAN);
foreach($chunkTiles as $tile){ //TODO non-hardcoded nbt data
foreach($chunkTiles as $tile){ //TODO rewrite TileEntity system
switch($tile->class){
case "Sign":
case TILE_SIGN:
$text = $tile->getText();
$nbt->setData(new Compound("", array(
new StringTag("Text1", $text[0]),
new StringTag("Text2", $text[1]),
new StringTag("Text3", $text[2]),
new StringTag("Text4", $text[3]),
new StringTag("id", "Sign"),
new IntTag("x", (int) $tile->x),
new IntTag("y", (int) $tile->y),
new IntTag("z", (int) $tile->z)
)));
$tileEntities .= $nbt->write();
$nbt->setData(new Compound("", array(
new StringTag("Text1", $text[0]),
new StringTag("Text2", $text[1]),
new StringTag("Text3", $text[2]),
new StringTag("Text4", $text[3]),
new StringTag("id", TILE_SIGN),
new IntTag("x", (int) $tile->x),
new IntTag("y", (int) $tile->y),
new IntTag("z", (int) $tile->z)
)));
$tileEntities .= $nbt->write();
break;
case "Furnace":
//nutting, not spawnable :D
case TILE_FURNACE:
//nutting, not spawnable :D
break;
case "Chest":
case TILE_CHEST:
if($tile->isPaired()){
$nbt->setData(new Compound("", array(
new StringTag("id", "Chest"),
new IntTag("x", (int) $tile->x),
new IntTag("y", (int) $tile->y),
new IntTag("z", (int) $tile->z)
new IntTag("z", (int) $tile->z),
new IntTag("pairx", (int) $tile->getPair()->x),
new IntTag("pairz", (int) $tile->getPair()->z)
)));
$tileEntities .= $nbt->write();
}else{
$nbt->setData(new Compound("", array(
new StringTag("id", TILE_CHEST),
new IntTag("x", (int) $tile->x),
new IntTag("y", (int) $tile->y),
new IntTag("z", (int) $tile->z),
)));
}
$tileEntities .= $nbt->write();
break;
case TILE_MOB_SPAWNER:
$nbt->setData(new Compound("", array(
new StringTag("id", TILE_MOB_SPAWNER),
new IntTag("x", (int) $tile->x),
new IntTag("y", (int) $tile->y),
new IntTag("z", (int) $tile->z),
new IntTag("EntityId", (int) $tile->data["EntityId"]),
)));
$tileEntities .= $nbt->write();
break;
}
}
@ -263,8 +315,11 @@ class Level{
}
public function freeAllChunks(Player $player){
foreach($this->usedChunks as $i => $c){
unset($this->usedChunks[$i][$player->CID]);
foreach($player->chunksLoaded as $chunk => $c){
$xz = explode(":", $chunk);
$x = $xz[0];
$z = $xz[1];
$player->stopUsingChunk($x, $z);
}
}
@ -293,7 +348,7 @@ class Level{
}
$now = microtime(true);
$this->players = $this->server->api->player->getAll($this);
$this->checkSleep();
if(count($this->changedCount) > 0){
arsort($this->changedCount);
$resendChunks = [];
@ -419,9 +474,45 @@ class Level{
}
}
foreach($this->level->fakeLoaded as $ind => $val){
$xz = explode(".", $val);
$this->level->unloadChunk($xz[0], $xz[1]);
unset($this->level->fakeLoaded[$ind]);
}
foreach($this->resendBlocksToPlayers as $playerCID => $blockz){
/**
* @var Player $player
*/
$player = $this->server->clients[$playerCID] ?? false;
if($player instanceof Player){
foreach($blockz as $xyz => $_){
$xyzz = explode(".", $xyz);
if(count($xyzz) == 3){
$x = (int) $xyzz[0];
$y = (int) $xyzz[1];
$z = (int) $xyzz[2];
$idm = $this->level->getBlock($x, $y, $z);
//$player->addToBlockSendQueue(new UpdateBlockPacket($x, $y, $z, $idm[0], $idm[1]));
$pk = new UpdateBlockPacket;
$pk->x = $x;
$pk->y = $y;
$pk->z = $z;
$pk->block = $idm[0] & 0xff;
$pk->meta = $idm[1] & 0xff;
$player->addToBlockSendQueue($pk);
}
unset($blockz[$xyz]);
}
$player->sendBlockUpdateQueue();
}
unset($this->resendBlocksToPlayers[$playerCID]);
}
}
public function setBlock(Vector3 $pos, Block $block, $update = true, $tiles = false, $direct = false){
$pos->x = (int)$pos->x;
$pos->y = (int)$pos->y;
$pos->z = (int)$pos->z;
if(!isset($this->level) or (($pos instanceof Position) and $pos->level !== $this) or $pos->y < 0){
return false;
}
@ -432,13 +523,7 @@ class Level{
}
$block->position($pos);
if($direct === true){
$pk = new UpdateBlockPacket;
$pk->x = $pos->x;
$pk->y = $pos->y;
$pk->z = $pos->z;
$pk->block = $block->getID();
$pk->meta = $block->getMetadata();
$this->server->api->player->broadcastPacket($this->players, $pk);
$this->sendBlockToAll($pos->x, $pos->y, $pos->z);
}else{
$i = ($pos->x >> 4) . ":" . ($pos->y >> 4) . ":" . ($pos->z >> 4);
if(!isset($this->changedBlocks[$i])){
@ -477,7 +562,7 @@ class Level{
return false;
}
$this->changedCount[$X . ":" . $Y . ":" . $Z] = 4096;
if(ADVANCED_CACHE == true){
if(ADVANCED_CACHE){
Cache::remove("world:{$this->name}:$X:$Z");
}
return $this->level->setMiniChunk($X, $Z, $Y, $data);

View file

@ -49,7 +49,8 @@ class LevelImport{
"spawnZ" => $level["SpawnZ"],
"extra" => "",
"width" => 16,
"height" => 8
"height" => 8,
"generator" => get_class(LevelAPI::createGenerator(LevelAPI::$defaultLevelType))
]);
$chunks = new PocketChunkParser();
$chunks->loadFile($this->path . "chunks.dat");
@ -72,8 +73,12 @@ class LevelImport{
$meta = $chunks->getChunkColumn($X, $Z, $x, $z, 1);
for($Y = 0; $Y < 8; ++$Y){
$chunk[$Y] .= substr($block, $Y << 4, 16);
$chunk[$Y] .= substr($meta, $Y << 3, 8);
$chunk[$Y] .= "\x00\x00\x00\x00\x00\x00\x00\x00";
$metaf = str_split(substr($meta, $Y << 3, 8));
foreach($metaf as $m2){
$chunk[$Y] .= chr(ord($m2) << 4) . chr(ord($m2) & 0xf);
}
$chunk[$Y] .= "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
$chunk[$Y] .= "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
}
}
}

View file

@ -13,6 +13,8 @@ class Tile extends Position{
public $attach;
public $metadata;
public $closed;
public $scheduledUpdate;
public $lastUpdate;
private $server;
function __construct(Level $level, $id, $class, $x, $y, $z, $data = []){
@ -361,7 +363,7 @@ class Tile extends Position{
$nbt->writeTAG_String("EntityId");
$nbt->writeTAG_Int((int) $this->data["EntityId"]);
$nbt->write(chr(NBT::TAG_SHORT));
/*$nbt->write(chr(NBT::TAG_SHORT));
$nbt->writeTAG_String("Delay");
$nbt->writeTAG_SHORT((int) $this->data["Delay"]);
@ -387,7 +389,7 @@ class Tile extends Position{
$nbt->write(chr(NBT::TAG_SHORT));
$nbt->writeTAG_String("SpawnRange");
$nbt->writeTAG_SHORT((int) $this->data["SpawnRange"]);
$nbt->writeTAG_SHORT((int) $this->data["SpawnRange"]);*/
//console(bin2hex($nbt->binary));

View file

@ -66,7 +66,7 @@ class ExperimentalGenerator implements NewLevelGenerator{
new OreType(new LapisOreBlock(), 1, 6, 0, 32),
new OreType(new GoldOreBlock(), 2, 8, 0, 32),
new OreType(new DiamondOreBlock(), 1, 7, 0, 16),
new OreType(new EmeraldOreBlock(), 1, 7, 0, 16), //TODO vanilla
new OreType(new EmeraldOreBlock(), 1, 2, 0, 16), //TODO vanilla
new OreType(new DirtBlock(), 20, 32, 0, 128),
new OreType(new GravelBlock(), 10, 16, 0, 128),
@ -85,6 +85,7 @@ class ExperimentalGenerator implements NewLevelGenerator{
$tallGrass->setBaseAmount(5);
$tallGrass->setRandomAmount(0);
$this->populators[] = $tallGrass;
$this->caveGenerator = new CaveGenerator($this->level->getSeed());
}
public function pickBiome(int $x, int $z){
@ -103,11 +104,8 @@ class ExperimentalGenerator implements NewLevelGenerator{
public function generateChunk($chunkX, $chunkZ){
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->level->getSeed());
$noiseArray = ExperimentalGenerator::getFastNoise3D($this->noiseBase, 16, 128, 16, 4, 8, 4, $chunkX * 16, 0, $chunkZ * 16);
$biomeCache = [];
for($chunkY = 0; $chunkY < 8; ++$chunkY){
$chunk = "";
$startY = $chunkY << 4;
@ -165,13 +163,15 @@ class ExperimentalGenerator implements NewLevelGenerator{
$this->level->setMiniChunk($chunkX, $chunkZ, $chunkY, $chunk);
}
foreach($this->genPopulators as $pop){
$pop->populate($this->level, $chunkX, $chunkZ, $this->random);
}
$this->caveGenerator->generate($this->level, $chunkX, $chunkZ);
}
public function populateChunk($chunkX, $chunkZ){
$this->level->level->setPopulated($chunkX, $chunkZ, true);
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->level->getSeed());
foreach($this->populators as $populator){
$populator->populate($this->level, $chunkX, $chunkZ, $this->random);

View file

@ -1,6 +1,6 @@
<?php
//from HellGenerator for PocketMine mcpe 0.11 by ж<EFBFBD>џдє‘
//from HellGenerator for PocketMine mcpe 0.11 by Р¶пїЅСџРґС”вЂ<EFBFBD>
class HellGenerator implements NewLevelGenerator{
@ -121,6 +121,7 @@ class HellGenerator implements NewLevelGenerator{
}
public function populateChunk($chunkX, $chunkZ){
$this->level->level->setPopulated($chunkX, $chunkZ, true);
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
foreach($this->populators as $populator){
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());

View file

@ -4,17 +4,20 @@ require_once("NewLevelGenerator.php");
/***REM_END***/
class NormalGenerator implements NewLevelGenerator{
const HIDDEN_FEATURES = false;
private $populators = array();
private $level;
private $random;
public $mtrandom;
private $worldHeight = 65;
private $waterHeight = 63;
private $noiseHills;
private $noisePatches;
private $noisePatchesSmall;
private $noiseBase;
private $biomeSelector;
private $caveGenerator;
private $mineshaftGenerator;
public function __construct(array $options = array()){
}
@ -27,10 +30,12 @@ class NormalGenerator implements NewLevelGenerator{
$this->level = $level;
$this->random = $random;
$this->random->setSeed($this->level->getSeed());
$this->mtrandom = new MTRandom($this->level->getSeed());
$this->noiseHills = new NoiseGeneratorPerlin($this->random, 3);
$this->noisePatches = new NoiseGeneratorPerlin($this->random, 2);
$this->noisePatchesSmall = new NoiseGeneratorPerlin($this->random, 2);
$this->noiseBase = new NoiseGeneratorPerlin($this->random, 16);
$this->biomeSelector = new NormalGeneratorBiomeSelector($this->random, BiomeSelector::$biomes[BIOME_PLAINS]);
$ores = new OrePopulator();
$ores->setOreTypes(array(
@ -40,7 +45,7 @@ class NormalGenerator implements NewLevelGenerator{
new OreType(new LapisOreBlock(), 1, 6, 0, 32),
new OreType(new GoldOreBlock(), 2, 8, 0, 32),
new OreType(new DiamondOreBlock(), 1, 7, 0, 16),
new OreType(new EmeraldOreBlock(), 1, 7, 0, 16), //TODO vanilla
new OreType(new EmeraldOreBlock(), 1, 2, 0, 16), //TODO vanilla
new OreType(new DirtBlock(), 20, 32, 0, 128),
new OreType(new GravelBlock(), 10, 16, 0, 128),
@ -49,28 +54,46 @@ class NormalGenerator implements NewLevelGenerator{
new OreType(new StoneBlock(5), 12, 16, 0, 128),
));
$this->populators[] = $ores;
$trees = new TreePopulator();
$trees->setBaseAmount(3);
$trees->setRandomAmount(0);
$trees = new BiomeBasedTreePopulator();
$trees->setBaseAmount(8); //TODO biome based amount?
$trees->setRandomAmount(4);
$this->populators[] = $trees;
$this->populators[] = new FlowerPatchPopulator();
$tallGrass = new TallGrassPopulator();
$tallGrass->setBaseAmount(5);
$tallGrass->setRandomAmount(0);
$this->populators[] = $tallGrass;
$this->caveGenerator = new CaveGenerator($this->level->getSeed());
$this->mineshaftGenerator = new MineshaftGenerator($this->level->getSeed());
}
public function pickBiome(int $x, int $z){
$hash = $x * 2345803 ^ $z * 9236449 ^ $this->level->level->getSeed();
$hash *= $hash + 223;
$xNoise = ((int)$hash) >> 20 & 3; //why dont u have types for local variables??
$zNoise = ((int)$hash) >> 22 & 3;
if($xNoise == 3){
$xNoise = 1;
}
if($zNoise == 3){
$zNoise = 1;
}
return $this->biomeSelector->pickBiome($x + $xNoise - 1, $z + $zNoise - 1);
}
public function generateChunk($chunkX, $chunkZ){
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
$hills = array();
$base = array();
$biomes = str_repeat(chr(BIOME_PLAINS), 256);
for($z = 0; $z < 16; ++$z){
for($x = 0; $x < 16; ++$x){
$biomes[($z << 4) + $x] = chr($this->pickBiome($chunkX * 16 + $x, $chunkZ * 16 + $z)->id);
$i = ($z << 4) + $x;
$hills[$i] = $this->noiseHills->noise3D($x + ($chunkX << 4), 0, $z + ($chunkZ << 4), 0.11, 12, true);
$hills[$i] = $this->noiseHills->noise2D($x + ($chunkX << 4), $z + ($chunkZ << 4), 0.11, 12, true);
$patches[$i] = $this->noisePatches->noise2D($x + ($chunkX << 4), $z + ($chunkZ << 4), 0.03, 16, true);
$patchesSmall[$i] = $this->noisePatchesSmall->noise2D($x + ($chunkX << 4), $z + ($chunkZ << 4), 0.5, 4, true);
$base[$i] = $this->noiseBase->noise2D($x + ($chunkX << 4), $z + ($chunkZ << 4), 0.7, 16, true);
if($base[$i] < 0){
$base[$i] *= 0.5;
@ -86,7 +109,7 @@ class NormalGenerator implements NewLevelGenerator{
$i = ($z << 4) + $x;
$height = $this->worldHeight + $hills[$i] * 14 + $base[$i] * 7;
$height = (int) $height;
$biomeID = ord($biomes[$i]);
for($y = $startY; $y < $endY; ++$y){
$diff = $height - $y;
if($y <= 4 and ($y === 0 or $this->random->nextFloat() < 0.33)){
@ -99,21 +122,19 @@ class NormalGenerator implements NewLevelGenerator{
}elseif($patches[$i] < -0.8){
$chunk .= "\x0d"; //gravel
}else{
$chunk .= "\x03"; //dirt
$chunk .= $biomeID === BIOME_DESERT ? chr(SANDSTONE) : chr(DIRT);
}
}elseif($y <= $this->waterHeight){
if(($this->waterHeight - $y) <= 1 and $diff === 0){
$chunk .= "\x0c"; //sand
$chunk .= ($biomeID === BIOME_TAIGA) ? chr(GRASS) : chr(SAND);
}elseif($diff === 0){
/*if($patchesSmall[$i] > 0.3){
$chunk .= "\x0d"; //gravel
}elseif($patchesSmall[$i] < -0.45){
$chunk .= "\x0c"; //sand
}else{*/
$chunk .= "\x03"; //dirt
//}
$chunk .= "\x03"; //dirt
}else{
//if($y === $this->waterHeight && $biomeID == BIOME_TAIGA){
// $chunk .= chr(ICE);
///}else{
$chunk .= "\x09"; //still_water
//}
}
}elseif($diff === 0){
if($patches[$i] > 0.7){
@ -121,7 +142,7 @@ class NormalGenerator implements NewLevelGenerator{
}elseif($patches[$i] < -0.8){
$chunk .= "\x0d"; //gravel
}else{
$chunk .= "\x02"; //grass
$chunk .= $biomeID === BIOME_DESERT ? chr(SAND) : chr(GRASS);
}
}else{
$chunk .= "\x00";
@ -132,15 +153,46 @@ class NormalGenerator implements NewLevelGenerator{
$chunk .= "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; //skylight/light
}
}
$this->level->level->setBiomeIdArrayForChunk($chunkX, $chunkZ, str_repeat(chr(BIOME_PLAINS), 256));
$this->level->setMiniChunk($chunkX, $chunkZ, $chunkY, $chunk);
}
$this->level->level->setBiomeIdArrayForChunk($chunkX, $chunkZ, $biomes);
if(self::HIDDEN_FEATURES) {
$this->caveGenerator->generate($this->level, $chunkX, $chunkZ); //TODO speedup
$this->mineshaftGenerator->generate($this->level, $chunkX, $chunkZ);
}
}
public function populateChunk($chunkX, $chunkZ){
$blockX = $chunkX * 16;
$blockZ = $chunkZ * 16;
$this->level->level->setPopulated($chunkX, $chunkZ, true);
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
$this->mtrandom->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
$biomeID = $this->level->level->getBiomeId($chunkX*16, $chunkZ*16);
$biome = BiomeSelector::get($biomeID);
if($biome === false){
ConsoleAPI::warn("Failed to get Biome with id {$biomeID} at $chunkX, $chunkZ");
}else{
$biome->decorator->decorate($this->level, $chunkX, $chunkZ, $this->random);
}
if(self::HIDDEN_FEATURES) {
//this.mineshaftGenerator.generateStructuresInChunk(this.worldObj, this.rand, par2, par3);
$this->mineshaftGenerator->generateStructuresInChunk($this->level, $this->mtrandom, $chunkX, $chunkZ);
for ($i = 0; $i < 8; ++$i){
$x = $blockX + $this->mtrandom->nextInt(16) + 8;
$y = $this->mtrandom->nextInt(128);
$z = $blockZ + $this->mtrandom->nextInt(16) + 8;
if(Feature::$DUNGEON->place($this->level, $this->mtrandom, $x, $y, $z)){
ConsoleAPI::debug("Placed Dungeon at $x $y $z");
}
}
}
foreach($this->populators as $populator){
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
$this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed()); //ty shoghicp for 250k bytes of randomness (where ~65536 are usable)
$populator->populate($this->level, $chunkX, $chunkZ, $this->random);
}
}

View file

@ -7,7 +7,7 @@ require_once("LevelGenerator.php");
class SuperflatGenerator implements LevelGenerator{
private $level, $random, $structure, $chunks, $options, $floorLevel, $populators = [];
public $preset;
public function __construct(array $options = []){
$this->preset = "2;7,59x1,3x3,2;1;spawn(radius=10 block=89),decoration(treecount=80 grasscount=45)";
$this->options = $options;
@ -78,9 +78,9 @@ class SuperflatGenerator implements LevelGenerator{
$metas = "";
for($y = $startY; $y < $endY; ++$y){
$blocks .= chr($this->structure[$y]->getID());
$metas .= substr(dechex($this->structure[$y]->getMetadata()), -1);
$metas .= chr($this->structure[$y]->getMetadata());
}
$this->chunks[$Y] .= $blocks . hex2bin($metas) . "\x00\x00\x00\x00\x00\x00\x00\x00";
$this->chunks[$Y] .= $blocks . $metas . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
}
}
}
@ -111,6 +111,7 @@ class SuperflatGenerator implements LevelGenerator{
for($Y = 0; $Y < 8; ++$Y){
$this->level->setMiniChunk($chunkX, $chunkZ, $Y, $this->chunks[$Y]);
}
$this->level->level->setBiomeIdArrayForChunk($chunkX, $chunkZ, str_repeat(chr(BIOME_PLAINS), 256));
}
public function populateChunk($chunkX, $chunkZ){

View file

@ -2,15 +2,27 @@
abstract class Biome{
public $id, $topBlocks, $fillerBlock, $name, $minY, $maxY;
public $decorator = false;
public function __construct($id, $name){
$this->name = $name;
$this->id = $id;
$this->decorator = $this->createBiomeDecorator();
}
public function setTopBlocks($id){
$this->topBlocks = $id;
}
public function createBiomeDecorator(){
return new BiomeDecorator();
}
public function getTree(Random $random){
return null;
}
public function getID(){
return $this->id;
}
@ -57,6 +69,7 @@ abstract class Biome{
BiomeSelector::registerBiome(new BiomeTaiga(BIOME_TAIGA, "Taiga"));
BiomeSelector::registerBiome(new BiomeForest(BIOME_FOREST, "Forest"));
BiomeSelector::registerBiome(new BiomeForest(BIOME_BIRCH_FOREST, "Birch Forest"));
BiomeSelector::registerBiome(new BiomeJungle(BIOME_JUNGLE, "Jungle"));
}

View file

@ -0,0 +1,9 @@
<?php
class BiomeDecorator
{
public function decorate(Level $level, $chunkX, $chunkZ, Random $random){
return new SmallTreeObject(SaplingBlock::JUNGLE);
}
}

View file

@ -3,19 +3,19 @@
class BiomeSelector
{
/** @var Biome */
private $fallback;
public $fallback;
/** @var NoiseGeneratorSimplex */
private $temperature;
public $temperature;
/** @var NoiseGeneratorSimplex */
private $rainfall;
public $rainfall;
/** @var Biome[] */
public static $biomes = [];
private $map = [];
public $map = [];
private $lookup;
public $lookup;
public function __construct(Random $random, Biome $fallback){
$this->fallback = $fallback;
@ -91,7 +91,6 @@ class BiomeSelector
public function pickBiome($x, $z){
$temperature = (int) ($this->getTemperature($x, $z) * 63);
$rainfall = (int) ($this->getRainfall($x, $z) * 63);
$biomeId = $this->map[$temperature + ($rainfall << 6)] ?? -1;
return self::$biomes[$biomeId] ?? $this->fallback;
}

View file

@ -0,0 +1,32 @@
<?php
class NormalGeneratorBiomeSelector extends BiomeSelector
{
public function getTemperature($x, $z){ //TODO cache
return ($this->temperature->noise2D($x * 0.001953125, $z * 0.001953125, 4, 0.0625, true) + 1) / 2;
}
public function getRainfall($x, $z){
return ($this->rainfall->noise2D($x * 0.001953125, $z * 0.001953125, 4, 0.0625, true) + 1) / 2;
}
public function getBiomeTR($t, $r){
if($r < 0.60){
if($t < 0.75){
return BIOME_PLAINS;
}else{
return BIOME_DESERT;
}
}else if($r < 0.80){
if($t < 0.25){
return BIOME_TAIGA;
}else if($t < 0.75){
return BIOME_FOREST;
}else{
return BIOME_JUNGLE;
}
}
return BIOME_PLAINS;
}
}

View file

@ -6,5 +6,9 @@ class BiomeDesert extends BiomeWithSand
parent::__construct($id, $name);
$this->setMinMax(63, 74);
}
public function createBiomeDecorator(){
return new DesertBiomeDecorator();
}
}

View file

@ -7,5 +7,13 @@ class BiomeForest extends BiomeWithGrass
$this->setMinMax(63, 81);
}
public function getTree(Random $random){
$f = $random->nextFloat();
if($f > 0.75){
return new SmallTreeObject(SaplingBlock::BIRCH);
}
return new SmallTreeObject(SaplingBlock::OAK);
}
}

View file

@ -0,0 +1,14 @@
<?php
class BiomeJungle extends BiomeWithGrass
{
public function __construct($id, $name){
parent::__construct($id, $name);
$this->setMinMax(63, 81);
}
public function getTree(Random $random){
return new SmallTreeObject(SaplingBlock::JUNGLE);
}
}

View file

@ -5,4 +5,8 @@ class BiomePlains extends BiomeWithGrass{
parent::__construct($id, $name);
$this->setMinMax(61, 68);
}
public function getTree(Random $random){
return $random->nextInt(10) == 0 ? new SmallTreeObject(SaplingBlock::OAK) : null;
}
}

View file

@ -13,5 +13,13 @@ class BiomeTaiga extends BiomeWithSnow
[DIRT, 0],
]);
}
public function getTree(Random $random){
$n = $random->nextInt(3);
if($n == 0){
return new PineTreeObject();
}
return new SpruceTreeObject();
}
}

View file

@ -0,0 +1,34 @@
<?php
class DesertBiomeDecorator extends BiomeDecorator
{
public function decorate(Level $level, $chunkX, $chunkZ, Random $random){
for($i = 0; $i < 2; ++$i){
$x = $chunkX*16 + $random->nextInt(16);
$z = $chunkZ*16 + $random->nextInt(16);
$y = $this->getHighestWorkableBlock($level, $x, $z);
$level->level->setBlockID($x, $y, $z, DEAD_BUSH);
}
for($i = 0; $i < 2; ++$i){
$x = $chunkX*16 + $random->nextInt(16);
$z = $chunkZ*16 + $random->nextInt(16);
$y = $this->getHighestWorkableBlock($level, $x, $z);
$cactiSize = $random->nextRange(0, 3);
for($yOff = 0; $yOff < $cactiSize; ++$yOff){
$level->level->setBlockID($x, $y + $yOff, $z, CACTUS);
}
}
}
private function getHighestWorkableBlock(Level $level, $x, $z){
for($y = 128; $y > 0; --$y){
$b = $level->level->getBlockID($x, $y, $z);
if($b == SAND && $level->level->getBlockID($x, $y + 1, $z) == 0){
return $y + 1;
}
}
return -1;
}
}

View file

@ -0,0 +1,167 @@
<?php
//b1.7.3
class CaveGenerator extends StructureBase
{
public function recursiveGenerate(Level $level, $chunkXoffsetted, $chunkZoffsetted, $chunkX, $chunkZ){
$nextInt = $this->rand->nextInt($this->rand->nextInt($this->rand->nextInt(40) + 1) + 1);
if($this->rand->nextInt(15) != 0){
$nextInt = 0;
}
for($i = 0; $i < $nextInt; ++$i){
$randX = ($chunkXoffsetted * 16) + $this->rand->nextInt(16);
$randY = $this->rand->nextInt($this->rand->nextInt(120) + 8);
$randZ = ($chunkZoffsetted * 16) + $this->rand->nextInt(16);
$i2 = 1;
if($this->rand->nextInt(4) == 0){
$this->generateLargeCaveNode($level, $chunkX, $chunkZ, $randX, $randY, $randZ);
$i2 = 1 + $this->rand->nextInt(4);
}
for($i3 = 0; $i3 < $i2; ++$i3){
$v17 = $this->rand->nextFloat() * M_PI * 2;
$v18 = ($this->rand->nextFloat() - 0.5) * 2 / 8;
$v19 = $this->rand->nextFloat() * 2 + $this->rand->nextFloat();
if($this->rand->nextInt(10) == 0) {
$v19 *= $this->rand->nextFloat() * $this->rand->nextFloat() * 3 + 1;
}
$this->generateCaveNode($level, $chunkX, $chunkZ, $randX, $randY, $randZ, $v19, $v17, $v18, 0, 0, 1);
}
}
}
public function generateLargeCaveNode(Level $level, $xCenter, $zCenter, $x, $y, $z){
$this->generateCaveNode($level, $xCenter, $zCenter, $x, $y, $z, 1 + ($this->rand->nextFloat() * 6), 0, 0, -1, -1, 0.5);
}
public function generateCaveNode(Level $level, $chunkX, $chunkZ, $x, $y, $z, $randFloat, $f1, $f2, $unk_1, $unk_2, $d3){
$chunkCenterX = $chunkX*16 + 8;
$chunkCenterZ = $chunkZ*16 + 8;
$f = $f3 = 0;
$random = new MTRandom($this->rand->nextInt());
if($unk_2 <= 0){
$i = ($this->range * 16) - 16;
$unk_2 = $i - $random->nextInt((int)($i / 4));
}
$z2 = false;
if($unk_1 == -1){
$unk_1 = (int)($unk_2 / 2);
$z2 = true;
}
$var27 = $random->nextInt((int)($unk_2 / 2)) + ($unk_2 / 4);
for($var28 = ($random->nextInt(6) == 0); $unk_1 < $unk_2; ++$unk_1){
$horizontalDiff = 1.5 + sin($unk_1 * M_PI / $unk_2) * $randFloat /* * 1 */;
$verticalDiff = $horizontalDiff * $d3;
$var33 = cos($f2);
$var34 = sin($f2);
$x += cos($f1) * $var33;
$y += $var34;
$z += sin($f1) * $var33;
$f2 = $var28 ? ($f2 * 0.92) : ($f2 * 0.7);
$f2 += $f3 * 0.1;
$f1 += $f * 0.1;
$f3 *= 0.9;
$f *= 0.75;
$f3 += ($random->nextFloat() - $random->nextFloat()) * $random->nextFloat() * 2;
$f += ($random->nextFloat() - $random->nextFloat()) * $random->nextFloat() * 2;
if(!$z2 && $unk_1 == $var27 && $randFloat > 1 && $unk_2 > 0){
//this.generateCaveNode(random.nextLong(), chunkX, chunkZ, par5ArrayOfByte, x, y, z, random.nextFloat() * 0.5F + 0.5F, f1 - ((float)Math.PI / 2F), f2 / 3.0F, unk_1, unk_2, 1.0D);
//this.generateCaveNode(random.nextLong(), chunkX, chunkZ, par5ArrayOfByte, x, y, z, random.nextFloat() * 0.5F + 0.5F, f1 + ((float)Math.PI / 2F), f2 / 3.0F, unk_1, unk_2, 1.0D);
$this->generateCaveNode($level, $chunkX, $chunkZ, $x, $y, $z, $random->nextFloat() * 0.5 + 0.5, $f1 - (M_PI / 2), $f2 / 3, $unk_1, $unk_2, 1);
$this->generateCaveNode($level, $chunkX, $chunkZ, $x, $y, $z, $random->nextFloat() * 0.5 + 0.5, $f1 + (M_PI / 2), $f2 / 3, $unk_1, $unk_2, 1);
return;
}
if($z2 || $random->nextInt(4) != 0){
$distFromCenterX = $x - $chunkCenterX;
$distFromCenterZ = $z - $chunkCenterZ;
$var39 = ($unk_2 - $unk_1);
$var41 = $randFloat + /*2 + 16*/ 18;
if($distFromCenterX*$distFromCenterX + $distFromCenterZ*$distFromCenterZ - $var39*$var39 > $var41*$var41){
return;
}
//if (x >= chunkCenterX - 16.0D - var29 * 2.0D && z >= chunkCenterZ - 16.0D - var29 * 2.0D && x <= chunkCenterX + 16.0D + var29 * 2.0D && z <= chunkCenterZ + 16.0D + var29 * 2.0D)
if($x >= $chunkCenterX - 16 - $horizontalDiff*2 && $z >= $chunkCenterZ - 16 - $horizontalDiff*2 && $x <= $chunkCenterX + 16 + $horizontalDiff*2 && $z <= $chunkCenterZ + 16 + $horizontalDiff*2){
$minX = floor($x - $horizontalDiff) - $chunkX*16 - 1;
$maxX = floor($x + $horizontalDiff) - $chunkX*16 + 1;
$minY = floor($y - $verticalDiff) - 1;
$maxY = floor($y + $verticalDiff) + 1;
$minZ = floor($z - $horizontalDiff) - $chunkZ*16 - 1;
$maxZ = floor($z + $horizontalDiff) - $chunkZ*16 + 1;
if($minX < 0) $minX = 0;
if($maxX > 16) $maxX = 16;
if($minY < 1) $minY = 1;
if($maxY > 120) $maxY = 120;
if($minZ < 0) $minZ = 0;
if($maxZ > 16) $maxZ = 16;
$hasWater = false;
for($blockX = $minX; !$hasWater && $blockX < $maxX; ++$blockX){
for($blockZ = $minZ; !$hasWater && $blockZ < $maxZ; ++$blockZ){
for($blockY = $maxY + 1; !$hasWater && $blockY >= $minY - 1; --$blockY){
if($blockY >= 0 && $blockY < 128){
$id = $level->level->getBlockID($blockX + $chunkX*16, $blockY, $blockZ + $chunkZ * 16);
$hasWater = $id == WATER || $id == STILL_WATER;
//if (blockY != minY - 1 && blockX != minX && blockX != maxX - 1 && blockZ != minZ && blockZ != maxZ - 1)
if($blockY != $minY - 1 && $blockX != $minX && $blockX != $maxX - 1 && $blockZ != $minZ && $blockZ != $maxZ - 1){
$blockY = $minY;
}
}
}
}
}
if(!$hasWater){
for($blockX = $minX; $blockX < $maxX; ++$blockX){
$var59 = (($blockX + $chunkX*16) + 0.5 - $x) / $horizontalDiff;
for($blockZ = $minZ; $blockZ < $maxZ; ++$blockZ){
$var46 = (($blockZ + $chunkZ*16) + 0.5 - $z) / $horizontalDiff;
$yPosition = $maxY;
$hasGrass = false;
if($var59*$var59 + $var46*$var46 < 1){
for($blockY = $maxY - 1; $blockY >= $minY; --$blockY){
$var51 = ($blockY + 0.5 - $y) / $verticalDiff;
if($var51 > -0.7 && $var59*$var59 + $var51*$var51 + $var46*$var46 < 1){
$blockID = $level->level->getBlockID($blockX + $chunkX*16, $yPosition, $blockZ + $chunkZ * 16);
$hasGrass = $blockID == GRASS;
if($blockID == STONE || $blockID == DIRT || $hasGrass){
if($blockY < 10){
$level->level->setBlockID($blockX + $chunkX*16, $yPosition, $blockZ + $chunkZ * 16, LAVA);
}else{
$level->level->setBlockID($blockX + $chunkX*16, $yPosition, $blockZ + $chunkZ * 16, 0);
if($hasGrass && $level->level->getBlockID($blockX + $chunkX*16, $yPosition - 1, $blockZ + $chunkZ * 16) == DIRT){
//ConsoleAPI::debug("place grass at ".($blockX + $chunkX*16).":".($yPosition - 1).":".($blockZ + $chunkZ * 16));
$level->level->setBlockID($blockX + $chunkX*16, $yPosition - 1, $blockZ + $chunkZ * 16, GRASS);
}
}
}
}
--$yPosition;
}
}
}
}
}
}
}
}
}
}

View file

@ -0,0 +1,19 @@
<?php
class MineshaftGenerator extends StructureGenerator
{
protected $spawnChance = 1;//0.01;
public function canSpawnStructureAt($chunkX, $chunkZ)
{
$v = $this->rand->nextFloat() < $this->spawnChance && $this->rand->nextInt(80) < max(abs($chunkX), abs($chunkZ));
if($v) ConsoleAPI::debug("u can spawn mineshaft at $chunkX $chunkZ");
return $v;
}
public function getStructureStart(Level $level, $chunkX, $chunkZ)
{
return new StructureMineshaftStart($level, $this->rand, $chunkX, $chunkZ);
}
}

View file

@ -0,0 +1,13 @@
<?php
abstract class Feature
{
public static $DUNGEON;
public static function init(){
self::$DUNGEON = new DungeonFeature();
}
public abstract function place(Level $level, MTRandom $rand, $x, $y, $z);
}

View file

@ -0,0 +1,82 @@
<?php
class DungeonFeature extends Feature
{
protected function selectEID(MTRandom $rand){
}
public function place(Level $level, MTRandom $rand, $initialX, $initialY, $initialZ)
{
$baseSize = 3;
$randomSizeX = $rand->nextInt(2) + 2;
$randomSizeZ = $rand->nextInt(2) + 2;
$var9 = 0;
$minX = $initialX - $randomSizeX - 1;
$maxX = $initialX + $randomSizeX + 1;
$minY = $initialY - 1;
$maxY = $initialY + $baseSize + 1;
$minZ = $initialZ - $randomSizeZ - 1;
$maxZ = $initialZ + $randomSizeZ + 1;
for($x = $minX; $x <= $maxX; ++$x){
for($y = $minY; $y <= $maxY; ++$y){
for($z = $minZ; $z <= $maxZ; ++$z){
$id = $level->level->getBlockID($x, $y, $z);
if($y == $minY && !StaticBlock::getIsSolid($id)){
return false;
}
if($y == $maxY && !StaticBlock::getIsSolid($id)){
return false;
}
if(($x == $minX || $x == $maxX || $z == $minZ || $z == $maxZ) && $y == $initialY && $id == 0 && $level->level->getBlockID($x, $y + 1, $z) == 0){
++$var9;
}
}
}
}
if($var9 < 1 || $var9 > 5) return false;
for($x = $minX; $x <= $maxX; ++$x){
for($y = $maxY; $y >= $minY; --$y){
for($z = $minZ; $z <= $maxZ; ++$z){
$id = $level->level->getBlockID($x, $y, $z);
if($x != $minX && $y != $minY && $z != $minZ && $x != $maxX && $y != $maxY && $z != $maxZ){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0);
}else if($y >= 0 && !StaticBlock::getIsSolid($id)){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0);
}else if(StaticBlock::getIsSolid($id)){
if($y == $minY && $rand->nextInt(4) != 0){
$level->fastSetBlockUpdate($x, $y, $z, MOSSY_COBBLESTONE, 0);
}else{
$level->fastSetBlockUpdate($x, $y, $z, COBBLESTONE, 0);
}
}
}
}
}
//TODO chest gen
$level->fastSetBlockUpdate($initialX, $initialY, $initialZ, MONSTER_SPAWNER, 0); //TODO bteter block placement system
ServerAPI::request()->api->tile->add($level, TILE_MOB_SPAWNER, $initialX, $initialY, $initialZ, [
"EntityId" => match($rand->nextInt(4)){
0 => MOB_SKELETON,
1, 2 => MOB_ZOMBIE,
3 => MOB_SPIDER
},
"id" => TILE_MOB_SPAWNER,
"x" => $initialX,
"y" => $initialY,
"z" => $initialZ,
]);
return true;
}
}

View file

@ -43,7 +43,7 @@ class AcaciaTreeObject extends TreeObject{
$var17 = $level->level->getBlockID($var23, $var16, $var13);
if ($var17 == AIR || $var17 == LEAVES || $var17 == LEAVES2)
if ($var17 == AIR || $var17 == LEAVES || $var17 == LEAVES2 || $var17 == SAPLING)
{
$level->fastSetBlockUpdate($var23, $var16, $var13, TRUNK2, 0);
$var14 = $var16;
@ -95,7 +95,7 @@ class AcaciaTreeObject extends TreeObject{
$var13 += Direction::offsetZ[$var15];
$var20 = $level->level->getBlockID($var23, $var19, $var13);
if ($var20 == AIR || $var20 == LEAVES || $var20 == LEAVES2)
if ($var20 == AIR || $var20 == LEAVES || $var20 == LEAVES2 || $var20 == SAPLING)
{
$level->fastSetBlockUpdate($var23, $var19, $var13, TRUNK2, 0);
$var14 = $var19;

View file

@ -8,13 +8,16 @@ class SmallTreeObject extends TreeObject{
private static $leavesHeight = 4;
private static $leafRadii = [1, 1.41, 2.83, 2.24];
public $type = 0; // All trees appear to be 4 tall
public $type = 0;
public $treeHeight = 7;
private $trunkHeight = 5;
private $addLeavesVines = false;
private $addLogVines = false;
private $addCocoaPlants = false;
public function __construct($treeType = 0){
parent::__construct();
$this->type = $treeType;
}
public function canPlaceObject(Level $level, Vector3 $pos, Random $random){
$radiusToCheck = 0;
for($yy = 0; $yy < $this->trunkHeight + 3; ++$yy){

View file

@ -1,7 +1,7 @@
<?php
class TreeObject{
public function __construct(){}
public $overridable = [
0 => true,
6 => true,
@ -21,15 +21,12 @@ class TreeObject{
}
break;
case SaplingBlock::BIRCH:
$tree = new SmallTreeObject();
$tree->type = SaplingBlock::BIRCH;
$tree = new SmallTreeObject(SaplingBlock::BIRCH);
break;
case SaplingBlock::JUNGLE:
$tree = new SmallTreeObject();
$tree->type = SaplingBlock::JUNGLE;
$tree = new SmallTreeObject(SaplingBlock::JUNGLE);
break;
case SaplingBlock::ACACIA:
console("acacia");
$tree = new AcaciaTreeObject();
break;
case SaplingBlock::DARK_OAK:

View file

@ -0,0 +1,33 @@
<?php
class BiomeBasedTreePopulator extends \TreePopulator
{
public function populate(Level $level, $chunkX, $chunkZ, Random $random){
$this->level = $level;
$amount = $random->nextRange(0, $this->randomAmount + 1) + $this->baseAmount;
for($i = 0; $i < $amount; ++$i){
$x = $random->nextRange($chunkX << 4, ($chunkX << 4) + 15);
$z = $random->nextRange($chunkZ << 4, ($chunkZ << 4) + 15);
$biomeID = $level->level->getBiomeId($x, $z);
$biome = BiomeSelector::get($biomeID);
$treeFeature = null;
if($biome instanceof Biome){
$treeFeature = $biome->getTree($random);
}
if($treeFeature instanceof TreeObject){
$y = $this->getHighestWorkableBlock($x, $z);
if($y === -1){
continue;
}
$v3 = new Vector3($x, $y, $z); //TODO no v3
if($treeFeature->canPlaceObject($level, $v3, $random)){
$treeFeature->placeObject($level, $v3, $random);
}
}else{
continue;
}
}
}
}

View file

@ -0,0 +1,45 @@
<?php
class FlowerPatchPopulator extends Populator
{
public static $flowerIDS = [
[DANDELION, 0],
[MULTIFLOWER, 0],
[MULTIFLOWER, 1],
[MULTIFLOWER, 2],
[MULTIFLOWER, 3],
[MULTIFLOWER, 4],
[MULTIFLOWER, 5],
[MULTIFLOWER, 6],
[MULTIFLOWER, 7],
[MULTIFLOWER, 8],
];
public function populate(Level $level, $chunkX, $chunkZ, Random $random)
{
$x = $chunkX*16 + $random->nextRange(0, 15);
$z = $chunkZ*16 + $random->nextRange(0, 15);
for($i = 0; $i < 4; ++$i){
$xPos = ($x + $random->nextRange(0, 7)) - $random->nextRange(0, 7);
$zPos = ($z + $random->nextRange(0, 7)) - $random->nextRange(0, 7);
$yPos = $this->getHighestWorkableBlock($level, $xPos, $zPos);
if($level->level->getBlockID($xPos, $yPos, $zPos) == 0){
$flowerIDMeta = self::$flowerIDS[$random->nextRange(0, count(self::$flowerIDS)-1)];
$level->level->setBlock($xPos, $yPos, $zPos, $flowerIDMeta[0], $flowerIDMeta[1]);
}
}
}
private function getHighestWorkableBlock(Level $level, $x, $z){
for($y = 128; $y > 0; --$y){
$b = $level->level->getBlockID($x, $y, $z);
if($b == GRASS || $b == DIRT){
return $y + 1;
}
}
return -1;
}
}

View file

@ -1,8 +1,8 @@
<?php
class TreePopulator extends Populator{
private $level;
private $randomAmount;
private $baseAmount;
public $level;
public $randomAmount;
public $baseAmount;
public function setRandomAmount($amount){
$this->randomAmount = $amount;
@ -33,7 +33,7 @@ class TreePopulator extends Populator{
}
}
private function getHighestWorkableBlock($x, $z){
public function getHighestWorkableBlock($x, $z){
for($y = 128; $y > 0; --$y){
$b = $this->level->level->getBlockID($x, $y, $z);
if($b !== DIRT and $b !== GRASS){

View file

@ -0,0 +1,28 @@
<?php
abstract class StructureBase
{
public $range = 8;
public $rand;
public function __construct(){
$this->rand = new MTRandom();
}
public function generate(Level $level, $chunkX, $chunkZ){
$range = $this->range;
$this->rand->setSeed($level->getSeed());
$seedInt1 = $this->rand->nextInt();
$seedInt2 = $this->rand->nextInt();
for($x = $chunkX - $range; $x <= $chunkX + $range; ++$x){
for($z = $chunkZ - $range; $z <= $chunkZ + $range; ++$z){
$this->rand->setSeed((($x * $seedInt1) + ($z * $seedInt2)) ^ $level->getSeed());
$this->recursiveGenerate($level, $x, $z, $chunkX, $chunkZ);
}
}
}
public function recursiveGenerate(Level $level, $chunkXoffsetted, $chunkZoffsetted, $chunkX, $chunkZ){}
}

View file

@ -0,0 +1,301 @@
<?php
abstract class StructureComponent
{
public AxisAlignedBB $boundingBox;
public $coordBaseMode = -1;
public $componentType = 0;
public function __construct($type){
$this->componentType = $type;
}
public function buildComponent(StructureComponent $component, $aList, MTRandom $random){}
public abstract function addComponentParts(Level $level, MTRandom $random, AxisAlignedBB $boundingBox): bool;
/**
* @param StructureComponent[] $aList
* @param AxisAlignedBB $boundingBox
*/
public static function findIntersecting($aList, AxisAlignedBB $boundingBox){
foreach($aList as $component){
if($component->boundingBox != null && $component->boundingBox->intersectsWith($boundingBox)){
return $component;
}
}
return null;
}
public function getCenter(){
return new Vector3(
(int)($this->boundingBox->minX + (($this->boundingBox->maxX - $this->boundingBox->minX + 1) / 2)),
(int)($this->boundingBox->minY + (($this->boundingBox->maxY - $this->boundingBox->minY + 1) / 2)),
(int)($this->boundingBox->minZ + (($this->boundingBox->maxZ - $this->boundingBox->minZ + 1) / 2)),
);
}
public function isLiquidInStructureBoundingBox(Level $level, AxisAlignedBB $boundingBox){
$minX = max($boundingBox->minX - 1, $boundingBox->minX); //TODO optimize?
$minY = max($boundingBox->minY - 1, $boundingBox->minY);
$minZ = max($boundingBox->minZ - 1, $boundingBox->minZ);
$maxX = min($boundingBox->maxX + 1, $boundingBox->maxX);
$maxY = min($boundingBox->maxY + 1, $boundingBox->maxY);
$maxZ = min($boundingBox->maxZ + 1, $boundingBox->maxZ);
for($x = $minX; $x <= $maxX; ++$x){
for($z = $minZ; $z <= $maxZ; ++$z){
$blockID = $level->level->getBlockID($x, $minY, $z);
if($blockID > 0 && StaticBlock::getIsLiquid($blockID)) return true;
$blockID = $level->level->getBlockID($x, $maxY, $z);
if($blockID > 0 && StaticBlock::getIsLiquid($blockID)) return true;
}
}
for($x = $minX; $x <= $maxX; ++$x){
for($y = $minY; $y <= $maxY; ++$y){
$blockID = $level->level->getBlockID($x, $y, $minZ);
if($blockID > 0 && StaticBlock::getIsLiquid($blockID)) return true;
$blockID = $level->level->getBlockID($x, $y, $maxZ);
if($blockID > 0 && StaticBlock::getIsLiquid($blockID)) return true;
}
}
for($z = $minZ; $z <= $maxZ; ++$z){
for($y = $minY; $y <= $maxY; ++$y){
$blockID = $level->level->getBlockID($minX, $y, $z);
if($blockID > 0 && StaticBlock::getIsLiquid($blockID)) return true;
$blockID = $level->level->getBlockID($maxX, $y, $z);
if($blockID > 0 && StaticBlock::getIsLiquid($blockID)) return true;
}
}
return false;
}
public function getXWithOffset($par1, $par2){
return match($this->coordBaseMode){
0, 2 => $this->boundingBox->minX + $par1,
1 => $this->boundingBox->maxX - $par2,
3 => $this->boundingBox->minX + $par2,
default => $par1
};
}
public function getYWithOffset($par1){
return $this->coordBaseMode == -1 ? $par1 : $par1 + $this->boundingBox->minY;
}
public function getZWithOffset($par1, $par2){
return match($this->coordBaseMode){
0 => $this->boundingBox->minZ + $par2,
1, 3 => $this->boundingBox->minZ + $par1,
2 => $this->boundingBox->maxZ - $par2,
default => $par2
};
}
public function getMetadataWithOffset($blockID, $blockMeta){
switch($blockID){
case WOODEN_DOOR_BLOCK:
case IRON_DOOR_BLOCK:
switch($this->coordBaseMode){
case 0:
return match($blockMeta){
0 => 2,
2 => 0,
default => $blockMeta
};
case 1:
return $blockMeta + 1 & 3;
case 3:
return $blockMeta + 3 & 3;
}
break;
case COBBLESTONE_STAIRS:
case WOODEN_STAIRS:
case NETHER_BRICKS_STAIRS:
case STONE_BRICK_STAIRS:
case SANDSTONE_STAIRS:
switch($this->coordBaseMode){
case 0:
return match($blockMeta){
2 => 3,
3 => 2,
default => $blockMeta
};
case 1:
return match($blockMeta){
0 => 2,
1 => 3,
2 => 0,
3 => 1,
default => $blockMeta
};
case 3:
return match($blockMeta){
0 => 2,
1 => 3,
2 => 1,
3 => 0,
default => $blockMeta
};
}
break;
case RAIL:
if($this->coordBaseMode == 1 || $this->coordBaseMode == 3){
return $blockMeta == 1 ? 0 : 1;
}
break;
case LADDER:
switch($this->coordBaseMode){
case 0:
return match($blockMeta){
2 => 3,
3 => 2,
default => $blockMeta
};
case 1:
return match($blockMeta){
2 => 4,
3 => 5,
4 => 2,
5 => 3,
default => $blockMeta
};
case 3:
return match($blockMeta){
2 => 5,
3 => 4,
4 => 2,
5 => 3,
default => $blockMeta
};
}
//case stone_button, not needed
//case pistonbase, pistonstickybase, level, dispenser, not needed
}
/* TODO directional blocks, tripwire source(not needed prob)
* if (this.coordBaseMode == 0)
{
if (blockMeta == 0 || blockMeta == 2) return Direction.rotateOpposite[blockMeta];
}
else if (this.coordBaseMode == 1)
{
if (blockMeta == 2) return 1;
if (blockMeta == 0) return 3;
if (blockMeta == 1) return 2;
if (blockMeta == 3) return 0;
}
else if (this.coordBaseMode == 3)
{
if (blockMeta == 2) return 3;
if (blockMeta == 0) return 1;
if (blockMeta == 1) return 2;
if (blockMeta == 3) return 0;
}
*/
return $blockMeta;
}
public function placeBlockAtCurrentPosition(Level $level, $blockID, $blockMeta, $par4, $par5, $par6, AxisAlignedBB $boundingBox){
$x = $this->getXWithOffset($par4, $par6);
$y = $this->getYWithOffset($par5);
$z = $this->getZWithOffset($par4, $par6);
if($boundingBox->isXYZInside($x, $y, $z)){
$level->fastSetBlockUpdate($x, $y, $z, $blockID, $blockMeta);
}
}
public function getBlockIdAtCurrentPosition(Level $level, $par2, $par3, $par4, AxisAlignedBB $boundingBox){
$x = $this->getXWithOffset($par2, $par4);
$y = $this->getYWithOffset($par3);
$z = $this->getZWithOffset($par2, $par4);
return !$boundingBox->isXYZInside($x, $y, $z) ? 0 : $level->level->getBlockID($x, $y, $z);
}
public function fillWithAir(Level $level, AxisAlignedBB $boundingBox, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){
for($y = $minY; $y <= $maxY; ++$y){
for($x = $minX; $x <= $maxX; ++$x){
for($z = $minZ; $z < $maxZ; ++$z){
$this->placeBlockAtCurrentPosition($level, AIR, 0, $x, $y, $z, $boundingBox);
}
}
}
}
public function fillWithBlocks(Level $level, AxisAlignedBB $boundingBox, $minX, $minY, $minZ, $maxX, $maxY, $maxZ, $blockID, $replaceID, $alwaysReplace){
for($y = $minY; $y <= $maxY; ++$y){
for($x = $minX; $x <= $maxX; ++$x){
for($z = $minZ; $z < $maxZ; ++$z){
if(!$alwaysReplace || $this->getBlockIdAtCurrentPosition($level, $x, $y, $z, $boundingBox) != 0){
if($y != $minY && $y != $maxY && $x != $minX && $x != $maxX && $z != $minZ && $z != $maxZ){
$this->placeBlockAtCurrentPosition($level, $replaceID, 0, $x, $y, $z, $boundingBox);
}else{
$this->placeBlockAtCurrentPosition($level, $blockID, 0, $x, $y, $z, $boundingBox);
}
}
}
}
}
}
public function fillWithMetadataBlocks(){throw new Exception("Not Implemented");} //TODO it is too long + not used for mineshafts i want now
public function fillWithRandomizedBlocks(){throw new Exception("Not Implemented");} //TODO it is too long + not used for mineshafts i want now
public function randomlyFillWithBlocks(Level $level, AxisAlignedBB $boundingBox, MTRandom $random, $randomChance, $minX, $minY, $minZ, $maxX, $maxY, $maxZ, $blockID, $replaceID, $alwaysReplace){
for($y = $minY; $y <= $maxY; ++$y){
for($x = $minX; $x <= $maxX; ++$x){
for($z = $minZ; $z < $maxZ; ++$z){
if($random->nextFloat() <= $randomChance && (!$alwaysReplace || $this->getBlockIdAtCurrentPosition($level, $x, $y, $z, $boundingBox) != 0)){
if($y != $minY && $y != $maxY && $x != $minX && $x != $maxX && $z != $minZ && $z != $maxZ){
$this->placeBlockAtCurrentPosition($level, $replaceID, 0, $x, $y, $z, $boundingBox);
}else{
$this->placeBlockAtCurrentPosition($level, $blockID, 0, $x, $y, $z, $boundingBox);
}
}
}
}
}
}
public function randomlyPlaceBlock(Level $level, AxisAlignedBB $boundingBox, MTRandom $random, $randomChance, $x, $y, $z, $blockID, $blockMeta){
if($random->nextFloat() < $randomChance) $this->placeBlockAtCurrentPosition($level, $blockID, $blockMeta, $x, $y, $z, $boundingBox);
}
public function randomlyRareFillWithBlocks(Level $level, AxisAlignedBB $boundingBox, $minX, $minY, $minZ, $maxX, $maxY, $maxZ, $blockID, $alwaysreplace){
$v11 = ($maxX - $minX + 1);
$v12 = ($maxY - $minY + 1);
$v13 = ($maxZ - $minZ + 1);
$v14 = $minX + $v11 / 2;
$v15 = $minZ + $v13 / 2;
for($y = $minY; $y <= $maxY; ++$y){
$v17 = ($y - $minY) / $v12;
for($x = $minX; $x <= $maxX; ++$x){
$v19 = ($x - $v14) / ($v11 * 0.5);
for($z = $minZ; $z <= $maxZ; ++$z){
$v21 = ($z - $v15) / ($v13 * 0.5);
if(!$alwaysreplace || $this->getBlockIdAtCurrentPosition($level, $x, $y, $z, $boundingBox) != 0){
$v22 = $v19*$v19 + $v17*$v17 + $v21*$v21;
if($v22 <= 1.05){
$this->placeBlockAtCurrentPosition($level, $blockID, 0, $x, $y, $z, $boundingBox);
}
}
}
}
}
}
public function clearCurrentPositionBlocksUpwards(){throw new Exception("Not Implemented");} //TODO implement, used for villages
public function fillCurrentPositionBlocksDownwards(){throw new Exception("Not Implemented");} //TODO implement, used for villages
public function generateStructureChestContents(){throw new Exception("Not Implemented");} //TODO implement
public function placeDoorAtCurrentPosition(){throw new Exception("Not Implemented");} //TODO implement
}

View file

@ -0,0 +1,39 @@
<?php
abstract class StructureGenerator extends StructureBase
{
/**
* @var StructureStart
*/
public $structureMap = []; //php array is hashmap
public function recursiveGenerate(Level $level, $chunkXoffsetted, $chunkZoffsetted, $chunkX, $chunkZ){
$chunkXZ = Utils::chunkPos2Int($chunkXoffsetted, $chunkZoffsetted);
if(!isset($this->structureMap[$chunkXZ])){
$this->rand->nextInt(); //shouldnt be neccessary, but vanilla has it.
if($this->canSpawnStructureAt($chunkXoffsetted, $chunkZoffsetted)){
$structureStrat = $this->getStructureStart($level, $chunkXoffsetted, $chunkZoffsetted);
$this->structureMap[$chunkXZ] = $structureStrat;
}
}
}
public function generateStructuresInChunk(Level $level, MTRandom $random, $chunkX, $chunkZ){
$chunkXCenter = ($chunkX << 4) + 8;
$chunkZCenter = ($chunkZ << 4) + 8;
$var7 = false;
foreach($this->structureMap as $start){
if($start->isSizeableStructure() && $start->boundingBox->intersectsWith($chunkXCenter, $chunkZCenter, $chunkXCenter + 15, $chunkZCenter + 15)){
$start->generateStructure($level, $random, new StructureAABB($chunkXCenter, 1, $chunkZCenter, $chunkXCenter + 15, 512, $chunkZCenter + 15));
$var7 = true;
}
}
return $var7;
}
public abstract function canSpawnStructureAt($chunkX, $chunkZ);
public abstract function getStructureStart(Level $level, $chunkX, $chunkZ);
}

View file

@ -0,0 +1,54 @@
<?php
abstract class StructureStart
{
/**
* @var StructureComponent[]
*/
public $components = [];
public $boundingBox;
public function generateStructure(Level $level, MTRandom $random, AxisAlignedBB $boundingBox){
foreach($this->components as $k => $component){
if($component->boundingBox->intersectsWith($boundingBox) && !$component->addComponentParts($level, $random, $boundingBox)){
unset($this->components[$k]);
}
}
}
public function updateBoundingBox(){
$this->boundingBox = new StructureAABB(0, 0, 0, 0, 0, 0);
foreach($this->components as $k => $component){
$this->boundingBox->expandTo($component->boundingBox);
}
}
public function markAvailableHeight(Level $level, MTRandom $random, $height){
$var4 = 63 - $height;
$var5 = $this->boundingBox->getYSize() + 1;
if($var5 < $var4) $var5 += $random->nextInt($var4 - $var5);
$var6 = (int)($var5 - $this->boundingBox->maxY);
$this->boundingBox->offset(0, $var6, 0);
foreach($this->components as $component){
$component->boundingBox->offset(0, $var6, 0);
}
}
public function setRandomHeight(Level $level, MTRandom $random, $par3, $par4){
$var5 = (int)($par4 - $par3 + 1 - $this->boundingBox->getYSize());
$var10 = $var5 > 1 ? $par3 + $random->nextInt($var5) : $par3;
$var6 = (int)($var10 - $this->boundingBox->minY);
$this->boundingBox->offset(0, $var6, 0);
foreach($this->components as $component){
$component->boundingBox->offset(0, $var6, 0);
}
}
public function isSizeableStructure(){
return true;
}
}

View file

@ -0,0 +1,43 @@
<?php
class StructureMineshaftPieces
{
//TODO chests
//private static final WeightedRandomChestContent[] mineshaftChestContents = new WeightedRandomChestContent[] {new WeightedRandomChestContent(Item.ingotIron.itemID, 0, 1, 5, 10), new WeightedRandomChestContent(Item.ingotGold.itemID, 0, 1, 3, 5), new WeightedRandomChestContent(Item.redstone.itemID, 0, 4, 9, 5), new WeightedRandomChestContent(Item.dyePowder.itemID, 4, 4, 9, 5), new WeightedRandomChestContent(Item.diamond.itemID, 0, 1, 2, 3), new WeightedRandomChestContent(Item.coal.itemID, 0, 3, 8, 10), new WeightedRandomChestContent(Item.bread.itemID, 0, 1, 3, 15), new WeightedRandomChestContent(Item.pickaxeIron.itemID, 0, 1, 1, 1), new WeightedRandomChestContent(Block.rail.blockID, 0, 4, 8, 1), new WeightedRandomChestContent(Item.melonSeeds.itemID, 0, 2, 4, 10), new WeightedRandomChestContent(Item.pumpkinSeeds.itemID, 0, 2, 4, 10)};
/**
* @return StructureComponent
*/
public static function getRandomComponent($aList, MTRandom $random, $par2, $par3, $par4, $par5, $par6){
$var7 = $random->nextInt(100);
/*if($var7 >= 80){
$var8 = ComponentMineshaftCross //TODO
if($var8 != null) return new ComponentMineshaftCross($par6, $random, $var8, $par5);
}else if($var7 >= 70){
$var8 = ComponentMineshaftStairs //TODO
if($var8 != null) return new ComponentMineshaftStairs($par6, $random, $var8, $par5);
}else{
$var8 = ComponentMineshaftCorridor //TODO
if($var8 != null) return new ComponentMineshaftCorridor($par6, $random, $var8, $par5);
}*/
return null;
}
public static function getNextMineShaftComponent(StructureComponent $component, $aList, MTRandom $random, $par3, $par4, $par5, $par6, $par7){
if($par7 > 8) return null;
if(abs($par3 - $component->boundingBox->minX) <= 80 && abs($par5 - $component->boundingBox->minZ) <= 80){
$var8 = self::getRandomComponent($aList, $random, $par3, $par4, $par5, $par6, $par7 + 1);
if($var8 != null){
$aList[] = $var8;
$var8->buildComponent($component, $aList, $random);
}
return $var8;
}
return null;
}
}

View file

@ -0,0 +1,13 @@
<?php
class StructureMineshaftStart extends StructureStart
{
public function __construct(Level $level, MTRandom $random, $par3, $par4){
$var5 = new ComponentMineshaftRoom(0, $random, ($par3 << 4) + 2, ($par4 << 4) + 2);
$this->components[] = $var5;
$var5->buildComponent($var5, $this->components, $random);
$this->updateBoundingBox();
$this->markAvailableHeight($level, $random, 10);
}
}

View file

@ -0,0 +1,91 @@
<?php
class ComponentMineshaftRoom extends StructureComponent
{
/**
* @var AxisAlignedBB[]
*/
public $roomsLinkedToTheRoom = [];
public function __construct($par1, MTRandom $random, $par3, $par4){
parent::__construct($par1);
$this->boundingBox = new AxisAlignedBB($par3, 50, $par4, $par3 + 7 + $random->nextInt(6), $par4 + 7, $par4 + 7 + $random->nextInt(6));
}
public function buildComponent(StructureComponent $component, $aList, MTRandom $random){
$var4 = $this->componentType;
$var6 = $this->boundingBox->getYSize() - 3 - 1;
if($var6 <= 0) $var6 = 1;
for($var5 = 0; $var5 < $this->boundingBox->getXSize(); $var5 += 4){
$var5 += $random->nextInt($this->boundingBox->getXSize());
if($var5 + 3 < $this->boundingBox->getXSize()) break;
//var7 = StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + var5, this.boundingBox.minY + par3Random.nextInt(var6) + 1, this.boundingBox.minZ - 1, 2, var4);
$var7 = StructureMineshaftPieces::getNextMineShaftComponent($component, $aList, $random, $this->boundingBox->minX + $var5, $this->boundingBox->minY + $random->nextInt($var6) + 1, $this->boundingBox->minZ - 1, 2, $var4);
if($var7 != null){
$var8 = $var7->boundingBox;
//this.roomsLinkedToTheRoom.add(new StructureBoundingBox(var8.minX, var8.minY, this.boundingBox.minZ, var8.maxX, var8.maxY, this.boundingBox.minZ + 1));
$this->roomsLinkedToTheRoom[] = new StructureAABB($var8->minX, $var8->minY, $this->boundingBox->minZ, $var8->maxX, $var8->maxY, $this->boundingBox->minZ + 1);
}
}
for($var5 = 0; $var5 < $this->boundingBox->getXSize(); $var5 += 4){
$var5 += $random->nextInt($this->boundingBox->getXSize());
if($var5 + 3 < $this->boundingBox->getXSize()) break;
//var7 = StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + var5, this.boundingBox.minY + par3Random.nextInt(var6) + 1, this.boundingBox.maxZ + 1, 0, var4);
$var7 = StructureMineshaftPieces::getNextMineShaftComponent($component, $aList, $random, $this->boundingBox->minX + $var5, $this->boundingBox->minY + $random->nextInt($var6) + 1, $this->boundingBox->maxZ + 1, 0, $var4);
if($var7 != null){
$var8 = $var7->boundingBox;
//this.roomsLinkedToTheRoom.add(new StructureBoundingBox(var8.minX, var8.minY, this.boundingBox.maxZ - 1, var8.maxX, var8.maxY, this.boundingBox.maxZ));
$this->roomsLinkedToTheRoom[] = new StructureAABB($var8->minX, $var8->minY, $this->boundingBox->maxZ - 1, $var8->maxX, $var8->maxY, $this->boundingBox->maxZ);
}
}
for($var5 = 0; $var5 < $this->boundingBox->getZSize(); $var5 += 4){
$var5 += $random->nextInt($this->boundingBox->getZSize());
if($var5 + 3 < $this->boundingBox->getZSize()) break;
//var7 = StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX - 1, this.boundingBox.minY + par3Random.nextInt(var6) + 1, this.boundingBox.minZ + var5, 1, var4);
$var7 = StructureMineshaftPieces::getNextMineShaftComponent($component, $aList, $random, $this->boundingBox->minX - 1, $this->boundingBox->minY + $random->nextInt($var6) + 1, $this->boundingBox->minZ + $var5, 1, $var4);
if($var7 != null){
$var8 = $var7->boundingBox;
//this.roomsLinkedToTheRoom.add(new StructureBoundingBox(this.boundingBox.minX, var8.minY, var8.minZ, this.boundingBox.minX + 1, var8.maxY, var8.maxZ));
$this->roomsLinkedToTheRoom[] = new StructureAABB($this->boundingBox->minX, $var8->minY, $var8->minZ, $this->boundingBox->minX + 1, $var8->maxY, $var8->maxZ);
}
}
for($var5 = 0; $var5 < $this->boundingBox->getZSize(); $var5 += 4){
$var5 += $random->nextInt($this->boundingBox->getZSize());
if($var5 + 3 < $this->boundingBox->getZSize()) break;
//var7 = StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.maxX + 1, this.boundingBox.minY + par3Random.nextInt(var6) + 1, this.boundingBox.minZ + var5, 3, var4);
$var7 = StructureMineshaftPieces::getNextMineShaftComponent($component, $aList, $random, $this->boundingBox->maxX + 1, $this->boundingBox->minY + $random->nextInt($var6) + 1, $this->boundingBox->minZ + $var5, 3, $var4);
if($var7 != null){
$var8 = $var7->boundingBox;
// this.roomsLinkedToTheRoom.add(new StructureBoundingBox(this.boundingBox.maxX - 1, var8.minY, var8.minZ, this.boundingBox.maxX, var8.maxY, var8.maxZ));
$this->roomsLinkedToTheRoom[] = new StructureAABB($this->boundingBox->maxX - 1, $var8->minY, $var8->minZ, $this->boundingBox->maxX, $var8->maxY, $var8->maxZ);
}
}
}
public function addComponentParts(Level $level, MTRandom $random, AxisAlignedBB $boundingBox): bool
{
if($this->isLiquidInStructureBoundingBox($level, $boundingBox)){
return false;
}
console("Adding Mineshaft start components! $boundingBox");
$this->fillWithBlocks($level, $boundingBox, $this->boundingBox->minX, $this->boundingBox->minY, $this->boundingBox->minZ, $this->boundingBox->maxX, $this->boundingBox->maxY, $this->boundingBox->maxZ, DIRT, 0, true);
$this->fillWithBlocks($level, $boundingBox, $this->boundingBox->minX, $this->boundingBox->minY + 1, $this->boundingBox->minZ, $this->boundingBox->maxX, min($this->boundingBox->minY + 3, $this->boundingBox->maxY), $this->boundingBox->maxZ, 0, 0, false);
foreach($this->roomsLinkedToTheRoom as $bb){
//this.fillWithBlocks(par1World, par3StructureBoundingBox, var5.minX, var5.maxY - 2, var5.minZ, var5.maxX, var5.maxY, var5.maxZ, 0, 0, false);
$this->fillWithBlocks($level, $boundingBox, $bb->minX, $bb->maxY - 2, $bb->minZ, $bb->maxX, $bb->maxY, $bb->maxZ, 0, 0, false);
}
$this->randomlyRareFillWithBlocks($level, $boundingBox, $this->boundingBox->minX, $this->boundingBox->minY + 4, $this->boundingBox->minZ, $this->boundingBox->maxX, $this->boundingBox->maxY, $this->boundingBox->maxZ, 0, false);
return true;
}
}

View file

@ -20,9 +20,9 @@ while getopts "p:f:l" OPTION 2> /dev/null; do
done
if [ "$PHP_BINARY" == "" ]; then
if [ -f ./bin/php5/bin/php ]; then
if [ -f ./bin/php7/bin/php ]; then
export PHPRC=""
PHP_BINARY="./bin/php5/bin/php"
PHP_BINARY="./bin/php7/bin/php"
elif [[ ! -z $(type php) ]]; then
PHP_BINARY=$(type -p php)
else