From 809195b688dc5fc4e57b24396b3f3368208a7a52 Mon Sep 17 00:00:00 2001
From: ArkQuark <74979909+ArkQuark@users.noreply.github.com>
Date: Thu, 20 Jan 2022 19:39:16 +0300
Subject: [PATCH] Updated to 1.4dev228 generation
---
src/API/LevelAPI.php | 16 +-
src/Player.php | 48 +-
src/Player.php.bak | 2434 +++++++++++++++++
src/build/compile.sh | 0
src/constants/GeneralConstants.php | 2 +-
src/constants/GeneralConstants.php.bak | 85 +
src/material/block/solid/Stonecutter.php | 14 +-
src/pmf/{Level.php => PMFLevel.php} | 400 +--
src/pmf/{Plugin.php => PMFPlugin.php} | 0
src/world/Entity.php | 9 +-
src/world/Level.php | 41 +-
src/world/LevelImport.php | 7 +-
src/world/generator/LevelGenerator.php | 7 +-
src/world/generator/NormalGenerator.php | 169 ++
src/world/generator/NormalGenerator.php.bak | 169 ++
src/world/generator/SuperflatGenerator.php | 8 +-
src/world/generator/TemporalGenerator.php | 95 -
src/world/generator/WorldGenerator.php | 28 +-
src/world/generator/noise/NoiseGenerator.php | 72 +
.../generator/noise/NoiseGeneratorOctaves.php | 4 +-
.../generator/noise/NoiseGeneratorPerlin.php | 195 +-
.../generator/noise/NoiseGeneratorSimplex.php | 438 +++
src/world/generator/noise/OctaveGenerator.php | 108 +
.../generator/noise/PerlinOctaveGenerator.php | 63 +
.../object/grass/TallGrassObject.php | 6 +-
.../object/grass/TallGrassObject.php.bak | 43 +
.../generator/object/tree/SmallTreeObject.php | 4 +-
.../object/tree/SmallTreeObject.php.bak | 104 +
.../generator/object/tree/TreeObject.php | 2 +
.../populator/MineshaftPopulator.php | 2 +-
.../generator/populator/OrePopulator.php | 4 +-
.../populator/TallGrassPopulator.php | 75 +
.../populator/TallGrassPopulator.php.bak | 75 +
.../generator/populator/TreePopulator.php | 69 +
.../generator/populator/TreePopulator.php.bak | 69 +
35 files changed, 4398 insertions(+), 467 deletions(-)
create mode 100644 src/Player.php.bak
mode change 100755 => 100644 src/build/compile.sh
create mode 100644 src/constants/GeneralConstants.php.bak
rename src/pmf/{Level.php => PMFLevel.php} (55%)
rename src/pmf/{Plugin.php => PMFPlugin.php} (100%)
create mode 100644 src/world/generator/NormalGenerator.php
create mode 100644 src/world/generator/NormalGenerator.php.bak
delete mode 100644 src/world/generator/TemporalGenerator.php
create mode 100644 src/world/generator/noise/NoiseGeneratorSimplex.php
create mode 100644 src/world/generator/noise/OctaveGenerator.php
create mode 100644 src/world/generator/noise/PerlinOctaveGenerator.php
create mode 100644 src/world/generator/object/grass/TallGrassObject.php.bak
create mode 100644 src/world/generator/object/tree/SmallTreeObject.php.bak
create mode 100644 src/world/generator/populator/TallGrassPopulator.php
create mode 100644 src/world/generator/populator/TallGrassPopulator.php.bak
create mode 100644 src/world/generator/populator/TreePopulator.php
create mode 100644 src/world/generator/populator/TreePopulator.php.bak
diff --git a/src/API/LevelAPI.php b/src/API/LevelAPI.php
index 722d6ddd..e93e6df3 100644
--- a/src/API/LevelAPI.php
+++ b/src/API/LevelAPI.php
@@ -94,7 +94,7 @@ class LevelAPI{
if(strtoupper($this->server->api->getProperty("level-type")) == "FLAT"){
$generator = new SuperflatGenerator($options);
}else{
- $generator = new TemporalGenerator($options);
+ $generator = new NormalGenerator($options);
}
}
$gen = new WorldGenerator($generator, $name, $seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)):(int) $seed);
@@ -227,20 +227,6 @@ class LevelAPI{
return $this->server->spawn;
}
- public function loadMap(){
- if($this->mapName !== false and trim($this->mapName) !== ""){
- if(!file_exists($this->mapDir."level.pmf")){
- $level = new LevelImport($this->mapDir);
- $level->import();
- }
- $this->level = new PMFLevel($this->mapDir."level.pmf");
- console("[INFO] Preparing level \"".$this->level->getData("name")."\"");
- $this->time = (int) $this->level->getData("time");
- $this->seed = (int) $this->level->getData("seed");
- $this->spawn = $this->level->getSpawn();
- }
- }
-
public function getAll(){
return $this->levels;
}
diff --git a/src/Player.php b/src/Player.php
index a56b15c7..28fdf6f1 100644
--- a/src/Player.php
+++ b/src/Player.php
@@ -63,6 +63,7 @@ class Player{
public $blocked = true;
public $achievements = array();
public $chunksLoaded = array();
+ private $viewDistance;
private $chunksOrder = array();
private $lastMeasure = 0;
private $bandwidthRaw = 0;
@@ -112,6 +113,7 @@ class Player{
$this->armor = array();
$this->gamemode = $this->server->gamemode;
$this->level = $this->server->api->level->getDefault();
+ $this->viewDistance = (int) $this->server->api->getProperty("view-distance");
$this->slot = 0;
$this->hotbar = array(0, -1, -1, -1, -1, -1, -1, -1, -1);
$this->packetStats = array(0,0);
@@ -148,22 +150,35 @@ class Player{
if(!($this->entity instanceof Entity) or $this->connected === false){
return false;
}
- $X = $this->entity->x >> 4;
- $Z = $this->entity->z >> 4;
- $v = new Vector2($X, $Z);
- $this->chunksOrder = array();
- for($x = 0; $x < 16; ++$x){
- for($z = 0; $z < 16; ++$z){
- $dist = $v->distance(new Vector2($x, $z));
- for($y = 0; $y < 8; ++$y){
- $d = $x.":".$y.":".$z;
- if(!isset($this->chunksLoaded[$d])){
- $this->chunksOrder[$d] = $dist;
+
+ $newOrder = array();
+ $lastLoaded = $this->chunksLoaded;
+ $centerX = intval($this->entity->x >> 4);
+ $centerZ = intval($this->entity->z >> 4);
+ $startX = $centerX - $this->viewDistance;
+ $startZ = $centerZ - $this->viewDistance;
+ $finalX = $centerX + $this->viewDistance;
+ $finalZ = $centerZ + $this->viewDistance;
+ for($X = $startX; $X <= $finalX; ++$X){
+ for($Z = $startZ; $Z <= $finalZ; ++$Z){
+ $distance = abs($X - $centerX) + abs($Z - $centerZ);
+ for($Y = 0; $Y < 8; ++$Y){
+ $index = "$X:$Y:$Z";
+ if(!isset($lastLoaded[$index])){
+ $newOrder[$index] = $distance;
+ }else{
+ unset($lastLoaded[$index]);
}
}
}
}
- asort($this->chunksOrder);
+ asort($newOrder);
+ $this->chunksOrder = $newOrder;
+ foreach($lastLoaded as $index => $distance){
+ $id = explode(":", $index);
+ $this->level->freeChunk($id[0], $id[2], $this);
+ unset($this->chunksLoaded[$index]);
+ }
}
public function getNextChunk(){
@@ -195,7 +210,7 @@ class Player{
$c = key($this->chunksOrder);
$d = @$this->chunksOrder[$c];
- if($c === null or $d === null){
+ if($c === null){
$this->server->schedule(40, array($this, "getNextChunk"));
return false;
}
@@ -305,7 +320,7 @@ class Player{
if($msg === true and $this->username != "" and $this->spawned !== false){
$this->server->api->chat->broadcast($this->username." left the game");
}
- $this->spawned = false;
+ $this->spawned = false;
console("[INFO] ".FORMAT_AQUA.$this->username.FORMAT_RESET."[/".$this->ip.":".$this->port."] logged out due to ".$reason);
$this->windows = array();
$this->armor = array();
@@ -1465,7 +1480,7 @@ class Player{
$this->sendInventory();
$this->sendSettings();
- $this->server->schedule(50, array($this, "orderChunks"), array(), true);
+ $this->server->schedule(30, array($this, "orderChunks"), array(), true);
$this->blocked = false;
$pk = new SetTimePacket;
@@ -1957,9 +1972,6 @@ class Player{
CARROT => 4,
POTATO => 1,
BAKED_POTATO => 6,
- //COOKIE => 2,
- //COOKED_FISH => 5,
- //RAW_FISH => 2,
);
$slot = $this->getSlot($this->slot);
if($this->entity->getHealth() < 20 and isset($items[$slot->getID()])){
diff --git a/src/Player.php.bak b/src/Player.php.bak
new file mode 100644
index 00000000..11d98e7b
--- /dev/null
+++ b/src/Player.php.bak
@@ -0,0 +1,2434 @@
+{$name})){
+ return ($this->{$name});
+ }
+ return null;
+ }
+
+ /**
+ * @param integer $clientID
+ * @param string $ip
+ * @param integer $port
+ * @param integer $MTU
+ */
+ public function __construct($clientID, $ip, $port, $MTU){
+ $this->bigCnt = 0;
+ $this->MTU = $MTU;
+ $this->server = ServerAPI::request();
+ $this->lastBreak = microtime(true);
+ $this->clientID = $clientID;
+ $this->CID = PocketMinecraftServer::clientID($ip, $port);
+ $this->ip = $ip;
+ $this->port = $port;
+ $this->spawnPosition = $this->server->spawn;
+ $this->timeout = microtime(true) + 20;
+ $this->inventory = array();
+ $this->armor = array();
+ $this->gamemode = $this->server->gamemode;
+ $this->level = $this->server->api->level->getDefault();
+ $this->viewDistance = (int) $this->server->api->getProperty("view-distance");
+ $this->slot = 0;
+ $this->hotbar = array(0, -1, -1, -1, -1, -1, -1, -1, -1);
+ $this->packetStats = array(0,0);
+ $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
+ $this->buffer->data = array();
+ $this->server->schedule(2, array($this, "handlePacketQueues"), array(), true);
+ $this->server->schedule(20 * 60, array($this, "clearQueue"), array(), true);
+ $this->evid[] = $this->server->event("server.close", array($this, "close"));
+ console("[DEBUG] New Session started with ".$ip.":".$port.". MTU ".$this->MTU.", Client ID ".$this->clientID, true, true, 2);
+ }
+
+ public function getSpawn(){
+ return $this->spawnPosition;
+ }
+
+ /**
+ * @param Vector3 $pos
+ */
+ public function setSpawn(Vector3 $pos){
+ if(!($pos instanceof Position)){
+ $level = $this->level;
+ }else{
+ $level = $pos->level;
+ }
+ $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $level);
+ $pk = new SetSpawnPositionPacket;
+ $pk->x = (int) $this->spawnPosition->x;
+ $pk->y = (int) $this->spawnPosition->y;
+ $pk->z = (int) $this->spawnPosition->z;
+ $this->dataPacket($pk);
+ }
+
+ public function orderChunks(){
+ if(!($this->entity instanceof Entity) or $this->connected === false){
+ return false;
+ }
+
+ $newOrder = array();
+ $lastLoaded = $this->chunksLoaded;
+ $centerX = intval($this->entity->x >> 4);
+ $centerZ = intval($this->entity->z >> 4);
+ $startX = $centerX - $this->viewDistance;
+ $startZ = $centerZ - $this->viewDistance;
+ $finalX = $centerX + $this->viewDistance;
+ $finalZ = $centerZ + $this->viewDistance;
+ for($X = $startX; $X <= $finalX; ++$X){
+ for($Z = $startZ; $Z <= $finalZ; ++$Z){
+ $distance = abs($X - $centerX) + abs($Z - $centerZ);
+ for($Y = 0; $Y < 8; ++$Y){
+ $index = "$X:$Y:$Z";
+ if(!isset($lastLoaded[$index])){
+ $newOrder[$index] = $distance;
+ }else{
+ unset($lastLoaded[$index]);
+ }
+ }
+ }
+ }
+ asort($newOrder);
+ $this->chunksOrder = $newOrder;
+ foreach($lastLoaded as $index => $distance){
+ $id = explode(":", $index);
+ $this->level->freeChunk($id[0], $id[2], $this);
+ unset($this->chunksLoaded[$index]);
+ }
+ }
+
+ public function getNextChunk(){
+ if($this->connected === false){
+ return false;
+ }
+
+ foreach($this->chunkCount as $count => $t){
+ if(isset($this->recoveryQueue[$count]) or isset($this->resendQueue[$count])){
+ $this->server->schedule(MAX_CHUNK_RATE, array($this, "getNextChunk"));
+ return;
+ }else{
+ unset($this->chunkCount[$count]);
+ }
+ }
+
+ 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){
+ while(($tile = $tiles->fetchArray(SQLITE3_ASSOC)) !== false){
+ $tile = $this->server->api->tile->getByID($tile["ID"]);
+ if($tile instanceof Tile){
+ $tile->spawn($this);
+ }
+ }
+ }
+ }
+
+ $c = key($this->chunksOrder);
+ $d = @$this->chunksOrder[$c];
+ if($c === null){
+ $this->server->schedule(40, array($this, "getNextChunk"));
+ return false;
+ }
+ unset($this->chunksOrder[$c]);
+ $this->chunksLoaded[$c] = true;
+ $id = explode(":", $c);
+ $X = $id[0];
+ $Z = $id[2];
+ $Y = $id[1];
+ $x = $X << 4;
+ $z = $Z << 4;
+ $y = $Y << 4;
+ $this->level->useChunk($X, $Z, $this);
+ $Yndex = 1 << $Y;
+ for($iY = 0; $iY < 8; ++$iY){
+ if(isset($this->chunksOrder["$X:$iY:$Z"])){
+ unset($this->chunksOrder["$X:$iY:$Z"]);
+ $this->chunksLoaded["$X:$iY:$Z"] = true;
+ $Yndex |= 1 << $iY;
+ }
+ }
+ $pk = new ChunkDataPacket;
+ $pk->chunkX = $X;
+ $pk->chunkZ = $Z;
+ $pk->data = $this->level->getOrderedChunk($X, $Z, $Yndex);
+ $cnt = $this->dataPacket($pk);
+ if($cnt === false){
+ return false;
+ }
+ $this->chunkCount = array();
+ foreach($cnt as $i => $count){
+ $this->chunkCount[$count] = true;
+ }
+
+ $this->lastChunk = array($x, $z);
+
+ $this->server->schedule(MAX_CHUNK_RATE, array($this, "getNextChunk"));
+ }
+
+ public function save(){
+ if($this->entity instanceof Entity){
+ $this->data->set("achievements", $this->achievements);
+ $this->data->set("position", array(
+ "level" => $this->entity->level->getName(),
+ "x" => (float) $this->entity->x,
+ "y" => $this->entity->y,
+ "z" => (float) $this->entity->z,
+ ));
+ $this->data->set("spawn", array(
+ "level" => $this->spawnPosition->level->getName(),
+ "x" => $this->spawnPosition->x,
+ "y" => $this->spawnPosition->y,
+ "z" => $this->spawnPosition->z,
+ ));
+ $inv = array();
+ foreach($this->inventory as $slot => $item){
+ if($item instanceof Item){
+ if($slot < (($this->gamemode & 0x01) === 0 ? PLAYER_SURVIVAL_SLOTS:PLAYER_CREATIVE_SLOTS)){
+ $inv[$slot] = array($item->getID(), $item->getMetadata(), $item->count);
+ }
+ }
+ }
+ $this->data->set("inventory", $inv);
+ $this->data->set("hotbar", $this->hotbar);
+
+ $armor = array();
+ foreach($this->armor as $slot => $item){
+ if($item instanceof Item){
+ $armor[$slot] = array($item->getID(), $item->getMetadata());
+ }
+ }
+ $this->data->set("armor", $armor);
+ if($this->entity instanceof Entity){
+ $this->data->set("health", $this->entity->getHealth());
+ }
+ $this->data->set("gamemode", $this->gamemode);
+ }
+ }
+
+ /**
+ * @param string $reason Reason for closing connection
+ * @param boolean $msg Set to false to silently disconnect player. No broadcast.
+ */
+ public function close($reason = "", $msg = true){
+ if($this->connected === true){
+ foreach($this->evid as $ev){
+ $this->server->deleteEvent($ev);
+ }
+ if($this->username != ""){
+ $this->server->api->handle("player.quit", $this);
+ $this->save();
+ }
+ $reason = $reason == "" ? "server stop":$reason;
+ $this->sendChat("You have been kicked. Reason: ".$reason."\n");
+ $this->sendBuffer();
+ $this->directDataPacket(new DisconnectPacket);
+ $this->connected = false;
+ $this->level->freeAllChunks($this);
+ $this->loggedIn = false;
+ $this->buffer = null;
+ unset($this->buffer);
+ $this->recoveryQueue = array();
+ $this->receiveQueue = array();
+ $this->resendQueue = array();
+ $this->ackQueue = array();
+ $this->server->api->player->remove($this->CID);
+ if($msg === true and $this->username != "" and $this->spawned !== false){
+ $this->server->api->chat->broadcast($this->username." left the game");
+ }
+ $this->spawned = false;
+ console("[INFO] ".FORMAT_AQUA.$this->username.FORMAT_RESET."[/".$this->ip.":".$this->port."] logged out due to ".$reason);
+ $this->windows = array();
+ $this->armor = array();
+ $this->inventory = array();
+ $this->chunksLoaded = array();
+ $this->chunksOrder = array();
+ $this->chunkCount = array();
+ $this->cratingItems = array();
+ $this->received = array();
+ }
+ }
+
+ /**
+ * @param Vector3 $pos
+ *
+ * @return boolean
+ */
+ public function sleepOn(Vector3 $pos){
+ foreach($this->server->api->player->getAll($this->level) as $p){
+ if($p->isSleeping instanceof Vector3){
+ if($pos->distance($p->isSleeping) <= 0.1){
+ return false;
+ }
+ }
+ }
+ $this->isSleeping = $pos;
+ $this->teleport(new Position($pos->x + 0.5, $pos->y + 1, $pos->z + 0.5, $this->level), false, false, false, false);
+ if($this->entity instanceof Entity){
+ $this->entity->updateMetadata();
+ }
+ $this->setSpawn($pos);
+ $this->server->schedule(60, array($this, "checkSleep"));
+ return true;
+ }
+
+ public function stopSleep(){
+ $this->isSleeping = false;
+ if($this->entity instanceof Entity){
+ $this->entity->updateMetadata();
+ }
+ }
+
+ 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
+ * @param $count
+ *
+ * @return boolean
+ */
+ public function hasSpace($type, $damage, $count){
+ $inv = $this->inventory;
+ while($count > 0){
+ $add = 0;
+ foreach($inv as $s => $item){
+ if($item->getID() === AIR){
+ $add = min($item->getMaxStackSize(), $count);
+ $inv[$s] = BlockAPI::getItem($type, $damage, $add);
+ break;
+ }elseif($item->getID() === $type and $item->getMetadata() === $damage){
+ $add = min($item->getMaxStackSize() - $item->count, $count);
+ if($add <= 0){
+ continue;
+ }
+ $inv[$s] = BlockAPI::getItem($type, $damage, $item->count + $add);
+ break;
+ }
+ }
+ if($add <= 0){
+ return false;
+ }
+ $count -= $add;
+ }
+ return true;
+ }
+
+ /**
+ * @param $type
+ * @param $damage
+ * @param integer $count
+ * @param boolean $send
+ *
+ * @return boolean
+ */
+ public function addItem($type, $damage, $count, $send = true){
+ while($count > 0){
+ $add = 0;
+ foreach($this->inventory as $s => $item){
+ if($item->getID() === AIR){
+ $add = min($item->getMaxStackSize(), $count);
+ $this->inventory[$s] = BlockAPI::getItem($type, $damage, $add);
+ if($send === true){
+ $this->sendInventorySlot($s);
+ }
+ break;
+ }elseif($item->getID() === $type and $item->getMetadata() === $damage){
+ $add = min($item->getMaxStackSize() - $item->count, $count);
+ if($add <= 0){
+ continue;
+ }
+ $item->count += $add;
+ if($send === true){
+ $this->sendInventorySlot($s);
+ }
+ break;
+ }
+ }
+ if($add <= 0){
+ return false;
+ }
+ $count -= $add;
+ }
+ return true;
+ }
+
+ public function removeItem($type, $damage, $count, $send = true){
+ while($count > 0){
+ $remove = 0;
+ foreach($this->inventory as $s => $item){
+ if($item->getID() === $type and $item->getMetadata() === $damage){
+ $remove = min($count, $item->count);
+ if($remove < $item->count){
+ $item->count -= $remove;
+ }else{
+ $this->inventory[$s] = BlockAPI::getItem(AIR, 0, 0);
+ }
+ if($send === true){
+ $this->sendInventorySlot($s);
+ }
+ break;
+ }
+ }
+ if($remove <= 0){
+ return false;
+ }
+ $count -= $remove;
+ }
+ return true;
+ }
+
+ /**
+ * @param integer $slot
+ * @param Item $item
+ * @param boolean $send
+ *
+ * @return boolean
+ */
+ public function setSlot($slot, Item $item, $send = true){
+ $this->inventory[(int) $slot] = $item;
+ if($send === true){
+ $this->sendInventorySlot((int) $slot);
+ }
+ return true;
+ }
+
+ /**
+ * @param integer $slot
+ *
+ * @return Item
+ */
+ public function getSlot($slot){
+ if(isset($this->inventory[(int) $slot])){
+ return $this->inventory[(int) $slot];
+ }else{
+ return BlockAPI::getItem(AIR, 0, 0);
+ }
+ }
+
+ public function sendInventorySlot($s){
+ $this->sendInventory();
+ return;
+ $s = (int) $s;
+ if(!isset($this->inventory[$s])){
+ $pk = new ContainerSetSlotPacket;
+ $pk->windowid = 0;
+ $pk->slot = (int) $s;
+ $pk->item = BlockAPI::getItem(AIR, 0, 0);
+ $this->dataPacket($pk);
+ }
+
+ $slot = $this->inventory[$s];
+ $pk = new ContainerSetSlotPacket;
+ $pk->windowid = 0;
+ $pk->slot = (int) $s;
+ $pk->item = $slot;
+ $this->dataPacket($pk);
+ return true;
+ }
+
+ public function setArmor($slot, Item $armor, $send = true){
+ $this->armor[(int) $slot] = $armor;
+ if($send === true){
+ $this->sendArmor($this);
+ }
+ return true;
+ }
+
+ /**
+ * @param integer $slot
+ *
+ * @return Item
+ */
+ public function getArmor($slot){
+ if(isset($this->armor[(int) $slot])){
+ return $this->armor[(int) $slot];
+ }else{
+ return BlockAPI::getItem(AIR, 0, 0);
+ }
+ }
+
+ public function hasItem($type, $damage = false){
+ foreach($this->inventory as $s => $item){
+ if($item->getID() === $type and ($item->getMetadata() === $damage or $damage === false) and $item->count > 0){
+ return $s;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @param mixed $data
+ * @param string $event
+ */
+ public function eventHandler($data, $event){
+ switch($event){
+ case "tile.update":
+ if($data->level === $this->level){
+ if($data->class === TILE_FURNACE){
+ foreach($this->windows as $id => $w){
+ if($w === $data){
+ $pk = new ContainerSetDataPacket;
+ $pk->windowid = $id;
+ $pk->property = 0; //Smelting
+ $pk->value = floor($data->data["CookTime"]);
+ $this->dataPacket($pk);
+
+ $pk = new ContainerSetDataPacket;
+ $pk->windowid = $id;
+ $pk->property = 1; //Fire icon
+ $pk->value = $data->data["BurnTicks"];
+ $this->dataPacket($pk);
+ }
+ }
+ }
+ }
+ break;
+ case "tile.container.slot":
+ if($data["tile"]->level === $this->level){
+ foreach($this->windows as $id => $w){
+ if($w === $data["tile"]){
+ $pk = new ContainerSetSlotPacket;
+ $pk->windowid = $id;
+ $pk->slot = $data["slot"] + (isset($data["offset"]) ? $data["offset"]:0);
+ $pk->item = $data["slotdata"];
+ $this->dataPacket($pk);
+ }
+ }
+ }
+ break;
+ case "player.armor":
+ if($data["player"]->level === $this->level){
+ if($data["eid"] === $this->eid){
+ $this->sendArmor($this);
+ break;
+ }
+ $pk = new PlayerArmorEquipmentPacket;
+ $pk->eid = $data["eid"];
+ $pk->slots = $data["slots"];
+ $this->dataPacket($pk);
+ }
+ break;
+ case "player.pickup":
+ if($data["eid"] === $this->eid){
+ $data["eid"] = 0;
+ $pk = new TakeItemEntityPacket;
+ $pk->eid = 0;
+ $pk->target = $data["entity"]->eid;
+ $this->dataPacket($pk);
+ if(($this->gamemode & 0x01) === 0x00){
+ $this->addItem($data["entity"]->type, $data["entity"]->meta, $data["entity"]->stack, false);
+ }
+ switch($data["entity"]->type){
+ case WOOD:
+ AchievementAPI::grantAchievement($this, "mineWood");
+ break;
+ case DIAMOND:
+ AchievementAPI::grantAchievement($this, "diamond");
+ break;
+ }
+ }elseif($data["entity"]->level === $this->level){
+ $pk = new TakeItemEntityPacket;
+ $pk->eid = $data["eid"];
+ $pk->target = $data["entity"]->eid;
+ $this->dataPacket($pk);
+ }
+ break;
+ case "player.equipment.change":
+ if($data["eid"] === $this->eid or $data["player"]->level !== $this->level){
+ break;
+ }
+ $data["slot"] = 0;
+
+ $pk = new PlayerEquipmentPacket;
+ $pk->eid = $data["eid"];
+ $pk->item = $data["item"]->getID();
+ $pk->meta = $data["item"]->getMetadata();
+ $pk->slot = $data["slot"];
+ $this->dataPacket($pk);
+
+ break;
+ case "entity.motion":
+ if($data->eid === $this->eid or $data->level !== $this->level){
+ break;
+ }
+ $pk = new SetEntityMotionPacket;
+ $pk->eid = $data->eid;
+ $pk->speedX = $data->speedX;
+ $pk->speedY = $data->speedY;
+ $pk->speedZ = $data->speedZ;
+ $this->dataPacket($pk);
+ break;
+ case "entity.animate":
+ if($data["eid"] === $this->eid or $data["entity"]->level !== $this->level){
+ break;
+ }
+ $pk = new AnimatePacket;
+ $pk->eid = $data["eid"];
+ $pk->action = $data["action"]; //1 swing arm,
+ $this->dataPacket($pk);
+ break;
+ case "entity.metadata":
+ if($data->eid === $this->eid){
+ $eid = 0;
+ }else{
+ $eid = $data->eid;
+ }
+ if($data->level === $this->level){
+ $pk = new SetEntityDataPacket;
+ $pk->eid = $eid;
+ $pk->metadata = $data->getMetadata();
+ $this->dataPacket($pk);
+ }
+ break;
+ case "entity.event":
+ if($data["entity"]->eid === $this->eid){
+ $eid = 0;
+ }else{
+ $eid = $data["entity"]->eid;
+ }
+ if($data["entity"]->level === $this->level){
+ $pk = new EntityEventPacket;
+ $pk->eid = $eid;
+ $pk->event = $data["event"];
+ $this->dataPacket($pk);
+ }
+ break;
+ case "server.chat":
+ if(($data instanceof Container) === true){
+ if(!$data->check($this->username) and !$data->check($this->iusername)){
+ return;
+ }else{
+ $message = $data->get();
+ $this->sendChat(preg_replace('/\x1b\[[0-9;]*m/', "", $message["message"]), $message["player"]); //Remove ANSI codes from chat
+ }
+ }else{
+ $message = (string) $data;
+ $this->sendChat(preg_replace('/\x1b\[[0-9;]*m/', "", (string) $data)); //Remove ANSI codes from chat
+ }
+ break;
+ }
+ }
+
+ /**
+ * @param string $message
+ * @param string $author
+ */
+ public function sendChat($message, $author = ""){
+ $mes = explode("\n", $message);
+ foreach($mes as $m){
+ if(preg_match_all('#@([@A-Za-z_]{1,})#', $m, $matches, PREG_OFFSET_CAPTURE) > 0){
+ $offsetshift = 0;
+ foreach($matches[1] as $selector){
+ if($selector[0]{0} === "@"){ //Escape!
+ $m = substr_replace($m, $selector[0], $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1);
+ --$offsetshift;
+ continue;
+ }
+ switch(strtolower($selector[0])){
+ case "player":
+ case "username":
+ $m = substr_replace($m, $this->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1);
+ $offsetshift += strlen($selector[0]) - strlen($this->username) + 1;
+ break;
+ }
+ }
+ }
+
+ if($m !== ""){
+ $pk = new MessagePacket;
+ $pk->source = ($author instanceof Player) ? $author->username:$author;
+ $pk->message = TextFormat::clean($m); //Colors not implemented :(
+ $this->dataPacket($pk);
+ }
+ }
+ }
+
+ public function sendSettings($nametags = true){
+ /*
+ bit mask | flag name
+ 0x00000001 world_inmutable
+ 0x00000002 -
+ 0x00000004 -
+ 0x00000008 - (autojump)
+ 0x00000010 -
+ 0x00000020 nametags_visible
+ 0x00000040 ?
+ 0x00000080 ?
+ 0x00000100 ?
+ 0x00000200 ?
+ 0x00000400 ?
+ 0x00000800 ?
+ 0x00001000 ?
+ 0x00002000 ?
+ 0x00004000 ?
+ 0x00008000 ?
+ 0x00010000 ?
+ 0x00020000 ?
+ 0x00040000 ?
+ 0x00080000 ?
+ 0x00100000 ?
+ 0x00200000 ?
+ 0x00400000 ?
+ 0x00800000 ?
+ 0x01000000 ?
+ 0x02000000 ?
+ 0x04000000 ?
+ 0x08000000 ?
+ 0x10000000 ?
+ 0x20000000 ?
+ 0x40000000 ?
+ 0x80000000 ?
+ */
+ $flags = 0;
+ if(($this->gamemode & 0x02) === 0x02){
+ $flags |= 0x01; //Do not allow placing/breaking blocks, adventure mode
+ }
+
+ if($nametags !== false){
+ $flags |= 0x20; //Show Nametags
+ }
+
+ $pk = new AdventureSettingsPacket;
+ $pk->flags = $flags;
+ $this->dataPacket($pk);
+ }
+
+ /**
+ * @param array $craft
+ * @param array $recipe
+ * @param $type
+ *
+ * @return array|bool
+ */
+ public function craftItems(array $craft, array $recipe, $type){
+ $craftItem = array(0, true, 0);
+ unset($craft[-1]);
+ foreach($craft as $slot => $item){
+ if($item instanceof Item){
+ $craftItem[0] = $item->getID();
+ if($item->getMetadata() !== $craftItem[1] and $craftItem[1] !== true){
+ $craftItem[1] = false;
+ }else{
+ $craftItem[1] = $item->getMetadata();
+ }
+ $craftItem[2] += $item->count;
+ }
+
+ }
+
+ $recipeItems = array();
+ foreach($recipe as $slot => $item){
+ if(!isset($recipeItems[$item->getID()])){
+ $recipeItems[$item->getID()] = array($item->getID(), $item->getMetadata(), $item->count);
+ }else{
+ if($item->getMetadata() !== $recipeItems[$item->getID()][1]){
+ $recipeItems[$item->getID()][1] = false;
+ }
+ $recipeItems[$item->getID()][2] += $item->count;
+ }
+ }
+
+ $res = CraftingRecipes::canCraft($craftItem, $recipeItems, $type);
+
+ if(!is_array($res) and $type === 1){
+ $res2 = CraftingRecipes::canCraft($craftItem, $recipeItems, 0);
+ if(is_array($res2)){
+ $res = $res2;
+ }
+ }
+
+ if(is_array($res)){
+
+ if($this->server->api->dhandle("player.craft", array("player" => $this, "recipe" => $recipe, "craft" => $craft, "type" => $type)) === false){
+ return false;
+ }
+ foreach($recipe as $slot => $item){
+ $s = $this->getSlot($slot);
+ $s->count -= $item->count;
+ if($s->count <= 0){
+ $this->setSlot($slot, BlockAPI::getItem(AIR, 0, 0), false);
+ }
+ }
+ foreach($craft as $slot => $item){
+ $s = $this->getSlot($slot);
+ if($s->count <= 0 or $s->getID() === AIR){
+ $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $item->count), false);
+ }else{
+ $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $s->count + $item->count), false);
+ }
+
+ switch($item->getID()){
+ case WORKBENCH:
+ AchievementAPI::grantAchievement($this, "buildWorkBench");
+ break;
+ case WOODEN_PICKAXE:
+ AchievementAPI::grantAchievement($this, "buildPickaxe");
+ break;
+ case FURNACE:
+ AchievementAPI::grantAchievement($this, "buildFurnace");
+ break;
+ case WOODEN_HOE:
+ AchievementAPI::grantAchievement($this, "buildHoe");
+ break;
+ case BREAD:
+ AchievementAPI::grantAchievement($this, "makeBread");
+ break;
+ case CAKE:
+ AchievementAPI::grantAchievement($this, "bakeCake");
+ break;
+ case STONE_PICKAXE:
+ case GOLD_PICKAXE:
+ case IRON_PICKAXE:
+ case DIAMOND_PICKAXE:
+ AchievementAPI::grantAchievement($this, "buildBetterPickaxe");
+ break;
+ case WOODEN_SWORD:
+ AchievementAPI::grantAchievement($this, "buildSword");
+ break;
+ case DIAMOND:
+ AchievementAPI::grantAchievement($this, "diamond");
+ break;
+ case CAKE:
+ $this->addItem(BUCKET, 0, 3, false);
+ break;
+
+ }
+ }
+ }
+ return $res;
+ }
+
+ /**
+ * @param Vector3 $pos
+ * @param float|boolean $yaw
+ * @param float|boolean $pitch
+ * @param float|boolean $terrain
+ * @param float|boolean $force
+ *
+ * @return boolean
+ */
+ public function teleport(Vector3 $pos, $yaw = false, $pitch = false, $terrain = true, $force = true){
+ if($this->entity instanceof Entity and $this->level instanceof Level){
+ $this->entity->check = false;
+ if($yaw === false){
+ $yaw = $this->entity->yaw;
+ }
+ if($pitch === false){
+ $pitch = $this->entity->pitch;
+ }
+ if($this->server->api->dhandle("player.teleport", array("player" => $this, "target" => $pos)) === false){
+ $this->entity->check = true;
+ return false;
+ }
+
+ if($pos instanceof Position and $pos->level instanceof Level and $pos->level !== $this->level){
+ if($this->server->api->dhandle("player.teleport.level", array("player" => $this, "origin" => $this->level, "target" => $pos->level)) === false){
+ $this->entity->check = true;
+ return false;
+ }
+
+ foreach($this->server->api->entity->getAll($this->level) as $e){
+ if($e !== $this->entity){
+ if($e->player instanceof Player){
+ $pk = new MoveEntityPacket_PosRot;
+ $pk->eid = $this->entity->eid;
+ $pk->x = -256;
+ $pk->y = 128;
+ $pk->z = -256;
+ $pk->yaw = 0;
+ $pk->pitch = 0;
+ $e->player->dataPacket($pk);
+
+ $pk = new MoveEntityPacket_PosRot;
+ $pk->eid = $e->eid;
+ $pk->x = -256;
+ $pk->y = 128;
+ $pk->z = -256;
+ $pk->yaw = 0;
+ $pk->pitch = 0;
+ $this->dataPacket($pk);
+ }else{
+ $pk = new RemoveEntityPacket;
+ $pk->eid = $e->eid;
+ $this->dataPacket($pk);
+ }
+ }
+ }
+
+
+ $this->level->freeAllChunks($this);
+ $this->level = $pos->level;
+ $this->chunksLoaded = array();
+ $this->server->api->entity->spawnToAll($this->entity);
+ $this->server->api->entity->spawnAll($this);
+
+ $pk = new SetTimePacket;
+ $pk->time = $this->level->getTime();
+ $this->dataPacket($pk);
+ $terrain = true;
+
+ foreach($this->server->api->player->getAll($this->level) as $player){
+ if($player !== $this and $player->entity instanceof Entity){
+ $pk = new MoveEntityPacket_PosRot;
+ $pk->eid = $player->entity->eid;
+ $pk->x = $player->entity->x;
+ $pk->y = $player->entity->y;
+ $pk->z = $player->entity->z;
+ $pk->yaw = $player->entity->yaw;
+ $pk->pitch = $player->entity->pitch;
+ $this->dataPacket($pk);
+
+ $pk = new PlayerEquipmentPacket;
+ $pk->eid = $this->eid;
+ $pk->item = $this->getSlot($this->slot)->getID();
+ $pk->meta = $this->getSlot($this->slot)->getMetadata();
+ $pk->slot = 0;
+ $player->dataPacket($pk);
+ $this->sendArmor($player);
+
+ $pk = new PlayerEquipmentPacket;
+ $pk->eid = $player->eid;
+ $pk->item = $player->getSlot($player->slot)->getID();
+ $pk->meta = $player->getSlot($player->slot)->getMetadata();
+ $pk->slot = 0;
+ $this->dataPacket($pk);
+ $player->sendArmor($this);
+ }
+ }
+ }
+
+ $this->lastCorrect = $pos;
+ $this->entity->fallY = false;
+ $this->entity->fallStart = false;
+ $this->entity->setPosition($pos, $yaw, $pitch);
+ $this->entity->resetSpeed();
+ $this->entity->updateLast();
+ $this->entity->calculateVelocity();
+ if($terrain === true){
+ $this->orderChunks();
+ $this->getNextChunk();
+ }
+ $this->entity->check = true;
+ if($force === true){
+ $this->forceMovement = $pos;
+ }
+ }
+
+ $pk = new MovePlayerPacket;
+ $pk->eid = 0;
+ $pk->x = $pos->x;
+ $pk->y = $pos->y;
+ $pk->z = $pos->z;
+ $pk->bodyYaw = $yaw;
+ $pk->pitch = $pitch;
+ $pk->yaw = $yaw;
+ $this->dataPacket($pk);
+ }
+
+ public function getGamemode(){
+ switch($this->gamemode){
+ case SURVIVAL:
+ return "survival";
+ case CREATIVE:
+ return "creative";
+ case ADVENTURE:
+ return "adventure";
+ case VIEW:
+ return "view";
+ }
+ }
+
+ public function setGamemode($gm){
+ if($gm < 0 or $gm > 3 or $this->gamemode === $gm){
+ return false;
+ }
+
+ if($this->server->api->dhandle("player.gamemode.change", array("player" => $this, "gamemode" => $gm)) === false){
+ return false;
+ }
+
+ $inv =& $this->inventory;
+ if(($this->gamemode & 0x01) === ($gm & 0x01)){
+ if(($gm & 0x01) === 0x01 and ($gm & 0x02) === 0x02){
+ $inv = array();
+ foreach(BlockAPI::$creative as $item){
+ $inv[] = BlockAPI::getItem(DANDELION, 0, 1);
+ }
+ }elseif(($gm & 0x01) === 0x01){
+ $inv = array();
+ foreach(BlockAPI::$creative as $item){
+ $inv[] = BlockAPI::getItem($item[0], $item[1], 1);
+ }
+ }
+ $this->gamemode = $gm;
+ $this->sendChat("Your gamemode has been changed to ".$this->getGamemode().".\n");
+ }else{
+ foreach($this->inventory as $slot => $item){
+ $inv[$slot] = BlockAPI::getItem(AIR, 0, 0);
+ }
+ $this->blocked = true;
+ $this->gamemode = $gm;
+ $this->sendChat("Your gamemode has been changed to ".$this->getGamemode().", you've to do a forced reconnect.\n");
+ $this->server->schedule(30, array($this, "close"), "gamemode change"); //Forces a kick
+ }
+ $this->inventory = $inv;
+ $this->sendSettings();
+ $this->sendInventory();
+ return true;
+ }
+
+ public function measureLag(){
+ if($this->connected === false){
+ return false;
+ }
+ if($this->packetStats[1] > 2){
+ $this->packetLoss = $this->packetStats[1] / max(1, $this->packetStats[0] + $this->packetStats[1]);
+ }else{
+ $this->packetLoss = 0;
+ }
+ $this->packetStats = array(0, 0);
+ array_shift($this->bandwidthStats);
+ $this->bandwidthStats[] = $this->bandwidthRaw / max(0.00001, microtime(true) - $this->lastMeasure);
+ $this->bandwidthRaw = 0;
+ $this->lagStat = array_sum($this->lag) / max(1, count($this->lag));
+ $this->lag = array();
+ $this->sendBuffer();
+ $this->lastMeasure = microtime(true);
+ }
+
+ public function getLag(){
+ return $this->lagStat * 1000;
+ }
+
+ public function getPacketLoss(){
+ return $this->packetLoss;
+ }
+
+ public function getBandwidth(){
+ return array_sum($this->bandwidthStats) / max(1, count($this->bandwidthStats));
+ }
+
+ public function clearQueue(){
+ if($this->connected === false){
+ return false;
+ }
+ ksort($this->received);
+ if(($cnt = count($this->received)) > PLAYER_MAX_QUEUE){
+ foreach($this->received as $c => $t){
+ unset($this->received[$c]);
+ --$cnt;
+ if($cnt <= PLAYER_MAX_QUEUE){
+ break;
+ }
+ }
+ }
+ }
+
+ public function handlePacketQueues(){
+ if($this->connected === false){
+ return false;
+ }
+ $time = microtime(true);
+ if($time > $this->timeout){
+ $this->close("timeout");
+ return false;
+ }
+
+ if(($ackCnt = count($this->ackQueue)) > 0){
+ rsort($this->ackQueue);
+ $safeCount = (int) (($this->MTU - 1) / 4);
+ $packetCnt = (int) ($ackCnt / $safeCount + 1);
+ for($p = 0; $p < $packetCnt; ++$p){
+ $pk = new RakNetPacket(RakNetInfo::ACK);
+ $pk->packets = array();
+ for($c = 0; $c < $safeCount; ++$c){
+ if(($k = array_pop($this->ackQueue)) === null){
+ break;
+ }
+ $pk->packets[] = $k;
+ }
+ $this->send($pk);
+ }
+ $this->ackQueue = array();
+ }
+
+ if(($receiveCnt = count($this->receiveQueue)) > 0){
+ ksort($this->receiveQueue);
+ foreach($this->receiveQueue as $count => $packets){
+ unset($this->receiveQueue[$count]);
+ foreach($packets as $p){
+ if($p instanceof RakNetDataPacket and $p->hasSplit === false){
+ if(isset($p->messageIndex) and $p->messageIndex !== false){
+ if($p->messageIndex > $this->receiveCount){
+ $this->receiveCount = $p->messageIndex;
+ }elseif($p->messageIndex !== 0){
+ 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:
+ continue;
+ }
+ }
+ $this->received[$p->messageIndex] = true;
+ }
+ $p->decode();
+ $this->handleDataPacket($p);
+ }
+ }
+ }
+ }
+
+ if($this->nextBuffer <= $time and $this->bufferLen > 0){
+ $this->sendBuffer();
+ }
+
+ $limit = $time - 5; //max lag
+ foreach($this->recoveryQueue as $count => $data){
+ if($data->sendtime > $limit){
+ break;
+ }
+ unset($this->recoveryQueue[$count]);
+ $this->resendQueue[$count] = $data;
+ }
+
+ if(($resendCnt = count($this->resendQueue)) > 0){
+ foreach($this->resendQueue as $count => $data){
+ unset($this->resendQueue[$count]);
+ $this->packetStats[1]++;
+ $this->lag[] = microtime(true) - $data->sendtime;
+ $data->sendtime = microtime(true);
+ $cnt = $this->send($data);
+ if(isset($this->chunkCount[$count])){
+ unset($this->chunkCount[$count]);
+ $this->chunkCount[$cnt[0]] = true;
+ }
+ }
+ }
+ }
+
+ public function handlePacket(RakNetPacket $packet){
+ if($this->connected === true){
+ $this->timeout = microtime(true) + 20;
+ switch($packet->pid()){
+ case RakNetInfo::NACK:
+ foreach($packet->packets as $count){
+ if(isset($this->recoveryQueue[$count])){
+ $this->resendQueue[$count] =& $this->recoveryQueue[$count];
+ $this->lag[] = microtime(true) - $this->recoveryQueue[$count]->sendtime;
+ unset($this->recoveryQueue[$count]);
+ }
+ ++$this->packetStats[1];
+ }
+ break;
+
+ case RakNetInfo::ACK:
+ foreach($packet->packets as $count){
+ if(isset($this->recoveryQueue[$count])){
+ $this->lag[] = microtime(true) - $this->recoveryQueue[$count]->sendtime;
+ unset($this->recoveryQueue[$count]);
+ unset($this->resendQueue[$count]);
+ }
+ ++$this->packetStats[0];
+ }
+ break;
+
+ case RakNetInfo::DATA_PACKET_0:
+ case RakNetInfo::DATA_PACKET_1:
+ case RakNetInfo::DATA_PACKET_2:
+ case RakNetInfo::DATA_PACKET_3:
+ case RakNetInfo::DATA_PACKET_4:
+ case RakNetInfo::DATA_PACKET_5:
+ case RakNetInfo::DATA_PACKET_6:
+ case RakNetInfo::DATA_PACKET_7:
+ case RakNetInfo::DATA_PACKET_8:
+ case RakNetInfo::DATA_PACKET_9:
+ case RakNetInfo::DATA_PACKET_A:
+ case RakNetInfo::DATA_PACKET_B:
+ case RakNetInfo::DATA_PACKET_C:
+ case RakNetInfo::DATA_PACKET_D:
+ case RakNetInfo::DATA_PACKET_E:
+ case RakNetInfo::DATA_PACKET_F:
+ $this->ackQueue[] = $packet->seqNumber;
+ $this->receiveQueue[$packet->seqNumber] = array();
+ foreach($packet->data as $pk){
+ $this->receiveQueue[$packet->seqNumber][] = $pk;
+ }
+ break;
+ }
+ }
+ }
+
+ public function handleDataPacket(RakNetDataPacket $packet){
+ if($this->connected === false){
+ return;
+ }
+
+ if(EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY){
+ return;
+ }
+
+ switch($packet->pid()){
+ case 0x01:
+ break;
+ case ProtocolInfo::PONG_PACKET:
+ break;
+ case ProtocolInfo::PING_PACKET:
+ $pk = new PongPacket;
+ $pk->ptime = $packet->time;
+ $pk->time = abs(microtime(true) * 1000);
+ $this->directDataPacket($pk);
+ break;
+ case ProtocolInfo::DISCONNECT_PACKET:
+ $this->close("client disconnect");
+ break;
+ case ProtocolInfo::CLIENT_CONNECT_PACKET:
+ if($this->loggedIn === true){
+ break;
+ }
+ $pk = new ServerHandshakePacket;
+ $pk->port = $this->port;
+ $pk->session = $packet->session;
+ $pk->session2 = Utils::readLong("\x00\x00\x00\x00\x04\x44\x0b\xa9");
+ $this->dataPacket($pk);
+ break;
+ case ProtocolInfo::CLIENT_HANDSHAKE_PACKET:
+ if($this->loggedIn === true){
+ break;
+ }
+ break;
+ case ProtocolInfo::LOGIN_PACKET:
+ if($this->loggedIn === true){
+ break;
+ }
+ $this->username = $packet->username;
+ $this->iusername = strtolower($this->username);
+ $this->loginData = array("clientId" => $packet->clientId, "loginData" => $packet->loginData);
+ if(count($this->server->clients) > $this->server->maxClients and !$this->server->api->ban->isOp($this->iusername)){
+ $this->close("server is full!", false);
+ return;
+ }
+ if($packet->protocol1 !== ProtocolInfo::CURRENT_PROTOCOL){
+ if($packet->protocol1 < ProtocolInfo::CURRENT_PROTOCOL){
+ $pk = new LoginStatusPacket;
+ $pk->status = 1;
+ $this->directDataPacket($pk);
+ }else{
+ $pk = new LoginStatusPacket;
+ $pk->status = 2;
+ $this->directDataPacket($pk);
+ }
+ $this->close("Incorrect protocol #".$packet->protocol1, false);
+ return;
+ }
+ if(preg_match('#[^a-zA-Z0-9_]#', $this->username) > 0 or $this->username === "" or $this->iusername === "rcon" or $this->iusername === "console" or $this->iusername === "server"){
+ $this->close("Bad username", false);
+ return;
+ }
+ if($this->server->api->handle("player.connect", $this) === false){
+ $this->close("Unknown reason", false);
+ return;
+ }
+
+ if($this->server->whitelist === true and !$this->server->api->ban->inWhitelist($this->iusername)){
+ $this->close("Server is white-listed", false);
+ return;
+ }elseif($this->server->api->ban->isBanned($this->iusername) or $this->server->api->ban->isIPBanned($this->ip)){
+ $this->close("You are banned!", false);
+ return;
+ }
+ $this->loggedIn = true;
+
+ $u = $this->server->api->player->get($this->iusername, false);
+ if($u !== false){
+ $u->close("logged in from another location");
+ }
+ if(!isset($this->CID) or $this->CID == null){
+ console("[DEBUG] Player ".$this->username." does not have a CID", true, true, 2);
+ $this->CID = Utils::readLong(Utils::getRandomBytes(8, false));
+ }
+
+ $this->server->api->player->add($this->CID);
+ if($this->server->api->handle("player.join", $this) === false){
+ $this->close("join cancelled", false);
+ return;
+ }
+
+ if(!($this->data instanceof Config)){
+ $this->close("no config created", false);
+ return;
+ }
+
+ $this->auth = true;
+ if(!$this->data->exists("inventory") or ($this->gamemode & 0x01) === 0x01){
+ if(($this->gamemode & 0x01) === 0x01){
+ $inv = array();
+ if(($this->gamemode & 0x02) === 0x02){
+ foreach(BlockAPI::$creative as $item){
+ $inv[] = array(DANDELION, 0, 1);
+ }
+ }else{
+ foreach(BlockAPI::$creative as $item){
+ $inv[] = array($item[0], $item[1], 1);
+ }
+ }
+ }
+ $this->data->set("inventory", $inv);
+ }
+ $this->achievements = $this->data->get("achievements");
+ $this->data->set("caseusername", $this->username);
+ $this->inventory = array();
+ foreach($this->data->get("inventory") as $slot => $item){
+ if(!is_array($item) or count($item) < 3){
+ $item = array(AIR, 0, 0);
+ }
+ $this->inventory[$slot] = BlockAPI::getItem($item[0], $item[1], $item[2]);
+ }
+
+ $this->armor = array();
+ foreach($this->data->get("armor") as $slot => $item){
+ $this->armor[$slot] = BlockAPI::getItem($item[0], $item[1], $item[0] === 0 ? 0:1);
+ }
+
+ $this->data->set("lastIP", $this->ip);
+ $this->data->set("lastID", $this->clientID);
+
+ $this->server->api->player->saveOffline($this->data);
+
+
+ $pk = new LoginStatusPacket;
+ $pk->status = 0;
+ $this->dataPacket($pk);
+
+ $pk = new StartGamePacket;
+ $pk->seed = $this->level->getSeed();
+ $pk->x = $this->data->get("position")["x"];
+ $pk->y = $this->data->get("position")["y"];
+ $pk->z = $this->data->get("position")["z"];
+ $pk->generator = 0;
+ $pk->gamemode = $this->gamemode & 0x01;
+ $pk->eid = 0;
+ $this->dataPacket($pk);
+
+ if(($this->gamemode & 0x01) === 0x01){
+ $this->slot = 0;
+ $this->hotbar = array();
+ }elseif($this->data->exists("hotbar")){
+ $this->hotbar = $this->data->get("hotbar");
+ $this->slot = $this->hotbar[0];
+ }else{
+ $this->slot = -1;//0
+ $this->hotbar = array(-1, -1, -1, -1, -1, -1, -1, -1, -1);
+ }
+ $this->entity = $this->server->api->entity->add($this->level, ENTITY_PLAYER, 0, array("player" => $this));
+ $this->eid = $this->entity->eid;
+ $this->server->query("UPDATE players SET EID = ".$this->eid." WHERE CID = ".$this->CID.";");
+ $this->entity->x = $this->data->get("position")["x"];
+ $this->entity->y = $this->data->get("position")["y"];
+ $this->entity->z = $this->data->get("position")["z"];
+ if(($level = $this->server->api->level->get($this->data->get("spawn")["level"])) !== false){
+ $this->spawnPosition = new Position($this->data->get("spawn")["x"], $this->data->get("spawn")["y"], $this->data->get("spawn")["z"], $level);
+
+ $pk = new SetSpawnPositionPacket;
+ $pk->x = (int) $this->spawnPosition->x;
+ $pk->y = (int) $this->spawnPosition->y;
+ $pk->z = (int) $this->spawnPosition->z;
+ $this->dataPacket($pk);
+ }
+ $this->entity->check = false;
+ $this->entity->setName($this->username);
+ $this->entity->data["CID"] = $this->CID;
+ $this->evid[] = $this->server->event("server.chat", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("entity.motion", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("entity.animate", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("entity.event", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("entity.metadata", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("player.equipment.change", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("player.armor", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("player.pickup", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("tile.container.slot", array($this, "eventHandler"));
+ $this->evid[] = $this->server->event("tile.update", array($this, "eventHandler"));
+ $this->lastMeasure = microtime(true);
+ $this->server->schedule(50, array($this, "measureLag"), array(), true);
+ console("[INFO] ".FORMAT_AQUA.$this->username.FORMAT_RESET."[/".$this->ip.":".$this->port."] logged in with entity id ".$this->eid." at (".$this->entity->level->getName().", ".round($this->entity->x, 2).", ".round($this->entity->y, 2).", ".round($this->entity->z, 2).")");
+ break;
+ case ProtocolInfo::READY_PACKET:
+ if($this->loggedIn === false){
+ break;
+ }
+ switch($packet->status){
+ case 1: //Spawn!!
+ if($this->spawned !== false){
+ break;
+ }
+ $this->entity->setHealth($this->data->get("health"), "spawn", true);
+ $this->spawned = true;
+ $this->server->api->player->spawnAllPlayers($this);
+ $this->server->api->player->spawnToAllPlayers($this);
+ $this->server->api->entity->spawnAll($this);
+ $this->server->api->entity->spawnToAll($this->entity);
+
+ $this->server->schedule(5, array($this->entity, "update"), array(), true);
+ $this->server->schedule(2, array($this->entity, "updateMovement"), array(), true);
+ $this->sendArmor();
+ $this->sendChat($this->server->motd."\n");
+
+ $this->sendInventory();
+ $this->sendSettings();
+ $this->server->schedule(30, array($this, "orderChunks"), array(), true);
+ $this->blocked = false;
+
+ $pk = new SetTimePacket;
+ $pk->time = $this->level->getTime();
+ $this->dataPacket($pk);
+
+ $pos = new Position($this->data->get("position")["x"], $this->data->get("position")["y"], $this->data->get("position")["z"], $this->level);
+ $pos = $this->level->getSafeSpawn($pos);
+ $this->teleport($pos);
+ $this->server->schedule(10, array($this, "teleport"), $pos);
+ $this->server->schedule(20, array($this, "teleport"), $pos);
+ $this->server->schedule(30, array($this, "teleport"), $pos);
+ $this->server->handle("player.spawn", $this);
+ break;
+ case 2://Chunk loaded?
+ break;
+ }
+ break;
+ case ProtocolInfo::ROTATE_HEAD_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ if(($this->entity instanceof Entity)){
+ if($this->blocked === true or $this->server->api->handle("player.move", $this->entity) === false){
+ if($this->lastCorrect instanceof Vector3){
+ $this->teleport($this->lastCorrect, $this->entity->yaw, $this->entity->pitch, false);
+ }
+ }else{
+ $this->entity->setPosition($this->entity, $packet->yaw, $this->entity->pitch);
+ }
+ }
+ break;
+ case ProtocolInfo::MOVE_PLAYER_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ if(($this->entity instanceof Entity) and $packet->messageIndex > $this->lastMovement){
+ $this->lastMovement = $packet->messageIndex;
+ $newPos = new Vector3($packet->x, $packet->y, $packet->z);
+ if($this->forceMovement instanceof Vector3){
+ if($this->forceMovement->distance($newPos) <= 0.7){
+ $this->forceMovement = false;
+ }else{
+ $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){
+ $this->teleport($this->lastCorrect, $this->entity->yaw, $this->entity->pitch, false);
+ }
+ if($this->blocked !== true){
+ console("[WARNING] ".$this->username." moved too quickly!");
+ }
+ }else{
+ $this->entity->setPosition($newPos, $packet->yaw, $packet->pitch);
+ }
+ }
+ break;
+ case ProtocolInfo::PLAYER_EQUIPMENT_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ $packet->eid = $this->eid;
+
+ $data = array();
+ $data["eid"] = $packet->eid;
+ $data["player"] = $this;
+
+ if($packet->slot === 0x28 or $packet->slot === 0){ //0 for 0.8.0 compatibility
+ $data["slot"] = -1;
+ $data["item"] = BlockAPI::getItem(AIR, 0, 0);
+ if($this->server->handle("player.equipment.change", $data) !== false){
+ $this->slot = -1;
+ }
+ break;
+ }else{
+ $packet->slot -= 9;
+ }
+
+
+ if(($this->gamemode & 0x01) === SURVIVAL){
+ $data["item"] = $this->getSlot($packet->slot);
+ if(!($data["item"] instanceof Item)){
+ break;
+ }
+ }elseif(($this->gamemode & 0x01) === CREATIVE){
+ $packet->slot = false;
+ foreach(BlockAPI::$creative as $i => $d){
+ if($d[0] === $packet->item and $d[1] === $packet->meta){
+ $packet->slot = $i;
+ }
+ }
+ if($packet->slot !== false){
+ $data["item"] = $this->getSlot($packet->slot);
+ }else{
+ break;
+ }
+ }else{
+ break;//?????
+ }
+
+ $data["slot"] = $packet->slot;
+
+ if($this->server->handle("player.equipment.change", $data) !== false){
+ $this->slot = $packet->slot;
+ if(($this->gamemode & 0x01) === SURVIVAL){
+ if(!in_array($this->slot, $this->hotbar)){
+ array_pop($this->hotbar);
+ array_unshift($this->hotbar, $this->slot);
+ }
+ }
+ }else{
+ //$this->sendInventorySlot($packet->slot);
+ $this->sendInventory();
+ }
+ if($this->entity->inAction === true){
+ $this->entity->inAction = false;
+ $this->entity->updateMetadata();
+ }
+ break;
+ case ProtocolInfo::REQUEST_CHUNK_PACKET:
+ break;
+ case ProtocolInfo::USE_ITEM_PACKET:
+ if(!($this->entity instanceof Entity)){
+ break;
+ }
+
+ $blockVector = new Vector3($packet->x, $packet->y, $packet->z);
+
+ if(($this->spawned === false or $this->blocked === true) and $packet->face >= 0 and $packet->face <= 5){
+ $target = $this->level->getBlock($blockVector);
+ $block = $target->getSide($packet->face);
+
+ $pk = new UpdateBlockPacket;
+ $pk->x = $target->x;
+ $pk->y = $target->y;
+ $pk->z = $target->z;
+ $pk->block = $target->getID();
+ $pk->meta = $target->getMetadata();
+ $this->dataPacket($pk);
+
+ $pk = new UpdateBlockPacket;
+ $pk->x = $block->x;
+ $pk->y = $block->y;
+ $pk->z = $block->z;
+ $pk->block = $block->getID();
+ $pk->meta = $block->getMetadata();
+ $this->dataPacket($pk);
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ $packet->eid = $this->eid;
+ $data = array();
+ $data["eid"] = $packet->eid;
+ $data["player"] = $this;
+ $data["face"] = $packet->face;
+ $data["x"] = $packet->x;
+ $data["y"] = $packet->y;
+ $data["z"] = $packet->z;
+ $data["item"] = $packet->item;
+ $data["meta"] = $packet->meta;
+ $data["fx"] = $packet->fx;
+ $data["fy"] = $packet->fy;
+ $data["fz"] = $packet->fz;
+ $data["posX"] = $packet->posX;
+ $data["posY"] = $packet->posY;
+ $data["posZ"] = $packet->posZ;
+
+ if($packet->face >= 0 and $packet->face <= 5){ //Use Block, place
+ if($this->entity->inAction === true){
+ $this->entity->inAction = false;
+ $this->entity->updateMetadata();
+ }
+
+ if($this->blocked === true or ($this->entity->position instanceof Vector3 and $blockVector->distance($this->entity->position) > 10)){
+
+ }elseif($this->getSlot($this->slot)->getID() !== $packet->item or ($this->getSlot($this->slot)->isTool() === false and $this->getSlot($this->slot)->getMetadata() !== $packet->meta)){
+ $this->sendInventorySlot($this->slot);
+ }else{
+ $this->server->api->block->playerBlockAction($this, $blockVector, $packet->face, $packet->fx, $packet->fy, $packet->fz);
+ break;
+ }
+ $target = $this->level->getBlock($blockVector);
+ $block = $target->getSide($packet->face);
+
+ $pk = new UpdateBlockPacket;
+ $pk->x = $target->x;
+ $pk->y = $target->y;
+ $pk->z = $target->z;
+ $pk->block = $target->getID();
+ $pk->meta = $target->getMetadata();
+ $this->dataPacket($pk);
+
+ $pk = new UpdateBlockPacket;
+ $pk->x = $block->x;
+ $pk->y = $block->y;
+ $pk->z = $block->z;
+ $pk->block = $block->getID();
+ $pk->meta = $block->getMetadata();
+ $this->dataPacket($pk);
+ break;
+ }elseif($packet->face === 0xff and $this->server->handle("player.action", $data) !== false){
+ $this->entity->inAction = true;
+ $this->startAction = microtime(true);
+ $this->entity->updateMetadata();
+ }
+ break;
+ case ProtocolInfo::PLAYER_ACTION_PACKET:
+ if($this->spawned === false or $this->blocked === true){
+ break;
+ }
+ $packet->eid = $this->eid;
+ $this->craftingItems = array();
+ $this->toCraft = array();
+
+ switch($packet->action){
+ case 5: //Shot arrow
+ if($this->entity->inAction === true){
+ if($this->getSlot($this->slot)->getID() === BOW){
+ if($this->startAction !== false){
+ $time = microtime(true) - $this->startAction;
+ $d = array(
+ "x" => $this->entity->x,
+ "y" => $this->entity->y + 1.6,
+ "z" => $this->entity->z,
+ );
+ $e = $this->server->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_ARROW, $d);
+ $e->yaw = $this->entity->yaw;
+ $e->pitch = $this->entity->pitch;
+ $rotation = ($this->entity->yaw - 90) % 360;
+ if($rotation < 0){
+ $rotation = (360 + $rotation);
+ }
+ $rotation = ($rotation + 180);
+ if($rotation >= 360){
+ $rotation = ($rotation - 360);
+ }
+ $X = 1;
+ $Z = 1;
+ $overturn = false;
+ if(0 <= $rotation and $rotation < 90){
+
+ }elseif(90 <= $rotation and $rotation < 180){
+ $rotation -= 90;
+ $X = (-1);
+ $overturn = true;
+ }elseif(180 <= $rotation and $rotation < 270){
+ $rotation -= 180;
+ $X = (-1);
+ $Z = (-1);
+ }elseif(270 <= $rotation and $rotation < 360){
+ $rotation -= 270;
+ $Z = (-1);
+ $overturn = true;
+ }
+ $rad = deg2rad($rotation);
+ $pitch = (-($this->entity->pitch));
+ $speed = 80;
+ $speedY = (sin(deg2rad($pitch)) * $speed);
+ $speedXZ = (cos(deg2rad($pitch)) * $speed);
+ if($overturn){
+ $speedX = (sin($rad) * $speedXZ * $X);
+ $speedZ = (cos($rad) * $speedXZ * $Z);
+ }
+ else{
+ $speedX = (cos($rad) * $speedXZ * $X);
+ $speedZ = (sin($rad) * $speedXZ * $Z);
+ }
+ $e->speedX = $speedX;
+ $e->speedZ = $speedZ;
+ $e->speedY = $speedY;
+ $this->server->api->entity->spawnToAll($e);
+ }
+ }
+ }
+ $this->startAction = false;
+ $this->entity->inAction = false;
+ $this->entity->updateMetadata();
+ break;
+ case 6: //get out of the bed
+ $this->stopSleep();
+ }
+ break;
+ case ProtocolInfo::REMOVE_BLOCK_PACKET:
+ $blockVector = new Vector3($packet->x, $packet->y, $packet->z);
+ if($this->spawned === false or $this->blocked === true or $this->entity->distance($blockVector) > 8){
+ $target = $this->level->getBlock($blockVector);
+
+ $pk = new UpdateBlockPacket;
+ $pk->x = $target->x;
+ $pk->y = $target->y;
+ $pk->z = $target->z;
+ $pk->block = $target->getID();
+ $pk->meta = $target->getMetadata();
+ $this->dataPacket($pk);
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ $this->server->api->block->playerBlockBreak($this, $blockVector);
+ break;
+ case ProtocolInfo::PLAYER_ARMOR_EQUIPMENT_PACKET:
+ if($this->spawned === false or $this->blocked === true){
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+
+ $packet->eid = $this->eid;
+ for($i = 0; $i < 4; ++$i){
+ $s = $packet->slots[$i];
+ if($s === 0 or $s === 255){
+ $s = BlockAPI::getItem(AIR, 0, 0);
+ }else{
+ $s = BlockAPI::getItem($s + 256, 0, 1);
+ }
+ $slot = $this->armor[$i];
+ if($slot->getID() !== AIR and $s->getID() === AIR){
+ $this->addItem($slot->getID(), $slot->getMetadata(), 1, false);
+ $this->armor[$i] = BlockAPI::getItem(AIR, 0, 0);
+ $packet->slots[$i] = 255;
+ }elseif($s->getID() !== AIR and $slot->getID() === AIR and ($sl = $this->hasItem($s->getID())) !== false){
+ $this->armor[$i] = $this->getSlot($sl);
+ $this->setSlot($sl, BlockAPI::getItem(AIR, 0, 0), false);
+ }elseif($s->getID() !== AIR and $slot->getID() !== AIR and ($slot->getID() !== $s->getID() or $slot->getMetadata() !== $s->getMetadata()) and ($sl = $this->hasItem($s->getID())) !== false){
+ $item = $this->armor[$i];
+ $this->armor[$i] = $this->getSlot($sl);
+ $this->setSlot($sl, $item, false);
+ }else{
+ $packet->slots[$i] = 255;
+ }
+
+ }
+ $this->sendArmor();
+ if($this->entity->inAction === true){
+ $this->entity->inAction = false;
+ $this->entity->updateMetadata();
+ }
+ break;
+ case ProtocolInfo::INTERACT_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ $packet->eid = $this->eid;
+ $data = array();
+ $data["target"] = $packet->target;
+ $data["eid"] = $packet->eid;
+ $data["action"] = $packet->action;
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ $target = $this->server->api->entity->get($packet->target);
+ if($target instanceof Entity and $this->entity instanceof Entity and $this->gamemode !== VIEW and $this->blocked === false and ($target instanceof Entity) and $this->entity->distance($target) <= 8){
+ $data["targetentity"] = $target;
+ $data["entity"] = $this->entity;
+ if($target->class === ENTITY_PLAYER and ($this->server->api->getProperty("pvp") == false or $this->server->difficulty <= 0 or ($target->player->gamemode & 0x01) === 0x01)){
+ break;
+ }elseif($this->server->handle("player.interact", $data) !== false){
+ $slot = $this->getSlot($this->slot);
+ switch($slot->getID()){
+ case WOODEN_SWORD:
+ case GOLD_SWORD:
+ $damage = 5;
+ break;
+ case STONE_SWORD:
+ $damage = 6;
+ break;
+ case IRON_SWORD:
+ $damage = 8;
+ break;
+ case DIAMOND_SWORD:
+ $damage = 10;
+ break;
+
+ case WOODEN_AXE:
+ case GOLD_AXE:
+ $damage = 3;
+ break;
+ case STONE_AXE:
+ $damage = 4;
+ break;
+ case IRON_AXE:
+ $damage = 5;
+ break;
+ case DIAMOND_AXE:
+ $damage = 6;
+ break;
+
+ case WOODEN_PICKAXE:
+ case GOLD_PICKAXE:
+ $damage = 2;
+ break;
+ case STONE_PICKAXE:
+ $damage = 3;
+ break;
+ case IRON_PICKAXE:
+ $damage = 4;
+ break;
+ case DIAMOND_PICKAXE:
+ $damage = 5;
+ break;
+
+ case WOODEN_SHOVEL:
+ case GOLD_SHOVEL:
+ $damage = 1;
+ break;
+ case STONE_SHOVEL:
+ $damage = 2;
+ break;
+ case IRON_SHOVEL:
+ $damage = 3;
+ break;
+ case DIAMOND_SHOVEL:
+ $damage = 4;
+ break;
+
+ default:
+ $damage = 1;//$this->server->difficulty;
+ }
+ $target->harm($damage, $this->eid);
+ if($slot->isTool() === true and ($this->gamemode & 0x01) === 0){
+ if($slot->useOn($target) and $slot->getMetadata() >= $slot->getMaxDurability()){
+ $this->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true);
+ }
+ }
+ }
+ }
+
+ break;
+ case ProtocolInfo::ANIMATE_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ $packet->eid = $this->eid;
+ $this->server->api->dhandle("entity.animate", array("eid" => $packet->eid, "entity" => $this->entity, "action" => $packet->action));
+ break;
+ case ProtocolInfo::RESPAWN_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ if(@$this->entity->dead === false){
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ $this->teleport($this->spawnPosition);
+ if($this->entity instanceof Entity){
+ $this->entity->fire = 0;
+ $this->entity->air = 300;
+ $this->entity->setHealth(20, "respawn", true);
+ $this->entity->updateMetadata();
+ }else{
+ break;
+ }
+ $this->sendInventory();
+ $this->blocked = false;
+ $this->server->handle("player.respawn", $this);
+ break;
+ case ProtocolInfo::SET_HEALTH_PACKET: //Not used
+ break;
+ case ProtocolInfo::ENTITY_EVENT_PACKET:
+ if($this->spawned === false or $this->blocked === true){
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ $packet->eid = $this->eid;
+ if($this->entity->inAction === true){
+ $this->entity->inAction = false;
+ $this->entity->updateMetadata();
+ }
+ switch($packet->event){
+ case 9: //Eating
+ $items = array(
+ APPLE => 4,
+ MUSHROOM_STEW => 10,
+ BEETROOT_SOUP => 10,
+ BREAD => 5,
+ RAW_PORKCHOP => 3,
+ COOKED_PORKCHOP => 8,
+ RAW_BEEF => 3,
+ STEAK => 8,
+ COOKED_CHICKEN => 6,
+ RAW_CHICKEN => 2,
+ MELON_SLICE => 2,
+ GOLDEN_APPLE => 10,
+ PUMPKIN_PIE => 8,
+ CARROT => 4,
+ POTATO => 1,
+ BAKED_POTATO => 6,
+ //COOKIE => 2,
+ //COOKED_FISH => 5,
+ //RAW_FISH => 2,
+ );
+ $slot = $this->getSlot($this->slot);
+ if($this->entity->getHealth() < 20 and isset($items[$slot->getID()])){
+
+ $pk = new EntityEventPacket;
+ $pk->eid = 0;
+ $pk->event = 9;
+ $this->dataPacket($pk);
+
+ $this->entity->heal($items[$slot->getID()], "eating");
+ --$slot->count;
+ if($slot->count <= 0){
+ $this->setSlot($this->slot, BlockAPI::getItem(AIR, 0, 0), false);
+ }
+ if($slot->getID() === MUSHROOM_STEW or $slot->getID() === BEETROOT_SOUP){
+ $this->addItem(BOWL, 0, 1, false);
+ }
+ }
+ break;
+ }
+ break;
+ case ProtocolInfo::DROP_ITEM_PACKET:
+ if($this->spawned === false or $this->blocked === true){
+ break;
+ }
+ $packet->eid = $this->eid;
+ $packet->item = $this->getSlot($this->slot);
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ $data["eid"] = $packet->eid;
+ $data["unknown"] = $packet->unknown;
+ $data["item"] = $packet->item;
+ $data["player"] = $this;
+ if($this->blocked === false and $this->server->handle("player.drop", $data) !== false){
+ $this->server->api->entity->drop(new Position($this->entity->x - 0.5, $this->entity->y, $this->entity->z - 0.5, $this->level), $packet->item);
+ $this->setSlot($this->slot, BlockAPI::getItem(AIR, 0, 0), false);
+ }
+ if($this->entity->inAction === true){
+ $this->entity->inAction = false;
+ $this->entity->updateMetadata();
+ }
+ break;
+ case ProtocolInfo::MESSAGE_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ if(trim($packet->message) != "" and strlen($packet->message) <= 255){
+ $message = $packet->message;
+ if($message{0} === "/"){ //Command
+ console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . " issued a command: " . FORMAT_AQUA . $message);
+ $this->server->api->console->run(substr($message, 1), $this);
+ }else{
+ $data = array("player" => $this, "message" => $message);
+ if($this->server->api->handle("player.chat", $data) !== false){
+ if(isset($data["message"])){
+ $this->server->api->chat->send($this, $data["message"]);
+ }else{
+ $this->server->api->chat->send($this, $message);
+ }
+ }
+ }
+ }
+ break;
+ case ProtocolInfo::CONTAINER_CLOSE_PACKET:
+ if($this->spawned === false){
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ if(isset($this->windows[$packet->windowid])){
+ if(is_array($this->windows[$packet->windowid])){
+ foreach($this->windows[$packet->windowid] as $ob){
+ $pk = new TileEventPacket;
+ $pk->x = $ob->x;
+ $pk->y = $ob->y;
+ $pk->z = $ob->z;
+ $pk->case1 = 1;
+ $pk->case2 = 0;
+ $this->server->api->player->broadcastPacket($this->level->players, $pk);
+ }
+ }elseif($this->windows[$packet->windowid]->class === TILE_CHEST){
+ $pk = new TileEventPacket;
+ $pk->x = $this->windows[$packet->windowid]->x;
+ $pk->y = $this->windows[$packet->windowid]->y;
+ $pk->z = $this->windows[$packet->windowid]->z;
+ $pk->case1 = 1;
+ $pk->case2 = 0;
+ $this->server->api->player->broadcastPacket($this->level->players, $pk);
+ }
+ }
+ unset($this->windows[$packet->windowid]);
+
+ $pk = new ContainerClosePacket;
+ $pk->windowid = $packet->windowid;
+ $this->dataPacket($pk);
+ break;
+ case ProtocolInfo::CONTAINER_SET_SLOT_PACKET:
+ if($this->spawned === false or $this->blocked === true){
+ break;
+ }
+
+ if($this->lastCraft <= (microtime(true) - 1)){
+ if(isset($this->toCraft[-1])){
+ $this->toCraft = array(-1 => $this->toCraft[-1]);
+ }else{
+ $this->toCraft = array();
+ }
+ $this->craftingItems = array();
+ }
+
+ if($packet->windowid === 0){
+ $craft = false;
+ $slot = $this->getSlot($packet->slot);
+ if($slot->count >= $packet->item->count and (($slot->getID() === $packet->item->getID() and $slot->getMetadata() === $packet->item->getMetadata()) or ($packet->item->getID() === AIR and $packet->item->count === 0)) and !isset($this->craftingItems[$packet->slot])){ //Crafting recipe
+ $use = BlockAPI::getItem($slot->getID(), $slot->getMetadata(), $slot->count - $packet->item->count);
+ $this->craftingItems[$packet->slot] = $use;
+ $craft = true;
+ }elseif($slot->count <= $packet->item->count and ($slot->getID() === AIR or ($slot->getID() === $packet->item->getID() and $slot->getMetadata() === $packet->item->getMetadata()))){ //Crafting final
+ $craftItem = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count - $slot->count);
+ if(count($this->toCraft) === 0){
+ $this->toCraft[-1] = 0;
+ }
+ $this->toCraft[$packet->slot] = $craftItem;
+ $craft = true;
+ }elseif(((count($this->toCraft) === 1 and isset($this->toCraft[-1])) or count($this->toCraft) === 0) and $slot->count > 0 and $slot->getID() > AIR and ($slot->getID() !== $packet->item->getID() or $slot->getMetadata() !== $packet->item->getMetadata())){ //Crafting final
+ $craftItem = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count);
+ if(count($this->toCraft) === 0){
+ $this->toCraft[-1] = 0;
+ }
+ $use = BlockAPI::getItem($slot->getID(), $slot->getMetadata(), $slot->count);
+ $this->craftingItems[$packet->slot] = $use;
+ $this->toCraft[$packet->slot] = $craftItem;
+ $craft = true;
+ }
+
+ if($craft === true){
+ $this->lastCraft = microtime(true);
+ }
+
+ if($craft === true and count($this->craftingItems) > 0 and count($this->toCraft) > 0 and ($recipe = $this->craftItems($this->toCraft, $this->craftingItems, $this->toCraft[-1])) !== true){
+ if($recipe === false){
+ $this->sendInventory();
+ $this->toCraft = array();
+ }else{
+ $this->toCraft = array(-1 => $this->toCraft[-1]);
+ }
+ $this->craftingItems = array();
+ }
+ }else{
+ $this->toCraft = array();
+ $this->craftingItems = array();
+ }
+ if(!isset($this->windows[$packet->windowid])){
+ break;
+ }
+
+ if(is_array($this->windows[$packet->windowid])){
+ $tiles = $this->windows[$packet->windowid];
+ if($packet->slot >= 0 and $packet->slot < CHEST_SLOTS){
+ $tile = $tiles[0];
+ $slotn = $packet->slot;
+ $offset = 0;
+ }elseif($packet->slot >= CHEST_SLOTS and $packet->slot <= (CHEST_SLOTS << 1)){
+ $tile = $tiles[1];
+ $slotn = $packet->slot - CHEST_SLOTS;
+ $offset = CHEST_SLOTS;
+ }else{
+ break;
+ }
+
+ $item = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count);
+
+ $slot = $tile->getSlot($slotn);
+ if($this->server->api->dhandle("player.container.slot", array(
+ "tile" => $tile,
+ "slot" => $packet->slot,
+ "offset" => $offset,
+ "slotdata" => $slot,
+ "itemdata" => $item,
+ "player" => $this,
+ )) === false){
+ $pk = new ContainerSetSlotPacket;
+ $pk->windowid = $packet->windowid;
+ $pk->slot = $packet->slot;
+ $pk->item = $slot;
+ $this->dataPacket($pk);
+ break;
+ }
+ if($item->getID() !== AIR and $slot->getID() == $item->getID()){
+ if($slot->count < $item->count){
+ if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false){
+ break;
+ }
+ }elseif($slot->count > $item->count){
+ $this->addItem($item->getID(), $item->getMetadata(), $slot->count - $item->count, false);
+ }
+ }else{
+ if($this->removeItem($item->getID(), $item->getMetadata(), $item->count, false) === false){
+ break;
+ }
+ $this->addItem($slot->getID(), $slot->getMetadata(), $slot->count, false);
+ }
+ $tile->setSlot($slotn, $item, true, $offset);
+ }else{
+ $tile = $this->windows[$packet->windowid];
+ if(($tile->class !== TILE_CHEST and $tile->class !== TILE_FURNACE) or $packet->slot < 0 or ($tile->class === TILE_CHEST and $packet->slot >= CHEST_SLOTS) or ($tile->class === TILE_FURNACE and $packet->slot >= FURNACE_SLOTS)){
+ break;
+ }
+ $item = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count);
+
+ $slot = $tile->getSlot($packet->slot);
+ if($this->server->api->dhandle("player.container.slot", array(
+ "tile" => $tile,
+ "slot" => $packet->slot,
+ "slotdata" => $slot,
+ "itemdata" => $item,
+ "player" => $this,
+ )) === false){
+ $pk = new ContainerSetSlotPacket;
+ $pk->windowid = $packet->windowid;
+ $pk->slot = $packet->slot;
+ $pk->item = $slot;
+ $this->dataPacket($pk);
+ break;
+ }
+
+ if($tile->class === TILE_FURNACE and $packet->slot == 2){
+ switch($slot->getID()){
+ case IRON_INGOT:
+ AchievementAPI::grantAchievement($this, "acquireIron");
+ break;
+ }
+ }
+
+ if($item->getID() !== AIR and $slot->getID() == $item->getID()){
+ if($slot->count < $item->count){
+ if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false){
+ break;
+ }
+ }elseif($slot->count > $item->count){
+ $this->addItem($item->getID(), $item->getMetadata(), $slot->count - $item->count, false);
+ }
+ }else{
+ if($this->removeItem($item->getID(), $item->getMetadata(), $item->count, false) === false){
+ break;
+ }
+ $this->addItem($slot->getID(), $slot->getMetadata(), $slot->count, false);
+ }
+ $tile->setSlot($packet->slot, $item);
+ }
+ break;
+ case ProtocolInfo::SEND_INVENTORY_PACKET: //TODO, Mojang, enable this ´^_^`
+ if($this->spawned === false){
+ break;
+ }
+ break;
+ case ProtocolInfo::ENTITY_DATA_PACKET:
+ if($this->spawned === false or $this->blocked === true){
+ break;
+ }
+ $this->craftingItems = array();
+ $this->toCraft = array();
+ $t = $this->server->api->tile->get(new Position($packet->x, $packet->y, $packet->z, $this->level));
+ if(($t instanceof Tile) and $t->class === TILE_SIGN){
+ if($t->data["creator"] !== $this->username){
+ $t->spawn($this);
+ }else{
+ $nbt = new NBT();
+ $nbt->load($packet->namedtag);
+ $d = array_shift($nbt->tree);
+ if($d["id"] !== TILE_SIGN){
+ $t->spawn($this);
+ }else{
+ $t->setText($d["Text1"], $d["Text2"], $d["Text3"], $d["Text4"]);
+ }
+ }
+ }
+ break;
+ default:
+ console("[DEBUG] Unhandled 0x".dechex($packet->pid())." data packet for ".$this->username." (".$this->clientID."): ".print_r($packet, true), true, true, 2);
+ break;
+ }
+ }
+
+ /**
+ * @param Player|string|boolean|void $player
+ */
+ public function sendArmor($player = false){
+ $data = array(
+ "player" => $this,
+ "eid" => $this->eid,
+ "slots" => array()
+ );
+ for($i = 0; $i < 4; ++$i){
+ if(isset($this->armor[$i]) and ($this->armor[$i] instanceof Item) and $this->armor[$i]->getID() > AIR){
+ $data["slots"][$i] = $this->armor[$i]->getID() !== AIR ? $this->armor[$i]->getID() - 256:0;
+ }else{
+ $this->armor[$i] = BlockAPI::getItem(AIR, 0, 0);
+ $data["slots"][$i] = 255;
+ }
+ }
+ if($player instanceof Player){
+ if($player === $this){
+ $pk = new ContainerSetContentPacket;
+ $pk->windowid = 0x78; //Armor window id
+ $pk->slots = $this->armor;
+ $this->dataPacket($pk);
+ }else{
+ $pk = new PlayerArmorEquipmentPacket;
+ $pk->eid = $this->eid;
+ $pk->slots = $data["slots"];
+ $player->dataPacket($pk);
+ }
+ }else{
+ $this->server->api->dhandle("player.armor", $data);
+ }
+ }
+
+ public function sendInventory(){
+ if(($this->gamemode & 0x01) === CREATIVE){
+ return;
+ }
+ $hotbar = array();
+ foreach($this->hotbar as $slot){
+ $hotbar[] = $slot <= -1 ? -1 : $slot + 9;
+ }
+
+ $pk = new ContainerSetContentPacket;
+ $pk->windowid = 0;
+ $pk->slots = $this->inventory;
+ $pk->hotbar = $hotbar;
+ $this->dataPacket($pk);
+ }
+
+ public function send(RakNetPacket $packet){
+ if($this->connected === true){
+ $packet->ip = $this->ip;
+ $packet->port = $this->port;
+ $this->bandwidthRaw += $this->server->send($packet);
+ }
+ }
+
+ public function sendBuffer(){
+ if($this->bufferLen > 0 and $this->buffer instanceof RakNetPacket){
+ $this->buffer->seqNumber = $this->counter[0]++;
+ $this->send($this->buffer);
+ }
+ $this->bufferLen = 0;
+ $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
+ $this->buffer->data = array();
+ $this->nextBuffer = microtime(true) + 0.1;
+ }
+
+ private function directBigRawPacket(RakNetDataPacket $packet){
+ if($this->connected === false){
+ return false;
+ }
+
+ $sendtime = microtime(true);
+
+ $size = $this->MTU - 34;
+ $buffer = str_split($packet->buffer, $size);
+ $bigCnt = $this->bigCnt;
+ $this->bigCnt = ($this->bigCnt + 1) % 0x10000;
+ $cnts = array();
+ $bufCount = count($buffer);
+ foreach($buffer as $i => $buf){
+ $cnts[] = $count = $this->counter[0]++;
+
+ $pk = new UnknownPacket;
+ $pk->packetID = $packet->pid();
+ $pk->reliability = 2;
+ $pk->hasSplit = true;
+ $pk->splitCount = $bufCount;
+ $pk->splitID = $bigCnt;
+ $pk->splitIndex = $i;
+ $pk->buffer = $buf;
+ $pk->messageIndex = $this->counter[3]++;
+
+ $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
+ $rk->data[] = $pk;
+ $rk->seqNumber = $count;
+ $rk->sendtime = $sendtime;
+ $this->recoveryQueue[$count] = $rk;
+ $this->send($rk);
+ }
+ return $cnts;
+ }
+
+ public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){
+ if($this->connected === false){
+ return false;
+ }
+
+ if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){
+ return array();
+ }
+
+ $packet->encode();
+ $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
+ $pk->data[] = $packet;
+ $pk->seqNumber = $this->counter[0]++;
+ $pk->sendtime = microtime(true);
+ if($recover !== false){
+ $this->recoveryQueue[$pk->seqNumber] = $pk;
+ }
+
+ $this->send($pk);
+ return array($pk->seqNumber);
+ }
+
+ /**
+ * @param integer $id
+ * @param array $data
+ *
+ * @return array|bool
+ */
+ public function dataPacket(RakNetDataPacket $packet){
+ if($this->connected === false){
+ return false;
+ }
+
+ if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){
+ return;
+ }
+
+ $packet->encode();
+ $len = strlen($packet->buffer) + 1;
+ $MTU = $this->MTU - 24;
+ if($len > $MTU){
+ return $this->directBigRawPacket($packet);
+ }
+
+ if(($this->bufferLen + $len) >= $MTU){
+ $this->sendBuffer();
+ }
+
+ $packet->messageIndex = $this->counter[3]++;
+ $packet->reliability = 2;
+ $this->buffer->data[] = $packet;
+ $this->bufferLen += 6 + $len;
+ return array();
+ }
+
+ /**
+ * @return string
+ */
+ function __toString(){
+ if($this->username != ""){
+ return $this->username;
+ }
+ return $this->clientID;
+ }
+
+}
diff --git a/src/build/compile.sh b/src/build/compile.sh
old mode 100755
new mode 100644
diff --git a/src/constants/GeneralConstants.php b/src/constants/GeneralConstants.php
index 6af9f80a..2dae4e07 100644
--- a/src/constants/GeneralConstants.php
+++ b/src/constants/GeneralConstants.php
@@ -32,7 +32,7 @@ define("SPECTATOR", 3);
//Players
-define("MAX_CHUNK_RATE", 20 / arg("max-chunks-per-second", 4)); //Default rate ~256 kB/s
+define("MAX_CHUNK_RATE", 20 / arg("max-chunks-per-second", 16)); //Default rate ~256 kB/s
define("PLAYER_MAX_QUEUE", 1024);
define("PLAYER_SURVIVAL_SLOTS", 36);
diff --git a/src/constants/GeneralConstants.php.bak b/src/constants/GeneralConstants.php.bak
new file mode 100644
index 00000000..7f44220f
--- /dev/null
+++ b/src/constants/GeneralConstants.php.bak
@@ -0,0 +1,85 @@
+id, 0, 1),
- );
+ if($item->isPickaxe()){
+ return array(
+ array($this->id, 0, 1),
+ );
+ } else {
+ return array(
+ array($this->id, 0, 0),
+ );
+ }
}
-}
\ No newline at end of file
+}
diff --git a/src/pmf/Level.php b/src/pmf/PMFLevel.php
similarity index 55%
rename from src/pmf/Level.php
rename to src/pmf/PMFLevel.php
index 1702cca7..61bb92e4 100644
--- a/src/pmf/Level.php
+++ b/src/pmf/PMFLevel.php
@@ -19,16 +19,17 @@
*
*/
-define("PMF_CURRENT_LEVEL_VERSION", 0x00);
-
class PMFLevel extends PMF{
- private $levelData = array();
- private $locationTable = array();
+ const VERSION = 0x01;
+ const DEFLATE_LEVEL = 9;
+
+ public $level;
+ public $levelData = array();
public $isLoaded = true;
- private $log = 4;
- private $payloadOffset = 0;
private $chunks = array();
private $chunkChange = array();
+ private $chunkInfo = array();
+ public $isGenerating = 0;
public function getData($index){
if(!isset($this->levelData[$index])){
@@ -45,19 +46,21 @@ class PMFLevel extends PMF{
return true;
}
- public function close(){
- $chunks = null;
- unset($chunks, $chunkChange, $locationTable);
- parent::close();
+ public function closeLevel(){
+ $this->chunks = null;
+ unset($this->chunks, $this->chunkChange, $this->chunkInfo, $this->level);
+ $this->close();
}
public function __construct($file, $blank = false){
+ $this->chunks = array();
+ $this->chunkChange = array();
+ $this->chunkInfo = array();
if(is_array($blank)){
$this->create($file, 0);
$this->levelData = $blank;
$this->createBlank();
$this->isLoaded = true;
- $this->log = (int) ((string) log($this->levelData["width"], 2));
}else{
if($this->load($file) !== false){
$this->parseInfo();
@@ -65,7 +68,6 @@ class PMFLevel extends PMF{
$this->isLoaded = false;
}else{
$this->isLoaded = true;
- $this->log = (int) ((string) log($this->levelData["width"], 2));
}
}else{
$this->isLoaded = false;
@@ -73,8 +75,8 @@ class PMFLevel extends PMF{
}
}
- public function saveData($locationTable = true){
- $this->levelData["version"] = PMF_CURRENT_LEVEL_VERSION;
+ public function saveData(){
+ $this->levelData["version"] = PMFLevel::VERSION;
@ftruncate($this->fp, 5);
$this->seek(5);
$this->write(chr($this->levelData["version"]));
@@ -84,33 +86,17 @@ class PMFLevel extends PMF{
$this->write(Utils::writeFloat($this->levelData["spawnX"]));
$this->write(Utils::writeFloat($this->levelData["spawnY"]));
$this->write(Utils::writeFloat($this->levelData["spawnZ"]));
- $this->write(chr($this->levelData["width"]));
$this->write(chr($this->levelData["height"]));
- $extra = gzdeflate($this->levelData["extra"], PMF_LEVEL_DEFLATE_LEVEL);
+ $this->write(Utils::writeShort(strlen($this->levelData["generator"])).$this->levelData["generator"]);
+ $settings = serialize($this->levelData["generatorSettings"]);
+ $this->write(Utils::writeShort(strlen($settings)).$settings);
+ $extra = gzdeflate($this->levelData["extra"], PMFLevel::DEFLATE_LEVEL);
$this->write(Utils::writeShort(strlen($extra)).$extra);
- $this->payloadOffset = ftell($this->fp);
-
- if($locationTable !== false){
- $this->writeLocationTable();
- }
}
private function createBlank(){
$this->saveData(false);
- $this->locationTable = array();
- $cnt = pow($this->levelData["width"], 2);
@mkdir(dirname($this->file)."/chunks/", 0755);
- for($index = 0; $index < $cnt; ++$index){
- $this->chunks[$index] = false;
- $this->chunkChange[$index] = false;
- $this->locationTable[$index] = array(
- 0 => 0,
- );
- $this->write(Utils::writeShort(0));
- $X = $Z = null;
- $this->getXZ($index, $X, $Z);
- @file_put_contents($this->getChunkPath($X, $Z), gzdeflate("", PMF_LEVEL_DEFLATE_LEVEL));
- }
if(!file_exists(dirname($this->file)."/entities.yml")){
$entities = new Config(dirname($this->file)."/entities.yml", CONFIG_YAML);
$entities->save();
@@ -127,7 +113,8 @@ class PMFLevel extends PMF{
}
$this->seek(5);
$this->levelData["version"] = ord($this->read(1));
- if($this->levelData["version"] > PMF_CURRENT_LEVEL_VERSION){
+ if($this->levelData["version"] > PMFLevel::VERSION){
+ console("[ERROR] New unsupported PMF Level format version #".$this->levelData["version"].", current version is #".PMFLevel::VERSION);
return false;
}
$this->levelData["name"] = $this->read(Utils::readShort($this->read(2), false));
@@ -136,92 +123,130 @@ class PMFLevel extends PMF{
$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));
- if(($this->levelData["width"] !== 16 and $this->levelData["width"] !== 32) or $this->levelData["height"] !== 8){
- return 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"] = "";
- $cnt = pow($this->levelData["width"], 2);
- for($index = 0; $index < $cnt; ++$index){
- $this->write("\x00\xFF"); //Force index recreation
- }
- fseek($this->fp, $this->payloadOffset);
+ if($this->levelData["version"] === 0){
+ $this->read(1);
+ $this->levelData["height"] = ord($this->read(1));
}else{
- $this->payloadOffset = ftell($this->fp);
+ $this->levelData["height"] = ord($this->read(1));
+ if($this->levelData["height"] !== 8){
+ return false;
+ }
+ $this->levelData["generator"] = $this->read(Utils::readShort($this->read(2), false));
+ $this->levelData["generatorSettings"] = unserialize($this->read(Utils::readShort($this->read(2), false)));
+
+ }
+ $this->levelData["extra"] = @gzinflate($this->read(Utils::readShort($this->read(2), false)));
+
+ if($this->levelData["version"] === 0){
+ $this->upgrade_From0_To1();
}
- return $this->readLocationTable();
}
- public function getIndex($X, $Z){
- $X = (int) $X;
- $Z = (int) $Z;
- return ($Z << $this->log) + $X;
+ private function upgrade_From0_To1(){
+ console("[NOTICE] Old PMF Level format version #0 detected, upgrading to version #1");
+ for($index = 0; $index < 256; ++$index){
+ $X = $index & 0x0F;
+ $Z = $index >> 4;
+
+ $bitflags = Utils::readShort($this->read(2));
+ $oldPath = dirname($this->file)."/chunks/".$Z.".".$X.".pmc";
+ $chunkOld = gzopen($oldPath, "rb");
+ $newPath = dirname($this->file)."/chunks/".(($X ^ $Z) & 0xff)."/".$Z.".".$X.".pmc";
+ @mkdir(dirname($newPath));
+ $chunkNew = gzopen($newPath, "wb".PMFLevel::DEFLATE_LEVEL);
+ gzwrite($chunkNew, chr($bitflags) . "\x00\x00\x00\x01");
+ while(gzeof($chunkOld) === false){
+ gzwrite($chunkNew, gzread($chunkOld, 65535));
+ }
+ gzclose($chunkNew);
+ gzclose($chunkOld);
+ @unlink($oldPath);
+ }
+ $this->levelData["version"] = 0x01;
+ $this->levelData["generator"] = "NormalGenerator";
+ $this->levelData["generatorSettings"] = "";
+ $this->saveData();
}
- public function getXZ($index, &$X = null, &$Z = null){
- $X = $index >> $this->log;
- $Z = $index & (pow($this->log, 2) - 1);
+ public static function getIndex($X, $Z){
+ return ($Z << 16) | ($X < 0 ? (~--$X & 0x7fff) | 0x8000 : $X & 0x7fff);
+ }
+
+ public static function getXZ($index, &$X = null, &$Z = null){
+ $Z = $index >> 16;
+ $X = ($index & 0x8000) === 0x8000 ? -($index & 0x7fff) : $index & 0x7fff;
return array($X, $Z);
}
- private function readLocationTable(){
- $this->locationTable = array();
- $cnt = pow($this->levelData["width"], 2);
- $this->seek($this->payloadOffset);
- for($index = 0; $index < $cnt; ++$index){
- $this->chunks[$index] = false;
- $this->chunkChange[$index] = false;
- $this->locationTable[$index] = array(
- 0 => Utils::readShort($this->read(2)), //16 bit flags
- );
- }
- return true;
- }
-
- private function writeLocationTable(){
- $cnt = pow($this->levelData["width"], 2);
- @ftruncate($this->fp, $this->payloadOffset);
- $this->seek($this->payloadOffset);
- for($index = 0; $index < $cnt; ++$index){
- $this->write(Utils::writeShort($this->locationTable[$index][0]));
- }
- }
-
private function getChunkPath($X, $Z){
- return dirname($this->file)."/chunks/".$Z.".".$X.".pmc";
+ return dirname($this->file)."/chunks/".(($X ^ $Z) & 0xff)."/".$Z.".".$X.".pmc";
+ }
+
+ public function generateChunk($X, $Z){
+ $path = $this->getChunkPath($X, $Z);
+ if(!file_exists(dirname($path))){
+ @mkdir(dirname($path), 0755);
+ }
+ $this->initCleanChunk($X, $Z);
+ $ret = $this->level->generateChunk($X, $Z);
+ $this->saveChunk($X, $Z);
+ $this->populateChunk($X - 1, $Z);
+ $this->populateChunk($X + 1, $Z);
+ $this->populateChunk($X, $Z - 1);
+ $this->populateChunk($X, $Z + 1);
+ $this->populateChunk($X + 1, $Z + 1);
+ $this->populateChunk($X + 1, $Z - 1);
+ $this->populateChunk($X - 1, $Z - 1);
+ $this->populateChunk($X - 1, $Z + 1);
+ return $ret;
+ }
+
+ public function populateChunk($X, $Z){
+ if($this->isGenerating === 0 and
+ !$this->isPopulated($X, $Z) and
+ $this->isGenerated($X - 1, $Z) and
+ $this->isGenerated($X, $Z - 1) and
+ $this->isGenerated($X + 1, $Z) and
+ $this->isGenerated($X, $Z + 1) and
+ $this->isGenerated($X + 1, $Z + 1) and
+ $this->isGenerated($X - 1, $Z - 1) and
+ $this->isGenerated($X + 1, $Z - 1) and
+ $this->isGenerated($X - 1, $Z + 1)){
+ $this->level->populateChunk($X, $Z);
+ $this->saveChunk($X, $Z);
+ }
}
public function loadChunk($X, $Z){
-
+ $X = (int) $X;
+ $Z = (int) $Z;
$index = self::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");
+ $path = $this->getChunkPath($X, $Z);
+ if(!file_exists($path)){
+ if($this->generateChunk($X, $Z) === false){
+ return false;
+ }elseif($this->isGenerating === 0){
+ $this->populateChunk($X, $Z);
+ return true;
+ }
+ }
+
+ $chunk = @gzopen($path, "rb");
if($chunk === false){
return false;
}
+ $this->chunkInfo[$index] = array(
+ 0 => ord(gzread($chunk, 1)),
+ 1 => Utils::readInt(gzread($chunk, 4)),
+ );
$this->chunks[$index] = array();
$this->chunkChange[$index] = array(-1 => false);
- for($Y = 0; $Y < $this->levelData["height"]; ++$Y){
+ for($Y = 0; $Y < $this->chunkInfo[$index][0]; ++$Y){
$t = 1 << $Y;
- if(($info[0] & $t) === $t){
+ if(($this->chunkInfo[$index][0] & $t) === $t){
// 4096 + 2048 + 2048, Block Data, Meta, Light
if(strlen($this->chunks[$index][$Y] = gzread($chunk, 8192)) < 8192){
console("[NOTICE] Empty corrupt chunk detected [$X,$Z,:$Y], recovering contents", true, true, 2);
@@ -232,6 +257,9 @@ class PMFLevel extends PMF{
}
}
@gzclose($chunk);
+ if($this->isGenerating === 0 and !$this->isPopulated($X, $Z)){
+ $this->populateChunk($X, $Z);
+ }
return true;
}
@@ -243,24 +271,25 @@ class PMFLevel extends PMF{
}elseif($save !== false){
$this->saveChunk($X, $Z);
}
- $index = $this->getIndex($X, $Z);
+ $index = self::getIndex($X, $Z);
$this->chunks[$index] = null;
$this->chunkChange[$index] = null;
- unset($this->chunks[$index], $this->chunkChange[$index]);
+ $this->chunkInfo[$index] = null;
+ unset($this->chunks[$index], $this->chunkChange[$index], $this->chunkInfo[$index]);
return true;
}
public function isChunkLoaded($X, $Z){
- $index = $this->getIndex($X, $Z);
- if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index])){
return false;
}
return true;
}
- protected function isMiniChunkEmpty($X, $Z, $Y){
- $index = $this->getIndex($X, $Z);
- if($this->chunks[$index][$Y] !== false){
+ public function isMiniChunkEmpty($X, $Z, $Y){
+ $index = self::getIndex($X, $Z);
+ if(isset($this->chunks[$index]) and $this->chunks[$index][$Y] !== false){
if(substr_count($this->chunks[$index][$Y], "\x00") < 8192){
return false;
}
@@ -272,48 +301,84 @@ class PMFLevel extends PMF{
if($this->isChunkLoaded($X, $Z) === false){
return false;
}
- $index = $this->getIndex($X, $Z);
+ $index = self::getIndex($X, $Z);
$this->chunks[$index][$Y] = str_repeat("\x00", 8192);
$this->chunkChange[$index][-1] = true;
$this->chunkChange[$index][$Y] = 8192;
- $this->locationTable[$index][0] |= 1 << $Y;
+ $this->chunkInfo[$index][0] |= 1 << $Y;
return true;
}
public function getMiniChunk($X, $Z, $Y){
- if($this->loadChunk($X, $Z) === false){
+ if($this->isChunkLoaded($X, $Z) === false and $this->loadChunk($X, $Z) === false){
return str_repeat("\x00", 8192);
}
- $index = $this->getIndex($X, $Z);
+ $index = self::getIndex($X, $Z);
if(!isset($this->chunks[$index][$Y]) or $this->chunks[$index][$Y] === false){
return str_repeat("\x00", 8192);
}
return $this->chunks[$index][$Y];
}
+ public function initCleanChunk($X, $Z){
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index])){
+ $this->chunks[$index] = array(
+ 0 => false,
+ 1 => false,
+ 2 => false,
+ 3 => false,
+ 4 => false,
+ 5 => false,
+ 6 => false,
+ 7 => false,
+ );
+ $this->chunkChange[$index] = array(
+ -1 => true,
+ 0 => 8192,
+ 1 => 8192,
+ 2 => 8192,
+ 3 => 8192,
+ 4 => 8192,
+ 5 => 8192,
+ 6 => 8192,
+ 7 => 8192,
+ );
+ $this->chunkInfo[$index] = array(
+ 0 => 0,
+ 1 => 0,
+ );
+ }
+ }
+
public function setMiniChunk($X, $Z, $Y, $data){
- if($this->isChunkLoaded($X, $Z) === false){
+ if($this->isGenerating > 0){
+ $this->initCleanChunk($X, $Z);
+ }elseif($this->isChunkLoaded($X, $Z) === false){
$this->loadChunk($X, $Z);
}
if(strlen($data) !== 8192){
return false;
}
- $index = $this->getIndex($X, $Z);
+ $index = self::getIndex($X, $Z);
$this->chunks[$index][$Y] = (string) $data;
$this->chunkChange[$index][-1] = true;
$this->chunkChange[$index][$Y] = 8192;
- $this->locationTable[$index][0] |= 1 << $Y;
+ $this->chunkInfo[$index][0] |= 1 << $Y;
return true;
}
public function getBlockID($x, $y, $z){
- if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){
+ if($y > 127 or $y < 0){
return 0;
}
$X = $x >> 4;
$Z = $z >> 4;
$Y = $y >> 4;
- $index = $this->getIndex($X, $Z);
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index])){
+ return 0;
+ }
$aX = $x - ($X << 4);
$aZ = $z - ($Z << 4);
$aY = $y - ($Y << 4);
@@ -322,17 +387,17 @@ class PMFLevel extends PMF{
}
public function setBlockID($x, $y, $z, $block){
- if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){
+ if($y > 127 or $y < 0){
return false;
}
$X = $x >> 4;
$Z = $z >> 4;
$Y = $y >> 4;
$block &= 0xFF;
- if($X >= 32 or $Z >= 32 or $Y >= $this->levelData["height"] or $y < 0){
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index])){
return false;
}
- $index = $this->getIndex($X, $Z);
$aX = $x - ($X << 4);
$aZ = $z - ($Z << 4);
$aY = $y - ($Y << 4);
@@ -347,13 +412,16 @@ class PMFLevel extends PMF{
}
public function getBlockDamage($x, $y, $z){
- if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){
+ if($y > 127 or $y < 0){
return 0;
}
$X = $x >> 4;
$Z = $z >> 4;
$Y = $y >> 4;
- $index = $this->getIndex($X, $Z);
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index])){
+ return 0;
+ }
$aX = $x - ($X << 4);
$aZ = $z - ($Z << 4);
$aY = $y - ($Y << 4);
@@ -367,17 +435,17 @@ class PMFLevel extends PMF{
}
public function setBlockDamage($x, $y, $z, $damage){
- if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){
+ if($y > 127 or $y < 0){
return false;
}
$X = $x >> 4;
$Z = $z >> 4;
$Y = $y >> 4;
$damage &= 0x0F;
- if($X >= 32 or $Z >= 32 or $Y >= $this->levelData["height"] or $y < 0){
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index])){
return false;
}
- $index = $this->getIndex($X, $Z);
$aX = $x - ($X << 4);
$aZ = $z - ($Z << 4);
$aY = $y - ($Y << 4);
@@ -406,15 +474,13 @@ class PMFLevel extends PMF{
$X = $x >> 4;
$Z = $z >> 4;
$Y = $y >> 4;
- if($x < 0 or $z < 0 or $X >= $this->levelData["width"] or $Z >= $this->levelData["width"] or $Y >= $this->levelData["height"] or $y < 0){
+ if($y < 0 or $y > 127){
return array(AIR, 0);
}
- $index = $this->getIndex($X, $Z);
- if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){
- if($this->loadChunk($X, $Z) === false){
- return array(AIR, 0);
- }
- }elseif($this->chunks[$index][$Y] === false){
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index]) and $this->loadChunk($X, $Z) === false){
+ return array(AIR, 0);
+ }elseif($this->chunks[$index][$Y] === false){
return array(AIR, 0);
}
$aX = $x - ($X << 4);
@@ -431,19 +497,17 @@ class PMFLevel extends PMF{
}
public function setBlock($x, $y, $z, $block, $meta = 0){
+ if($y > 127 or $y < 0){
+ return false;
+ }
$X = $x >> 4;
$Z = $z >> 4;
$Y = $y >> 4;
$block &= 0xFF;
$meta &= 0x0F;
- if($X >= 32 or $Z >= 32 or $Y >= $this->levelData["height"] or $y < 0){
+ $index = self::getIndex($X, $Z);
+ if(!isset($this->chunks[$index]) and $this->loadChunk($X, $Z) === false){
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;
- }
}elseif($this->chunks[$index][$Y] === false){
$this->fillMiniChunk($X, $Z, $Y);
}
@@ -469,16 +533,6 @@ class PMFLevel extends PMF{
++$this->chunkChange[$index][$Y];
}
$this->chunkChange[$index][-1] = true;
- if($old_b instanceof LiquidBlock)
- {
- $pos = new Position($x, $y, $z, $this->level);
- for($side = 0; $side <= 5; ++$side)
- {
- $b = $pos->getSide($side);
- if($b instanceof LavaBlock) { ServerAPI::request()->api->block->scheduleBlockUpdate(new Position($b, 0, 0, $this->level), 40, BLOCK_UPDATE_NORMAL); }
- else { ServerAPI::request()->api->block->scheduleBlockUpdate(new Position($b, 0, 0, $this->level), 10, BLOCK_UPDATE_NORMAL); }
- }
- }
return true;
}
return false;
@@ -490,32 +544,70 @@ class PMFLevel extends PMF{
if(!$this->isChunkLoaded($X, $Z)){
return false;
}
- $index = $this->getIndex($X, $Z);
+ $index = self::getIndex($X, $Z);
if(!isset($this->chunkChange[$index]) or $this->chunkChange[$index][-1] === false){//No changes in chunk
return true;
}
- $chunk = @gzopen($this->getChunkPath($X, $Z), "wb".PMF_LEVEL_DEFLATE_LEVEL);
+ $path = $this->getChunkPath($X, $Z);
+ if(!file_exists(dirname($path))){
+ @mkdir(dirname($path), 0755);
+ }
$bitmap = 0;
- for($Y = 0; $Y < $this->levelData["height"]; ++$Y){
+ for($Y = 0; $Y < 8; ++$Y){
if($this->chunks[$index][$Y] !== false and ((isset($this->chunkChange[$index][$Y]) and $this->chunkChange[$index][$Y] === 0) or !$this->isMiniChunkEmpty($X, $Z, $Y))){
- gzwrite($chunk, $this->chunks[$index][$Y]);
$bitmap |= 1 << $Y;
}else{
$this->chunks[$index][$Y] = false;
}
$this->chunkChange[$index][$Y] = 0;
}
+ $chunk = @gzopen($path, "wb".PMFLevel::DEFLATE_LEVEL);
+ gzwrite($chunk, chr($bitmap));
+ gzwrite($chunk, Utils::writeInt($this->chunkInfo[$index][1]));
+ for($Y = 0; $Y < 8; ++$Y){
+ $t = 1 << $Y;
+ if(($bitmap & $t) === $t){
+ gzwrite($chunk, $this->chunks[$index][$Y]);
+ }
+ }
+ gzclose($chunk);
$this->chunkChange[$index][-1] = false;
- $this->locationTable[$index][0] = $bitmap;
- $this->seek($this->payloadOffset + ($index << 1));
- $this->write(Utils::writeShort($this->locationTable[$index][0]));
+ $this->chunkInfo[$index][0] = $bitmap;
return true;
}
+ public function setPopulated($X, $Z){
+ if(!$this->isChunkLoaded($X, $Z)){
+ return false;
+ }
+ $index = self::getIndex($X, $Z);
+ $this->chunkInfo[$index][1] |= 0b00000000000000000000000000000001;
+ }
+
+ public function unsetPopulated($X, $Z){
+ if(!$this->isChunkLoaded($X, $Z)){
+ return false;
+ }
+ $index = self::getIndex($X, $Z);
+ $this->chunkInfo[$index][1] &= ~0b00000000000000000000000000000001;
+ }
+
+ public function isPopulated($X, $Z){
+ if(!$this->isChunkLoaded($X, $Z)){
+ return false;
+ }
+ $index = self::getIndex($X, $Z);
+ return ($this->chunkInfo[$index][1] & 0b00000000000000000000000000000001) > 0;
+ }
+
+ public function isGenerated($X, $Z){
+ return file_exists($this->getChunkPath($X, $Z));
+ }
+
public function doSaveRound(){
foreach($this->chunks as $index => $chunk){
- $this->getXZ($index, $X, $Z);
+ self::getXZ($index, $X, $Z);
$this->saveChunk($X, $Z);
}
}
diff --git a/src/pmf/Plugin.php b/src/pmf/PMFPlugin.php
similarity index 100%
rename from src/pmf/Plugin.php
rename to src/pmf/PMFPlugin.php
diff --git a/src/world/Entity.php b/src/world/Entity.php
index 3f473604..11e3e81f 100644
--- a/src/world/Entity.php
+++ b/src/world/Entity.php
@@ -136,7 +136,7 @@ class Entity extends Position{
$this->setHealth(10000000, "generic");
$this->server->schedule(5, array($this, "updateFuse"), array(), true);
$this->update();
- }elseif($this->type === (OBJECT_ARROW or OBJECT_SNOWBALL)){
+ }elseif($this->type === OBJECT_ARROW){
$this->server->schedule(1210, array($this, "update")); //Despawn
$this->update();
}
@@ -164,7 +164,7 @@ class Entity extends Position{
}
public function getDrops(){
- if($this->class === ENTITY_PLAYER and $this->player instanceof Player and ($this->player->gamemode & 0x01) === 0){
+ if($this->class === ENTITY_PLAYER and ($this->player->gamemode & 0x01) === 0){
$inv = array();
for($i = 0; $i < PLAYER_SURVIVAL_SLOTS; ++$i){
$slot = $this->player->getSlot($i);
@@ -201,7 +201,6 @@ class Entity extends Position{
case MOB_PIGMAN:
return array(
array(COOKED_PORKCHOP, 0, mt_rand(0,2)),
- array(GOLD_INGOT, 0, mt_rand(0,2)),
);
case MOB_CREEPER:
return array(
@@ -266,7 +265,7 @@ class Entity extends Position{
$this->close(); //Despawn timer
return false;
}
- }elseif($this->class === ENTITY_OBJECT and ($this->type === OBJECT_ARROW or OBJECT_SNOWBALL)){
+ }elseif($this->class === ENTITY_OBJECT and $this->type === OBJECT_ARROW){
if(($time - $this->spawntime) >= 60){
$this->close(); //Despawn timer
return false;
@@ -297,7 +296,7 @@ class Entity extends Position{
}
}
- if($this->class !== ENTITY_PLAYER and ($this->x <= 0 or $this->z <= 0 or $this->x >= 256 or $this->z >= 256 or $this->y >= 128 or $this->y <= 0)){
+ if($this->class !== ENTITY_PLAYER and ($this->y >= 128 or $this->y <= 0)){
$this->close();
return false;
}
diff --git a/src/world/Level.php b/src/world/Level.php
index af3995a1..dc8a8bff 100644
--- a/src/world/Level.php
+++ b/src/world/Level.php
@@ -21,7 +21,7 @@
class Level{
public $entities, $tiles, $blockUpdates, $nextSave, $players = array(), $level;
- private $time, $startCheck, $startTime, $server, $name, $usedChunks, $changedBlocks, $changedCount, $stopTime;
+ private $time, $startCheck, $startTime, $server, $name, $usedChunks, $changedBlocks, $changedCount, $stopTime, $generator;
public function __construct(PMFLevel $level, Config $entities, Config $tiles, Config $blockUpdates, $name){
$this->server = ServerAPI::request();
@@ -40,6 +40,17 @@ class Level{
$this->usedChunks = array();
$this->changedBlocks = array();
$this->changedCount = array();
+ if(class_exists($this->level->levelData["generator"])){
+ $gen = $this->level->levelData["generator"];
+ $this->generator = new $gen((array) $this->level->levelData["generatorSettings"]);
+ }else{
+ if(strtoupper($this->server->api->getProperty("level-type")) == "FLAT"){
+ $this->generator = new SuperflatGenerator();
+ }else{
+ $this->generator = new NormalGenerator();
+ }
+ }
+ $this->generator->init($this, new Random($this->level->levelData["seed"]));
}
public function close(){
@@ -93,9 +104,8 @@ class Level{
$now = microtime(true);
$this->players = $this->server->api->player->getAll($this);
- if(count($this->changedCount) > 0){
+ if($this->level->isGenerating === 0 and count($this->changedCount) > 0){
arsort($this->changedCount);
- $resendChunks = array();
foreach($this->changedCount as $index => $count){
if($count < 582){//Optimal value, calculated using the relation between minichunks and single packets
break;
@@ -128,10 +138,10 @@ class Level{
if(count($c) === 0){
unset($this->usedChunks[$i]);
$X = explode(".", $i);
- $Z = array_pop($X);
- $X = array_pop($X);
+ $Z = (int) array_pop($X);
+ $X = (int) array_pop($X);
if(!$this->isSpawnChunk($X, $Z)){
- $this->level->unloadChunk((int) $X, (int) $Z, $this->server->saveEnabled);
+ $this->level->unloadChunk($X, $Z, $this->server->saveEnabled);
}
}
}
@@ -139,10 +149,23 @@ class Level{
}
}
+ public function generateChunk($X, $Z){
+ ++$this->level->isGenerating;
+ $this->generator->generateChunk($X, $Z);
+ --$this->level->isGenerating;
+ return true;
+ }
+
+ public function populateChunk($X, $Z){
+ $this->level->setPopulated($X, $Z);
+ $this->generator->populateChunk($X, $Z);
+ return true;
+ }
+
public function __destruct(){
if(isset($this->level)){
$this->save(false, false);
- $this->level->close();
+ $this->level->closeLevel();
unset($this->level);
}
}
@@ -392,14 +415,14 @@ class Level{
if(!isset($this->level)){
return false;
}
-
+
if($force !== true and $this->isSpawnChunk($X, $Z)){
return false;
}
Cache::remove("world:{$this->name}:$X:$Z");
return $this->level->unloadChunk($X, $Z, $this->server->saveEnabled);
}
-
+
public function isSpawnChunk($X, $Z){
$spawnX = $this->level->getData("spawnX") >> 4;
$spawnZ = $this->level->getData("spawnZ") >> 4;
diff --git a/src/world/LevelImport.php b/src/world/LevelImport.php
index 39676d2f..b2af2f7a 100644
--- a/src/world/LevelImport.php
+++ b/src/world/LevelImport.php
@@ -64,9 +64,10 @@ class LevelImport{
"spawnX" => $level["SpawnX"],
"spawnY" => $level["SpawnY"],
"spawnZ" => $level["SpawnZ"],
- "extra" => "",
- "width" => 16,
- "height" => 8
+ "height" => 8,
+ "generator" => "NormalGenerator",
+ "generatorSettings" => "",
+ "extra" => ""
));
$chunks = new PocketChunkParser();
$chunks->loadFile($this->path."chunks.dat");
diff --git a/src/world/generator/LevelGenerator.php b/src/world/generator/LevelGenerator.php
index 5da98645..939d356f 100644
--- a/src/world/generator/LevelGenerator.php
+++ b/src/world/generator/LevelGenerator.php
@@ -20,7 +20,8 @@
*/
interface LevelGenerator{
- public function __construct(array $options = array());
+
+ public function __construct(array $settings = array());
public function init(Level $level, Random $random);
@@ -28,7 +29,9 @@ interface LevelGenerator{
public function populateChunk($chunkX, $chunkZ);
- public function populateLevel();
+ public function getSettings();
+
+ //public function populateLevel();
public function getSpawn();
}
\ No newline at end of file
diff --git a/src/world/generator/NormalGenerator.php b/src/world/generator/NormalGenerator.php
new file mode 100644
index 00000000..bf24d764
--- /dev/null
+++ b/src/world/generator/NormalGenerator.php
@@ -0,0 +1,169 @@
+level = $level;
+ $this->random = $random;
+ $this->random->setSeed($this->level->getSeed());
+ $this->noiseHills = new NoiseGeneratorSimplex($this->random, 3);
+ $this->noisePatches = new NoiseGeneratorSimplex($this->random, 2);
+ $this->noisePatchesSmall = new NoiseGeneratorSimplex($this->random, 2);
+ $this->noiseBase = new NoiseGeneratorSimplex($this->random, 16);
+
+
+ $ores = new OrePopulator();
+ $ores->setOreTypes(array(
+ new OreType(new CoalOreBlock(), 20, 16, 0, 128),
+ new OreType(New IronOreBlock(), 20, 8, 0, 64),
+ new OreType(new RedstoneOreBlock(), 8, 7, 0, 16),
+ 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 DirtBlock(), 20, 32, 0, 128),
+ new OreType(new GravelBlock(), 10, 16, 0, 128),
+ ));
+ $this->populators[] = $ores;
+
+ $trees = new TreePopulator();
+ $trees->setBaseAmount(3);
+ $trees->setRandomAmount(0);
+ $this->populators[] = $trees;
+
+ $tallGrass = new TallGrassPopulator();
+ $tallGrass->setBaseAmount(5);
+ $tallGrass->setRandomAmount(0);
+ $this->populators[] = $tallGrass;
+ }
+
+ public function generateChunk($chunkX, $chunkZ){
+ $this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
+ $hills = array();
+ $patchesSmall = array();
+ $base = array();
+ for($z = 0; $z < 16; ++$z){
+ for($x = 0; $x < 16; ++$x){
+ $i = ($z << 4) + $x;
+ $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;
+ }
+ }
+ }
+
+ for($chunkY = 0; $chunkY < 8; ++$chunkY){
+ $chunk = "";
+ $startY = $chunkY << 4;
+ $endY = $startY + 16;
+ for($z = 0; $z < 16; ++$z){
+ for($x = 0; $x < 16; ++$x){
+ $i = ($z << 4) + $x;
+ $height = $this->worldHeight + $hills[$i] * 14 + $base[$i] * 7;
+ $height = (int) $height;
+
+ for($y = $startY; $y < $endY; ++$y){
+ $diff = $height - $y;
+ if($y <= 4 and ($y === 0 or $this->random->nextFloat() < 0.75)){
+ $chunk .= "\x07"; //bedrock
+ }elseif($diff > 2){
+ $chunk .= "\x01"; //stone
+ }elseif($diff > 0){
+ if($patches[$i] > 0.7){
+ $chunk .= "\x01"; //stone
+ }elseif($patches[$i] < -0.8){
+ $chunk .= "\x0d"; //gravel
+ }else{
+ $chunk .= "\x03"; //dirt
+ }
+ }elseif($y <= $this->waterHeight){
+ if(($this->waterHeight - $y) <= 1 and $diff === 0){
+ $chunk .= "\x0c"; //sand
+ }elseif($diff === 0){
+ if($patchesSmall[$i] > 0.3){
+ $chunk .= "\x0d"; //gravel
+ }elseif($patchesSmall[$i] < -0.45){
+ $chunk .= "\x0c"; //sand
+ }else{
+ $chunk .= "\x03"; //dirt
+ }
+ }else{
+ $chunk .= "\x09"; //still_water
+ }
+ }elseif($diff === 0){
+ if($patches[$i] > 0.7){
+ $chunk .= "\x01"; //stone
+ }elseif($patches[$i] < -0.8){
+ $chunk .= "\x0d"; //gravel
+ }else{
+ $chunk .= "\x02"; //grass
+ }
+ }else{
+ $chunk .= "\x00";
+ }
+ }
+ $chunk .= "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
+ }
+ }
+ $this->level->setMiniChunk($chunkX, $chunkZ, $chunkY, $chunk);
+ }
+
+ }
+
+ public function populateChunk($chunkX, $chunkZ){
+ $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());
+ $populator->populate($this->level, $chunkX, $chunkZ, $this->random);
+ }
+ }
+
+ public function getSpawn(){
+ return $this->level->getSafeSpawn(new Vector3(127.5, 128, 127.5));
+ }
+
+}
\ No newline at end of file
diff --git a/src/world/generator/NormalGenerator.php.bak b/src/world/generator/NormalGenerator.php.bak
new file mode 100644
index 00000000..d14d41c5
--- /dev/null
+++ b/src/world/generator/NormalGenerator.php.bak
@@ -0,0 +1,169 @@
+level = $level;
+ $this->random = $random;
+ $this->random->setSeed($this->level->getSeed());
+ $this->noiseHills = new NoiseGeneratorSimplex($this->random, 3);
+ $this->noisePatches = new NoiseGeneratorSimplex($this->random, 2);
+ $this->noisePatchesSmall = new NoiseGeneratorSimplex($this->random, 2);
+ $this->noiseBase = new NoiseGeneratorSimplex($this->random, 16);
+
+
+ $ores = new OrePopulator();
+ $ores->setOreTypes(array(
+ new OreType(new CoalOreBlock(), 20, 16, 0, 128),
+ new OreType(New IronOreBlock(), 20, 8, 0, 64),
+ new OreType(new RedstoneOreBlock(), 8, 7, 0, 16),
+ 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 DirtBlock(), 20, 32, 0, 128),
+ new OreType(new GravelBlock(), 10, 16, 0, 128),
+ ));
+ $this->populators[] = $ores;
+
+ $trees = new TreePopulator();
+ $trees->setBaseAmount(3);
+ $trees->setRandomAmount(0);
+ $this->populators[] = $trees;
+
+ $tallGrass = new TallGrassPopulator();
+ $tallGrass->setBaseAmount(5);
+ $tallGrass->setRandomAmount(0);
+ $this->populators[] = $tallGrass;
+ }
+
+ public function generateChunk($chunkX, $chunkZ){
+ $this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
+ $hills = array();
+ $patchesSmall = array();
+ $base = array();
+ for($z = 0; $z < 16; ++$z){
+ for($x = 0; $x < 16; ++$x){
+ $i = ($z << 4) + $x;
+ $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;
+ }
+ }
+ }
+
+ for($chunkY = 0; $chunkY < 8; ++$chunkY){
+ $chunk = "";
+ $startY = $chunkY << 4;
+ $endY = $startY + 16;
+ for($z = 0; $z < 16; ++$z){
+ for($x = 0; $x < 16; ++$x){
+ $i = ($z << 4) + $x;
+ $height = $this->worldHeight + $hills[$i] * 14 + $base[$i] * 7;
+ $height = (int) $height;
+
+ for($y = $startY; $y < $endY; ++$y){
+ $diff = $height - $y;
+ if($y <= 4 and ($y === 0 or $this->random->nextFloat() < 0.75)){
+ $chunk .= "\x07"; //bedrock
+ }elseif($diff > 2){
+ $chunk .= "\x01"; //stone
+ }elseif($diff > 0){
+ if($patches[$i] > 0.7){
+ $chunk .= "\x01"; //stone
+ }elseif($patches[$i] < -0.8){
+ $chunk .= "\x0d"; //gravel
+ }else{
+ $chunk .= "\x03"; //dirt
+ }
+ }elseif($y <= $this->waterHeight){
+ if(($this->waterHeight - $y) <= 1 and $diff === 0){
+ $chunk .= "\x0c"; //sand
+ }elseif($diff === 0){
+ if($patchesSmall[$i] > 0.3){
+ $chunk .= "\x0d"; //gravel
+ }elseif($patchesSmall[$i] < -0.45){
+ $chunk .= "\x0c"; //sand
+ }else{
+ $chunk .= "\x03"; //dirt
+ }
+ }else{
+ $chunk .= "\x09"; //still_water
+ }
+ }elseif($diff === 0){
+ if($patches[$i] > 0.7){
+ $chunk .= "\x01"; //stone
+ }elseif($patches[$i] < -0.8){
+ $chunk .= "\x0d"; //gravel
+ }else{
+ $chunk .= "\x02"; //grass
+ }
+ }else{
+ $chunk .= "\x00";
+ }
+ }
+ $chunk .= "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
+ }
+ }
+ $this->level->setMiniChunk($chunkX, $chunkZ, $chunkY, $chunk);
+ }
+
+ }
+
+ public function populateChunk($chunkX, $chunkZ){
+ $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());
+ $populator->populate($this->level, $chunkX, $chunkZ, $this->random);
+ }
+ }
+
+ public function getSpawn(){
+ return $this->level->getSafeSpawn(new Vector3(127.5, 128, 127.5));
+ }
+
+}
\ No newline at end of file
diff --git a/src/world/generator/SuperflatGenerator.php b/src/world/generator/SuperflatGenerator.php
index b7235694..d5787445 100644
--- a/src/world/generator/SuperflatGenerator.php
+++ b/src/world/generator/SuperflatGenerator.php
@@ -26,6 +26,10 @@ require_once("LevelGenerator.php");
class SuperflatGenerator implements LevelGenerator{
private $level, $random, $structure, $chunks, $options, $floorLevel, $populators = array();
+ public function getSettings(){
+ return $this->options;
+ }
+
public function __construct(array $options = array()){
$this->preset = "2;7,59x1,3x3,2;1;spawn(radius=10 block=89),decoration(treecount=80 grasscount=45)";
$this->options = $options;
@@ -125,9 +129,9 @@ class SuperflatGenerator implements LevelGenerator{
}
}
- public function populateChunk($chunkX, $chunkZ){
+ public function populateChunk($chunkX, $chunkZ){
+ $this->random->setSeed(0xdeadbeef ^ ($chunkX << 8) ^ $chunkZ ^ $this->level->getSeed());
foreach($this->populators as $populator){
- $this->random->setSeed((int) ($chunkX * 0xdead + $chunkZ * 0xbeef) ^ $this->level->getSeed());
$populator->populate($this->level, $chunkX, $chunkZ, $this->random);
}
}
diff --git a/src/world/generator/TemporalGenerator.php b/src/world/generator/TemporalGenerator.php
deleted file mode 100644
index d03fde3d..00000000
--- a/src/world/generator/TemporalGenerator.php
+++ /dev/null
@@ -1,95 +0,0 @@
-level = $level;
- $this->random = $random;
- $this->index = mt_rand(0, count(TemporalGenerator::$levels) - 1);
- $this->world = new PocketChunkParser();
- $this->world->loadRaw(gzinflate(gzinflate(base64_decode(TemporalGenerator::$levels[$this->index][4]))), "");
- $this->world->loadMap();
- $this->level->setSeed(TemporalGenerator::$levels[$this->index][0]);
- }
-
- public function generateChunk($chunkX, $chunkZ){
-
- }
-
- public function populateChunk($chunkX, $chunkZ){
-
- }
-
- public function populateLevel(){
- for($Z = 0; $Z < 16; ++$Z){
- for($X = 0; $X < 16; ++$X){
- $chunk = array(
- 0 => "",
- 1 => "",
- 2 => "",
- 3 => "",
- 4 => "",
- 5 => "",
- 6 => "",
- 7 => ""
- );
- for($z = 0; $z < 16; ++$z){
- for($x = 0; $x < 16; ++$x){
- $block = $this->world->getChunkColumn($X, $Z, $x, $z, 0);
- $meta = $this->world->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";
- }
- }
- }
- foreach($chunk as $Y => $data){
- $this->level->setMiniChunk($X, $Z, $Y, $data);
- }
- }
- console("[NOTICE] Importing level ".ceil(($Z + 1)/0.16)."%");
- }
- $this->level->save(true, true);
- $this->world->map = null;
- $this->world = null;
- }
-
- public function getSpawn(){
- return new Vector3(TemporalGenerator::$levels[$this->index][1], TemporalGenerator::$levels[$this->index][2], TemporalGenerator::$levels[$this->index][3]);
- }
-}
\ No newline at end of file
diff --git a/src/world/generator/WorldGenerator.php b/src/world/generator/WorldGenerator.php
index 4b79bf8f..b9b842d5 100644
--- a/src/world/generator/WorldGenerator.php
+++ b/src/world/generator/WorldGenerator.php
@@ -21,10 +21,9 @@
class WorldGenerator{
private $seed, $level, $path, $random, $generator, $width;
- public function __construct(LevelGenerator $generator, $name, $seed = false, $width = 16, $height = 8){
+ public function __construct(LevelGenerator $generator, $name, $seed = false, $height = 8){
$this->seed = $seed !== false ? (int) $seed:Utils::readInt(Utils::getRandomBytes(4, false));
$this->random = new Random($this->seed);
- $this->width = (int) $width;
$this->height = (int) $height;
$this->path = DATA_PATH."worlds/".$name."/";
$this->generator = $generator;
@@ -35,9 +34,10 @@ class WorldGenerator{
"spawnX" => 128,
"spawnY" => 128,
"spawnZ" => 128,
- "extra" => "",
- "width" => $this->width,
- "height" => $this->height
+ "height" => $this->height,
+ "generator" => get_class($this->generator),
+ "generatorSettings" => $this->generator->getSettings(),
+ "extra" => ""
));
$entities = new Config($this->path."entities.yml", CONFIG_YAML);
$tiles = new Config($this->path."tiles.yml", CONFIG_YAML);
@@ -47,23 +47,15 @@ class WorldGenerator{
public function generate(){
$this->generator->init($this->level, $this->random);
- for($Z = 0; $Z < $this->width; ++$Z){
- for($X = 0; $X < $this->width; ++$X){
- $this->generator->generateChunk($X, $Z);
+
+ //Generate 4 chunks for spawning players
+ for($Z = 7; $Z <= 8; ++$Z){
+ for($X = 7; $X <= 8; ++$X){
+ $this->level->level->loadChunk($X, $Z);
}
- console("[NOTICE] Generating level ".ceil((($Z + 1)/$this->width) * 100)."%");
- }
- console("[NOTICE] Populating level");
- $this->generator->populateLevel();
- for($Z = 0; $Z < $this->width; ++$Z){
- for($X = 0; $X < $this->width; ++$X){
- $this->generator->populateChunk($X, $Z);
- }
- console("[NOTICE] Populating level ".ceil((($Z + 1)/$this->width) * 100)."%");
}
$this->level->setSpawn($this->generator->getSpawn());
- $this->level->save(true, true);
}
public function close(){
diff --git a/src/world/generator/noise/NoiseGenerator.php b/src/world/generator/noise/NoiseGenerator.php
index b6d24472..ca0b655a 100644
--- a/src/world/generator/noise/NoiseGenerator.php
+++ b/src/world/generator/noise/NoiseGenerator.php
@@ -19,6 +19,78 @@
*
*/
+
abstract class NoiseGenerator{
+ protected $perm = array();
+ protected $offsetX = 0;
+ protected $offsetY = 0;
+ protected $offsetZ = 0;
+ protected $octaves = 8;
+ public static function floor($x){
+ return $x >= 0 ? (int) $x : (int) ($x - 1);
+ }
+
+ public static function fade($x){
+ return $x * $x * $x * ($x * ($x * 6 - 15) + 10);
+ }
+
+ public static function lerp($x, $y, $z){
+ return $y + $x * ($z - $y);
+ }
+
+ public static function grad($hash, $x, $y, $z){
+ $hash &= 15;
+ $u = $hash < 8 ? $x : $y;
+ $v = $hash < 4 ? $y : (($hash === 12 or $hash === 14) ? $x : $z);
+ return (($hash & 1) === 0 ? $u : -$u) + (($hash & 2) === 0 ? $v : -$v);
+ }
+
+ abstract public function getNoise2D($x, $z);
+
+ abstract public function getNoise3D($x, $y, $z);
+
+ public function noise2D($x, $z, $frequency, $amplitude, $normalized = false){
+ $result = 0;
+ $amp = 1;
+ $freq = 1;
+ $max = 0;
+
+ for($i = 0; $i < $this->octaves; ++$i){
+ $result += $this->getNoise2D($x * $freq, $z * $freq) * $amp;
+ $max += $amp;
+ $freq *= $frequency;
+ $amp *= $amplitude;
+ }
+ if($normalized === true){
+ $result /= $max;
+ }
+
+ return $result;
+ }
+
+ public function noise3D($x, $y, $z, $frequency, $amplitude, $normalized = false){
+ $result = 0;
+ $amp = 1;
+ $freq = 1;
+ $max = 0;
+
+ for($i = 0; $i < $this->octaves; ++$i){
+ $result += $this->getNoise3D($x * $freq, $y * $freq, $z * $freq) * $amp;
+ $max += $amp;
+ $freq *= $frequency;
+ $amp *= $amplitude;
+ }
+ if($normalized === true){
+ $result /= $max;
+ }
+
+ return $result;
+ }
+
+ public function setOffset($x, $y, $z){
+ $this->offsetX = $x;
+ $this->offsetY = $y;
+ $this->offsetZ = $z;
+ }
}
\ No newline at end of file
diff --git a/src/world/generator/noise/NoiseGeneratorOctaves.php b/src/world/generator/noise/NoiseGeneratorOctaves.php
index ac566143..a5e857c6 100644
--- a/src/world/generator/noise/NoiseGeneratorOctaves.php
+++ b/src/world/generator/noise/NoiseGeneratorOctaves.php
@@ -23,7 +23,7 @@
require_once("NoiseGenerator.php");
/***REM_END***/
-class NoiseGeneratorOctaves extends NoiseGenerator{
+abstract class NoiseGeneratorOctaves extends NoiseGenerator{
public $octaves;
private $generatorCollection;
public function __construct(Random $random, $octaves){
@@ -65,4 +65,4 @@ class NoiseGeneratorOctaves extends NoiseGenerator{
}
return $floats;
}
-}
\ No newline at end of file
+}
diff --git a/src/world/generator/noise/NoiseGeneratorPerlin.php b/src/world/generator/noise/NoiseGeneratorPerlin.php
index 079bda1f..8fcf6a34 100644
--- a/src/world/generator/noise/NoiseGeneratorPerlin.php
+++ b/src/world/generator/noise/NoiseGeneratorPerlin.php
@@ -24,146 +24,79 @@ require_once("NoiseGenerator.php");
/***REM_END***/
class NoiseGeneratorPerlin extends NoiseGenerator{
- private $permutations = array();
- public $xCoord, $yCoord, $zCoord;
+ public static $grad3 = [
+ [1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0],
+ [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1],
+ [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1]
+ ];
- public function __construct($random = false){
- if(!($random instanceof Random)){
- $random = new Random();
- }
- $this->xCoord = $random->nextFloat() * 256;
- $this->yCoord = $random->nextFloat() * 256;
- $this->zCoord = $random->nextFloat() * 256;
+
+ public function __construct(Random $random, $octaves){
+ $this->octaves = $octaves;
+ $this->offsetX = $random->nextFloat() * 256;
+ $this->offsetY = $random->nextFloat() * 256;
+ $this->offsetZ = $random->nextFloat() * 256;
for($i = 0; $i < 512; ++$i){
- $this->permutations[$i] = 0;
- }
- for($i = 0; $i < 256; ++$i){
- $this->permutations[$i] = $i;
+ $this->perm[$i] = 0;
}
for($i = 0; $i < 256; ++$i){
- $j = $random->nextRange(0, 256 - $i) + $i;
- $k = $this->permutations[$i];
- $this->permutations[$i] = $this->permutations[$j];
- $this->permutations[$j] = $k;
- $this->permutations[$i + 256] = $this->permutations[$i];
- }
-
- }
-
- public final function curve($par1, $par2, $par3){
- return $par2 + $par1 * ($par3 - $par2);
- }
-
- public function grad2D($int, $par1, $par2){
- $i = $int & 0x0F;
- $d1 = (1 - (($i & 0x08) >> 3)) * $par1;
- $d2 = ($i === 12 or $i === 14) ? $par1:($i < 4 ? 0:$par2);
-
- return (($i & 0x01) === 0 ? $d1:-$d1) + (($i & 0x02) === 0 ? $d2:-$d2);
- }
-
- public function grad3D($int, $par1, $par2, $par3){
- $i = $int & 0x0F;
- $d1 = $i < 8 ? $par1 : $par2;
- $d2 = ($i === 12 or $i === 14) ? $par1:($i < 4 ? $par2:$par3);
-
- return (($i & 0x01) === 0 ? $d1:-$d1) + (($i & 0x02) === 0 ? $d2:-$d2);
- }
-
- public function populateNoiseArray(&$floats, $par1, $par2, $par3, $int1, $int2, $int3, $par4, $par5, $par6, $par7){
- if($int2 === 1){
- $n = 0;
- $d3 = 1 / $par7;
- for($i1 = 0; $i1 < $int1; ++$i1){
- $d4 = $par1 + $i1 * $par4 + $this->xCoord;
- $i2 = (int) $d4;
- if($d4 < $i2){
- --$i2;
- }
- $i3 = $i2 & 0xFF;
- $d4 -= $i2;
- $d5 = $d4 * $d4 * $d4 * ($d4 * ($d4 * 6 - 15) + 10);
-
- for($i4 = 0; $i4 < $int3; ++$i4){
- $d6 = $par3 + $i4 * $par6 + $this->zCoord;
- $i5 = (int) $d6;
- if($d6 < $i5){
- --$i5;
- }
- $i6 = $i5 & 0xFF;
- $d6 -= $i5;
- $d7 = $d6 * $d6 * $d6 * ($d6 * ($d6 * 6 - 15) + 10);
-
- $i = $this->permutations[$i3];
- $j = $this->permutations[$i] + $i6;
- $k = $this->permutations[$i3 + 1];
- $m = $this->permutations[$k] + $i6;
- $d1 = $this->curve($d5, $this->grad2D($this->permutations[$j], $d4, $d6), $this->grad3D($this->permutations[$m], $d4 - 1, 0, $d6));
- $d2 = $this->curve($d5, $this->grad3D($this->permutations[$j + 1], $d4, 0, $d6 - 1), $this->grad3D($this->permutations[$m + 1], $d4 - 1, 0, $d6 - 1));
-
- $d8 = $this->curve($d7, $d1, $d2);
- $floats[$n++] += $d8 * $d3;
- }
- }
- return;
+ $this->perm[$i] = $random->nextRange(0, 255);
}
- $d9 = 1 / $par7;
- $m = -1;
- $n = 0;
- $i = 0;
-
- for($i4 = 0; $i4 < $int1; ++$i4){
- $d6 = $par1 + $i4 * $par4 + $this->xCoord;
- $i5 = (int) $d6;
- if($d6 < $i5){
- --$i5;
- }
- $i6 = $i5 & 0xFF;
- $d6 -= $i5;
- $d7 = $d6 * $d6 * $d6 * ($d6 * ($d6 * 6 - 15) + 10);
+ for($i = 0; $i < 256; ++$i){
+ $pos = $random->nextRange(0, 255 - $i) + $i;
+ $old = $this->perm[$i];
- for($i12 = 0; $i12 < $int3; ++$i12){
- $d12 = $par3 + $i12 * $par6 + $this->zCoord;
- $i13 = (int) $d12;
- if($d12 < $i13){
- --$i13;
- }
- $i14 = $i13 & 0xFF;
- $d12 -= $i13;
- $d13 = $d12 * $d12 * $d12 * ($d12 * ($d12 * 6 - 15) + 10);
-
- for($i15 = 0; $i15 < $int2; ++$i15){
- $d14 = $par2 + $i15 * $par5 + $this->yCoord;
- $i16 = (int) $d14;
- if($d14 < $i16){
- --$i16;
- }
- $d14 -= $i16;
- $d15 = $d14 * $d14 * $d14 * ($d14 * ($d14 * 6 - 15) + 10);
-
- if($i15 === 0 or $i17 !== $m){
- $m = $i17;
- $i7 = $this->permutations[$i6] + $i17;
- $i8 = $this->permutations[$i7] + $i14;
- $i9 = $this->permutations[$i7 + 1] + $i14;
- $i10 = $this->permutations[$i6 + 1] + $i17;
- $n = $this->permutations[$i10] + $i14;
- $i11 = $this->permutations[$i10 + 1] + $i14;
- $d10 = $this->curve($d7, $this->grad3D($this->permutations[$i8], $d6, $d14, $d12), $this->grad3D($this->permutations[$n], $d6 - 1, $d14, $d12));
- $d4 = $this->curve($d7, $this->grad3D($this->permutations[$i9], $d6, $d14 - 1, $d12), $this->grad3D($this->permutations[$i11], $d6 - 1, $d14 - 1, $d12));
- $d11 = $this->curve($d7, $this->grad3D($this->permutations[$i8 + 1], $d6, $d14, $d12 - 1), $this->grad3D($this->permutations[$n + 1], $d6 - 1, $d14, $d12 - 1));
- $d5 = $this->curve($d7, $this->grad3D($this->permutations[$i9 + 1], $d6, $d14 - 1, $d12 - 1), $this->grad3D($this->permutations[$i11 + 1], $d6 - 1, $d14 - 1, $d12 - 1));
- }
-
- $d16 = $this->curve($d15, $d10, $d4);
- $d17 = $this->curve($d15, $d11, $d5);
- $d18 = $this->curve($d13, $d16, $d17);
- $floats[$i++] += $d18 * $d9;
- }
- }
+ $this->perm[$i] = $this->perm[$pos];
+ $this->perm[$pos] = $old;
+ $this->perm[$i + 256] = $this->perm[$i];
}
+
+ }
+
+ public function getNoise3D($x, $y, $z){
+ $x += $this->offsetX;
+ $y += $this->offsetY;
+ $z += $this->offsetZ;
+
+ $floorX = self::floor($x);
+ $floorY = self::floor($y);
+ $floorZ = self::floor($z);
+
+ $X = $floorX & 0xFF;
+ $Y = $floorY & 0xFF;
+ $Z = $floorZ & 0xFF;
+
+ $x -= $floorX;
+ $y -= $floorY;
+ $z -= $floorZ;
+
+ //Fade curves
+ $fX = self::fade($x);
+ $fY = self::fade($y);
+ $fZ = self::fade($z);
+
+ //Cube corners
+ $A = $this->perm[$X] + $Y;
+ $AA = $this->perm[$A] + $Z;
+ $AB = $this->perm[$A + 1] + $Z;
+ $B = $this->perm[$X + 1] + $Y;
+ $BA = $this->perm[$B] + $Z;
+ $BB = $this->perm[$B + 1] + $Z;
+
+ return self::lerp($fZ, self::lerp($fY, self::lerp($fX, self::grad($this->perm[$AA], $x, $y, $z),
+ self::grad($this->perm[$BA], $x - 1, $y, $z)),
+ self::lerp($fX, self::grad($this->perm[$AB], $x, $y - 1, $z),
+ self::grad($this->perm[$BB], $x - 1, $y - 1, $z))),
+ self::lerp($fY, self::lerp($fX, self::grad($this->perm[$AA + 1], $x, $y, $z - 1),
+ self::grad($this->perm[$BA + 1], $x - 1, $y, $z - 1)),
+ self::lerp($fX, self::grad($this->perm[$AB + 1], $x, $y - 1, $z - 1),
+ self::grad($this->perm[$BB + 1], $x - 1, $y - 1, $z - 1))));
+ }
+
+ public function getNoise2D($x, $y){
+ return $this->getNoise3D($x, $y, 0);
}
}
\ No newline at end of file
diff --git a/src/world/generator/noise/NoiseGeneratorSimplex.php b/src/world/generator/noise/NoiseGeneratorSimplex.php
new file mode 100644
index 00000000..2989ba71
--- /dev/null
+++ b/src/world/generator/noise/NoiseGeneratorSimplex.php
@@ -0,0 +1,438 @@
+
+ * This is a modified version of the freely published version in the paper by
+ * Stefan Gustavson at
+ *
+ * http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
+ */
+class NoiseGeneratorSimplex extends NoiseGeneratorPerlin{
+ protected static $SQRT_3;
+ protected static $SQRT_5;
+ protected static $F2;
+ protected static $G2;
+ protected static $G22;
+ protected static $F3;
+ protected static $G3;
+ protected static $F4;
+ protected static $G4;
+ protected static $G42;
+ protected static $G43;
+ protected static $G44;
+ protected static $grad4 = [[0, 1, 1, 1],[0, 1, 1, -1],[0, 1, -1, 1],[0, 1, -1, -1],
+ [0, -1, 1, 1],[0, -1, 1, -1],[0, -1, -1, 1],[0, -1, -1, -1],
+ [1, 0, 1, 1],[1, 0, 1, -1],[1, 0, -1, 1],[1, 0, -1, -1],
+ [-1, 0, 1, 1],[-1, 0, 1, -1],[-1, 0, -1, 1],[-1, 0, -1, -1],
+ [1, 1, 0, 1],[1, 1, 0, -1],[1, -1, 0, 1],[1, -1, 0, -1],
+ [-1, 1, 0, 1],[-1, 1, 0, -1],[-1, -1, 0, 1],[-1, -1, 0, -1],
+ [1, 1, 1, 0],[1, 1, -1, 0],[1, -1, 1, 0],[1, -1, -1, 0],
+ [-1, 1, 1, 0],[-1, 1, -1, 0],[-1, -1, 1, 0],[-1, -1, -1, 0]];
+ protected static $simplex = [
+ [0, 1, 2, 3],[0, 1, 3, 2],[0, 0, 0, 0],[0, 2, 3, 1],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[1, 2, 3, 0],
+ [0, 2, 1, 3],[0, 0, 0, 0],[0, 3, 1, 2],[0, 3, 2, 1],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[1, 3, 2, 0],
+ [0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],
+ [1, 2, 0, 3],[0, 0, 0, 0],[1, 3, 0, 2],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[2, 3, 0, 1],[2, 3, 1, 0],
+ [1, 0, 2, 3],[1, 0, 3, 2],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[2, 0, 3, 1],[0, 0, 0, 0],[2, 1, 3, 0],
+ [0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],
+ [2, 0, 1, 3],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[3, 0, 1, 2],[3, 0, 2, 1],[0, 0, 0, 0],[3, 1, 2, 0],
+ [2, 1, 0, 3],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[3, 1, 0, 2],[0, 0, 0, 0],[3, 2, 0, 1],[3, 2, 1, 0]];
+ protected $offsetW;
+
+ public function __construct(Random $random, $octaves){
+ parent::__construct($random, $octaves);
+ $this->offsetW = $random->nextFloat() * 256;
+ self::$SQRT_3 = sqrt(3);
+ self::$SQRT_5 = sqrt(5);
+ self::$F2 = 0.5 * (self::$SQRT_3 - 1);
+ self::$G2 = (3 - self::$SQRT_3) / 6;
+ self::$G22 = self::$G2 * 2.0 - 1;
+ self::$F3 = 1.0 / 3.0;
+ self::$G3 = 1.0 / 6.0;
+ self::$F4 = (self::$SQRT_5 - 1.0) / 4.0;
+ self::$G4 = (5.0 - self::$SQRT_5) / 20.0;
+ self::$G42 = self::$G4 * 2.0;
+ self::$G43 = self::$G4 * 3.0;
+ self::$G44 = self::$G4 * 4.0 - 1.0;
+ }
+
+ protected static function dot2D($g, $x, $y){
+ return $g[0] * $x + $g[1] * $y;
+ }
+
+ protected static function dot3D($g, $x, $y, $z){
+ return $g[0] * $x + $g[1] * $y + $g[2] * $z;
+ }
+
+ protected static function dot4D($g, $x, $y, $z, $w){
+ return $g[0] * $x + $g[1] * $y + $g[2] * $z + $g[3] * $w;
+ }
+
+ public function getNoise3D($x, $y, $z){
+ $x += $this->offsetX;
+ $y += $this->offsetY;
+ $z += $this->offsetZ;
+
+ // Skew the input space to determine which simplex cell we're in
+ $s = ($x + $y + $z) * self::$F3; // Very nice and simple skew factor for 3D
+ $i = self::floor($x + $s);
+ $j = self::floor($y + $s);
+ $k = self::floor($z + $s);
+ $t = ($i + $j + $k) * self::$G3;
+ $X0 = $i - $t; // Unskew the cell origin back to (x,y,z) space
+ $Y0 = $j - $t;
+ $Z0 = $k - $t;
+ $x0 = $x - $X0; // The x,y,z distances from the cell origin
+ $y0 = $y - $Y0;
+ $z0 = $z - $Z0;
+
+ // For the 3D case, the simplex shape is a slightly irregular tetrahedron.
+
+ // Determine which simplex we are in.
+ if($x0 >= $y0){
+ if($y0 >= $z0){
+ $i1 = 1;
+ $j1 = 0;
+ $k1 = 0;
+ $i2 = 1;
+ $j2 = 1;
+ $k2 = 0;
+ }// X Y Z order
+ elseif($x0 >= $z0){
+ $i1 = 1;
+ $j1 = 0;
+ $k1 = 0;
+ $i2 = 1;
+ $j2 = 0;
+ $k2 = 1;
+ }// X Z Y order
+ else{
+ $i1 = 0;
+ $j1 = 0;
+ $k1 = 1;
+ $i2 = 1;
+ $j2 = 0;
+ $k2 = 1;
+ }// Z X Y order
+ }else{ // x0perm[$ii + $this->perm[$jj + $this->perm[$kk]]] % 12;
+ $gi1 = $this->perm[$ii + $i1 + $this->perm[$jj + $j1 + $this->perm[$kk + $k1]]] % 12;
+ $gi2 = $this->perm[$ii + $i2 + $this->perm[$jj + $j2 + $this->perm[$kk + $k2]]] % 12;
+ $gi3 = $this->perm[$ii + 1 + $this->perm[$jj + 1 + $this->perm[$kk + 1]]] % 12;
+
+ // Calculate the contribution from the four corners
+ $t0 = 0.6 - $x0 * $x0 - $y0 * $y0 - $z0 * $z0;
+ if($t0 < 0){
+ $n0 = 0.0;
+ }else{
+ $t0 *= $t0;
+ $n0 = $t0 * $t0 * self::dot3D(self::$grad3[$gi0], $x0, $y0, $z0);
+ }
+
+ $t1 = 0.6 - $x1 * $x1 - $y1 * $y1 - $z1 * $z1;
+ if($t1 < 0){
+ $n1 = 0.0;
+ }else{
+ $t1 *= $t1;
+ $n1 = $t1 * $t1 * self::dot3D(self::$grad3[$gi1], $x1, $y1, $z1);
+ }
+
+ $t2 = 0.6 - $x2 * $x2 - $y2 * $y2 - $z2 * $z2;
+ if($t2 < 0){
+ $n2 = 0.0;
+ }else{
+ $t2 *= $t2;
+ $n2 = $t2 * $t2 * self::dot3D(self::$grad3[$gi2], $x2, $y2, $z2);
+ }
+
+ $t3 = 0.6 - $x3 * $x3 - $y3 * $y3 - $z3 * $z3;
+ if($t3 < 0){
+ $n3 = 0.0;
+ }else{
+ $t3 *= $t3;
+ $n3 = $t3 * $t3 * self::dot3D(self::$grad3[$gi3], $x3, $y3, $z3);
+ }
+
+ // Add contributions from each corner to get the noise value.
+ // The result is scaled to stay just inside [-1,1]
+ return 32.0 * ($n0 + $n1 + $n2 + $n3);
+ }
+
+ public function getNoise2D($x, $y){
+ $x += $this->offsetX;
+ $y += $this->offsetY;
+
+ // Skew the input space to determine which simplex cell we're in
+ $s = ($x + $y) * self::$F2; // Hairy factor for 2D
+ $i = self::floor($x + $s);
+ $j = self::floor($y + $s);
+ $t = ($i + $j) * self::$G2;
+ $X0 = $i - $t; // Unskew the cell origin back to (x,y) space
+ $Y0 = $j - $t;
+ $x0 = $x - $X0; // The x,y distances from the cell origin
+ $y0 = $y - $Y0;
+
+ // For the 2D case, the simplex shape is an equilateral triangle.
+
+ // Determine which simplex we are in.
+ if($x0 > $y0){
+ $i1 = 1;
+ $j1 = 0;
+ }// lower triangle, XY order: (0,0)->(1,0)->(1,1)
+ else{
+ $i1 = 0;
+ $j1 = 1;
+ }// upper triangle, YX order: (0,0)->(0,1)->(1,1)
+
+ // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
+ // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
+ // c = (3-sqrt(3))/6
+
+ $x1 = $x0 - $i1 + self::$G2; // Offsets for middle corner in (x,y) unskewed coords
+ $y1 = $y0 - $j1 + self::$G2;
+ $x2 = $x0 + self::$G22; // Offsets for last corner in (x,y) unskewed coords
+ $y2 = $y0 + self::$G22;
+
+ // Work out the hashed gradient indices of the three simplex corners
+ $ii = $i & 255;
+ $jj = $j & 255;
+ $gi0 = $this->perm[$ii + $this->perm[$jj]] % 12;
+ $gi1 = $this->perm[$ii + $i1 + $this->perm[$jj + $j1]] % 12;
+ $gi2 = $this->perm[$ii + 1 + $this->perm[$jj + 1]] % 12;
+
+ // Calculate the contribution from the three corners
+ $t0 = 0.5 - $x0 * $x0 - $y0 * $y0;
+ if($t0 < 0){
+ $n0 = 0.0;
+ }else{
+ $t0 *= $t0;
+ $n0 = $t0 * $t0 * self::dot2D(self::$grad3[$gi0], $x0, $y0); // (x,y) of grad3 used for 2D gradient
+ }
+
+ $t1 = 0.5 - $x1 * $x1 - $y1 * $y1;
+ if($t1 < 0){
+ $n1 = 0.0;
+ }else{
+ $t1 *= $t1;
+ $n1 = $t1 * $t1 * self::dot2D(self::$grad3[$gi1], $x1, $y1);
+ }
+
+ $t2 = 0.5 - $x2 * $x2 - $y2 * $y2;
+ if($t2 < 0){
+ $n2 = 0.0;
+ }else{
+ $t2 *= $t2;
+ $n2 = $t2 * $t2 * self::dot2D(self::$grad3[$gi2], $x2, $y2);
+ }
+
+ // Add contributions from each corner to get the noise value.
+ // The result is scaled to return values in the interval [-1,1].
+ return 70.0 * ($n0 + $n1 + $n2);
+ }
+
+ /**
+ * Computes and returns the 4D simplex noise for the given coordinates in
+ * 4D space
+ *
+ * @param x X coordinate
+ * @param y Y coordinate
+ * @param z Z coordinate
+ * @param w W coordinate
+ * @return Noise at given location, from range -1 to 1
+ */
+ /*public function getNoise4D(x, y, z, w){
+ x += offsetX;
+ y += offsetY;
+ z += offsetZ;
+ w += offsetW;
+
+ n0, n1, n2, n3, n4; // Noise contributions from the five corners
+
+ // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
+ s = (x + y + z + w) * self::$F4; // Factor for 4D skewing
+ i = floor(x + s);
+ j = floor(y + s);
+ k = floor(z + s);
+ l = floor(w + s);
+
+ t = (i + j + k + l) * self::$G4; // Factor for 4D unskewing
+ X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
+ Y0 = j - t;
+ Z0 = k - t;
+ W0 = l - t;
+ x0 = x - X0; // The x,y,z,w distances from the cell origin
+ y0 = y - Y0;
+ z0 = z - Z0;
+ w0 = w - W0;
+
+ // For the 4D case, the simplex is a 4D shape I won't even try to describe.
+ // To find out which of the 24 possible simplices we're in, we need to
+ // determine the magnitude ordering of x0, y0, z0 and w0.
+ // The method below is a good way of finding the ordering of x,y,z,w and
+ // then find the correct traversal order for the simplex we’re in.
+ // First, six pair-wise comparisons are performed between each possible pair
+ // of the four coordinates, and the results are used to add up binary bits
+ // for an integer index.
+ c1 = (x0 > y0) ? 32 : 0;
+ c2 = (x0 > z0) ? 16 : 0;
+ c3 = (y0 > z0) ? 8 : 0;
+ c4 = (x0 > w0) ? 4 : 0;
+ c5 = (y0 > w0) ? 2 : 0;
+ c6 = (z0 > w0) ? 1 : 0;
+ c = c1 + c2 + c3 + c4 + c5 + c6;
+ i1, j1, k1, l1; // The integer offsets for the second simplex corner
+ i2, j2, k2, l2; // The integer offsets for the third simplex corner
+ i3, j3, k3, l3; // The integer offsets for the fourth simplex corner
+
+ // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
+ // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0;
+ j1 = simplex[c][1] >= 3 ? 1 : 0;
+ k1 = simplex[c][2] >= 3 ? 1 : 0;
+ l1 = simplex[c][3] >= 3 ? 1 : 0;
+
+ // The number 2 in the "simplex" array is at the second largest coordinate.
+ i2 = simplex[c][0] >= 2 ? 1 : 0;
+ j2 = simplex[c][1] >= 2 ? 1 : 0;
+ k2 = simplex[c][2] >= 2 ? 1 : 0;
+ l2 = simplex[c][3] >= 2 ? 1 : 0;
+
+ // The number 1 in the "simplex" array is at the second smallest coordinate.
+ i3 = simplex[c][0] >= 1 ? 1 : 0;
+ j3 = simplex[c][1] >= 1 ? 1 : 0;
+ k3 = simplex[c][2] >= 1 ? 1 : 0;
+ l3 = simplex[c][3] >= 1 ? 1 : 0;
+
+ // The fifth corner has all coordinate offsets = 1, so no need to look that up.
+
+ x1 = x0 - i1 + self::$G4; // Offsets for second corner in (x,y,z,w) coords
+ y1 = y0 - j1 + self::$G4;
+ z1 = z0 - k1 + self::$G4;
+ w1 = w0 - l1 + self::$G4;
+
+ x2 = x0 - i2 + self::$G42; // Offsets for third corner in (x,y,z,w) coords
+ y2 = y0 - j2 + self::$G42;
+ z2 = z0 - k2 + self::$G42;
+ w2 = w0 - l2 + self::$G42;
+
+ x3 = x0 - i3 + self::$G43; // Offsets for fourth corner in (x,y,z,w) coords
+ y3 = y0 - j3 + self::$G43;
+ z3 = z0 - k3 + self::$G43;
+ w3 = w0 - l3 + self::$G43;
+
+ x4 = x0 + self::$G44; // Offsets for last corner in (x,y,z,w) coords
+ y4 = y0 + self::$G44;
+ z4 = z0 + self::$G44;
+ w4 = w0 + self::$G44;
+
+ // Work out the hashed gradient indices of the five simplex corners
+ ii = i & 255;
+ jj = j & 255;
+ kk = k & 255;
+ ll = l & 255;
+
+ gi0 = $this->perm[ii + $this->perm[jj + $this->perm[kk + $this->perm[ll]]]] % 32;
+ gi1 = $this->perm[ii + i1 + $this->perm[jj + j1 + $this->perm[kk + k1 + $this->perm[ll + l1]]]] % 32;
+ gi2 = $this->perm[ii + i2 + $this->perm[jj + j2 + $this->perm[kk + k2 + $this->perm[ll + l2]]]] % 32;
+ gi3 = $this->perm[ii + i3 + $this->perm[jj + j3 + $this->perm[kk + k3 + $this->perm[ll + l3]]]] % 32;
+ gi4 = $this->perm[ii + 1 + $this->perm[jj + 1 + $this->perm[kk + 1 + $this->perm[ll + 1]]]] % 32;
+
+ // Calculate the contribution from the five corners
+ t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
+ if(t0 < 0){
+ n0 = 0.0;
+ }else{
+ t0 *= t0;
+ n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0);
+ }
+
+ t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
+ if(t1 < 0){
+ n1 = 0.0;
+ }else{
+ t1 *= t1;
+ n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1);
+ }
+
+ t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
+ if(t2 < 0){
+ n2 = 0.0;
+ }else{
+ t2 *= t2;
+ n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2);
+ }
+
+ t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
+ if(t3 < 0){
+ n3 = 0.0;
+ }else{
+ t3 *= t3;
+ n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3);
+ }
+
+ t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
+ if(t4 < 0){
+ n4 = 0.0;
+ }else{
+ t4 *= t4;
+ n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4);
+ }
+
+ // Sum up and scale the result to cover the range [-1,1]
+ return 27.0 * (n0 + n1 + n2 + n3 + n4);
+ }*/
+}
\ No newline at end of file
diff --git a/src/world/generator/noise/OctaveGenerator.php b/src/world/generator/noise/OctaveGenerator.php
new file mode 100644
index 00000000..962801be
--- /dev/null
+++ b/src/world/generator/noise/OctaveGenerator.php
@@ -0,0 +1,108 @@
+octaves = $octaves;
+ }
+
+ public function setScale($scale){
+ $this->setXScale($scale);
+ $this->setYScale($scale);
+ $this->setZScale($scale);
+ }
+
+ public function getXScale(){
+ return $this->xScale;
+ }
+
+ public function setXScale($scale){
+ $this->xScale = $scale;
+ }
+
+ public function getYScale(){
+ return $this->yScale;
+ }
+
+ public function setYScale($scale){
+ $this->yScale = $scale;
+ }
+
+ public function getZScale(){
+ return $this->zScale;
+ }
+
+ public function setZScale($scale){
+ $this->zScale = $scale;
+ }
+
+ public function getOctaves(){
+ $array = array();
+ foreach($this->octaves as $index => $value){
+ $array[$index] = clone $value;
+ }
+ return $array;
+ }
+
+ //1D-noise
+ public function noise1D($x, $frequency, $amplitude, $normalized = false){
+ return $this->noise3D($x, 0, 0, $frequency, $amplitude, $normalized);
+ }
+
+ //2D-noise
+ public function noise2D($x, $y, $frequency, $amplitude, $normalized = false){
+ return $this->noise3D($x, $y, 0, $frequency, $amplitude, $normalized);
+ }
+
+ //3D-noise
+ public function noise3D($x, $y, $z, $frequency, $amplitude, $normalized = false){
+ $result = 0;
+ $amp = 1;
+ $freq = 1;
+ $max = 0;
+
+ $x *= $this->xScale;
+ $y *= $this->yScale;
+ $z *= $this->zScale;
+
+ foreach($this->octaves as $noiseGenerator){
+ $result += $octave->noise($x * $freq, $y * $freq, $z * $freq) * $amp;
+ $max += $amp;
+ $freq *= $frequency;
+ $amp *= $amplitude;
+ }
+ if($normalized === true){
+ $result /= $max;
+ }
+
+ return $result;
+ }
+
+ /*public function generateNoiseOctaves($x, $y, $z, $frequency, $amplitude){
+
+ }*/
+}
\ No newline at end of file
diff --git a/src/world/generator/noise/PerlinOctaveGenerator.php b/src/world/generator/noise/PerlinOctaveGenerator.php
new file mode 100644
index 00000000..53a79884
--- /dev/null
+++ b/src/world/generator/noise/PerlinOctaveGenerator.php
@@ -0,0 +1,63 @@
+octaves = array();
+ for($o = 0; $o < $octaves; ++$o){
+ $this->octaves[$o] = new NoiseGeneratorPerlin($random);
+ }
+ }
+
+ /*public function generateNoiseOctaves($x, $y, $z, $sizeX, $sizeY, $sizeZ, $fX, $fY, $fZ){
+ $adouble = array_fill(0, $sizeX * $sizeY * $sizeZ, 0.0);
+
+ $d3 = 1.0;
+
+ foreach($this->octaves as $octave){
+ $dX = $x * $d3 * $fX;
+ $dY = $y * $d3 * $fY;
+ $dZ = $x * $d3 * $fZ;
+
+ $x1 = NoiseGenerator::floor($dX);
+ $z1 = NoiseGenerator::floor($dZ);
+
+ $dX -= $x1;
+ $dZ -= $z1;
+
+ $x1 %= 16777216;
+ $z1 %= 16777216;
+ //$x1 &= 0xFFFFFF;
+ //$z1 &= 0xFFFFFF;
+
+ $dX += $x1;
+ $dZ += $z1;
+ $octave->populateNoiseArray($adouble, $dX, $dY, $dZ, $sizeX, $sizeY, $sizeZ, $fX * $d3, $fY * $d3, $fZ * $d3, $d3);
+ $d3 *= 0.5;
+ }
+
+ return $adouble;
+ }*/
+}
\ No newline at end of file
diff --git a/src/world/generator/object/grass/TallGrassObject.php b/src/world/generator/object/grass/TallGrassObject.php
index 18053fd6..32a0f45f 100644
--- a/src/world/generator/object/grass/TallGrassObject.php
+++ b/src/world/generator/object/grass/TallGrassObject.php
@@ -23,11 +23,11 @@
class TallGrassObject{
public static function growGrass(Level $level, Vector3 $pos, Random $random, $count = 15, $radius = 10){
$arr = array(
- BlockAPI::get(DANDELION, 0),
- BlockAPI::get(CYAN_FLOWER, 0),
- BlockAPI::get(TALL_GRASS, 1),
+ BlockAPI::get(37, 0),
+ BlockAPI::get(38, 0),
BlockAPI::get(TALL_GRASS, 1),
BlockAPI::get(TALL_GRASS, 2),
+ BlockAPI::get(TALL_GRASS, 1),
BlockAPI::get(TALL_GRASS, 1)
);
$arrC = count($arr) - 1;
diff --git a/src/world/generator/object/grass/TallGrassObject.php.bak b/src/world/generator/object/grass/TallGrassObject.php.bak
new file mode 100644
index 00000000..2ae719f1
--- /dev/null
+++ b/src/world/generator/object/grass/TallGrassObject.php.bak
@@ -0,0 +1,43 @@
+nextRange($pos->x - $radius, $pos->x + $radius);
+ $z = $random->nextRange($pos->z - $radius, $pos->z + $radius);
+ if($level->level->getBlockID($x, $pos->y + 1, $z) === AIR and $level->level->getBlockID($x, $pos->y, $z) === GRASS){
+ $t = $arr[$random->nextRange(0, $arrC)];
+ $level->setBlockRaw(new Vector3($x, $pos->y + 1, $z), $t);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/world/generator/object/tree/SmallTreeObject.php b/src/world/generator/object/tree/SmallTreeObject.php
index cd7b1610..31c05bdc 100644
--- a/src/world/generator/object/tree/SmallTreeObject.php
+++ b/src/world/generator/object/tree/SmallTreeObject.php
@@ -25,7 +25,7 @@ require_once("TreeObject.php");
class SmallTreeObject extends TreeObject{
public $type = 0;
- private $trunkHeight = 5;
+ private $trunkHeight = 4;
private static $leavesHeight = 4; // All trees appear to be 4 tall
private static $leafRadii = array( 1, 1.41, 2.83, 2.24 );
@@ -76,7 +76,7 @@ class SmallTreeObject extends TreeObject{
{
// The size is a slight variation on the trunkheight
$radius = self::$leafRadii[ $leaflevel ] + $leafPre;
- $bRadius = 3;
+ $bRadius = 2;
for( $xx = -$bRadius; $xx <= $bRadius; ++ $xx )
{
for( $zz = -$bRadius; $zz <= $bRadius; ++ $zz )
diff --git a/src/world/generator/object/tree/SmallTreeObject.php.bak b/src/world/generator/object/tree/SmallTreeObject.php.bak
new file mode 100644
index 00000000..5fdce523
--- /dev/null
+++ b/src/world/generator/object/tree/SmallTreeObject.php.bak
@@ -0,0 +1,104 @@
+trunkHeight + 3; ++$yy) {
+ if($yy == 1 or $yy === $this->trunkHeight) {
+ ++$radiusToCheck;
+ }
+ for($xx = -$radiusToCheck; $xx < ($radiusToCheck + 1); ++$xx){
+ for($zz = -$radiusToCheck; $zz < ($radiusToCheck + 1); ++$zz){
+ if(!isset($this->overridable[$level->level->getBlockID($pos->x + $xx, $pos->y + $yy, $pos->z + $zz)])){
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ public function placeObject(Level $level, Vector3 $pos, Random $random){
+ // The base dirt block
+ $dirtpos = new Vector3( $pos->x, $pos->y - 1, $pos->z );
+ $level->setBlockRaw( $dirtpos, new DirtBlock() );
+
+ // Adjust the tree trunk's height randomly
+ // plot [-14:11] int( x / 8 ) + 5
+ // - min=4 (all leaves are 4 tall, some trunk must show)
+ // - max=6 (top leaves are within ground-level whacking range
+ // on all small trees)
+ $heightPre = $random->nextRange(-14, 11);
+ $this->trunkHeight = intval( $heightPre / 8 ) + 5;
+
+ // Adjust the starting leaf density using the trunk height as a
+ // starting position (tall trees with skimpy leaves don't look
+ // too good)
+ $leafPre = $random->nextRange($this->trunkHeight, 10) / 20; // (TODO: seed may apply)
+
+ // Now build the tree (from the top down)
+ $leaflevel = 0;
+ for( $yy = ($this->trunkHeight + 1); $yy >= 0; --$yy )
+ {
+ if( $leaflevel < self::$leavesHeight )
+ {
+ // The size is a slight variation on the trunkheight
+ $radius = self::$leafRadii[ $leaflevel ] + $leafPre;
+ $bRadius = 2;
+ for( $xx = -$bRadius; $xx <= $bRadius; ++ $xx )
+ {
+ for( $zz = -$bRadius; $zz <= $bRadius; ++ $zz )
+ {
+ if( sqrt(($xx * $xx) + ($zz * $zz)) <= $radius )
+ {
+ $leafpos = new Vector3( $pos->x + $xx,
+ $pos->y + $yy,
+ $pos->z + $zz );
+ $level->setBlockRaw($leafpos, new LeavesBlock( $this->type ) );
+ }
+ }
+ }
+ $leaflevel ++;
+ }
+
+ // Place the trunk last
+ if($leaflevel > 1)
+ {
+ $trunkpos = new Vector3( $pos->x, $pos->y + $yy, $pos->z );
+ $level->setBlockRaw($trunkpos, new WoodBlock( $this->type ) );
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/world/generator/object/tree/TreeObject.php b/src/world/generator/object/tree/TreeObject.php
index 86677c8c..10970233 100644
--- a/src/world/generator/object/tree/TreeObject.php
+++ b/src/world/generator/object/tree/TreeObject.php
@@ -23,6 +23,8 @@
class TreeObject{
public $overridable = array(
0 => true,
+ 2 => true,
+ 3 => true,
6 => true,
17 => true,
18 => true,
diff --git a/src/world/generator/populator/MineshaftPopulator.php b/src/world/generator/populator/MineshaftPopulator.php
index b4bb29a5..98e30892 100644
--- a/src/world/generator/populator/MineshaftPopulator.php
+++ b/src/world/generator/populator/MineshaftPopulator.php
@@ -32,4 +32,4 @@ class MineshaftPopulator extends Populator{
}
}
-}
\ No newline at end of file
+}
diff --git a/src/world/generator/populator/OrePopulator.php b/src/world/generator/populator/OrePopulator.php
index 390cbcba..5ae016ad 100644
--- a/src/world/generator/populator/OrePopulator.php
+++ b/src/world/generator/populator/OrePopulator.php
@@ -25,9 +25,9 @@ class OrePopulator extends Populator{
foreach($this->oreTypes as $type){
$ore = new OreObject($random, $type);
for($i = 0; $i < $ore->type->clusterCount; ++$i){
- $x = $random->nextRange($chunkX << 4, ($chunkX << 4) + 16);
+ $x = $random->nextRange($chunkX << 4, ($chunkX << 4) + 15);
$y = $random->nextRange($ore->type->minHeight, $ore->type->maxHeight);
- $z = $random->nextRange($chunkZ << 4, ($chunkZ << 4) + 16);
+ $z = $random->nextRange($chunkZ << 4, ($chunkZ << 4) + 15);
if($ore->canPlaceObject($level, $x, $y, $z)){
$ore->placeObject($level, new Vector3($x, $y, $z));
}
diff --git a/src/world/generator/populator/TallGrassPopulator.php b/src/world/generator/populator/TallGrassPopulator.php
new file mode 100644
index 00000000..34479a0d
--- /dev/null
+++ b/src/world/generator/populator/TallGrassPopulator.php
@@ -0,0 +1,75 @@
+randomAmount = $amount;
+ }
+
+ public function setBaseAmount($amount){
+ $this->baseAmount = $amount;
+ }
+
+ 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);
+ for($size = 30; $size > 0; --$size){
+ $xx = $x - 7 + $random->nextRange(0, 15);
+ $zz = $z - 7 + $random->nextRange(0, 15);
+ $yy = $this->getHighestWorkableBlock($xx, $zz);
+ $vector = new Vector3($xx, $yy, $zz);
+ if($yy !== -1 and $this->canTallGrassStay($this->level->getBlockRaw($vector))){
+ if(mt_rand(1,4) == 1){
+ $this->level->setBlockRaw($vector, new TallGrassBlock(2));
+ }else{
+ $this->level->setBlockRaw($vector, new TallGrassBlock(1));
+ }
+
+ }
+ }
+ }
+ }
+
+ private function canTallGrassStay(Block $block){
+ return $block->getID() === AIR and $block->getSide(0)->getID() === GRASS;
+ }
+
+ private function getHighestWorkableBlock($x, $z){
+ for($y = 128; $y > 0; --$y){
+ $b = $this->level->getBlockRaw(new Vector3($x, $y, $z));
+ if($b->getID() === AIR or $b->getID() === LEAVES){
+ if(--$y <= 0){
+ return -1;
+ }
+ }else{
+ break;
+ }
+ }
+ return ++$y;
+ }
+}
\ No newline at end of file
diff --git a/src/world/generator/populator/TallGrassPopulator.php.bak b/src/world/generator/populator/TallGrassPopulator.php.bak
new file mode 100644
index 00000000..f24521ea
--- /dev/null
+++ b/src/world/generator/populator/TallGrassPopulator.php.bak
@@ -0,0 +1,75 @@
+randomAmount = $amount;
+ }
+
+ public function setBaseAmount($amount){
+ $this->baseAmount = $amount;
+ }
+
+ 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);
+ for($size = 30; $size > 0; --$size){
+ $xx = $x - 7 + $random->nextRange(0, 15);
+ $zz = $z - 7 + $random->nextRange(0, 15);
+ $yy = $this->getHighestWorkableBlock($xx, $zz);
+ $vector = new Vector3($xx, $yy, $zz);
+ if($yy !== -1 and $this->canTallGrassStay($this->level->getBlockRaw($vector))){
+ if(mt_rand(1,4) == 1){
+ $this->level->setBlockRaw($vector, new TallGrassBlock(2));
+ }else{
+ $this->level->setBlockRaw($vector, new TallGrassBlock(1);
+ }
+
+ }
+ }
+ }
+ }
+
+ private function canTallGrassStay(Block $block){
+ return $block->getID() === AIR and $block->getSide(0)->getID() === GRASS;
+ }
+
+ private function getHighestWorkableBlock($x, $z){
+ for($y = 128; $y > 0; --$y){
+ $b = $this->level->getBlockRaw(new Vector3($x, $y, $z));
+ if($b->getID() === AIR or $b->getID() === LEAVES){
+ if(--$y <= 0){
+ return -1;
+ }
+ }else{
+ break;
+ }
+ }
+ return ++$y;
+ }
+}
\ No newline at end of file
diff --git a/src/world/generator/populator/TreePopulator.php b/src/world/generator/populator/TreePopulator.php
new file mode 100644
index 00000000..6f8f4a29
--- /dev/null
+++ b/src/world/generator/populator/TreePopulator.php
@@ -0,0 +1,69 @@
+randomAmount = $amount;
+ }
+
+ public function setBaseAmount($amount){
+ $this->baseAmount = $amount;
+ }
+
+ 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);
+ $y = $this->getHighestWorkableBlock($x, $z);
+ if($y === -1){
+ continue;
+ }
+ if($random->nextFloat() > 0.75){
+ $meta = SaplingBlock::BIRCH;
+ }elseif(($random->nextFloat() < 0.75) and ($random->nextFloat() > 0.25)){
+ $meta = SaplingBlock::OAK;
+ }else{
+ $meta = SaplingBlock::JUNGLE;
+ }
+ TreeObject::growTree($this->level, new Vector3($x, $y, $z), $random, $meta);
+ }
+ }
+
+ private function getHighestWorkableBlock($x, $z){
+ for($y = 128; $y > 0; --$y){
+ $b = $this->level->getBlockRaw(new Vector3($x, $y, $z));
+ if($b->getID() !== DIRT and $b->getID() !== GRASS){
+ if(--$y <= 0){
+ return -1;
+ }
+ }else{
+ break;
+ }
+ }
+ return ++$y;
+ }
+}
\ No newline at end of file
diff --git a/src/world/generator/populator/TreePopulator.php.bak b/src/world/generator/populator/TreePopulator.php.bak
new file mode 100644
index 00000000..a24e0d8b
--- /dev/null
+++ b/src/world/generator/populator/TreePopulator.php.bak
@@ -0,0 +1,69 @@
+randomAmount = $amount;
+ }
+
+ public function setBaseAmount($amount){
+ $this->baseAmount = $amount;
+ }
+
+ 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);
+ $y = $this->getHighestWorkableBlock($x, $z);
+ if($y === -1){
+ continue;
+ }
+ if($random->nextFloat() > 0.75){
+ $meta = SaplingBlock::BIRCH;
+ }elseif(($random->nextFloat() < 0.75) and ($random->nextFloat() > 0.25)){
+ $meta = SaplingBlock::OAK;
+ }else{
+ $meta = SaplingBlock::JUNGLE;
+ }
+ TreeObject::growTree($this->level, new Vector3($x, $y, $z), $random, $meta);
+ }
+ }
+
+ private function getHighestWorkableBlock($x, $z){
+ for($y = 128; $y > 0; --$y){
+ $b = $this->level->getBlockRaw(new Vector3($x, $y, $z));
+ if($b->getID() !== DIRT and $b->getID() !== GRASS){
+ if(--$y <= 0){
+ return -1;
+ }
+ }else{
+ break;
+ }
+ }
+ return ++$y;
+ }
+}
\ No newline at end of file