Covariant Ptr type

master
Nicole Collings 2020-08-02 17:16:40 -07:00
parent 6fd5acae0a
commit b312193969
100 changed files with 779 additions and 826 deletions

View File

@ -3,7 +3,7 @@
-- Otherwise, calls zepha.block_place and returned the function's returned values.
function zepha.block_interact_or_place(player, target, stack)
local stack = stack or player:get_wield_stack()
local target_block = zepha.get_block(target.pos)
local target_block = player.dim:get_block(target.pos)
local target_def = zepha.registered_blocks[target_block]
local stack_def = zepha.registered_blocks[stack and stack.name or nil]
@ -24,7 +24,7 @@ end
-- Interacts with the targeted block. Returns true if the block has an on_interact or
-- on_interact_client callback, returns false otherwise.
function zepha.block_interact(player, target)
local block = zepha.get_block(target.pos)
local block = player.dim:get_block(target.pos)
local def = zepha.registered_blocks[block]
local cb = zepha.server and "on_interact" or "on_interact_client"
@ -43,21 +43,21 @@ function zepha.block_place(player, target, stack)
local stack_def = zepha.registered_blocks[stack and stack.name or nil]
if stack == nil or stack_def == nil then return stack, nil end
zepha.set_block(target.pos_above, stack.name)
player.dim:set_block(target.pos_above, stack.name)
stack.count = stack.count - 1
return stack, target.pos_above
end
function zepha.block_hit(player, target)
local block = zepha.get_block(target.pos)
local block = player.dim:get_block(target.pos)
local def = zepha.registered_blocks[block]
-- Don't do anything, return a small timeout to avoid spamming the function.
if not def then return 0, 0.1 end
local damage, timeout = zepha.get_hit_impact(player, block)
zepha.block_damage_add(target.pos, damage)
player.dim:add_block_damage(target.pos, damage)
return damage, timeout
end

View File

@ -217,8 +217,7 @@ add_library(Zepha_Core
lua/ServerModHandler.cpp
lua/ServerModHandler.h
lua/usertype/cAnimationManager.h
lua/usertype/cItemStack.h
lua/usertype/cLuaEntity.h
lua/usertype/cLuaEntity.h
lua/usertype/LocalLuaAnimationManager.cpp
lua/usertype/LocalLuaAnimationManager.h
lua/usertype/LocalLuaEntity.cpp
@ -227,8 +226,8 @@ add_library(Zepha_Core
lua/usertype/Player.h
lua/usertype/LuaGuiElement.cpp
lua/usertype/LuaGuiElement.h
lua/usertype/LuaItemStack.cpp
lua/usertype/LuaItemStack.h
lua/usertype/ItemStack.cpp
lua/usertype/ItemStack.h
lua/usertype/ServerLocalLuaEntity.cpp
lua/usertype/ServerLocalLuaEntity.h
lua/usertype/ServerLuaEntity.cpp
@ -325,4 +324,4 @@ add_library(Zepha_Core
game/entity/Collision.cpp
game/entity/Collision.h
net/server/conn/ServerClient.cpp
net/server/conn/ServerClient.h lua/modules/Dimension.cpp lua/modules/Dimension.h)
net/server/conn/ServerClient.h lua/modules/Dimension.cpp lua/modules/Dimension.h util/CovariantPtr.h)

View File

@ -20,18 +20,6 @@
#include "StartGame.h"
int main(int argc, char* argv[]) {
// sol::state lua;
// lua.open_libraries(sol::lib::base);
//
// lua.script(R"(
// number = 32
// )");
//
// unsigned short n = lua.get<unsigned short>("number");
// std::cout << n << std::endl;
return StartGame(argc, argv);
}

View File

@ -15,11 +15,11 @@ LocalSubgame::LocalSubgame(const std::string& texPath) :
textures.loadDirectory(texPath);
}
void LocalSubgame::initApi(LocalWorld &world, ClientState& state) {
void LocalSubgame::initApi(WorldPtr world, ClientState& state) {
lua->init(world, state);
}
void LocalSubgame::loadPlayer(std::shared_ptr<LocalPlayer> player) {
void LocalSubgame::loadPlayer(PlayerPtr player) {
lua->loadPlayer(player);
}

View File

@ -13,6 +13,7 @@
#include "gen/LocalBiomeAtlas.h"
#include "LocalDefinitionAtlas.h"
#include "texture/TextureAtlas.h"
#include "../util/CovariantPtr.h"
#include "../lua/LocalLuaParser.h"
class LocalPlayer;
@ -24,8 +25,8 @@ public:
explicit LocalSubgame(const std::string& texPath);
~LocalSubgame();
void initApi(LocalWorld &world, ClientState& state);
void loadPlayer(std::shared_ptr<LocalPlayer> player);
void initApi(WorldPtr world, ClientState& state);
void loadPlayer(PlayerPtr player);
void update(double delta);
std::string texPath;
@ -38,8 +39,8 @@ public:
TextureAtlas textures;
private:
std::unique_ptr<LocalLuaParser> lua;
std::unique_ptr<LocalBiomeAtlas> biomes;
std::unique_ptr<LocalDefinitionAtlas> defs;
std::shared_ptr<LocalLuaParser> lua;
std::shared_ptr<LocalBiomeAtlas> biomes;
std::shared_ptr<LocalDefinitionAtlas> defs;
};

View File

@ -19,7 +19,7 @@ ServerSubgame::ServerSubgame(const std::string& subgame, unsigned int seed) :
else if (!cf_file_exists(subgamePath.data())) throw std::runtime_error("Subgame does not exist.");
}
void ServerSubgame::init(ServerWorld &world) {
void ServerSubgame::init(WorldPtr world) {
lua->init(world, subgamePath);
}

View File

@ -21,7 +21,7 @@ public:
ServerSubgame(const std::string& subgame, unsigned int seed);
~ServerSubgame();
void init(ServerWorld& world);
void init(WorldPtr world);
void update(double delta);
std::string subgamePath;

View File

@ -12,12 +12,12 @@
#include "../../def/DefinitionAtlas.h"
#include "../../def/item/SelectionBox.h"
bool Collision::isOnGround(Subgame& game, Dimension& dim, SelectionBox& collision, glm::vec3 pos, glm::vec3 vel) {
bool Collision::isOnGround(SubgamePtr game, DimensionPtr dim, SelectionBox& collision, glm::vec3 pos, glm::vec3 vel) {
pos.y -= 0.05f;
return collidesAt(game, dim, collision, pos) && vel.y <= 0;
}
void Collision::moveCollide(Subgame& game, Dimension& dim, SelectionBox& collision, glm::vec3& pos, glm::vec3& vel, float stepUpAmount) {
void Collision::moveCollide(SubgamePtr game, DimensionPtr dim, SelectionBox& collision, glm::vec3& pos, glm::vec3& vel, float stepUpAmount) {
const static double increment = 0.05;
double moved = 0;
@ -57,7 +57,7 @@ void Collision::moveCollide(Subgame& game, Dimension& dim, SelectionBox& collisi
}
}
bool Collision::collidesAt(Subgame& game, Dimension& dim, SelectionBox& collision, glm::vec3& pos, float stepUpMax) {
bool Collision::collidesAt(SubgamePtr game, DimensionPtr dim, SelectionBox& collision, glm::vec3& pos, float stepUpMax) {
// Find the minimum vertical increase needed to step up
float stepUpAmount = 0;
@ -71,7 +71,7 @@ bool Collision::collidesAt(Subgame& game, Dimension& dim, SelectionBox& collisio
offset.z = collision.a.z;
while (true) {
glm::vec3 offsetPos = glm::floor(pos + offset);
auto &def = game.getDefs().blockFromId(dim.getBlock(offsetPos));
auto &def = game->getDefs().blockFromId(dim->getBlock(offsetPos));
if (def.solid)
for (auto &cBox : def.cBoxes)
@ -103,7 +103,7 @@ bool Collision::collidesAt(Subgame& game, Dimension& dim, SelectionBox& collisio
offset.z = collision.a.z;
while (true) {
glm::vec3 offsetPos = glm::floor(pos + offset);
auto& def = game.getDefs().blockFromId(dim.getBlock(offsetPos));
auto& def = game->getDefs().blockFromId(dim->getBlock(offsetPos));
if (def.solid) {
for (auto &cBox : def.cBoxes) {

View File

@ -6,13 +6,15 @@
#include <glm/vec3.hpp>
#include "../../util/CovariantPtr.h"
class Subgame;
class Dimension;
class SelectionBox;
class Collision {
public:
static bool isOnGround(Subgame& game, Dimension& dim, SelectionBox& collision, glm::vec3 pos, glm::vec3 vel);
static void moveCollide(Subgame& game, Dimension& dimension, SelectionBox& collision, glm::vec3& pos, glm::vec3& vel, float stepUpAmount = 0);
static bool collidesAt(Subgame& game, Dimension& dimension, SelectionBox& collision, glm::vec3& pos, float stepUpMax = 0);
static bool isOnGround(SubgamePtr game, DimensionPtr dim, SelectionBox& collision, glm::vec3 pos, glm::vec3 vel);
static void moveCollide(SubgamePtr game, DimensionPtr dim, SelectionBox& collision, glm::vec3& pos, glm::vec3& vel, float stepUpAmount = 0);
static bool collidesAt(SubgamePtr game, DimensionPtr dim, SelectionBox& collision, glm::vec3& pos, float stepUpMax = 0);
};

View File

@ -12,15 +12,15 @@
#include "../scene/world/LocalWorld.h"
#include "components/compound/GuiLabelledGraph.h"
DebugGui::DebugGui(glm::vec2 bufferSize, LocalSubgame& game, LocalWorld& world) :
DebugGui::DebugGui(glm::vec2 bufferSize, SubgamePtr game, WorldPtr world) :
game(game),
world(world) {
auto fpsHistogramRef = game.textures["histogram"];
auto genericHistogramRef = game.textures["histogram_white"];
auto fontRef = game.textures["font"];
auto fpsHistogramRef = game.l()->textures["histogram"];
auto genericHistogramRef = game.l()->textures["histogram_white"];
auto fontRef = game.l()->textures["font"];
Font f(game.textures, fontRef);
Font f(game.l()->textures, fontRef);
auto crosshairText = std::make_shared<GuiText>("crosshairText");
crosshairText->create({2, 2}, {}, {0.2, 0.2, 0.2, 0.5}, {1, 1, 1, 1}, f);
@ -78,7 +78,7 @@ void DebugGui::positionElements(glm::vec2 bufferSize) {
get<GuiLabelledGraph>("gpuGraph")->setPos({bufferWidth - 254, 90 + 80});
}
void DebugGui::update(LocalPlayer& player, double fps, int /*chunks*/, int drawCalls, int ssGen, int ssPack) {
void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chunks*/, int drawCalls, int ssGen, int ssPack) {
{ //Top Right Graphs
get<GuiLabelledGraph>("fpsGraph")->pushValue(static_cast<float>(fps));
@ -95,17 +95,17 @@ void DebugGui::update(LocalPlayer& player, double fps, int /*chunks*/, int drawC
}
{ //Bottom Right Graphs
get<GuiLabelledGraph>("meshGraph")->pushValue(world.lastMeshUpdates);
get<GuiLabelledGraph>("interpGraph")->pushValue(world.mapBlocksInterpolated);
get<GuiLabelledGraph>("meshGraph")->pushValue(world.l()->lastMeshUpdates);
get<GuiLabelledGraph>("interpGraph")->pushValue(world.l()->mapBlocksInterpolated);
get<GuiLabelledGraph>("genGraph")->pushValue(static_cast<float>(ssGen));
get<GuiLabelledGraph>("packetGraph")->pushValue(static_cast<float>(ssPack));
}
{ //Top-left Data
unsigned int biomeID = world.getActiveDimension().getBiome(glm::floor(player.getPos()));
std::string biome = game.getBiomes().biomeFromId(biomeID).identifier;
unsigned int biomeID = world.l()->getActiveDimension()->getBiome(glm::floor(player->getPos()));
std::string biome = game->getBiomes().biomeFromId(biomeID).identifier;
glm::vec3 playerPos = glm::floor(player.getPos());
glm::vec3 playerPos = glm::floor(player->getPos());
glm::vec3 chunkPos = Space::Chunk::world::fromBlock(playerPos);
glm::vec3 mapBlockPos = Space::MapBlock::world::fromChunk(chunkPos);
glm::vec3 regionPos = Space::Region::world::fromChunk(chunkPos);
@ -120,22 +120,22 @@ void DebugGui::update(LocalPlayer& player, double fps, int /*chunks*/, int drawC
using namespace Util;
str << "Player: " << vecToString(playerPos);
str << " (" << floatVecToString(player.getPos()) << ")" << std::endl << std::endl;
str << " (" << floatVecToString(player->getPos()) << ")" << std::endl << std::endl;
str << "Chunk: " << vecToString(posOffsetFromChunk) << " [" << vecToString(chunkPos) << "]" << std::endl;
str << "MapBlock: " << vecToString(posOffsetFromBlock) << " [" << vecToString(mapBlockPos) << "]" << std::endl;
str << "Region: " << vecToString(posOffsetFromRegion) << " [" << vecToString(regionPos) << "]" << std::endl << std::endl;
str << "Vel: " << floatVecToString(player.getVel()) << std::endl;
str << "Yaw: " << floatToString(player.getYaw()) << ", ";
str << "Pitch: " << floatToString(player.getPitch()) << std::endl << std::endl;
str << "Vel: " << floatVecToString(player->getVel()) << std::endl;
str << "Yaw: " << floatToString(player->getYaw()) << ", ";
str << "Pitch: " << floatToString(player->getPitch()) << std::endl << std::endl;
str << "Biome: " << biome << std::endl << std::endl;
str << "Texture Slots: " << game.textures.textureSlotsUsed << " / " << game.textures.maxTextureSlots
<< " (" << round(game.textures.textureSlotsUsed / static_cast<float>(game.textures.maxTextureSlots) * 100) << "%)" << std::endl << std::endl;
str << "Texture Slots: " << game.l()->textures.textureSlotsUsed << " / " << game.l()->textures.maxTextureSlots
<< " (" << round(game.l()->textures.textureSlotsUsed / static_cast<float>(game.l()->textures.maxTextureSlots) * 100) << "%)" << std::endl << std::endl;
Target thing = player.getPointedThing();
Target thing = player->getPointedThing();
if (thing.type == Target::Type::BLOCK) {
std::string face =
thing.face == EVec::TOP ? "TOP" :
@ -146,7 +146,7 @@ void DebugGui::update(LocalPlayer& player, double fps, int /*chunks*/, int drawC
thing.face == EVec::BACK ? "BACK" :
"NONE" ;
str << "Pointing At: " << game.getDefs().blockFromId(world.getActiveDimension().getBlock(thing.pos)).identifier << std::endl;
str << "Pointing At: " << game->getDefs().blockFromId(world.l()->getActiveDimension()->getBlock(thing.pos)).identifier << std::endl;
str << "Pointed Position: " << vecToString(thing.pos) << std::endl;
str << "Pointed Face: " << face << std::endl;
}
@ -158,12 +158,12 @@ void DebugGui::update(LocalPlayer& player, double fps, int /*chunks*/, int drawC
}
{ //Crosshair Text
Target target = player.getPointedThing();
Target target = player->getPointedThing();
std::ostringstream crossText;
if (target.type == Target::Type::BLOCK) {
crossText << game.getDefs().blockFromId(world.getActiveDimension().getBlock(target.pos)).name
<< " (" << game.getDefs().blockFromId(world.getActiveDimension().getBlock(target.pos)).identifier << ")" << std::endl;
crossText << game->getDefs().blockFromId(world.l()->getActiveDimension()->getBlock(target.pos)).name
<< " (" << game->getDefs().blockFromId(world.l()->getActiveDimension()->getBlock(target.pos)).identifier << ")" << std::endl;
}
get<GuiText>("crosshairText")->setText(crossText.str());
}

View File

@ -6,22 +6,24 @@
#include "components/basic/GuiContainer.h"
#include "../../util/CovariantPtr.h"
class LocalPlayer;
class LocalSubgame;
class LocalWorld;
class DebugGui : public GuiContainer {
public:
DebugGui(glm::vec2 bufferSize, LocalSubgame& game, LocalWorld& world);
DebugGui(glm::vec2 bufferSize, SubgamePtr game, WorldPtr world);
void bufferResized(glm::vec2 bufferSize);
void changeVisibilityState(int state);
void positionElements(glm::vec2 bufferSize);
void update(LocalPlayer& player, double fps, int chunks, int drawCalls, int ssGen, int ssPack);
void update(std::shared_ptr<LocalPlayer> player, double fps, int chunks, int drawCalls, int ssGen, int ssPack);
private:
int displayMode;
LocalWorld& world;
LocalSubgame& game;
WorldPtr world;
SubgamePtr game;
};

View File

@ -6,7 +6,7 @@
#include "../graph/Renderer.h"
GameGui::GameGui(LocalInventoryRefs& refs, glm::vec2 bufferSize, LocalSubgame& defs, Renderer& renderer) :
GameGui::GameGui(InventoryRefsPtr refs, glm::vec2 bufferSize, SubgamePtr defs, Renderer& renderer) :
refs(refs),
defs(defs),
win(bufferSize),
@ -18,7 +18,7 @@ GameGui::GameGui(LocalInventoryRefs& refs, glm::vec2 bufferSize, LocalSubgame& d
hudRoot->add(hudLuaRoot);
menuRoot->add(menuLuaRoot);
handList->create({3, 3}, {}, {}, refs.getCursorList(), refs.getCursorList(), defs);
handList->create({3, 3}, {}, {}, refs.l()->getCursorList(), refs.l()->getCursorList(), defs);
menuRoot->add(handList);
}

View File

@ -9,7 +9,7 @@
class GameGui {
public:
explicit GameGui(LocalInventoryRefs& refs, glm::vec2 bufferSize, LocalSubgame& defs, Renderer& renderer);
explicit GameGui(InventoryRefsPtr refs, glm::vec2 bufferSize, SubgamePtr defs, Renderer& renderer);
void winResized(glm::ivec2 win);
void update(double delta);
@ -26,7 +26,7 @@ public:
void drawHud(Renderer& renderer);
void drawMenu(Renderer& renderer);
private:
LocalSubgame& defs;
SubgamePtr defs;
Renderer& renderer;
glm::ivec2 win {};
@ -43,6 +43,6 @@ private:
std::shared_ptr<GuiInventoryList> handList = std::make_shared<GuiInventoryList>("hand");
LocalInventoryRefs& refs;
InventoryRefsPtr refs;
};

View File

@ -11,11 +11,11 @@
class GameGuiBuilder : public GuiBuilder {
public:
GameGuiBuilder(LocalInventoryRefs& refs, LocalSubgame& defs, std::shared_ptr<GuiContainer> root) :
defs(defs), refs(refs), GuiBuilder(defs.textures, defs.models, root) {};
GameGuiBuilder(InventoryRefsPtr refs, SubgamePtr defs, std::shared_ptr<GuiContainer> root) :
defs(defs), refs(refs), GuiBuilder(defs.l()->textures, defs.l()->models, root) {};
std::shared_ptr<GuiComponent> createComponent(LuaGuiElement& elem, glm::ivec2 bounds) override;
private:
LocalInventoryRefs& refs;
LocalSubgame& defs;
InventoryRefsPtr refs;
SubgamePtr defs;
};

View File

@ -15,8 +15,8 @@
GuiInventoryList::GuiInventoryList(const std::string &key) : GuiContainer(key) {}
std::shared_ptr<GuiInventoryList> GuiInventoryList::fromSerialized(const LuaGuiElement& elem, LocalSubgame &game,
glm::ivec2 bounds, LocalInventoryRefs& refs) {
std::shared_ptr<GuiInventoryList> GuiInventoryList::fromSerialized(const LuaGuiElement& elem,
SubgamePtr game, glm::ivec2 bounds, InventoryRefsPtr refs) {
glm::vec2 pos = SerialGui::get<glm::vec2>(elem, "position", bounds);
// glm::vec2 offset = SerialGui::get<glm::vec2>(elem, "position_anchor");
@ -29,23 +29,23 @@ std::shared_ptr<GuiInventoryList> GuiInventoryList::fromSerialized(const LuaGuiE
unsigned short start = static_cast<unsigned short>(elem.get_or<float>("start", 1) - 1);
unsigned short length = static_cast<unsigned short>(elem.get_or<float>("length", 0));
auto invList = refs.getInventory(source).getListPtr(list);
auto invList = refs->getInventory(source)->getList(list).l();
auto inv = std::make_shared<GuiInventoryList>(elem.key);
inv->create(glm::vec2(SerialGui::SCALE_MODIFIER), padding * SerialGui::SCALE_MODIFIER,
slotspc * SerialGui::SCALE_MODIFIER, invList, refs.getCursorList(), game, start, length);
slotspc * SerialGui::SCALE_MODIFIER, invList, refs.l()->getCursorList(), game, start, length);
inv->setPos(pos);
return inv;
}
void GuiInventoryList::create(glm::vec2 scale, glm::vec4 padding, glm::ivec2 innerPadding,
std::shared_ptr<LocalInventoryList> list, std::shared_ptr<LocalInventoryList> cursor, LocalSubgame& defs,
InventoryListPtr list, InventoryListPtr cursor, SubgamePtr defs,
unsigned short start, unsigned short length) {
this->list = list;
this->cursor = cursor;
this->defs = &defs;
this->defs = defs;
this->start = start;
this->length = length;
@ -59,7 +59,7 @@ void GuiInventoryList::create(glm::vec2 scale, glm::vec4 padding, glm::ivec2 inn
drawContents();
myCallback = std::make_shared<std::function<void()>>(std::bind(&GuiInventoryList::drawContents, this));
list->addGuiCallback(myCallback);
list.l()->addGuiCallback(myCallback);
setCallback(CallbackType::PRIMARY, nullptr);
setCallback(CallbackType::SECONDARY, nullptr);
@ -106,7 +106,7 @@ void GuiInventoryList::interactEvent(glm::ivec2 pos, bool primary) {
if (index >= list->getLength()) return;
list->interact(*cursor, primary, index);
list->interact(cursor, primary, index);
}
void GuiInventoryList::drawContents() {
@ -120,8 +120,8 @@ void GuiInventoryList::drawContents() {
empty();
auto fontRef = defs->textures["font"];
Font f(defs->textures, fontRef);
auto fontRef = defs.l()->textures["font"];
Font f(defs.l()->textures, fontRef);
for (unsigned short i = 0; i < list->getLength() / list->getWidth(); i++) {
for (unsigned short j = 0; j < list->getWidth(); j++) {
@ -146,5 +146,5 @@ void GuiInventoryList::drawContents() {
}
GuiInventoryList::~GuiInventoryList() {
if (list != nullptr) list->removeGuiCallback(myCallback);
if (list) list.l()->removeGuiCallback(myCallback);
}

View File

@ -6,6 +6,7 @@
#include "../basic/GuiRect.h"
#include "../basic/GuiContainer.h"
#include "../../../../util/CovariantPtr.h"
class LocalSubgame;
class LuaGuiElement;
@ -18,11 +19,11 @@ public:
GuiInventoryList(const std::string& key);
~GuiInventoryList() override;
static std::shared_ptr<GuiInventoryList> fromSerialized(const LuaGuiElement& elem, LocalSubgame &game,
glm::ivec2 bounds, LocalInventoryRefs& refs);
static std::shared_ptr<GuiInventoryList> fromSerialized(const LuaGuiElement& elem,
SubgamePtr game, glm::ivec2 bounds, InventoryRefsPtr refs);
void create(glm::vec2 scale, glm::vec4 padding, glm::ivec2 innerPadding,
std::shared_ptr<LocalInventoryList> list, std::shared_ptr<LocalInventoryList> cursor, LocalSubgame& defs,
InventoryListPtr list, InventoryListPtr cursor, SubgamePtr defs,
unsigned short start = 0, unsigned short length = 0);
void setCallback(CallbackType type, const callback& cb) override;
@ -34,13 +35,13 @@ private:
std::shared_ptr<GuiRect> hoverRect = std::make_shared<GuiRect>("hover_rect");
std::shared_ptr<std::function<void()>> myCallback = nullptr;
std::shared_ptr<LocalInventoryList> list;
std::shared_ptr<LocalInventoryList> cursor;
InventoryListPtr list;
InventoryListPtr cursor;
unsigned short start;
unsigned short length;
glm::ivec2 innerPadding;
LocalSubgame* defs = nullptr;
SubgamePtr defs = SubgamePtr();
};

View File

@ -6,7 +6,7 @@
#include "InventoryList.h"
Inventory::Inventory(Subgame &game, const std::string& name) : game(game), name(name) {}
Inventory::Inventory(SubgamePtr game, const std::string& name) : game(game), name(name) {}
bool Inventory::hasList(const std::string &name) {
return lists.count(name);
@ -16,13 +16,7 @@ void Inventory::removeList(const std::string &name) {
lists.erase(name);
}
InventoryList& Inventory::getList(const std::string &name) {
if (lists.count(name)) return *lists[name];
throw std::runtime_error("List " + name + " doesn't exist in Inventory " + this->name + ".");
}
std::shared_ptr<InventoryList> Inventory::getListPtr(const std::string &name) {
// A dirty hack to cause LocalInventory to create a temp list.
try { getList(name); } catch (...) {}
return lists[name];
InventoryListPtr Inventory::getList(const std::string &name) {
if (lists.count(name)) return InventoryListPtr(lists[name]);
throw std::runtime_error("List " + name + " doesn't exist in inventory " + this->name + ".");
}

View File

@ -7,6 +7,7 @@
#include <map>
#include <string>
#include <memory>
#include "../../util/CovariantPtr.h"
class Subgame;
class InventoryList;
@ -14,18 +15,17 @@ class InventoryList;
class Inventory {
public:
Inventory(const Inventory& o) = delete;
explicit Inventory(Subgame& game, const std::string& name);
explicit Inventory(SubgamePtr game, const std::string& name);
virtual bool hasList(const std::string& name);
virtual InventoryList& getList(const std::string& name);
std::shared_ptr<InventoryList> getListPtr(const std::string& name);
virtual InventoryListPtr getList(const std::string& name);
virtual void createList(const std::string& name, unsigned short length, unsigned short width) = 0;
virtual void removeList(const std::string& name);
protected:
Subgame& game;
SubgamePtr game;
std::string name;
std::map<std::string, std::shared_ptr<InventoryList>> lists;

View File

@ -7,10 +7,10 @@
#include "../../def/ItemDef.h"
#include "../../net/Serializer.h"
#include "../../def/DefinitionAtlas.h"
#include "../../lua/usertype/LuaItemStack.h"
#include "../../lua/usertype/ItemStack.h"
InventoryList::InventoryList(Subgame& game, const std::string& name, const std::string& invName, unsigned short size, unsigned short width) :
InventoryList::InventoryList(SubgamePtr game, const std::string& name, const std::string& invName, unsigned short size, unsigned short width) :
game(game),
name(name),
items(size),
@ -65,7 +65,7 @@ ItemStack InventoryList::placeStack(unsigned short i, const ItemStack &stack, bo
else {
if (otherStack.count) {
if (otherStack.id == stack.id) {
unsigned short maxStack = game.getDefs().fromId(stack.id).maxStackSize;
unsigned short maxStack = game->getDefs().fromId(stack.id).maxStackSize;
if (allowedPut >= stack.count && allowedPut + otherStack.count < maxStack) {
setStack(i, {stack.id, static_cast<unsigned short>(otherStack.count + allowedPut)});
// if (on_put) on_put(i+1, LuaItemStack(otherStack, defs));
@ -123,7 +123,7 @@ ItemStack InventoryList::splitStack(unsigned short i, bool playerInitiated) {
}
ItemStack InventoryList::addStack(ItemStack stack, bool playerInitiated) {
unsigned short maxStack = game.getDefs().fromId(stack.id).maxStackSize;
unsigned short maxStack = game->getDefs().fromId(stack.id).maxStackSize;
unsigned short i = 0;
while (i < items.size() && stack.count > 0) {
@ -159,7 +159,7 @@ ItemStack InventoryList::addStack(ItemStack stack, bool playerInitiated) {
}
unsigned short InventoryList::stackFits(const ItemStack &stack) {
unsigned short maxStack = game.getDefs().fromId(stack.id).maxStackSize;
unsigned short maxStack = game->getDefs().fromId(stack.id).maxStackSize;
unsigned short i = 0;
unsigned short fits = 0;
@ -218,14 +218,14 @@ ItemStack InventoryList::removeStack(unsigned short ind, unsigned short count) {
}
}
void InventoryList::interact(InventoryList& cursor, bool primary, unsigned short ind) {
void InventoryList::interact(InventoryListPtr cursor, bool primary, unsigned short ind) {
if (primary) {
cursor.setStack(0, placeStack(ind, cursor.getStack(0), true));
cursor->setStack(0, placeStack(ind, cursor->getStack(0), true));
}
else {
auto handStack = cursor.getStack(0);
auto handStack = cursor->getStack(0);
if (handStack.count == 0) {
cursor.setStack(0, splitStack(ind, true));
cursor->setStack(0, splitStack(ind, true));
}
else {
auto listStack = getStack(ind);
@ -234,10 +234,10 @@ void InventoryList::interact(InventoryList& cursor, bool primary, unsigned short
handStack.count -= 1;
if (handStack.count == 0) handStack.id = 0;
if (overflow.count != 0) handStack.count += overflow.count;
cursor.setStack(0, handStack);
cursor->setStack(0, handStack);
}
else {
cursor.setStack(0, placeStack(ind, cursor.getStack(0), true));
cursor->setStack(0, placeStack(ind, cursor->getStack(0), true));
}
}
}
@ -277,6 +277,6 @@ Packet InventoryList::createPacket() {
// return luaCallbacks[static_cast<size_t>(type)];
//}
Subgame &InventoryList::getGame() {
SubgamePtr InventoryList::getGame() {
return game;
}

View File

@ -18,7 +18,7 @@ public:
enum class Callback { ALLOW_TAKE, ALLOW_PUT, ON_TAKE, ON_PUT };
InventoryList(const InventoryList& o) = delete;
InventoryList(Subgame& game, const std::string& name, const std::string& invName, unsigned short size, unsigned short width);
InventoryList(SubgamePtr game, const std::string& name, const std::string& invName, unsigned short size, unsigned short width);
std::string getName() const;
@ -44,15 +44,15 @@ public:
// Removes up to count items from ind, returns the items removed
virtual ItemStack removeStack(unsigned short ind, unsigned short count);
virtual void interact(InventoryList& cursor, bool primary, unsigned short ind);
virtual void interact(InventoryListPtr cursor, bool primary, unsigned short ind);
// sol::protected_function getLuaCallback(Callback type);
// void setLuaCallback(Callback type, sol::protected_function cb);
Subgame& getGame();
SubgamePtr getGame();
protected:
Subgame& game;
SubgamePtr game;
std::string name, invName;
unsigned short width = 0;

View File

@ -6,13 +6,13 @@
#include "../../def/Subgame.h"
InventoryRefs::InventoryRefs(Subgame& game) : game(game) {}
InventoryRefs::InventoryRefs(SubgamePtr game) : game(game) {}
bool InventoryRefs::hasInventory(const std::string &inv) {
return inventories.count(inv);
}
Inventory& InventoryRefs::getInventory(const std::string &inv) {
InventoryPtr InventoryRefs::getInventory(const std::string &inv) {
if (!inventories.count(inv)) throw std::runtime_error("Inventory " + inv + " doesn't exist~!");
return *inventories.at(inv);
return inventories.at(inv);
}

View File

@ -8,20 +8,22 @@
#include <memory>
#include <unordered_map>
#include "../../util/CovariantPtr.h"
class Subgame;
class Inventory;
class InventoryRefs {
public:
InventoryRefs(const InventoryRefs& o) = delete;
explicit InventoryRefs(Subgame& game);
explicit InventoryRefs(SubgamePtr game);
virtual bool hasInventory(const std::string& inv);
virtual Inventory& createInventory(const std::string& inv) = 0;
virtual Inventory& getInventory(const std::string& inv);
virtual InventoryPtr createInventory(const std::string& inv) = 0;
virtual InventoryPtr getInventory(const std::string& inv);
protected:
Subgame& game;
SubgamePtr game;
std::unordered_map<std::string, std::shared_ptr<Inventory>> inventories {};
};

View File

@ -7,10 +7,10 @@
#include "../../def/ItemDef.h"
#include "../../def/Subgame.h"
#include "../../def/DefinitionAtlas.h"
#include "../../lua/usertype/LuaItemStack.h"
#include "../../lua/usertype/ItemStack.h"
ItemStack::ItemStack(LuaItemStack &stack, Subgame& game) :
id((stack.get_count() == 0) ? DefinitionAtlas::AIR : game.getDefs().fromStr(stack.get_name()).index),
ItemStack::ItemStack(Api::Usertype::ItemStack& stack, SubgamePtr game) :
id((stack.get_count() == 0) ? DefinitionAtlas::AIR : game->getDefs().fromStr(stack.get_name()).index),
count((this->id == DefinitionAtlas::AIR) ? 0 : stack.get_count()) {}
ItemStack::ItemStack(unsigned int id, unsigned short count) :

View File

@ -6,14 +6,14 @@
#include <string>
class Subgame;
class LuaItemStack;
#include "../../util/CovariantPtr.h"
#include "../../lua/usertype/ItemStack.h"
class ItemStack {
public:
ItemStack() = default;
ItemStack(unsigned int id, unsigned short count);
ItemStack(LuaItemStack& stack, Subgame& game);
ItemStack(Api::Usertype::ItemStack& stack, SubgamePtr game);
bool operator!=(const ItemStack& b) const;
bool operator==(const ItemStack& b) const;

View File

@ -7,9 +7,9 @@
#include "LocalInventoryList.cpp"
#include "../../net/client/ClientNetworkInterpreter.h"
LocalInventoryList& LocalInventory::getList(const std::string &name) {
if (hasList(name)) createList(name, 0, 0);
return static_cast<LocalInventoryList&>(Inventory::getList(name));
InventoryListPtr LocalInventory::getList(const std::string &name) {
if (!hasList(name)) createList(name, 0, 0);
return Inventory::getList(name);
}
void LocalInventory::createList(const std::string &name, unsigned short length, unsigned short width) {
@ -17,11 +17,6 @@ void LocalInventory::createList(const std::string &name, unsigned short length,
net.invWatch(this->name, name);
}
std::shared_ptr<LocalInventoryList> LocalInventory::getListPtr(const std::string &name) {
if (!hasList(name)) createList(name, 0, 0);
return std::static_pointer_cast<LocalInventoryList>(lists[name]);
}
void LocalInventory::setPersistant(const std::string &list, bool persistant) {
if (!lists.count(name)) return;
std::static_pointer_cast<LocalInventoryList>(lists[list])->persistant = persistant;

View File

@ -19,15 +19,13 @@ class ClientNetworkInterpreter;
class LocalInventory : public Inventory {
public:
LocalInventory(LocalSubgame& game, const std::string& name, ClientNetworkInterpreter& net) :
LocalInventory(SubgamePtr game, const std::string& name, ClientNetworkInterpreter& net) :
Inventory(game, name), net(net) {}
virtual LocalInventoryList& getList(const std::string& name) override;
std::shared_ptr<LocalInventoryList> getListPtr(const std::string& name);
virtual InventoryListPtr getList(const std::string& name) override;
virtual void createList(const std::string& name, unsigned short length, unsigned short width) override;
void setPersistant(const std::string& list, bool persistant);
bool pruneLists(double time);

View File

@ -6,13 +6,13 @@
#include "../../net/client/ClientNetworkInterpreter.h"
LocalInventoryList::LocalInventoryList(Subgame& game, const std::string& name,
LocalInventoryList::LocalInventoryList(SubgamePtr game, const std::string& name,
const std::string& invName, unsigned short size, unsigned short width,
ClientNetworkInterpreter& net) :
InventoryList(game, name, invName, size, width),
net(net) {}
void LocalInventoryList::interact(InventoryList &hand, bool primary, unsigned short ind) {
void LocalInventoryList::interact(InventoryListPtr hand, bool primary, unsigned short ind) {
InventoryList::interact(hand, primary, ind);
net.invInteract(invName, name, primary, ind);
}

View File

@ -12,11 +12,11 @@ class ClientNetworkInterpreter;
class LocalInventoryList : public InventoryList {
public:
LocalInventoryList(Subgame& game, const std::string& name,
LocalInventoryList(SubgamePtr game, const std::string& name,
const std::string& invName, unsigned short size, unsigned short width,
ClientNetworkInterpreter& net);
void interact(InventoryList& hand, bool primary, unsigned short ind) override;
void interact(InventoryListPtr hand, bool primary, unsigned short ind) override;
void setData(unsigned int size, unsigned int width, std::vector<ItemStack> items);
void addGuiCallback(std::shared_ptr<std::function<void()>> cb);

View File

@ -11,11 +11,11 @@
#include "../../def/LocalDefinitionAtlas.h"
#include "../../net/client/ClientNetworkInterpreter.h"
LocalInventoryRefs::LocalInventoryRefs(Subgame& game, ClientNetworkInterpreter& net) : InventoryRefs(game), net(net) {}
LocalInventoryRefs::LocalInventoryRefs(SubgamePtr game, ClientNetworkInterpreter& net) : InventoryRefs(game), net(net) {}
void LocalInventoryRefs::init() {
createInventory("current_player");
getInventory("current_player").createList("cursor", 1, 1);
getInventory("current_player")->createList("cursor", 1, 1);
watch("current_player", "cursor");
}
@ -28,13 +28,9 @@ void LocalInventoryRefs::update(double delta, ClientNetworkInterpreter& net) {
}
}
LocalInventory& LocalInventoryRefs::createInventory(const std::string &inv) {
if (!inventories.count(inv)) inventories.emplace(inv, std::make_shared<LocalInventory>(static_cast<LocalSubgame&>(game), inv, net));
return static_cast<LocalInventory&>(*inventories[inv]);
}
LocalInventory& LocalInventoryRefs::getInventory(const std::string &inv) {
return static_cast<LocalInventory&>(InventoryRefs::getInventory(inv));
InventoryPtr LocalInventoryRefs::createInventory(const std::string &inv) {
if (!inventories.count(inv)) inventories.emplace(inv, std::make_shared<LocalInventory>(game, inv, net));
return inventories[inv];
}
void LocalInventoryRefs::packetReceived(std::unique_ptr<PacketView> p) {
@ -57,7 +53,7 @@ void LocalInventoryRefs::packetReceived(std::unique_ptr<PacketView> p) {
stacks.push_back({id, count});
}
static_cast<LocalInventoryList&>(inventories[source]->getList(list)).setData(size, width, stacks);
inventories[source]->getList(list).l()->setData(size, width, stacks);
}
void LocalInventoryRefs::watch(const std::string &inv, const std::string &list, bool persistant) {
@ -81,8 +77,8 @@ std::shared_ptr<LocalInventoryList> LocalInventoryRefs::getHandList() {
void LocalInventoryRefs::setHandList(const std::string &list) {
if (handList && list == handList->getName()) return;
if (handList) unWatch("current_player", handList->getName());
handList = getInventory("current_player").getListPtr(list);
getInventory("current_player").setPersistant(list, true);
handList = getInventory("current_player")->getList(list).l();
getInventory("current_player").l()->setPersistant(list, true);
}
std::shared_ptr<LocalInventoryList> LocalInventoryRefs::getWieldList() {
@ -92,12 +88,10 @@ std::shared_ptr<LocalInventoryList> LocalInventoryRefs::getWieldList() {
void LocalInventoryRefs::setWieldList(const std::string &list) {
if (wieldList && list == wieldList->getName()) return;
if (wieldList) unWatch("current_player", wieldList->getName());
wieldList = getInventory("current_player").getListPtr(list);
getInventory("current_player").setPersistant(list, true);
wieldList = getInventory("current_player")->getList(list).l();
getInventory("current_player").l()->setPersistant(list, true);
}
std::shared_ptr<LocalInventoryList> LocalInventoryRefs::getCursorList() {
return std::static_pointer_cast<LocalInventoryList>(
std::static_pointer_cast<LocalInventory>(inventories["current_player"])
->getListPtr("cursor"));
return inventories["current_player"]->getList("cursor").l();
}

View File

@ -20,14 +20,13 @@ class ClientNetworkInterpreter;
class LocalInventoryRefs : public InventoryRefs {
public:
LocalInventoryRefs(Subgame& game, ClientNetworkInterpreter& net);
LocalInventoryRefs(SubgamePtr game, ClientNetworkInterpreter& net);
void packetReceived(std::unique_ptr<PacketView> p);
void init();
void update(double delta, ClientNetworkInterpreter& net);
virtual LocalInventory& createInventory(const std::string &inv) override;
virtual LocalInventory& getInventory(const std::string &inv) override;
virtual InventoryPtr createInventory(const std::string &inv) override;
void watch(const std::string& inv, const std::string& list, bool persistant = false);
void unWatch(const std::string& inv, const std::string& list);

View File

@ -10,10 +10,6 @@ void ServerInventory::createList(const std::string &name, unsigned short length,
lists.emplace(name, std::make_shared<ServerInventoryList>(game, clients, name, this->name, length, width));
}
ServerInventoryList& ServerInventory::getList(const std::string &name) {
return static_cast<ServerInventoryList&>(Inventory::getList(name));
}
//void ServerInventory::sendDirtyLists() {
// for (auto& list : lists) {
// if (list.second->dirty) {

View File

@ -17,11 +17,10 @@ class ServerClients;
class ServerInventory : public Inventory {
public:
ServerInventory(ServerSubgame& game, const std::string& name, ServerClients& clients) :
ServerInventory(SubgamePtr game, const std::string& name, ServerClients& clients) :
Inventory(game, name), clients(clients) {};
virtual void createList(const std::string& name, unsigned short length, unsigned short width) override;
virtual ServerInventoryList& getList(const std::string& name) override;
// void sendDirtyLists();
private:

View File

@ -7,11 +7,11 @@
#include "ServerInventoryList.h"
#include "../../net/Packet.h"
#include "../../lua/usertype/LuaItemStack.h"
#include "../../lua/usertype/ItemStack.h"
#include "../../net/server/conn/ServerPlayer.h"
#include "../../net/server/conn/ServerClients.h"
ServerInventoryList::ServerInventoryList(Subgame& game, ServerClients& list,
ServerInventoryList::ServerInventoryList(SubgamePtr game, ServerClients& list,
const std::string& name, const std::string& invName, unsigned short size, unsigned short width) :
InventoryList(game, name, invName, size, width),
clients(list) {}

View File

@ -14,8 +14,8 @@ class Packet;
class ServerInventoryList : public InventoryList {
public:
ServerInventoryList(Subgame& defs, ServerClients& list, const std::string& name,
const std::string& invName, unsigned short size, unsigned short width);
ServerInventoryList(SubgamePtr defs, ServerClients& list, const std::string& name,
const std::string& invName, unsigned short size, unsigned short width);
bool addWatcher(unsigned int id);
bool removeWatcher(unsigned int id);

View File

@ -7,7 +7,7 @@
#include "ServerInventory.h"
#include "ServerInventoryList.h"
ServerInventoryRefs::ServerInventoryRefs(Subgame& game, ServerClients& clients) :
ServerInventoryRefs::ServerInventoryRefs(SubgamePtr game, ServerClients& clients) :
InventoryRefs(game), clients(clients) {}
void ServerInventoryRefs::update() {
@ -15,22 +15,18 @@ void ServerInventoryRefs::update() {
// std::static_pointer_cast<ServerInventory>(inv.second)->sendDirtyLists();
}
ServerInventory& ServerInventoryRefs::createInventory(const std::string &inv) {
if (!inventories.count(inv)) inventories.emplace(inv, std::make_shared<ServerInventory>(static_cast<ServerSubgame&>(game), inv, clients));
return static_cast<ServerInventory&>(*inventories[inv]);
}
ServerInventory& ServerInventoryRefs::getInventory(const std::string &inv) {
return static_cast<ServerInventory&>(InventoryRefs::getInventory(inv));
InventoryPtr ServerInventoryRefs::createInventory(const std::string &inv) {
if (!inventories.count(inv)) inventories.emplace(inv, std::make_shared<ServerInventory>(game, inv, clients));
return inventories[inv];
}
bool ServerInventoryRefs::addWatcher(const std::string &inv, const std::string &list, unsigned int id) {
std::string invReal = inv == "current_player" ? "player:" + std::to_string(id) : inv;
if (!hasInventory(invReal)) return false;
auto& inventory = getInventory(invReal);
if (!inventory.hasList(list)) return false;
inventory.getList(list).addWatcher(id);
auto inventory = getInventory(invReal);
if (!inventory->hasList(list)) return false;
inventory->getList(list).s()->addWatcher(id);
return true;
}
@ -39,9 +35,9 @@ bool ServerInventoryRefs::removeWatcher(const std::string &inv, const std::strin
std::string invReal = inv == "current_player" ? "player:" + std::to_string(id) : inv;
if (!hasInventory(invReal)) return false;
auto& inventory = getInventory(invReal);
if (!inventory.hasList(list)) return false;
inventory.getList(list).removeWatcher(id);
auto inventory = getInventory(invReal);
if (!inventory->hasList(list)) return false;
inventory->getList(list).s()->removeWatcher(id);
return true;
}
@ -49,12 +45,12 @@ bool ServerInventoryRefs::removeWatcher(const std::string &inv, const std::strin
bool ServerInventoryRefs::interact(bool primary, const std::string &inv, const std::string &list, unsigned short ind, unsigned int id) {
std::string playerInv = "player:" + std::to_string(id);
if (!hasInventory(playerInv)) return false;
auto& playerInventory = getInventory(playerInv);
auto playerInventory = getInventory(playerInv);
if (!hasInventory(inv)) return false;
auto& inventory = getInventory(inv);
if (!inventory.hasList(list)) return false;
auto inventory = getInventory(inv);
if (!inventory->hasList(list)) return false;
inventory.getList(list).interact(playerInventory.getList("cursor"), primary, ind);
inventory->getList(list).s()->interact(playerInventory->getList("cursor"), primary, ind);
return true;
}

View File

@ -13,12 +13,11 @@ class ServerInventoryList;
class ServerInventoryRefs : public InventoryRefs {
public:
ServerInventoryRefs(Subgame& game, ServerClients& clients);
ServerInventoryRefs(SubgamePtr game, ServerClients& clients);
void update();
virtual ServerInventory& createInventory(const std::string &inv) override;
virtual ServerInventory& getInventory(const std::string &inv) override;
virtual InventoryPtr createInventory(const std::string &inv) override;
bool addWatcher(const std::string& inv, const std::string& list, unsigned int id);
bool removeWatcher(const std::string& inv, const std::string& list, unsigned int id);

View File

@ -10,16 +10,16 @@
#include "../../net/PacketView.h"
GameScene::GameScene(ClientState& state) : Scene(state),
game(state.defs),
world(game, state.connection, state.renderer),
game(std::make_shared<LocalSubgame>(state.defs)),
world(std::make_shared<LocalWorld>(game, state.connection, state.renderer)),
debugGui(state.renderer.window.getSize(), game, world) {
Packet r(PacketType::CONNECT_DATA_RECVD);
r.sendTo(state.connection.getPeer(), PacketChannel::CONNECT);
world.connect();
game.initApi(world, state);
if (world.initPlayer()) game.loadPlayer(world.getPlayer());
world.l()->connect();
game.l()->initApi(world, state);
if (world.l()->initPlayer()) game.l()->loadPlayer(world.l()->getPlayer());
state.renderer.window.addResizeCallback("gamescene", Util::bind_this(&debugGui, &DebugGui::bufferResized));
state.renderer.setClearColor(148, 194, 240);
@ -29,21 +29,21 @@ GameScene::GameScene(ClientState& state) : Scene(state),
void GameScene::update() {
Window& window = state.renderer.window;
game.update(state.delta);
world.update(state.delta);
game.l()->update(state.delta);
world->update(state.delta);
for (auto entity : entities) entity->update(state.delta);
debugGui.update(*world.getPlayer(), state.fps, world.getActiveDimension().getMeshChunkCount(),
drawCalls, world.getNet().serverSideChunkGens, world.getNet().recvPackets);
debugGui.update(world.l()->getPlayer().l(), state.fps, world.l()->getActiveDimension().l()->getMeshChunkCount(),
drawCalls, world.l()->getNet().serverSideChunkGens, world.l()->getNet().recvPackets);
world.getNet().serverSideChunkGens = 0;
world.getNet().recvPackets = 0;
world.l()->getNet().serverSideChunkGens = 0;
world.l()->getNet().recvPackets = 0;
if (window.input.keyPressed(GLFW_KEY_F1)) {
hudVisible = !hudVisible;
debugGui.changeVisibilityState(hudVisible ? debugVisible ? 0 : 2 : 1);
world.getPlayer()->setHudVisible(hudVisible);
world.l()->getPlayer().l()->setHudVisible(hudVisible);
}
if (window.input.keyPressed(GLFW_KEY_F3)) {
@ -57,22 +57,22 @@ void GameScene::draw() {
Camera& camera = renderer.camera;
renderer.beginChunkDeferredCalls();
renderer.enableTexture(&game.textures.atlasTexture);
renderer.enableTexture(&game.l()->textures.atlasTexture);
drawCalls = world.renderChunks(renderer);
drawCalls = world.l()->renderChunks(renderer);
renderer.beginEntityDeferredCalls();
for (auto entity : entities) entity->draw(renderer);
world.renderEntities(renderer);
world.l()->renderEntities(renderer);
renderer.endDeferredCalls();
renderer.beginGUIDrawCalls();
renderer.enableTexture(&game.textures.atlasTexture);
renderer.enableTexture(&game.l()->textures.atlasTexture);
world.getPlayer()->drawHud(renderer);
world.l()->getPlayer().l()->drawHud(renderer);
debugGui.draw(renderer);
world.getPlayer()->drawMenu(renderer);
world.l()->getPlayer().l()->drawMenu(renderer);
renderer.swapBuffers();
}

View File

@ -24,8 +24,8 @@ public:
void cleanup() override;
public:
LocalSubgame& game;
LocalWorld world;
SubgamePtr game;
WorldPtr world;
DebugGui debugGui;
std::vector<Drawable*> entities;

View File

@ -11,14 +11,13 @@
#include "../../../net/Deserializer.h"
#include "../../../def/item/BlockDef.h"
#include "../../../world/chunk/Chunk.h"
#include "../../inventory/LocalInventoryList.h"
#include "../../../net/client/ClientNetworkInterpreter.h"
LocalPlayer::LocalPlayer(LocalSubgame& game, LocalDimension& dim, Renderer &renderer) :
LocalPlayer::LocalPlayer(SubgamePtr game, DimensionPtr dim, Renderer &renderer) :
Player(game, dim),
renderer(renderer),
wireframe({1, 1, 1}),
gameGui(*static_cast<LocalWorld&>(dim.getWorld()).getRefs(), renderer.window.getSize(), game, renderer) {
gameGui(dim->getWorld().getRefs().l(), renderer.window.getSize(), game.l(), renderer) {
handItemModel.parent = &handModel;
@ -44,7 +43,7 @@ void LocalPlayer::update(Input &input, double delta, glm::vec2 mouseDelta) {
void LocalPlayer::assertField(Packet packet) {
packet.type = PacketType::THIS_PLAYER_INFO;
static_cast<LocalWorld&>(dim.getWorld()).getNet().sendPacket(packet, PacketChannel::INTERACT);
static_cast<LocalWorld&>(dim->getWorld()).getNet().sendPacket(packet, PacketChannel::INTERACT);
}
void LocalPlayer::handleAssertion(Deserializer &d) {
@ -81,13 +80,13 @@ void LocalPlayer::setLookOffset(glm::vec3 eyeOffset, bool assert) {
void LocalPlayer::setHandList(const std::string &list, bool assert) {
Player::setHandList(list, assert);
static_cast<LocalWorld&>(dim.getWorld()).getRefs()->setHandList(list);
dim->getWorld().getRefs().l()->setHandList(list);
updateWieldAndHandItems();
}
void LocalPlayer::setWieldList(const std::string& list, bool assert) {
Player::setWieldList(list, false);
static_cast<LocalWorld&>(dim.getWorld()).getRefs()->setWieldList(list);
dim->getWorld().getRefs().l()->setWieldList(list);
setWieldIndex(wieldIndex);
updateWieldAndHandItems();
if (assert) assertField(Serializer().append(
@ -95,7 +94,7 @@ void LocalPlayer::setWieldList(const std::string& list, bool assert) {
}
void LocalPlayer::setWieldIndex(unsigned short index, bool assert) {
auto wieldList = static_cast<LocalWorld&>(dim.getWorld()).getRefs()->getWieldList();
auto wieldList = dim->getWorld().getRefs().l()->getWieldList();
wieldIndex = index % std::max((wieldList ? wieldList->getLength() : 1), 1);
updateWieldAndHandItems();
if (assert) assertField(Serializer().append(
@ -136,8 +135,8 @@ void LocalPlayer::setHudVisible(bool hudVisible) {
// Misc Getters
//
LocalInventory& LocalPlayer::getInventory() {
return static_cast<LocalWorld&>(dim.getWorld()).getRefs()->getInventory("current_player");
InventoryPtr LocalPlayer::getInventory() {
return dim->getWorld().getRefs()->getInventory("current_player");
}
Target& LocalPlayer::getPointedThing() {
@ -250,7 +249,7 @@ void LocalPlayer::updateCamera() {
renderer.camera.setYaw(yaw);
renderer.camera.setPitch(pitch);
auto type = game.getDefs().fromId(wieldItem).type;
auto type = game->getDefs().fromId(wieldItem).type;
glm::vec3 eyesPos = pos + getLookOffset();
renderer.camera.setPos(eyesPos);
@ -300,14 +299,14 @@ void LocalPlayer::findPointedThing(Input &input) {
glm::ivec3 currChunkPos = Space::Chunk::world::fromBlock(roundedPos);
if (currChunkPos != chunkPos || blockChunk == nullptr) {
chunkPos = currChunkPos;
blockChunk = dim.getChunk(chunkPos);
blockChunk = dim->getChunk(chunkPos);
if (blockChunk == nullptr) continue;
lock = blockChunk->aquireLock();
}
unsigned int blockID = blockChunk->getBlock(Space::Block::relative::toChunk(roundedPos));
auto& boxes = game.getDefs().blockFromId(blockID).sBoxes;
auto& boxes = game->getDefs().blockFromId(blockID).sBoxes;
for (auto& sBox : boxes) {
auto face = sBox.intersects(rayEnd, roundedPos);
@ -327,7 +326,7 @@ void LocalPlayer::updateWireframe() {
wireframe.setVisible(false);
}
else if (target.type == Target::Type::BLOCK) {
auto& boxes = game.getDefs().blockFromId(dim.getBlock(target.pos)).sBoxes;
auto& boxes = game->getDefs().blockFromId(dim->getBlock(target.pos)).sBoxes;
float distance = glm::distance(pos, target.pos + glm::vec3(0.5));
wireframe.updateMesh(boxes, 0.002f + distance * 0.0014f);
@ -342,11 +341,11 @@ void LocalPlayer::updateWireframe() {
void LocalPlayer::interact(Input& input, double delta) {
if (target.type == Target::Type::BLOCK) {
if (input.mouseDown(GLFW_MOUSE_BUTTON_LEFT) && breakTime == 0) {
breakInterval = dim.blockHit(target, static_cast<LocalWorld&>(dim.getWorld()).getPlayer());
breakInterval = dim->blockHit(target, static_cast<LocalWorld&>(dim->getWorld()).getPlayer());
breakTime += delta;
}
else if (input.mousePressed(GLFW_MOUSE_BUTTON_RIGHT))
dim.blockPlaceOrInteract(target, static_cast<LocalWorld&>(dim.getWorld()).getPlayer());
dim->blockPlaceOrInteract(target, static_cast<LocalWorld&>(dim->getWorld()).getPlayer());
}
if (breakTime > 0) breakTime += delta;
@ -354,20 +353,16 @@ void LocalPlayer::interact(Input& input, double delta) {
}
void LocalPlayer::updateWieldAndHandItems() {
auto handList = static_cast<LocalWorld&>(dim.getWorld()).getRefs()->getHandList();
auto wieldList = static_cast<LocalWorld&>(dim.getWorld()).getRefs()->getWieldList();
auto handList = dim->getWorld().getRefs().l()->getHandList();
auto wieldList = dim->getWorld().getRefs().l()->getWieldList();
handItem = handList && handList->getLength() > 0 ? handList->getStack(0).id : 0;
wieldItem = wieldList && wieldList->getLength() > wieldIndex ? wieldList->getStack(wieldIndex).id : 0;
auto& model = game.getDefs().fromId(wieldItem <= DefinitionAtlas::AIR ? handItem : wieldItem).entityModel;
auto& model = game->getDefs().fromId(wieldItem <= DefinitionAtlas::AIR ? handItem : wieldItem).entityModel;
handItemModel.setModel(model);
}
LocalPlayer::~LocalPlayer() {
renderer.window.removeResizeCallback("player");
}
LocalDimension& LocalPlayer::getDimension() {
return static_cast<LocalDimension&>(dim);
}
}

View File

@ -23,14 +23,13 @@ class LocalPlayer : public virtual DrawableEntity, public Player {
public:
enum class PlayerControl { FORWARD, LEFT, BACKWARD, RIGHT, JUMP, MOD1, MOD2 };
LocalPlayer(LocalSubgame &game, LocalDimension& dim, Renderer &renderer);
LocalPlayer(SubgamePtr game, DimensionPtr dim, Renderer &renderer);
void update(Input &input, double delta, glm::vec2 mouseDelta);
virtual void assertField(Packet packet) override;
virtual void handleAssertion(Deserializer& d) override;
virtual LocalInventory& getInventory() override;
virtual LocalDimension& getDimension() override;
virtual InventoryPtr getInventory() override;
virtual void setPos(glm::vec3 pos, bool assert = false) override;
virtual void setLookOffset(glm::vec3 eyeOffset, bool assert = false) override;

View File

@ -9,10 +9,10 @@
#include "../../../net/PacketView.h"
#include "WorldInterpolationStream.h"
LocalWorld::LocalWorld(LocalSubgame& game, ServerConnection& conn, Renderer& renderer) :
LocalWorld::LocalWorld(SubgamePtr game, ServerConnection& conn, Renderer& renderer) :
World(game),
renderer(renderer),
net(conn, game, *this),
net(conn, *this),
refs(std::make_shared<LocalInventoryRefs>(game, net)),
worldGenStream(std::make_shared<WorldInterpolationStream>(55, game)) {}
@ -23,15 +23,15 @@ void LocalWorld::connect() {
bool LocalWorld::initPlayer() {
if (defaultDimension.empty()) return false;
player = std::make_shared<LocalPlayer>(static_cast<LocalSubgame&>(game), getDefaultDimension(), renderer);
activeDimension = getDefaultDimensionPtr();
player = PlayerPtr(std::make_shared<LocalPlayer>(game, getDefaultDimension(), renderer));
activeDimension = getDefaultDimension().l();
return true;
}
void LocalWorld::update(double delta) {
World::update(delta);
if (player) player->update(renderer.window.input, delta, renderer.window.input.mouseDelta());
if (*player) player.l()->update(renderer.window.input, delta, renderer.window.input.mouseDelta());
refs->update(delta, net);
net.update();
@ -51,7 +51,7 @@ void LocalWorld::handlePlayerEntPacket(std::unique_ptr<PacketView> p) {
if (player->getId() == id) return;
bool found = false;
for (auto& entity : getActiveDimension().playerEntities) {
for (auto& entity : getActiveDimension().l()->playerEntities) {
if (entity.getId() == id) {
entity.interpPos(p->d.read<glm::vec3>());
entity.interpRotateZ(-p->d.read<float>() + 90);
@ -74,53 +74,24 @@ void LocalWorld::commitChunk(std::shared_ptr<Chunk> c) {
activeDimension->setChunk(std::move(c));
}
LocalDimension& LocalWorld::createDimension(const std::string &identifier) {
this->dimensions.emplace_back(std::make_shared<LocalDimension>(static_cast<LocalSubgame&>(game), *this, identifier, this->dimensions.size()));
return static_cast<LocalDimension&>(*dimensions[dimensions.size() - 1]);
DimensionPtr LocalWorld::createDimension(const std::string &identifier) {
this->dimensions.emplace_back(std::make_shared<LocalDimension>(game, *this, identifier, this->dimensions.size()));
return dimensions[dimensions.size() - 1];
}
LocalDimension& LocalWorld::getDefaultDimension() {
return static_cast<LocalDimension&>(World::getDefaultDimension());
}
LocalDimension& LocalWorld::getDimension(unsigned int index) {
return static_cast<LocalDimension&>(*dimensions[index]);
}
LocalDimension& LocalWorld::getDimension(const std::string &identifier) {
for (auto& dimension : dimensions)
if (dimension->getIdentifier() == identifier)
return static_cast<LocalDimension&>(*dimension);
throw std::runtime_error("No dimension named " + identifier + " found.");
}
std::shared_ptr<LocalDimension> LocalWorld::getDefaultDimensionPtr() {
for (auto& dimension : dimensions)
if (dimension->getIdentifier() == defaultDimension)
return std::static_pointer_cast<LocalDimension>(dimension);
throw std::runtime_error("No default dimension set.");
}
std::shared_ptr<LocalDimension> LocalWorld::getDimensionPtr(const std::string &identifier) {
for (auto& dimension : dimensions)
if (dimension->getIdentifier() == identifier)
return std::static_pointer_cast<LocalDimension>(dimension);
throw std::runtime_error("No dimension named " + identifier + " found.");
DimensionPtr LocalWorld::getActiveDimension() {
return activeDimension;
}
ClientNetworkInterpreter& LocalWorld::getNet() {
return net;
}
LocalDimension& LocalWorld::getActiveDimension() {
return *activeDimension;
}
std::shared_ptr<LocalPlayer> LocalWorld::getPlayer() {
PlayerPtr LocalWorld::getPlayer() {
return player;
}
std::shared_ptr<LocalInventoryRefs> LocalWorld::getRefs() {
InventoryRefsPtr LocalWorld::getRefs() {
return refs;
}
@ -130,7 +101,7 @@ int LocalWorld::renderChunks(Renderer &renderer) {
void LocalWorld::renderEntities(Renderer &renderer) {
activeDimension->renderEntities(renderer);
player->draw(renderer);
player.l()->draw(renderer);
}
//void LocalWorld::updateBlockDamages(double delta) {

View File

@ -18,7 +18,7 @@ class WorldInterpolationStream;
class LocalWorld : public World {
public:
LocalWorld(LocalSubgame& game, ServerConnection& conn, Renderer& window);
LocalWorld(SubgamePtr game, ServerConnection& conn, Renderer& window);
void connect();
bool initPlayer();
@ -28,20 +28,13 @@ public:
void handlePlayerEntPacket(std::unique_ptr<PacketView> p);
void commitChunk(std::shared_ptr<Chunk> chunk);
virtual LocalDimension& createDimension(const std::string& identifier) override;
virtual DimensionPtr createDimension(const std::string& identifier) override;
virtual LocalDimension& getDefaultDimension() override;
virtual LocalDimension& getDimension(unsigned int index) override;
virtual LocalDimension& getDimension(const std::string& identifier) override;
std::shared_ptr<LocalDimension> getDefaultDimensionPtr();
std::shared_ptr<LocalDimension> getDimensionPtr(const std::string& identifier);
DimensionPtr getActiveDimension();
PlayerPtr getPlayer();
virtual InventoryRefsPtr getRefs() override;
ClientNetworkInterpreter& getNet();
LocalDimension& getActiveDimension();
std::shared_ptr<LocalPlayer> getPlayer();
std::shared_ptr<LocalInventoryRefs> getRefs();
int renderChunks(Renderer &render);
void renderEntities(Renderer &renderer);
@ -53,7 +46,7 @@ private:
ClientNetworkInterpreter net;
std::shared_ptr<LocalInventoryRefs> refs;
std::shared_ptr<LocalPlayer> player = nullptr;
PlayerPtr player {};
std::shared_ptr<LocalDimension> activeDimension = nullptr;

View File

@ -11,8 +11,7 @@
#include "../../../world/chunk/Chunk.h"
#include "../../../world/LocalDimension.h"
MeshGenStream::MeshGenStream(LocalSubgame& game, LocalDimension &dimension) :
game(game),
MeshGenStream::MeshGenStream(SubgamePtr game, LocalDimension &dimension) :
dimension(dimension),
noiseSampler({NoiseSample {16}, NoiseSample {16}, NoiseSample {16}}) {
@ -31,7 +30,7 @@ MeshGenStream::MeshGenStream(LocalSubgame& game, LocalDimension &dimension) :
noiseSampler[2].populate([&](glm::ivec3 pos) { return offsetTurbulence.GetValue(pos.x, pos.y, pos.z + 8); });
threads.reserve(THREADS);
for (int i = 0; i < THREADS; i++) threads.emplace_back(game, noiseSampler);
for (int i = 0; i < THREADS; i++) threads.emplace_back(*game.l(), noiseSampler);
}
std::vector<ChunkMeshDetails*> MeshGenStream::update() {

View File

@ -11,6 +11,7 @@
#include "ChunkMeshDetails.h"
#include "../../../util/Vec.h"
#include "../../../util/CovariantPtr.h"
#include "../../../def/gen/NoiseSample.h"
class Chunk;
@ -23,7 +24,7 @@ public:
static const int THREADS = 4;
static const int THREAD_QUEUE_SIZE = 32;
explicit MeshGenStream(LocalSubgame& game, LocalDimension& dimension);
explicit MeshGenStream(SubgamePtr game, LocalDimension& dimension);
~MeshGenStream();
void queue(glm::ivec3 pos, bool priority = false);
@ -57,7 +58,6 @@ public:
private:
LocalDimension& dimension;
LocalSubgame& game;
std::array<NoiseSample, 3> noiseSampler;
std::deque<glm::ivec3> queuedTasks;

View File

@ -86,4 +86,8 @@ unsigned short Player::getWieldIndex() {
void Player::setWieldIndex(unsigned short index, bool assert) {
wieldIndex = index;
if (assert) assertField(Serializer().append(NetField::WIELD_INDEX).append(index).packet());
}
}
DimensionPtr Player::getDimension() {
return dim;
}

View File

@ -8,6 +8,7 @@
#include <glm/vec3.hpp>
#include "../../entity/Entity.h"
#include "../../../util/CovariantPtr.h"
#include "../../../def/DefinitionAtlas.h"
class World;
@ -24,7 +25,7 @@ public:
ID, POS, VEL, PITCH, YAW, LOOK_OFF, FLYING,
HAND_INV, WIELD_INV, WIELD_INDEX };
Player(Subgame& game, Dimension& dim, unsigned int id = 0) :
Player(SubgamePtr game, DimensionPtr dim, unsigned int id = 0) :
game(game), dim(dim), id(id), lookOffset(0, 1.65, 0) {
collision = {{-0.3, 0, -0.3}, {0.3, 1.8, 0.3}};
}
@ -56,8 +57,8 @@ public:
virtual unsigned short getWieldIndex();
virtual void setWieldIndex(unsigned short index, bool assert = false);
virtual Inventory& getInventory() = 0;
virtual Dimension& getDimension() = 0;
virtual InventoryPtr getInventory() = 0;
DimensionPtr getDimension();
virtual void handleAssertion(Deserializer& d) = 0;
protected:
@ -65,8 +66,8 @@ protected:
unsigned int id = 0;
Subgame& game;
Dimension& dim;
SubgamePtr game;
DimensionPtr dim;
float yaw = 0;
float pitch = 0;

View File

@ -6,13 +6,13 @@
#include "../../../world/Dimension.h"
World::World(Subgame &game) : game(game) {}
World::World(SubgamePtr game) : game(game) {}
void World::update(double delta) {
for (auto& dimension : dimensions) dimension->update(delta);
}
Dimension& World::getDefaultDimension() {
DimensionPtr World::getDefaultDimension() {
if (defaultDimension.empty()) throw std::runtime_error("No default dimension was set.");
return getDimension(defaultDimension);
}
@ -21,22 +21,11 @@ void World::setDefaultDimension(const std::string& defaultDimension) {
this->defaultDimension = defaultDimension;
}
//double World::getBlockDamage(glm::ivec3 pos) const {
// return blockDamages.count(pos) ? blockDamages.at(pos).curr : 0;
//}
//
//double World::setBlockDamage(glm::ivec3 pos, double damage) {
// if (blockDamages.count(pos)) blockDamages[pos].curr = damage;
// else blockDamages.insert({pos, Damage { damage, static_cast<double>(game.getDefs().blockFromId(getBlock(pos)).health)}});
// return getBlockDamage(pos);
//}
//
//void World::updateBlockDamages() {
// for (auto it = blockDamages.begin(); it != blockDamages.end(); ) {
// if (it->second.curr > it->second.max) {
// setBlock(it->first, DefinitionAtlas::AIR);
// it = blockDamages.erase(it);
// }
// else it++;
// }
//}
DimensionPtr World::getDimension(unsigned int index) {
return dimensions[index];
}
DimensionPtr World::getDimension(const std::string &identifier) {
for (auto& dimension : dimensions) if (dimension->getIdentifier() == identifier) return dimension;
throw std::runtime_error("No dimension named " + identifier + " found.");
}

View File

@ -9,6 +9,7 @@
#include <unordered_map>
#include "../../../util/Vec.h"
#include "../../../util/CovariantPtr.h"
class Subgame;
class Dimension;
@ -16,24 +17,22 @@ class Dimension;
class World {
public:
World(const World& o) = delete;
explicit World(Subgame& game);
explicit World(SubgamePtr game);
virtual void update(double delta);
virtual Dimension& createDimension(const std::string& identifier) = 0;
virtual DimensionPtr createDimension(const std::string& identifier) = 0;
virtual Dimension& getDefaultDimension();
virtual DimensionPtr getDefaultDimension();
virtual void setDefaultDimension(const std::string& defaultDimension);
virtual Dimension& getDimension(unsigned int index) = 0;
virtual Dimension& getDimension(const std::string& identifier) = 0;
virtual DimensionPtr getDimension(unsigned int index);
virtual DimensionPtr getDimension(const std::string& identifier);
virtual InventoryRefsPtr getRefs() = 0;
protected:
std::string defaultDimension {};
std::vector<std::shared_ptr<Dimension>> dimensions;
struct Damage { double curr, max; };
std::unordered_map<glm::ivec3, Damage, Vec::ivec3> blockDamages;
Subgame& game;
SubgamePtr game;
};

View File

@ -10,9 +10,9 @@
#include "../../../def/gen/LocalBiomeAtlas.h"
#include "../../../def/LocalDefinitionAtlas.h"
WorldInterpolationStream::WorldInterpolationStream(unsigned int seed, LocalSubgame& game) {
WorldInterpolationStream::WorldInterpolationStream(unsigned int seed, SubgamePtr game) {
threads.reserve(THREADS);
for (int i = 0; i < THREADS; i++) threads.emplace_back(game, seed);
for (int i = 0; i < THREADS; i++) threads.emplace_back(*game.l(), seed);
}
void WorldInterpolationStream::queuePacket(std::unique_ptr<PacketView> p) {

View File

@ -12,6 +12,7 @@
#include "../../../util/Vec.h"
#include "../../../def/gen/MapGen.h"
#include "../../../util/CovariantPtr.h"
class Chunk;
class LocalSubgame;
@ -22,7 +23,7 @@ public:
static const int THREADS = 4;
static const int THREAD_QUEUE_SIZE = 16;
WorldInterpolationStream(unsigned int seed, LocalSubgame& game);
WorldInterpolationStream(unsigned int seed, SubgamePtr game);
// Queue parsing of packet `p`.
void queuePacket(std::unique_ptr<PacketView> p);

View File

@ -17,10 +17,10 @@
#include "usertype/Player.h"
#include "usertype/Inventory.h"
#include "usertype/Dimension.h"
#include "usertype/ItemStack.h"
#include "usertype/InventoryList.h"
#include "usertype/LuaGuiElement.h"
#include "usertype/cItemStack.h"
#include "usertype/cLuaEntity.h"
#include "usertype/cAnimationManager.h"
@ -31,19 +31,19 @@
#include "modules/create_structure.h"
LocalLuaParser::LocalLuaParser(LocalSubgame& game): LuaParser(game), game(game), keybinds(this) {}
LocalLuaParser::LocalLuaParser(LocalSubgame& game): LuaParser(game), keybinds(this) {}
void LocalLuaParser::init(LocalWorld& world, ClientState& state) {
void LocalLuaParser::init(WorldPtr world, ClientState& state) {
lua.open_libraries(sol::lib::base, sol::lib::string, sol::lib::math, sol::lib::table);
loadApi(game, world);
loadApi(world);
handler.executeMods(std::bind(&LocalLuaParser::runFileSandboxed, this, std::placeholders::_1));
state.renderer.window.input.setCallback(std::bind(&LuaKeybindHandler::keybindHandler, &keybinds, std::placeholders::_1, std::placeholders::_2));
registerDefs(game);
registerDefs();
}
void LocalLuaParser::loadPlayer(std::shared_ptr<LocalPlayer> player) {
void LocalLuaParser::loadPlayer(PlayerPtr player) {
core["player"] = Api::Usertype::LocalPlayer(player);
}
@ -60,7 +60,7 @@ LocalModHandler& LocalLuaParser::getHandler() {
return handler;
}
void LocalLuaParser::loadApi(LocalSubgame &defs, LocalWorld &world) {
void LocalLuaParser::loadApi(WorldPtr world) {
//Create Zepha Table
core = lua.create_table();
lua["zepha"] = core;
@ -69,12 +69,12 @@ void LocalLuaParser::loadApi(LocalSubgame &defs, LocalWorld &world) {
// Types
ClientApi::entity (lua);
ClientApi::animation_manager (lua);
ClientApi::item_stack (lua);
ClientApi::gui_element (lua);
Api::Usertype::Target::bind(Api::State::CLIENT, lua, core);
Api::Usertype::Dimension::bind(Api::State::CLIENT, lua, core);
Api::Usertype::Inventory::bind(Api::State::CLIENT, lua, core);
Api::Usertype::Dimension::bind(Api::State::CLIENT, lua, core);
Api::Usertype::ItemStack::bind(Api::State::CLIENT, lua, core);
Api::Usertype::LocalPlayer::bind(Api::State::CLIENT, lua, core);
Api::Usertype::InventoryList::bind(Api::State::CLIENT, lua, core);
@ -82,8 +82,8 @@ void LocalLuaParser::loadApi(LocalSubgame &defs, LocalWorld &world) {
// Modules
modules.emplace_back(std::make_unique<Api::Module::Time>(Api::State::CLIENT, lua, core));
modules.emplace_back(std::make_unique<Api::Module::Register>(Api::State::CLIENT, core, game, world));
modules.emplace_back(std::make_unique<Api::Module::Dimension>(Api::State::CLIENT, core, game, world));
modules.emplace_back(std::make_unique<Api::Module::Register>(Api::State::CLIENT, core, game, *world.l()));
modules.emplace_back(std::make_unique<Api::Module::Dimension>(Api::State::CLIENT, core, game, *world.l()));
bindModules();
@ -94,10 +94,11 @@ void LocalLuaParser::loadApi(LocalSubgame &defs, LocalWorld &world) {
lua.set_function("runfile", &LocalLuaParser::runFileSandboxed, this);
}
void LocalLuaParser::registerDefs(LocalSubgame &defs) {
RegisterBlocks ::client(core, defs);
RegisterItems ::client(core, defs);
RegisterBiomes ::client(core, defs);
void LocalLuaParser::registerDefs() {
auto& local = static_cast<LocalSubgame&>(game);
RegisterBlocks ::client(core, local);
RegisterItems ::client(core, local);
RegisterBiomes ::client(core, local);
RegisterKeybinds::client(core, keybinds);
}

View File

@ -8,6 +8,7 @@
#include "LocalModHandler.h"
#include "LuaKeybindHandler.h"
#include "../util/CovariantPtr.h"
class LocalPlayer;
class LocalWorld;
@ -17,21 +18,19 @@ class LocalSubgame;
class LocalLuaParser : public LuaParser {
public:
explicit LocalLuaParser(LocalSubgame& game);
void init(LocalWorld& world, ClientState& state);
void loadPlayer(std::shared_ptr<LocalPlayer> player);
void init(WorldPtr world, ClientState& state);
void loadPlayer(PlayerPtr player);
void update(double delta);
void update(double delta) override;
LocalModHandler& getHandler();
private:
void loadApi(LocalSubgame &defs, LocalWorld &world);
void registerDefs(LocalSubgame &defs);
void loadApi(WorldPtr world);
void registerDefs();
virtual sol::protected_function_result errorCallback(sol::protected_function_result r) const override;
sol::protected_function_result runFileSandboxed(const std::string& file);
LocalSubgame& game;
LuaKeybindHandler keybinds;
LocalModHandler handler;
double delta = 0;

View File

@ -12,6 +12,7 @@
#include "modules/SubgameModule.h"
#include "Lua.h"
#include "../util/CovariantPtr.h"
class Subgame;

View File

@ -20,10 +20,10 @@
#include "usertype/Player.h"
#include "usertype/Inventory.h"
#include "usertype/Dimension.h"
#include "usertype/ItemStack.h"
#include "usertype/InventoryList.h"
#include "usertype/sLuaEntity.h"
#include "usertype/cItemStack.h"
// Modules
#include "modules/Time.h"
@ -32,16 +32,16 @@
#include "modules/create_structure.h"
ServerLuaParser::ServerLuaParser(ServerSubgame& game) : LuaParser(game), game(game) {}
ServerLuaParser::ServerLuaParser(ServerSubgame& game) : LuaParser(game) {}
void ServerLuaParser::init(ServerWorld& world, const std::string& path) {
void ServerLuaParser::init(WorldPtr world, const std::string& path) {
lua.open_libraries(sol::lib::base, sol::lib::string, sol::lib::math, sol::lib::table);
loadApi(game, world);
handler.loadMods(game, path + "mods");
loadApi(world);
handler.loadMods(static_cast<ServerSubgame&>(game), path + "mods");
handler.executeMods(std::bind(&ServerLuaParser::runFileSandboxed, this, std::placeholders::_1));
registerDefs(game);
registerDefs();
std::cout << Log::info << "Loaded " << handler.cGetMods().size() << " mods: [ ";
for (unsigned int i = 0; i < handler.cGetMods().size(); i++)
@ -88,7 +88,7 @@ void ServerLuaParser::playerDisconnected(std::shared_ptr<ServerPlayer> player) {
}
}
void ServerLuaParser::loadApi(ServerSubgame &defs, ServerWorld &world) {
void ServerLuaParser::loadApi(WorldPtr world) {
//Create Zepha Table
core = lua.create_table();
lua["zepha"] = core;
@ -96,11 +96,11 @@ void ServerLuaParser::loadApi(ServerSubgame &defs, ServerWorld &world) {
// Types
ServerApi::entity (lua);
ClientApi::item_stack (lua);
Api::Usertype::Target::bind(Api::State::SERVER, lua, core);
Api::Usertype::Dimension::bind(Api::State::SERVER, lua, core);
Api::Usertype::Inventory::bind(Api::State::SERVER, lua, core);
Api::Usertype::Dimension::bind(Api::State::SERVER, lua, core);
Api::Usertype::ItemStack::bind(Api::State::SERVER, lua, core);
Api::Usertype::ServerPlayer::bind(Api::State::SERVER, lua, core);
Api::Usertype::InventoryList::bind(Api::State::SERVER, lua, core);
@ -109,8 +109,8 @@ void ServerLuaParser::loadApi(ServerSubgame &defs, ServerWorld &world) {
// Modules
modules.emplace_back(std::make_unique<Api::Module::Time>(Api::State::SERVER, lua, core));
modules.emplace_back(std::make_unique<Api::Module::Register>(Api::State::SERVER, core, game, world));
modules.emplace_back(std::make_unique<Api::Module::Dimension>(Api::State::SERVER, core, game, world));
modules.emplace_back(std::make_unique<Api::Module::Register>(Api::State::SERVER, core, game, *world.s()));
modules.emplace_back(std::make_unique<Api::Module::Dimension>(Api::State::SERVER, core, game, *world.s()));
Api::create_structure (lua, core);
@ -121,10 +121,11 @@ void ServerLuaParser::loadApi(ServerSubgame &defs, ServerWorld &world) {
lua.set_function("runfile", &ServerLuaParser::runFileSandboxed, this);
}
void ServerLuaParser::registerDefs(ServerSubgame &defs) {
RegisterBlocks::server(core, defs);
RegisterItems ::server(core, defs);
RegisterBiomes::server(core, defs);
void ServerLuaParser::registerDefs() {
auto& server = static_cast<ServerSubgame&>(game);
RegisterBlocks::server(core, server);
RegisterItems ::server(core, server);
RegisterBiomes::server(core, server);
}
sol::protected_function_result ServerLuaParser::errorCallback(sol::protected_function_result r) const {

View File

@ -17,7 +17,7 @@ class ServerPlayer;
class ServerLuaParser : public LuaParser {
public:
explicit ServerLuaParser(ServerSubgame& game);
void init(ServerWorld& world, const std::string& rootPath);
void init(WorldPtr world, const std::string& rootPath);
virtual void update(double delta) override;
@ -27,14 +27,12 @@ public:
void playerDisconnected(std::shared_ptr<ServerPlayer> client);
private:
void loadApi(ServerSubgame& defs, ServerWorld& world);
void registerDefs(ServerSubgame &defs);
void loadApi(WorldPtr world);
void registerDefs();
virtual sol::protected_function_result errorCallback(sol::protected_function_result r) const override;
sol::protected_function_result runFileSandboxed(const std::string& file);
ServerSubgame& game;
ServerModHandler handler;
double delta = 0;
};

View File

@ -25,15 +25,9 @@ void Api::Module::Dimension::setDefaultDimension(const std::string& identifier)
}
sol::object Api::Module::Dimension::getDefaultDimension(const sol::this_state s) {
std::shared_ptr<::Dimension> dim = state == State::CLIENT ?
std::static_pointer_cast<::Dimension>(static_cast<LocalWorld&>(world).getDefaultDimensionPtr()) :
std::static_pointer_cast<::Dimension>(static_cast<ServerWorld&>(world).getDefaultDimensionPtr());
return sol::make_object(s, Api::Usertype::Dimension(dim));
return sol::make_object(s, Api::Usertype::Dimension(world.getDefaultDimension()));
}
sol::object Api::Module::Dimension::getDimension(sol::this_state s, const std::string& identifier) {
std::shared_ptr<::Dimension> dim = state == State::CLIENT ?
std::static_pointer_cast<::Dimension>(static_cast<LocalWorld&>(world).getDimensionPtr(identifier)) :
std::static_pointer_cast<::Dimension>(static_cast<ServerWorld&>(world).getDimensionPtr(identifier));
return sol::make_object(s, Api::Usertype::Dimension(dim));
return sol::make_object(s, Api::Usertype::Dimension(world.getDimension(identifier)));
}

View File

@ -16,35 +16,35 @@
#include "../../world/ServerDimension.h"
std::string Api::Usertype::Dimension::get_block(glm::ivec3 pos) {
return dimension->getGame().getDefs().fromId(dimension->getBlock(pos)).identifier;
return dim->getGame()->getDefs().fromId(dim->getBlock(pos)).identifier;
}
void Api::Usertype::Dimension::set_block(glm::ivec3 pos, const std::string &block) {
dimension->setBlock(pos, dimension->getGame().getDefs().fromStr(block).index);
dim->setBlock(pos, dim->getGame()->getDefs().fromStr(block).index);
}
void Api::Usertype::Dimension::remove_block(glm::ivec3 pos) {
dimension->setBlock(pos, DefinitionAtlas::AIR);
dim->setBlock(pos, DefinitionAtlas::AIR);
}
double Api::Usertype::Dimension::get_block_damage(glm::ivec3 pos) {
return dimension->getBlockDamage(pos);
return dim->getBlockDamage(pos);
}
double Api::Usertype::Dimension::set_block_damage(glm::ivec3 pos, double damage) {
return dimension->setBlockDamage(pos, damage);
return dim->setBlockDamage(pos, damage);
}
double Api::Usertype::Dimension::add_block_damage(glm::ivec3 pos, double damage) {
return dimension->setBlockDamage(pos, dimension->getBlockDamage(pos) + damage);
return dim->setBlockDamage(pos, dim->getBlockDamage(pos) + damage);
}
std::string Api::Usertype::Dimension::get_biome(glm::ivec3 pos) {
return dimension->getGame().getBiomes().biomeFromId(dimension->getBiome(pos)).identifier;
return dim->getGame()->getBiomes().biomeFromId(dim->getBiome(pos)).identifier;
}
void Api::Usertype::Dimension::set_biome(glm::ivec3 pos, const std::string &biome) {
dimension->setBiome(pos, dimension->getGame().getBiomes().biomeFromStr(biome).index);
dim->setBiome(pos, dim->getGame()->getBiomes().biomeFromStr(biome).index);
}
sol::table Api::Usertype::Dimension::add_entity_c(sol::this_state s, glm::vec3 pos,
@ -70,7 +70,7 @@ sol::table Api::Usertype::Dimension::add_entity_c(sol::this_state s, glm::vec3 p
auto entity = std::make_unique<::DrawableEntity>();
entity->setPos(pos);
auto ref = std::make_shared<LocalLuaEntity>(std::move(entity), dimension->nextEntityInd(), static_cast<LocalSubgame&>(dimension->getGame()));
auto ref = std::make_shared<LocalLuaEntity>(std::move(entity), dim->nextEntityInd(), dim->getGame().l());
luaEntity["object"] = ref;
ref->set_display_type(*displayType, *displayObject, displayTexture);
@ -79,7 +79,7 @@ sol::table Api::Usertype::Dimension::add_entity_c(sol::this_state s, glm::vec3 p
auto on_create = def.get<sol::optional<sol::protected_function>>("on_create");
if (on_create) (*on_create)(luaEntity, staticData);
std::static_pointer_cast<LocalDimension>(dimension)->addLocalEntity(ref);
dim.l()->addLocalEntity(ref);
return luaEntity;
}
@ -104,10 +104,10 @@ sol::table Api::Usertype::Dimension::add_entity_s(sol::this_state s, glm::vec3 p
auto displayTexture = luaEntity.get<sol::optional<std::string>>("display_texture");
if (strncmp(displayType->data(), "model", 5) == 0 && !displayTexture) throw std::runtime_error("entity '" + identifier + "' is missing the display_texture property.");
unsigned int ind = dimension->nextEntityInd();
unsigned int ind = dim->nextEntityInd();
auto entity = std::make_unique<ServerEntity>(ind);
entity->setPos(pos);
auto ref = std::make_shared<ServerLuaEntity>(std::move(entity), ind, static_cast<ServerSubgame&>(dimension->getGame()));
auto ref = std::make_shared<ServerLuaEntity>(std::move(entity), ind, dim->getGame());
luaEntity["object"] = ref;
ref->set_display_type(*displayType, *displayObject, displayTexture);
@ -116,7 +116,7 @@ sol::table Api::Usertype::Dimension::add_entity_s(sol::this_state s, glm::vec3 p
auto on_create = def.get<sol::optional<sol::protected_function>>("on_create");
if (on_create) (*on_create)(luaEntity, staticData);
std::static_pointer_cast<ServerDimension>(dimension)->addLuaEntity(ref);
dim.s()->addLuaEntity(ref);
return luaEntity;
}
@ -134,7 +134,7 @@ void Api::Usertype::Dimension::remove_entity_c(sol::this_state s, sol::table ent
if (onDestroy) (*onDestroy)();
core["entities"][(*object)->id] = sol::nil;
std::static_pointer_cast<LocalDimension>(dimension)->removeLocalEntity(*object);
dim.l()->removeLocalEntity(*object);
}
void Api::Usertype::Dimension::remove_entity_s(sol::this_state s, sol::table entity) {
@ -151,7 +151,7 @@ void Api::Usertype::Dimension::remove_entity_s(sol::this_state s, sol::table ent
if (onDestroy) (*onDestroy)();
core["entities"][(*object)->id] = sol::nil;
std::static_pointer_cast<ServerDimension>(dimension)->removeLuaEntity(*object);
dim.s()->removeLuaEntity(*object);
}
void Api::Usertype::Dimension::bind(State state, sol::state &lua, sol::table &core) {

View File

@ -8,15 +8,16 @@
#include <glm/vec3.hpp>
#include "SubgameUsertype.h"
#include "../../util/CovariantPtr.h"
class Dimension;
namespace Api::Usertype {
class Dimension : public SubgameUsertype {
public:
Dimension(std::shared_ptr<::Dimension> dimension) : dimension(dimension) {}
Dimension(DimensionPtr dim) : dim(dim) {}
std::shared_ptr<::Dimension> dimension;
DimensionPtr dim;
std::string get_block(glm::ivec3 pos);
void set_block(glm::ivec3 pos, const std::string& block);

View File

@ -10,17 +10,17 @@
sol::object Api::Usertype::Inventory::add_list(sol::this_state s, std::string name, int size, int width) {
inventory.createList(name, size, width);
return sol::make_object<InventoryList>(s, InventoryList(inventory.getListPtr(name)));
inventory->createList(name, size, width);
return sol::make_object<InventoryList>(s, InventoryList(inventory->getList(name)));
}
sol::object Api::Usertype::Inventory::get_list(sol::this_state s, std::string name) {
if (!inventory.hasList(name)) return sol::nil;
return sol::make_object<InventoryList>(s, InventoryList(inventory.getListPtr(name)));
if (!inventory->hasList(name)) return sol::nil;
return sol::make_object<InventoryList>(s, InventoryList(inventory->getList(name)));
}
void Api::Usertype::Inventory::remove_list(std::string name) {
inventory.removeList(name);
inventory->removeList(name);
}
void Api::Usertype::Inventory::set_default_list(sol::object list) {

View File

@ -8,14 +8,14 @@
#include "SubgameUsertype.h"
class Inventory;
#include "../../util/CovariantPtr.h"
namespace Api::Usertype {
class Inventory : public SubgameUsertype {
public:
Inventory(::Inventory& inventory) : inventory(inventory) {}
Inventory(InventoryPtr inventory) : inventory(inventory) {}
::Inventory& inventory;
InventoryPtr inventory;
sol::object add_list(sol::this_state s, std::string name, int size, int width);
sol::object get_list(sol::this_state s, std::string name);

View File

@ -33,63 +33,63 @@ std::string Api::Usertype::InventoryList::get_name() {
return list->getName();
}
LuaItemStack Api::Usertype::InventoryList::get_stack(unsigned short i) {
Api::Usertype::ItemStack Api::Usertype::InventoryList::get_stack(unsigned short i) {
if (i < 1 || i > list->getLength()) throw "index is outside of list bounds.";
return LuaItemStack(list->getStack(i - 1), list->getGame());
return ItemStack(list->getStack(i - 1), list->getGame());
}
void Api::Usertype::InventoryList::set_stack(unsigned short i, LuaItemStack stack) {
void Api::Usertype::InventoryList::set_stack(unsigned short i, ItemStack stack) {
if (i < 1 || i > list->getLength()) throw "index is outside of list bounds.";
list->setStack(i - 1, ItemStack(stack, list->getGame()));
list->setStack(i - 1, ::ItemStack(stack, list->getGame()));
}
void Api::Usertype::InventoryList::set_stack(unsigned short i, sol::table stack) {
if (i < 1 || i > list->getLength()) throw "index is outside of list bounds.";
list->setStack(i - 1, ItemStack(list->getGame().getDefs().fromStr(stack[1]).index, stack[2]));
list->setStack(i - 1, ::ItemStack(list->getGame()->getDefs().fromStr(stack[1]).index, stack[2]));
}
LuaItemStack Api::Usertype::InventoryList::place_stack(unsigned short i, LuaItemStack stack) {
Api::Usertype::ItemStack Api::Usertype::InventoryList::place_stack(unsigned short i, ItemStack stack) {
if (i < 1 || i > list->getLength()) throw "index is outside of list bounds.";
return LuaItemStack(list->placeStack(i - 1, ItemStack(stack, list->getGame())), list->getGame());
return ItemStack(list->placeStack(i - 1, ::ItemStack(stack, list->getGame())), list->getGame());
}
LuaItemStack Api::Usertype::InventoryList::place_stack(unsigned short i, sol::table stack) {
Api::Usertype::ItemStack Api::Usertype::InventoryList::place_stack(unsigned short i, sol::table stack) {
if (i < 1 || i > list->getLength()) throw "index is outside of list bounds.";
return LuaItemStack(list->placeStack(i - 1, ItemStack(list->getGame().getDefs().fromStr(stack[1]).index, stack[2])), list->getGame());
return ItemStack(list->placeStack(i - 1, ::ItemStack(list->getGame()->getDefs().fromStr(stack[1]).index, stack[2])), list->getGame());
}
LuaItemStack Api::Usertype::InventoryList::split_stack(unsigned short i) {
Api::Usertype::ItemStack Api::Usertype::InventoryList::split_stack(unsigned short i) {
if (i < 1 || i > list->getLength()) throw "index is outside of list bounds.";
return LuaItemStack(list->splitStack(i - 1), list->getGame());
return ItemStack(list->splitStack(i - 1), list->getGame());
}
LuaItemStack Api::Usertype::InventoryList::add_stack(LuaItemStack stack) {
return LuaItemStack(list->addStack(ItemStack(stack, list->getGame())), list->getGame());
Api::Usertype::ItemStack Api::Usertype::InventoryList::add_stack(ItemStack stack) {
return ItemStack(list->addStack(::ItemStack(stack, list->getGame())), list->getGame());
}
LuaItemStack Api::Usertype::InventoryList::add_stack(sol::table stack) {
return LuaItemStack(list->addStack(ItemStack(list->getGame().getDefs().fromStr(stack[1]).index, stack[2])), list->getGame());
Api::Usertype::ItemStack Api::Usertype::InventoryList::add_stack(sol::table stack) {
return ItemStack(list->addStack(::ItemStack(list->getGame()->getDefs().fromStr(stack[1]).index, stack[2])), list->getGame());
}
int Api::Usertype::InventoryList::stack_fits(LuaItemStack stack) {
return list->stackFits(ItemStack(stack, list->getGame()));
int Api::Usertype::InventoryList::stack_fits(ItemStack stack) {
return list->stackFits(::ItemStack(stack, list->getGame()));
}
int Api::Usertype::InventoryList::stack_fits(sol::table stack) {
return list->stackFits(ItemStack(list->getGame().getDefs().fromStr(stack[1]).index, stack[2]));
return list->stackFits(::ItemStack(list->getGame()->getDefs().fromStr(stack[1]).index, stack[2]));
}
LuaItemStack Api::Usertype::InventoryList::take_stack(LuaItemStack request) {
return LuaItemStack(list->takeStack(ItemStack(request, list->getGame())), list->getGame());
Api::Usertype::ItemStack Api::Usertype::InventoryList::take_stack(ItemStack request) {
return ItemStack(list->takeStack(::ItemStack(request, list->getGame())), list->getGame());
}
LuaItemStack Api::Usertype::InventoryList::take_stack(sol::table request) {
return LuaItemStack(list->takeStack(ItemStack(list->getGame().getDefs().fromStr(request[1]).index, request[2])), list->getGame());
Api::Usertype::ItemStack Api::Usertype::InventoryList::take_stack(sol::table request) {
return ItemStack(list->takeStack(::ItemStack(list->getGame()->getDefs().fromStr(request[1]).index, request[2])), list->getGame());
}
LuaItemStack Api::Usertype::InventoryList::remove_stack(unsigned short i, unsigned short count) {
Api::Usertype::ItemStack Api::Usertype::InventoryList::remove_stack(unsigned short i, unsigned short count) {
if (i < 1 || i > list->getLength()) throw "index is outside of list bounds.";
return LuaItemStack(list->removeStack(i - 1, count), list->getGame());
return ItemStack(list->removeStack(i - 1, count), list->getGame());
}
//void LuaInventoryList::set_callback(ServerInventoryList::Callback t, sol::safe_function fun) {
@ -110,21 +110,21 @@ void Api::Usertype::InventoryList::bind(State state, sol::state &lua, sol::table
"get_stack", &InventoryList::get_stack,
"set_stack", sol::overload(
sol::resolve<void(unsigned short, LuaItemStack)>(&InventoryList::set_stack),
sol::resolve<void(unsigned short, ItemStack)>(&InventoryList::set_stack),
sol::resolve<void(unsigned short, sol::table)>(&InventoryList::set_stack)),
"place_stack", sol::overload(
sol::resolve<LuaItemStack(unsigned short, LuaItemStack)>(&InventoryList::place_stack),
sol::resolve<LuaItemStack(unsigned short, sol::table)>(&InventoryList::place_stack)),
sol::resolve<ItemStack(unsigned short, ItemStack)>(&InventoryList::place_stack),
sol::resolve<ItemStack(unsigned short, sol::table)>(&InventoryList::place_stack)),
"split_stack", &InventoryList::split_stack,
"add_stack", sol::overload(
sol::resolve<LuaItemStack(LuaItemStack)>(&InventoryList::add_stack),
sol::resolve<LuaItemStack(sol::table)>(&InventoryList::add_stack)),
sol::resolve<ItemStack(ItemStack)>(&InventoryList::add_stack),
sol::resolve<ItemStack(sol::table)>(&InventoryList::add_stack)),
"stack_fits", sol::overload(
sol::resolve<int(LuaItemStack)>(&InventoryList::stack_fits),
sol::resolve<int(ItemStack)>(&InventoryList::stack_fits),
sol::resolve<int(sol::table)>(&InventoryList::stack_fits)),
"take_stack", sol::overload(
sol::resolve<LuaItemStack(LuaItemStack)>(&InventoryList::take_stack),
sol::resolve<LuaItemStack(sol::table)>(&InventoryList::take_stack)),
sol::resolve<ItemStack(ItemStack)>(&InventoryList::take_stack),
sol::resolve<ItemStack(sol::table)>(&InventoryList::take_stack)),
"remove_stack", &InventoryList::remove_stack
);
else lua.new_usertype<InventoryList>("InventoryListRef",
@ -134,21 +134,21 @@ void Api::Usertype::InventoryList::bind(State state, sol::state &lua, sol::table
"get_stack", &InventoryList::get_stack,
"set_stack", sol::overload(
sol::resolve<void(unsigned short, LuaItemStack)>(&InventoryList::set_stack),
sol::resolve<void(unsigned short, ItemStack)>(&InventoryList::set_stack),
sol::resolve<void(unsigned short, sol::table)>(&InventoryList::set_stack)),
"place_stack", sol::overload(
sol::resolve<LuaItemStack(unsigned short, LuaItemStack)>(&InventoryList::place_stack),
sol::resolve<LuaItemStack(unsigned short, sol::table)>(&InventoryList::place_stack)),
sol::resolve<ItemStack(unsigned short, ItemStack)>(&InventoryList::place_stack),
sol::resolve<ItemStack(unsigned short, sol::table)>(&InventoryList::place_stack)),
"split_stack", &InventoryList::split_stack,
"add_stack", sol::overload(
sol::resolve<LuaItemStack(LuaItemStack)>(&InventoryList::add_stack),
sol::resolve<LuaItemStack(sol::table)>(&InventoryList::add_stack)),
sol::resolve<ItemStack(ItemStack)>(&InventoryList::add_stack),
sol::resolve<ItemStack(sol::table)>(&InventoryList::add_stack)),
"stack_fits", sol::overload(
sol::resolve<int(LuaItemStack)>(&InventoryList::stack_fits),
sol::resolve<int(ItemStack)>(&InventoryList::stack_fits),
sol::resolve<int(sol::table)>(&InventoryList::stack_fits)),
"take_stack", sol::overload(
sol::resolve<LuaItemStack(LuaItemStack)>(&InventoryList::take_stack),
sol::resolve<LuaItemStack(sol::table)>(&InventoryList::take_stack)),
sol::resolve<ItemStack(ItemStack)>(&InventoryList::take_stack),
sol::resolve<ItemStack(sol::table)>(&InventoryList::take_stack)),
"remove_stack", &InventoryList::remove_stack
);
}

View File

@ -8,16 +8,15 @@
#include "SubgameUsertype.h"
#include "LuaItemStack.h"
class InventoryList;
#include "ItemStack.h"
#include "../../util/CovariantPtr.h"
namespace Api::Usertype {
class InventoryList : public SubgameUsertype {
public:
InventoryList(std::shared_ptr<::InventoryList> list) : list(list) {}
InventoryList(InventoryListPtr list) : list(list) {}
std::shared_ptr<::InventoryList> list;
InventoryListPtr list;
void set_length(int length);
int get_length();
@ -29,26 +28,26 @@ namespace Api::Usertype {
std::string get_name();
LuaItemStack get_stack(unsigned short i);
ItemStack get_stack(unsigned short i);
void set_stack(unsigned short i, LuaItemStack stack);
void set_stack(unsigned short i, ItemStack stack);
void set_stack(unsigned short i, sol::table stack);
LuaItemStack place_stack(unsigned short i, LuaItemStack stack);
LuaItemStack place_stack(unsigned short i, sol::table stack);
ItemStack place_stack(unsigned short i, ItemStack stack);
ItemStack place_stack(unsigned short i, sol::table stack);
LuaItemStack split_stack(unsigned short i);
ItemStack split_stack(unsigned short i);
LuaItemStack add_stack(LuaItemStack stack);
LuaItemStack add_stack(sol::table stack);
ItemStack add_stack(ItemStack stack);
ItemStack add_stack(sol::table stack);
int stack_fits(LuaItemStack stack);
int stack_fits(ItemStack stack);
int stack_fits(sol::table stack);
LuaItemStack take_stack(LuaItemStack request);
LuaItemStack take_stack(sol::table request);
ItemStack take_stack(ItemStack request);
ItemStack take_stack(sol::table request);
LuaItemStack remove_stack(unsigned short ind, unsigned short count);
ItemStack remove_stack(unsigned short ind, unsigned short count);
// void set_callback(ServerInventoryList::Callback t, sol::safe_function fun);
// sol::safe_function get_callback(ServerInventoryList::Callback t);

View File

@ -0,0 +1,52 @@
//
// Created by aurailus on 2019-12-17.
//
#include "ItemStack.h"
#include "../Lua.h"
#include "../../def/ItemDef.h"
#include "../../def/Subgame.h"
#include "../../def/DefinitionAtlas.h"
#include "../../game/inventory/ItemStack.h"
Api::Usertype::ItemStack::ItemStack(const ::ItemStack& stack, SubgamePtr game) :
name((stack.count == 0 ? "" : game->getDefs().fromId(stack.id).identifier)),
count(stack.count) {}
Api::Usertype::ItemStack::ItemStack(const std::string& name, unsigned short count) :
name(name), count(count) {}
Api::Usertype::ItemStack::ItemStack(sol::table tbl) :
name(tbl.get<std::string>(1)), count(tbl.get<unsigned short>(2)) {}
std::string Api::Usertype::ItemStack::get_name() {
return name;
}
void Api::Usertype::ItemStack::set_name(std::string name) {
this->name = name;
}
int Api::Usertype::ItemStack::get_count() {
return count;
}
void Api::Usertype::ItemStack::set_count(int count) {
this->count = count;
}
bool Api::Usertype::ItemStack::is_empty() {
return count == 0;
}
void Api::Usertype::ItemStack::bind(State state, sol::state &lua, sol::table &core) {
lua.new_usertype<ItemStack>("ItemStack",
sol::constructors<ItemStack(sol::table), ItemStack(std::string, unsigned short)>(),
"name", sol::property(&ItemStack::get_name, &ItemStack::set_name),
"count", sol::property(&ItemStack::get_count, &ItemStack::set_count),
"is_empty", &ItemStack::is_empty
);
}

View File

@ -0,0 +1,38 @@
//
// Created by aurailus on 2019-12-17.
//
#pragma once
#include <string>
#include <sol/forward.hpp>
#include "SubgameUsertype.h"
#include "../../util/CovariantPtr.h"
class Subgame;
class ItemStack;
namespace Api::Usertype {
class ItemStack : SubgameUsertype {
public:
ItemStack() = default;
explicit ItemStack(sol::table tbl);
ItemStack(const ::ItemStack& stack, SubgamePtr game);
ItemStack(const std::string& name, unsigned short count);
std::string get_name();
void set_name(std::string name);
int get_count();
void set_count(int count);
bool is_empty();
static void bind(State state, sol::state &lua, sol::table &core);
private:
std::string name;
unsigned short count;
};
}

View File

@ -85,7 +85,7 @@ float LocalLuaEntity::get_scale() {
void LocalLuaEntity::set_display_type(const std::string &type, const std::string &arg, sol::optional<std::string> arg2) {
if (strncmp(type.data(), "gameobject", 10) == 0) {
ItemDef& def = defs.getDefs().fromStr(arg);
ItemDef& def = game->getDefs().fromStr(arg);
if (def.type == ItemDef::Type::BLOCK)
entity->setModel(static_cast<BlockDef&>(def).entityModel);
@ -94,7 +94,7 @@ void LocalLuaEntity::set_display_type(const std::string &type, const std::string
}
else if (strncmp(type.data(), "model", 5) == 0 && arg2 && !arg2->empty()) {
auto model = std::make_shared<Model>();
model->fromSerialized(defs.models.models[arg], {defs.textures[*arg2]});
model->fromSerialized(game.l()->models.models[arg], {game.l()->textures[*arg2]});
entity->setModel(model);
}
}

View File

@ -5,6 +5,7 @@
#pragma once
#include "../Lua.h"
#include "../../util/CovariantPtr.h"
#include "LocalLuaAnimationManager.h"
#include "../../game/entity/DrawableEntity.h"
@ -12,12 +13,12 @@ class LocalSubgame;
class LocalLuaEntity {
public:
LocalLuaEntity(std::unique_ptr<DrawableEntity> entity, unsigned int id, LocalSubgame& defs) :
entity(std::move(entity)), id(id), defs(defs), manager(*this->entity) {}
LocalLuaEntity(std::unique_ptr<DrawableEntity> entity, unsigned int id, SubgamePtr game) :
entity(std::move(entity)), id(id), game(game), manager(*this->entity) {}
std::unique_ptr<DrawableEntity> entity = nullptr;
unsigned int id;
LocalSubgame& defs;
SubgamePtr game;
LocalLuaAnimationManager manager;

View File

@ -1,41 +0,0 @@
//
// Created by aurailus on 2019-12-17.
//
#include "LuaItemStack.h"
#include "../Lua.h"
#include "../../def/ItemDef.h"
#include "../../def/Subgame.h"
#include "../../def/DefinitionAtlas.h"
#include "../../game/inventory/ItemStack.h"
LuaItemStack::LuaItemStack(const ItemStack &stack, Subgame& game) :
name((stack.count == 0 ? "" : game.getDefs().fromId(stack.id).identifier)),
count(stack.count) {}
LuaItemStack::LuaItemStack(const std::string& name, unsigned short count) :
name(name), count(count) {}
LuaItemStack::LuaItemStack(sol::table tbl) :
name(tbl.get<std::string>(1)), count(tbl.get<unsigned short>(2)) {}
std::string LuaItemStack::get_name() {
return name;
}
void LuaItemStack::set_name(std::string name) {
this->name = name;
}
int LuaItemStack::get_count() {
return count;
}
void LuaItemStack::set_count(int count) {
this->count = count;
}
bool LuaItemStack::is_empty() {
return count == 0;
}

View File

@ -1,30 +0,0 @@
//
// Created by aurailus on 2019-12-17.
//
#pragma once
#include <string>
#include <sol/forward.hpp>
class Subgame;
class ItemStack;
class LuaItemStack {
public:
LuaItemStack() = default;
LuaItemStack(const ItemStack& stack, Subgame& game);
LuaItemStack(const std::string& name, unsigned short count);
LuaItemStack(sol::table tbl);
std::string get_name();
void set_name(std::string name);
int get_count();
void set_count(int count);
bool is_empty();
private:
std::string name;
unsigned short count;
};

View File

@ -6,8 +6,10 @@
#include "Player.h"
#include "LuaItemStack.h"
#include "ItemStack.h"
#include "InventoryList.h"
#include "../../net/server/world/ServerWorld.h"
#include "../../game/scene/world/LocalWorld.h"
#include "../../game/scene/world/LocalPlayer.h"
unsigned int Api::Usertype::ServerPlayer::get_id() {
@ -54,18 +56,20 @@ Api::Usertype::Inventory Api::Usertype::ServerPlayer::get_inventory() {
return Inventory(player->getInventory());
}
Api::Usertype::Dimension Api::Usertype::ServerPlayer::get_dimension() {
return Dimension(player->getDimension());
}
sol::object Api::Usertype::ServerPlayer::get_hand_list(sol::this_state s) {
auto listStr = player->getHandList();
if (listStr.empty()) return sol::nil;
return sol::make_object<InventoryList>(s,
InventoryList(player->getInventory().getListPtr(listStr)));
return sol::make_object<InventoryList>(s, InventoryList(player->getInventory()->getList(listStr)));
}
sol::object Api::Usertype::ServerPlayer::get_hand_stack(sol::this_state s) {
auto listStr = player->getHandList();
if (listStr.empty()) return sol::nil;
return sol::make_object<LuaItemStack>(s,
InventoryList(player->getInventory().getListPtr(listStr)).get_stack(1));
return sol::make_object<ItemStack>(s, InventoryList(player->getInventory()->getList(listStr)).get_stack(1));
}
void Api::Usertype::ServerPlayer::set_hand_list(sol::optional<sol::object> list) {
@ -78,8 +82,7 @@ void Api::Usertype::ServerPlayer::set_hand_list(sol::optional<sol::object> list)
sol::object Api::Usertype::ServerPlayer::get_wield_list(sol::this_state s) {
auto listStr = player->getWieldList();
if (listStr.empty()) return sol::nil;
return sol::make_object<InventoryList>(s,
InventoryList(player->getInventory().getListPtr(listStr)));
return sol::make_object<InventoryList>(s, InventoryList(player->getInventory()->getList(listStr)));
}
void Api::Usertype::ServerPlayer::set_wield_list(sol::optional<sol::object> list) {
@ -100,8 +103,8 @@ void Api::Usertype::ServerPlayer::set_wield_index(unsigned int index) {
sol::object Api::Usertype::ServerPlayer::get_wield_stack(sol::this_state s) {
auto listStr = player->getWieldList();
if (listStr.empty()) return sol::nil;
return sol::make_object<LuaItemStack>(s, InventoryList(player->getInventory()
.getListPtr(listStr)).get_stack(player->getWieldIndex() + 1));
return sol::make_object<ItemStack>(s, InventoryList(player->getInventory()
->getList(listStr)).get_stack(player->getWieldIndex() + 1));
}
void Api::Usertype::ServerPlayer::set_flying(bool shouldFly) {
@ -135,35 +138,37 @@ void Api::Usertype::ServerPlayer::bind(State state, sol::state &lua, sol::table
"set_wield_index", &ServerPlayer::set_wield_index,
"get_wield_stack", &ServerPlayer::get_wield_stack,
"get_dimension", &ServerPlayer::get_dimension,
"pos", sol::property(&ServerPlayer::get_pos, &ServerPlayer::set_pos),
"block_pos", sol::property(&ServerPlayer::get_block_pos, &ServerPlayer::set_pos),
"vel", sol::property(&ServerPlayer::get_vel, &ServerPlayer::set_vel),
"look_yaw", sol::property(&ServerPlayer::get_look_yaw, &ServerPlayer::set_look_yaw),
"look_pitch", sol::property(&ServerPlayer::get_look_pitch, &ServerPlayer::set_look_pitch),
"dim", sol::property(&ServerPlayer::get_dimension),
"flying", sol::property(&ServerPlayer::set_flying, &ServerPlayer::get_flying)
);
}
bool Api::Usertype::LocalPlayer::is_in_menu() {
return std::static_pointer_cast<::LocalPlayer>(player)->isInMenu();
return player.l()->isInMenu();
}
void Api::Usertype::LocalPlayer::show_menu(std::shared_ptr<LuaGuiElement> root) {
return std::static_pointer_cast<::LocalPlayer>(player)->showMenu(root);
return player.l()->showMenu(root);
}
void Api::Usertype::LocalPlayer::close_menu() {
return std::static_pointer_cast<::LocalPlayer>(player)->closeMenu();
return player.l()->closeMenu();
}
std::shared_ptr<LuaGuiElement> Api::Usertype::LocalPlayer::get_hud() {
std::cout << "Getting hud " << std::endl;
return std::static_pointer_cast<::LocalPlayer>(player)->getHud();
return player.l()->getHud();
}
void Api::Usertype::LocalPlayer::set_hud(std::shared_ptr<LuaGuiElement> hud) {
std::static_pointer_cast<::LocalPlayer>(player)->setHud(hud);
player.l()->setHud(hud);
}
void Api::Usertype::LocalPlayer::bind(State state, sol::state &lua, sol::table &core) {
@ -188,6 +193,8 @@ void Api::Usertype::LocalPlayer::bind(State state, sol::state &lua, sol::table &
"set_wield_index", &LocalPlayer::set_wield_index,
"get_wield_stack", &LocalPlayer::get_wield_stack,
"get_dimension", &LocalPlayer::get_dimension,
"show_menu", &LocalPlayer::show_menu,
"close_menu", &LocalPlayer::close_menu,
"set_hud", &LocalPlayer::set_hud,
@ -198,6 +205,7 @@ void Api::Usertype::LocalPlayer::bind(State state, sol::state &lua, sol::table &
"vel", sol::property(&LocalPlayer::get_vel, &LocalPlayer::set_vel),
"look_yaw", sol::property(&LocalPlayer::get_look_yaw, &LocalPlayer::set_look_yaw),
"look_pitch", sol::property(&LocalPlayer::get_look_pitch, &LocalPlayer::set_look_pitch),
"dim", sol::property(&LocalPlayer::get_dimension),
"flying", sol::property(&LocalPlayer::set_flying, &LocalPlayer::get_flying),

View File

@ -9,6 +9,7 @@
#include <memory>
#include "Inventory.h"
#include "Dimension.h"
#include "../../game/scene/world/LocalPlayer.h"
class LuaGuiElement;
@ -16,9 +17,9 @@ class LuaGuiElement;
namespace Api::Usertype {
class ServerPlayer : public SubgameUsertype {
public:
ServerPlayer(std::shared_ptr<::Player> player) : player(player) {}
ServerPlayer(PlayerPtr player) : player(player) {}
std::shared_ptr<::Player> player;
PlayerPtr player;
unsigned int get_id();
@ -44,6 +45,7 @@ namespace Api::Usertype {
void set_wield_list(sol::optional<sol::object> list);
Inventory get_inventory();
Dimension get_dimension();
unsigned int get_wield_index();
void set_wield_index(unsigned int index);
@ -56,8 +58,7 @@ namespace Api::Usertype {
class LocalPlayer : public ServerPlayer {
public:
LocalPlayer(std::shared_ptr<::LocalPlayer> player) :
ServerPlayer(std::static_pointer_cast<::Player>(player)) {}
LocalPlayer(PlayerPtr player) : ServerPlayer(player) {}
bool is_in_menu();
void show_menu(std::shared_ptr<LuaGuiElement> root);

View File

@ -12,11 +12,10 @@
#include "../../def/item/CraftItemDef.h"
#include "../../def/LocalDefinitionAtlas.h"
ServerLocalLuaEntity::ServerLocalLuaEntity(unsigned int id, LocalSubgame &defs, const std::string &appearance,
ServerLocalLuaEntity::ServerLocalLuaEntity(unsigned int id, SubgamePtr game, const std::string &appearance,
const std::string &arg1, const std::string &arg2) :
id(id),
defs(defs) {
game(game) {
setDisplayType(appearance, arg1, arg2);
}
@ -25,7 +24,7 @@ void ServerLocalLuaEntity::setDisplayType(const std::string &type, const std::st
if (strncmp(type.data(), "gameobject", 10) == 0 &&
(strncmp(displayType.data(), "gameobject", 10) || arg2 != displayArg2)) {
ItemDef& def = defs.getDefs().fromStr(arg2);
ItemDef& def = game->getDefs().fromStr(arg2);
if (def.type == ItemDef::Type::BLOCK)
entity->setModel(static_cast<BlockDef&>(def).entityModel);
@ -35,7 +34,7 @@ void ServerLocalLuaEntity::setDisplayType(const std::string &type, const std::st
else if (strncmp(type.data(), "model", 5) == 0 && !arg2.empty() &&
(strncmp(displayType.data(), "model", 5) || arg != displayArg1 || arg != displayArg2)) {
auto model = std::make_shared<Model>();
model->fromSerialized(defs.models.models[arg], {defs.textures[arg2]});
model->fromSerialized(game.l()->models.models[arg], {game.l()->textures[arg2]});
entity->setModel(model);
}
else return;

View File

@ -6,17 +6,18 @@
#include <string>
#include "../../util/CovariantPtr.h"
#include "../../game/entity/DrawableEntity.h"
class LocalSubgame;
class ServerLocalLuaEntity {
public:
ServerLocalLuaEntity(unsigned int id, LocalSubgame& defs, const std::string& appearance, const std::string& arg1, const std::string& arg2);
ServerLocalLuaEntity(unsigned int id, SubgamePtr game, const std::string& appearance, const std::string& arg1, const std::string& arg2);
void setDisplayType(const std::string& type, const std::string& arg, const std::string& arg2);
LocalSubgame& defs;
SubgamePtr game;
std::unique_ptr<DrawableEntity> entity = std::make_unique<DrawableEntity>();
unsigned int id;

View File

@ -83,7 +83,7 @@ float ServerLuaEntity::get_scale() {
void ServerLuaEntity::set_display_type(const std::string &type, const std::string &arg, sol::optional<std::string> arg2) {
if (strncmp(type.data(), "gameobject", 10) == 0) {
ItemDef& def = defs.getDefs().fromStr(arg);
ItemDef& def = game->getDefs().fromStr(arg);
// if (def.index == 0) throw "Invalid gameobject to display";
if (def.type == ItemDef::Type::BLOCK)

View File

@ -7,18 +7,19 @@
#include <memory>
#include "../Lua.h"
#include "../../util/CovariantPtr.h"
#include "../../net/server/world/ServerEntity.h"
class ServerSubgame;
class ServerLuaEntity {
public:
ServerLuaEntity(std::unique_ptr<ServerEntity> entity, unsigned int id, ServerSubgame& defs) :
entity(std::move(entity)), id(id), defs(defs) {}
ServerLuaEntity(std::unique_ptr<ServerEntity> entity, unsigned int id, SubgamePtr game) :
entity(std::move(entity)), id(id), game(game) {}
std::unique_ptr<ServerEntity> entity = nullptr;
unsigned int id;
ServerSubgame& defs;
SubgamePtr game;
void snap_pos(glm::vec3 pos);
void set_pos(glm::vec3 pos);

View File

@ -1,21 +0,0 @@
//
// Created by aurailus on 2019-12-17.
//
#pragma once
#include "../Lua.h"
#include "LuaItemStack.h"
namespace ClientApi {
static void item_stack(sol::state& lua) {
lua.new_usertype<LuaItemStack>("ItemStack",
sol::constructors<LuaItemStack(sol::table), LuaItemStack(std::string, unsigned short)>(),
"name", sol::property(&LuaItemStack::get_name, &LuaItemStack::set_name),
"count", sol::property(&LuaItemStack::get_count, &LuaItemStack::set_count),
"is_empty", &LuaItemStack::is_empty
);
}
}

View File

@ -14,7 +14,7 @@
#include "../../game/scene/world/LocalWorld.h"
#include "../../game/scene/world/LocalPlayer.h"
ClientNetworkInterpreter::ClientNetworkInterpreter(ServerConnection &connection, LocalSubgame &defs, LocalWorld& world) :
ClientNetworkInterpreter::ClientNetworkInterpreter(ServerConnection &connection, LocalWorld& world) :
world(world), connection(connection) {}
void ClientNetworkInterpreter::init(std::function<void(std::unique_ptr<PacketView>)> invCallback) {
@ -81,14 +81,14 @@ void ClientNetworkInterpreter::receivedPacket(std::unique_ptr<PacketView> p) {
case PacketType::BLOCK_SET: {
auto pos = p->d.read<glm::ivec3>();
auto block = p->d.read<unsigned int>();
world.getActiveDimension().setBlock(pos, block);
world.getActiveDimension()->setBlock(pos, block);
break; }
case PacketType::ENTITY_INFO:
world.getActiveDimension().serverEntityInfo(*p); break;
world.getActiveDimension().l()->serverEntityInfo(*p); break;
case PacketType::ENTITY_REMOVED:
world.getActiveDimension().serverEntityRemoved(p->d.read<unsigned int>()); break;
world.getActiveDimension().l()->serverEntityRemoved(p->d.read<unsigned int>()); break;
case PacketType::INV_DATA:
onInvPacket(std::move(p)); break;

View File

@ -10,6 +10,7 @@
#include "../Serializer.h"
#include "ServerConnection.h"
#include "../../util/CovariantPtr.h"
class Model;
class LocalPlayer;
@ -22,7 +23,7 @@ enum class NetPlayerField;
class ClientNetworkInterpreter {
public:
ClientNetworkInterpreter(const ClientNetworkInterpreter& other) = delete;
ClientNetworkInterpreter(ServerConnection& connection, LocalSubgame& defs, LocalWorld& world);
ClientNetworkInterpreter(ServerConnection& connection, LocalWorld& world);
void init(std::function<void(std::unique_ptr<PacketView>)> invCallback);
void update();

View File

@ -21,11 +21,11 @@ Server::Server(unsigned short port, const std::string& subgame) :
config(game),
clients(game),
handler(port, 32),
game(subgame, seed),
world(seed, game, clients) {
game(std::make_shared<ServerSubgame>(subgame, seed)),
world(std::make_shared<ServerWorld>(seed, game, clients)) {
game.init(world);
world.init("world");
game.s()->init(world);
world.s()->init("world");
config.init();
std::cout << Log::info << "Server started successfully, listening for clients." << Log::endl;
@ -36,8 +36,8 @@ void Server::update() {
const static long interval_ns = static_cast<long>((1000 / 60.f) * 1000000L);
Timer loop("");
world.update(0);
game.update(delta);
world->update(delta);
game.s()->update(delta);
ENetEvent event;
while (handler.update(&event) && loop.elapsedNs() < interval_ns) {
@ -92,7 +92,7 @@ void Server::packetReceived(ENetEvent& e) {
// Function returns true if a player is to be created.
if (config.handlePacket(*client, p)) {
auto clientShared = clients.getClient(client->id);
if (clientShared) clients.createPlayer(clientShared, world.getDimension("default"));
if (clientShared) clients.createPlayer(clientShared, world->getDefaultDimension());
}
}
@ -162,21 +162,21 @@ void Server::playerPacketReceived(PacketView& p, ServerPlayer& player) {
case PacketType::INV_WATCH:
p.d.read<std::string>(source).read<std::string>(list);
if (!world.getRefs()->addWatcher(source, list, player.getId()))
if (!world->getRefs().s()->addWatcher(source, list, player.getId()))
Serializer().append(source).append(list).packet(PacketType::INV_INVALID)
.sendTo(player.getPeer(), PacketChannel::INTERACT);
break;
case PacketType::INV_UNWATCH:
p.d.read<std::string>(source).read<std::string>(list);
if (!world.getRefs()->removeWatcher(source, list, player.getId()))
if (!world->getRefs().s()->removeWatcher(source, list, player.getId()))
Serializer().append(source).append(list).packet(PacketType::INV_INVALID)
.sendTo(player.getPeer(), PacketChannel::INVENTORY);
break;
case PacketType::INV_INTERACT:
p.d.read<unsigned short>(a).read<std::string>(source).read<std::string>(list).read<unsigned short>(ind);
world.getRefs()->interact(a, source, list, ind, player.getId());
world->getRefs().s()->interact(a, source, list, ind, player.getId());
break;
}
}

View File

@ -29,9 +29,9 @@ private:
unsigned short port = 0;
unsigned int seed = 0;
ServerSubgame game;
SubgamePtr game;
ServerClients clients;
ServerWorld world;
WorldPtr world;
NetHandler handler;
ServerConfig config;

View File

@ -15,17 +15,17 @@
#include "../../../def/ServerDefinitionAtlas.h"
#include "../../../lua/ServerLuaParser.h"
ServerConfig::ServerConfig(ServerSubgame &defs) : game(defs) {}
ServerConfig::ServerConfig(SubgamePtr game) : game(game) {}
void ServerConfig::init() {
blockIdentifierList.reserve(static_cast<unsigned long>(game.getDefs().size()));
for (unsigned int i = 0; i < game.getDefs().size(); i++) {
blockIdentifierList.push_back(game.getDefs().fromId(i).identifier);
blockIdentifierList.reserve(static_cast<unsigned long>(game->getDefs().size()));
for (unsigned int i = 0; i < game->getDefs().size(); i++) {
blockIdentifierList.push_back(game->getDefs().fromId(i).identifier);
}
biomeIdentifierList.reserve(static_cast<unsigned long>(game.getBiomes().size()));
for (unsigned int i = 0; i < game.getBiomes().size(); i++) {
biomeIdentifierList.push_back(game.getBiomes().biomeFromId(i).identifier);
biomeIdentifierList.reserve(static_cast<unsigned long>(game->getBiomes().size()));
for (unsigned int i = 0; i < game->getBiomes().size(); i++) {
biomeIdentifierList.push_back(game->getBiomes().biomeFromId(i).identifier);
}
}
@ -37,7 +37,7 @@ bool ServerConfig::handlePacket(ServerClient& client, PacketView& r) {
case PacketType::SERVER_INFO: {
Serializer()
.append(game.getBiomes().seed)
.append(game.s()->getBiomes().seed)
.packet(PacketType::SERVER_INFO)
.sendTo(client.peer, PacketChannel::CONNECT);
break;
@ -60,7 +60,7 @@ bool ServerConfig::handlePacket(ServerClient& client, PacketView& r) {
}
case PacketType::MODS: {
game.getParser().sendModsPacket(client.peer);
game.s()->getParser().sendModsPacket(client.peer);
break;
}
@ -70,7 +70,7 @@ bool ServerConfig::handlePacket(ServerClient& client, PacketView& r) {
Serializer s {};
for (ServerTexture& texture : game.assets.textures) {
for (ServerTexture& texture : game.s()->assets.textures) {
if (packetSize + 20 + texture.data.length() > MAX_PACKET_SIZE && packetSize != 0) {
s.append(static_cast<int>(AssetType::END));
Packet p(PacketType::MEDIA);
@ -91,7 +91,7 @@ bool ServerConfig::handlePacket(ServerClient& client, PacketView& r) {
packetSize += texture.data.length() + 20;
}
for (SerializedModel& model : game.assets.models) {
for (SerializedModel& model : game.s()->assets.models) {
if (packetSize + 16 + model.data.length() > MAX_PACKET_SIZE && packetSize != 0) {
s.append(static_cast<int>(AssetType::END));
Packet p(PacketType::MEDIA);

View File

@ -5,6 +5,7 @@
#pragma once
#include "../../PacketView.h"
#include "../../../util/CovariantPtr.h"
class PacketView;
class ServerClient;
@ -12,14 +13,14 @@ class ServerSubgame;
class ServerConfig {
public:
explicit ServerConfig(ServerSubgame& defs);
explicit ServerConfig(SubgamePtr game);
void init();
//Bool: Create player
bool handlePacket(ServerClient& client, PacketView& p);
private:
ServerSubgame& game;
SubgamePtr game;
std::vector<std::string> blockIdentifierList {};
std::vector<std::string> biomeIdentifierList {};
};

View File

@ -14,7 +14,7 @@
#include "../../../def/ServerSubgame.h"
#include "../../../lua/ServerLuaParser.h"
ServerClients::ServerClients(ServerSubgame& game) :
ServerClients::ServerClients(SubgamePtr game) :
game(game) {}
void ServerClients::init(ServerWorld *world) {
@ -39,7 +39,7 @@ void ServerClients::handleDisconnect(ENetEvent e) {
// Disconnect the player, if it exists.
for (auto it = players.begin(); it != players.end();) {
if ((*it)->getId() == id) {
game.getParser().playerDisconnected(*it);
game.s()->getParser().playerDisconnected(*it);
players.erase(it);
break;
}
@ -50,13 +50,13 @@ void ServerClients::handleDisconnect(ENetEvent e) {
}
}
void ServerClients::createPlayer(std::shared_ptr<ServerClient> client, ServerDimension& dimension) {
void ServerClients::createPlayer(std::shared_ptr<ServerClient> client, DimensionPtr dimension) {
auto player = std::make_shared<ServerPlayer>(*client, game, dimension);
player->getInventory().createList("cursor", 1, 1);
player->getInventory()->createList("cursor", 1, 1);
client->player = player;
players.push_back(player);
game.getParser().playerConnected(player);
game.s()->getParser().playerConnected(player);
Serializer()
.appendE(Player::NetField::ID).append(player->getId())

View File

@ -8,6 +8,8 @@
#include <memory>
#include <enet/enet.h>
#include "../../../util/CovariantPtr.h"
class ServerWorld;
class ServerClient;
class ServerPlayer;
@ -16,13 +18,13 @@ class ServerDimension;
class ServerClients {
public:
explicit ServerClients(ServerSubgame& game);
explicit ServerClients(SubgamePtr game);
void init(ServerWorld* world);
void handleConnect(ENetEvent e);
void handleDisconnect(ENetEvent e);
void createPlayer(std::shared_ptr<ServerClient> client, ServerDimension& dimension);
void createPlayer(std::shared_ptr<ServerClient> client, DimensionPtr dimension);
const std::shared_ptr<ServerClient> getClient(unsigned int id) const;
const std::shared_ptr<ServerPlayer> getPlayer(unsigned int id) const;
@ -30,6 +32,6 @@ public:
std::list<std::shared_ptr<ServerPlayer>> players;
private:
ServerSubgame& game;
SubgamePtr game;
ServerWorld* world;
};

View File

@ -10,9 +10,9 @@
#include "../world/ServerWorld.h"
#include "../../../game/inventory/ServerInventoryRefs.h"
ServerPlayer::ServerPlayer(ServerClient& client, ServerSubgame& game, ServerDimension& dim) :
ServerPlayer::ServerPlayer(ServerClient& client, SubgamePtr game, DimensionPtr dim) :
Player(game, dim, client.id), client(client),
inventory(static_cast<ServerWorld&>(dim.getWorld()).getRefs()->createInventory("player:" + std::to_string(id))) {}
inventory(dim->getWorld().getRefs()->createInventory("player:" + std::to_string(id))) {}
void ServerPlayer::assertField(Packet packet) {
packet.type = PacketType::THIS_PLAYER_INFO;
@ -44,14 +44,10 @@ void ServerPlayer::setPos(glm::vec3 pos, bool assert) {
if (newMapBlock != lastMapBlock && !changedMapBlocks) changedMapBlocks = true;
}
ServerInventory& ServerPlayer::getInventory() {
InventoryPtr ServerPlayer::getInventory() {
return inventory;
}
ServerDimension &ServerPlayer::getDimension() {
return static_cast<ServerDimension&>(dim);
}
ENetPeer* ServerPlayer::getPeer() {
return client.peer;
}
}

View File

@ -21,14 +21,13 @@ enum class NetPlayerField;
class ServerPlayer : public Player {
public:
ServerPlayer(ServerClient& client, ServerSubgame& game, ServerDimension& dim);
ServerPlayer(ServerClient& client, SubgamePtr game, DimensionPtr dim);
virtual void assertField(Packet packet) override;
virtual void handleAssertion(Deserializer& d) override;
virtual void setPos(glm::vec3 pos, bool assert = false) override;
virtual ServerInventory& getInventory() override;
virtual ServerDimension& getDimension() override;
virtual InventoryPtr getInventory() override;
ENetPeer* getPeer();
@ -37,5 +36,5 @@ public:
private:
ServerClient& client;
ServerInventory& inventory;
InventoryPtr inventory;
};

View File

@ -6,12 +6,10 @@
#include "../../../def/ServerSubgame.h"
#include "../../../world/chunk/Chunk.h"
#include "../../../def/gen/ServerBiomeAtlas.h"
#include "../../../def/ServerDefinitionAtlas.h"
ServerGenStream::ServerGenStream(unsigned int seed, ServerSubgame& game) {
ServerGenStream::ServerGenStream(unsigned int seed, SubgamePtr game) {
threads.reserve(THREADS);
for (int i = 0; i < THREADS; i++) threads.emplace_back(game, seed);
for (int i = 0; i < THREADS; i++) threads.emplace_back(*game.s(), seed);
}
bool ServerGenStream::queue(glm::ivec4 pos) {

View File

@ -9,6 +9,7 @@
#include <unordered_set>
#include "../../../def/gen/MapGen.h"
#include "../../../util/CovariantPtr.h"
class ServerSubgame;
@ -22,7 +23,7 @@ public:
std::vector<std::shared_ptr<Chunk>> chunks;
};
explicit ServerGenStream(unsigned int seed, ServerSubgame& game);
explicit ServerGenStream(unsigned int seed, SubgamePtr game);
~ServerGenStream();
// Add the MapBlock position `pos` to the generation queue.

View File

@ -46,7 +46,7 @@ std::unique_ptr<std::vector<std::unique_ptr<ServerPacketStream::FinishedJob>>> S
queuedMap.erase(pos);
queuedTasks.pop();
auto mapBlock = world.getDimension(pos.w).getMapBlock(glm::ivec3(pos));
auto mapBlock = world.getDimension(pos.w)->getMapBlock(glm::ivec3(pos));
if (!mapBlock) continue;
j.pos = pos;

View File

@ -18,11 +18,11 @@
#include "../../../world/chunk/Chunk.h"
#include "../../../lua/usertype/Target.h"
#include "../../../world/chunk/MapBlock.h"
#include "../../../lua/usertype/LuaItemStack.h"
#include "../../../lua/usertype/ItemStack.h"
#include "../../../lua/usertype/ServerLuaEntity.h"
#include "../../../game/inventory/ServerInventoryRefs.h"
ServerWorld::ServerWorld(unsigned int seed, ServerSubgame& game, ServerClients& clients) :
ServerWorld::ServerWorld(unsigned int seed, SubgamePtr game, ServerClients& clients) :
World(game),
seed(seed),
clients(clients),
@ -62,12 +62,9 @@ ServerWorld::ServerWorld(unsigned int seed, ServerSubgame& game, ServerClients&
}
void ServerWorld::init(const std::string& worldDir) {
genStream = std::make_unique<ServerGenStream>(seed, static_cast<ServerSubgame&>(game));
genStream = std::make_unique<ServerGenStream>(seed, game);
packetStream = std::make_unique<ServerPacketStream>(*this);
// fileManip = std::make_shared<FileManipulator>("worlds/" + worldDir + "/");
createDimension("default"); //TODO: Do not do not
generateMapBlock(0, {0, 0, 0});
}
void ServerWorld::update(double delta) {
@ -78,18 +75,18 @@ void ServerWorld::update(double delta) {
auto finishedGen = genStream->update();
for (auto& data : *finishedGen) {
auto& dimension = getDimension(data.pos.w);
auto dimension = getDimension(data.pos.w);
for (const auto& chunk : data.chunks) {
generatedMapBlocks.insert(data.pos);
updatedChunks.insert(glm::ivec4(chunk->pos, data.pos.w));
dimension.setChunk(chunk);
dimension->setChunk(chunk);
}
// auto resend = dimension.calculateEdgeLight(mb.pos);
// changed.insert(resend.begin(), resend.end());
dimension.getMapBlock(glm::ivec3(data.pos))->generated = true;
dimension->getMapBlock(glm::ivec3(data.pos))->generated = true;
packetStream->queue(data.pos);
}
@ -159,38 +156,23 @@ void ServerWorld::update(double delta) {
}
}
ServerDimension& ServerWorld::createDimension(const std::string &identifier) {
this->dimensions.emplace_back(std::make_shared<ServerDimension>(static_cast<ServerSubgame&>(game), *this, identifier, this->dimensions.size()));
return static_cast<ServerDimension&>(*dimensions[dimensions.size() - 1]);
DimensionPtr ServerWorld::createDimension(const std::string &identifier) {
this->dimensions.emplace_back(std::make_shared<ServerDimension>(game, *this, identifier, this->dimensions.size()));
return dimensions[dimensions.size() - 1];
}
ServerDimension& ServerWorld::getDimension(unsigned int index) {
return static_cast<ServerDimension&>(*dimensions[index]);
DimensionPtr ServerWorld::getDimension(unsigned int index) {
return dimensions[index];
}
ServerDimension& ServerWorld::getDimension(const std::string &identifier) {
DimensionPtr ServerWorld::getDimension(const std::string &identifier) {
for (auto& dimension : dimensions)
if (dimension->getIdentifier() == identifier)
return static_cast<ServerDimension&>(*dimension);
if (dimension->getIdentifier() == identifier) return dimension;
throw std::runtime_error("No dimension named " + identifier + " found.");
}
std::shared_ptr<ServerDimension> ServerWorld::getDefaultDimensionPtr() {
for (auto& dimension : dimensions)
if (dimension->getIdentifier() == defaultDimension)
return std::static_pointer_cast<ServerDimension>(dimension);
throw std::runtime_error("No default dimension set.");
}
std::shared_ptr<ServerDimension> ServerWorld::getDimensionPtr(const std::string &identifier) {
for (auto& dimension : dimensions)
if (dimension->getIdentifier() == identifier)
return std::static_pointer_cast<ServerDimension>(dimension);
throw std::runtime_error("No dimension named " + identifier + " found.");
}
std::shared_ptr<ServerInventoryRefs> ServerWorld::getRefs() {
return refs;
InventoryRefsPtr ServerWorld::getRefs() {
return InventoryRefsPtr(refs);
}
void ServerWorld::changedMapBlocks(ServerPlayer& player) {
@ -205,17 +187,17 @@ void ServerWorld::generateMapBlocks(ServerPlayer& player) {
for (const auto &c : generateOrder) {
glm::ivec3 mapBlockPos = playerMapBlock + c;
auto existing = player.getDimension().getMapBlock(mapBlockPos);
auto existing = player.getDimension()->getMapBlock(mapBlockPos);
if (existing && existing->generated) continue;
else generating += generateMapBlock(player.getDimension().getInd(), mapBlockPos);
else generating += generateMapBlock(player.getDimension()->getInd(), mapBlockPos);
}
std::cout << "Player moved, generating " << generating << " MapBlocks." << std::endl;
}
bool ServerWorld::generateMapBlock(unsigned int dim, glm::ivec3 pos) {
auto& dimension = getDimension(dim);
if(!dimension.getMapBlock(pos) || !dimension.getMapBlock(pos)->generated) return genStream->queue(glm::ivec4(pos, dim));
auto dimension = getDimension(dim);
if(!dimension->getMapBlock(pos) || !dimension->getMapBlock(pos)->generated) return genStream->queue(glm::ivec4(pos, dim));
return false;
}
@ -235,7 +217,7 @@ void ServerWorld::sendChunksToPlayer(ServerPlayer& client) {
for (int k = bounds.first.z; k < bounds.second.z; k++) {
glm::ivec3 pos {i, j, k};
if (isInBounds(pos, oldBounds)) continue;
packetStream->queue(glm::ivec4(pos, client.getDimension().getInd()));
packetStream->queue(glm::ivec4(pos, client.getDimension()->getInd()));
}
}
}
@ -245,4 +227,4 @@ bool ServerWorld::isInBounds(glm::ivec3 cPos, std::pair<glm::ivec3, glm::ivec3>
return (cPos.x >= bounds.first.x && cPos.x <= bounds.second.x
&& cPos.y >= bounds.first.y && cPos.y <= bounds.second.y
&& cPos.z >= bounds.first.z && cPos.z <= bounds.second.z);
}
}

View File

@ -21,20 +21,17 @@ class ServerPacketStream;
class ServerWorld : public World {
public:
explicit ServerWorld(unsigned int seed, ServerSubgame& game, ServerClients& clients);
explicit ServerWorld(unsigned int seed, SubgamePtr game, ServerClients& clients);
void init(const std::string& worldDir);
void update(double delta) override;
virtual ServerDimension& createDimension(const std::string& identifier) override;
virtual DimensionPtr createDimension(const std::string& identifier) override;
virtual ServerDimension& getDimension(unsigned int index) override;
virtual ServerDimension& getDimension(const std::string& identifier) override;
virtual DimensionPtr getDimension(unsigned int index) override;
virtual DimensionPtr getDimension(const std::string& identifier) override;
std::shared_ptr<ServerDimension> getDefaultDimensionPtr();
std::shared_ptr<ServerDimension> getDimensionPtr(const std::string& identifier);
std::shared_ptr<ServerInventoryRefs> getRefs();
virtual InventoryRefsPtr getRefs() override;
private:
void changedMapBlocks(ServerPlayer& player);
static bool isInBounds(glm::ivec3 pos, std::pair<glm::ivec3, glm::ivec3>& bounds);

View File

@ -1,5 +0,0 @@
//
// Created by aurailus on 2020-08-02.
//
#include "CovariantPtr.h"

View File

@ -6,17 +6,57 @@
#include <memory>
template <typename B, typename L, typename S,
typename = typename std::enable_if<std::is_base_of<B, S>::value>::type,
typename = typename std::enable_if<std::is_base_of<B, L>::value>::type>
class World;
class LocalWorld;
class ServerWorld;
class Player;
class LocalPlayer;
class ServerPlayer;
class Subgame;
class LocalSubgame;
class ServerSubgame;
class Dimension;
class LocalDimension;
class ServerDimension;
class Inventory;
class LocalInventory;
class ServerInventory;
class InventoryList;
class LocalInventoryList;
class ServerInventoryList;
class InventoryRefs;
class LocalInventoryRefs;
class ServerInventoryRefs;
template <typename B, typename L, typename S>
class CovariantPtr {
std::shared_ptr<B> b;
std::shared_ptr<B> b = nullptr;
public:
CovariantPtr() = default;
CovariantPtr(std::shared_ptr<B> ptr) : b(ptr) {}
CovariantPtr(std::shared_ptr<L> ptr) : b(std::dynamic_pointer_cast<B>(ptr)) {}
CovariantPtr(std::shared_ptr<S> ptr) : b(std::dynamic_pointer_cast<B>(ptr)) {}
void operator=(std::nullptr_t) { b = nullptr; }
operator bool() { return b != nullptr; }
std::shared_ptr<B> operator*() { return b; }
std::shared_ptr<B> operator->() { return b; }
std::shared_ptr<L> l() { auto ptr = std::dynamic_pointer_cast<L>(b); if (!ptr) throw std::bad_cast(); return ptr; }
std::shared_ptr<S> s() { auto ptr = std::dynamic_pointer_cast<S>(b); if (!ptr) throw std::bad_cast(); return ptr; }
};
};
typedef CovariantPtr<World, LocalWorld, ServerWorld> WorldPtr;
typedef CovariantPtr<Player, LocalPlayer, ServerPlayer> PlayerPtr;
typedef CovariantPtr<Subgame, LocalSubgame, ServerSubgame> SubgamePtr;
typedef CovariantPtr<Dimension, LocalDimension, ServerDimension> DimensionPtr;
typedef CovariantPtr<Inventory, LocalInventory, ServerInventory> InventoryPtr;
typedef CovariantPtr<InventoryList, LocalInventoryList, ServerInventoryList> InventoryListPtr;
typedef CovariantPtr<InventoryRefs, LocalInventoryRefs, ServerInventoryRefs> InventoryRefsPtr;

View File

@ -16,7 +16,7 @@ bool Dimension::setBlock(glm::ivec3 pos, unsigned int block) {
if (!DimensionBase::setBlock(pos, block)) return false;
auto &def = game.getDefs().blockFromId(block);
auto &def = game->getDefs().blockFromId(block);
glm::ivec4 oldLight = chunk->getLight(Space::Block::index(pos));
glm::ivec3 newLight = def.lightSource;
@ -98,7 +98,7 @@ std::unordered_set<glm::ivec3, Vec::ivec3> Dimension::propogateAddNodes() {
}
bool sunDown = (channel == SUNLIGHT_CHANNEL && lightLevel == 15 && i.y == -1);
if (game.getDefs().blockFromId(chunk->getBlock(ind)).lightPropagates && (sunDown || chunk->getLight(ind, channel) + 2 <= lightLevel)) {
if (game->getDefs().blockFromId(chunk->getBlock(ind)).lightPropagates && (sunDown || chunk->getLight(ind, channel) + 2 <= lightLevel)) {
int subtract = sunDown ? 0 : 1;
chunk->setLight(ind, channel, lightLevel - subtract);
lightAddQueue[channel].emplace(ind, chunk);
@ -139,7 +139,7 @@ std::unordered_set<glm::ivec3, Vec::ivec3> Dimension::propogateRemoveNodes() {
unsigned char checkLight = chunk->getLight(ind, channel);
if (checkLight != 0 && (checkLight < node.value || (channel == SUNLIGHT_CHANNEL && i.y == -1 && node.value == 15))) {
unsigned int replaceLight = (channel == SUNLIGHT_CHANNEL ? 0 :
game.getDefs().blockFromId(chunk->getBlock(Space::Block::index(check))).lightSource[channel]);
game->getDefs().blockFromId(chunk->getBlock(Space::Block::index(check))).lightSource[channel]);
chunk->setLight(ind, channel, replaceLight);
if (replaceLight) lightAddQueue[channel].emplace(ind, chunk);
@ -276,4 +276,4 @@ void Dimension::setAndReflowSunlight(glm::ivec3 pos, unsigned char level) {
chunk->setLight(ind, 3, level);
lightAddQueue[SUNLIGHT_CHANNEL].emplace(ind, chunk.get());
}
}

View File

@ -20,18 +20,16 @@ public:
typedef std::unordered_set<glm::ivec3, Vec::ivec3> relitChunks;
Dimension(const Dimension& o) = delete;
Dimension(Subgame& game, World& world, const std::string& identifier, unsigned int ind) :
Dimension(SubgamePtr game, World& world, const std::string& identifier, unsigned int ind) :
DimensionBase(game, world, identifier, ind) {}
virtual void update(double delta) = 0;
// Override setBlock to update lighting.
bool setBlock(glm::ivec3 pos, unsigned int block) override;
virtual void blockPlace(const Target &target, std::shared_ptr<Player> player) = 0;
virtual void blockPlaceOrInteract(const Target &target, std::shared_ptr<Player> player) = 0;
virtual void blockInteract(const Target &target, std::shared_ptr<Player> player) = 0;
virtual double blockHit(const Target &target, std::shared_ptr<Player> player) = 0;
virtual void blockPlace(const Target &target, PlayerPtr player) = 0;
virtual void blockPlaceOrInteract(const Target &target, PlayerPtr player) = 0;
virtual void blockInteract(const Target &target, PlayerPtr player) = 0;
virtual double blockHit(const Target &target, PlayerPtr player) = 0;
unsigned int nextEntityInd();

View File

@ -8,15 +8,24 @@
#include "chunk/Region.h"
#include "chunk/MapBlock.h"
#include "../def/Subgame.h"
#include "../def/item/BlockDef.h"
#include "../def/DefinitionAtlas.h"
DimensionBase::DimensionBase(Subgame &game, World& world, const std::string &identifier, unsigned int ind) :
DimensionBase::DimensionBase(SubgamePtr game, World& world, const std::string &identifier, unsigned int ind) :
game(game), world(world), identifier(identifier), ind(ind) {}
std::string DimensionBase::getIdentifier() const {
return identifier;
}
unsigned int DimensionBase::getInd() {
return ind;
}
void DimensionBase::update(double delta) {
updateBlockDamage(delta);
}
std::shared_ptr<Region> DimensionBase::getRegion(glm::ivec3 regionPosition) {
if (!regions.count(regionPosition)) return nullptr;
return regions[regionPosition];
@ -80,6 +89,29 @@ bool DimensionBase::setBlock(glm::ivec3 pos, unsigned int block) {
return chunk->setBlock(Space::Block::relative::toChunk(pos), block);
}
double DimensionBase::getBlockDamage(glm::ivec3 pos) const {
double damage = blockDamages.count(pos) ? blockDamages.at(pos).curr : 0;
std::cout << damage << std::endl;
return damage;
}
double DimensionBase::setBlockDamage(glm::ivec3 pos, double damage) {
if (blockDamages.count(pos)) blockDamages[pos].curr = damage;
else blockDamages.insert({pos, Damage { damage, static_cast<double>(game->getDefs().blockFromId(getBlock(pos)).health)}});
return getBlockDamage(pos);
// double totalDamage = World::setBlockDamage(pos, damage);
// BlockCrackEntity* block = nullptr;
// if (crackEntities.count(pos)) block = crackEntities[pos];
// else block = new BlockCrackEntity(game.defs->blockFromId(getBlock(pos)), game.textures, pos);
// block->setDamage(damage);
// block->time = 0;
//
// return totalDamage;
}
unsigned int DimensionBase::getBiome(glm::ivec3 pos) {
auto chunk = getChunk(Space::Chunk::world::fromBlock(pos));
if (!chunk) return 0;
@ -111,14 +143,25 @@ std::shared_ptr<MapBlock> DimensionBase::getOrCreateMapBlock(glm::ivec3 mapBlock
return (*region)[index];
}
Subgame &DimensionBase::getGame() {
SubgamePtr DimensionBase::getGame() {
return game;
}
World &DimensionBase::getWorld() {
World& DimensionBase::getWorld() {
return world;
}
void DimensionBase::updateBlockDamage(double delta) {
for (auto it = blockDamages.begin(); it != blockDamages.end();) {
if (it->second.curr > it->second.max) {
setBlock(it->first, DefinitionAtlas::AIR);
it = blockDamages.erase(it);
}
else it++;
}
}
std::shared_ptr<Chunk> DimensionBase::combinePartials(std::shared_ptr<Chunk> a, std::shared_ptr<Chunk> b) {
std::shared_ptr<Chunk> src;
std::shared_ptr<Chunk> res;
@ -140,26 +183,4 @@ std::shared_ptr<Chunk> DimensionBase::combinePartials(std::shared_ptr<Chunk> a,
res->partial = !res->generated;
res->countRenderableBlocks();
return res;
}
double DimensionBase::getBlockDamage(glm::ivec3 pos) const {
return 0;
}
double DimensionBase::setBlockDamage(glm::ivec3 pos, double damage) {
return 0;
//TODO: WOwdowadoawod
// double totalDamage = World::setBlockDamage(pos, damage);
// BlockCrackEntity* block = nullptr;
// if (crackEntities.count(pos)) block = crackEntities[pos];
// else block = new BlockCrackEntity(game.defs->blockFromId(getBlock(pos)), game.textures, pos);
// block->setDamage(damage);
// block->time = 0;
//
// return totalDamage;
}
unsigned int DimensionBase::getInd() {
return ind;
}
}

View File

@ -6,10 +6,10 @@
#pragma once
#include <memory>
#include <unordered_map>
#include "../util/Vec.h"
#include "../util/CovariantPtr.h"
class World;
class Chunk;
@ -20,9 +20,12 @@ class DefinitionAtlas;
class DimensionBase {
public:
DimensionBase(Subgame& game, World& world, const std::string& identifier, unsigned int ind);
DimensionBase(SubgamePtr game, World& world, const std::string& identifier, unsigned int ind);
std::string getIdentifier() const;
unsigned int getInd();
virtual void update(double delta);
std::shared_ptr<Region> getRegion(glm::ivec3 regionPosition);
void removeRegion(glm::ivec3 pos);
@ -45,17 +48,18 @@ public:
unsigned int getBiome(glm::ivec3 pos);
virtual bool setBiome(glm::ivec3 pos, unsigned int biome);
unsigned int getInd();
SubgamePtr getGame();
World& getWorld();
virtual Subgame& getGame();
virtual World& getWorld();
protected:
virtual void updateBlockDamage(double delta);
// Combine two chunk partials, or a chunk and a chunk partial.
// If both are partials `b` takes preference, if one is a fully generated chunk the partial takes preference.
// TODO: Make this more efficient using proper RIE traversal.
static std::shared_ptr<Chunk> combinePartials(std::shared_ptr<Chunk> a, std::shared_ptr<Chunk> b);
Subgame& game;
SubgamePtr game;
World& world;
typedef std::unordered_map<glm::ivec3, std::shared_ptr<Region>, Vec::ivec3> block_region_map;
@ -63,9 +67,11 @@ protected:
std::string identifier;
unsigned int ind;
struct Damage { double curr, max; };
std::unordered_map<glm::ivec3, Damage, Vec::ivec3> blockDamages;
private:
inline std::shared_ptr<Region> getOrCreateRegion(glm::ivec3 pos);
inline std::shared_ptr<MapBlock> getOrCreateMapBlock(glm::ivec3 mapBlockPosition);
};

View File

@ -11,7 +11,7 @@
#include "../lua/usertype/Target.h"
#include "../lua/usertype/Player.h"
#include "../world/chunk/MapBlock.h"
#include "../lua/usertype/LuaItemStack.h"
#include "../lua/usertype/ItemStack.h"
#include "../game/scene/world/LocalWorld.h"
#include "../lua/usertype/LocalLuaEntity.h"
#include "../game/scene/world/LocalPlayer.h"
@ -21,19 +21,19 @@
#include "../lua/usertype/ServerLocalLuaEntity.h"
//#include "../game/inventory/LocalInventoryList.h"
LocalDimension::LocalDimension(LocalSubgame &game, LocalWorld& world, const std::string& identifier, unsigned int ind) :
Dimension(game, world, identifier, ind), meshGenStream(std::make_shared<MeshGenStream>(game, *this)) {}
LocalDimension::LocalDimension(SubgamePtr game, LocalWorld& world, const std::string& identifier, unsigned int ind) :
Dimension(game, static_cast<World&>(world), identifier, ind), meshGenStream(std::make_shared<MeshGenStream>(game, *this)) {}
void LocalDimension::update(double delta) {
Dimension::update(delta);
finishMeshes();
for (auto& entity : localEntities ) entity->entity->update(delta);
for (auto& entity : serverEntities) entity->entity->update(delta);
for (auto& entity : playerEntities) entity.update(delta);
//TODO: Fix playerpos.
glm::ivec3 playerPos {};
auto clientMapBlock = Space::MapBlock::world::fromBlock(playerPos);
auto clientMapBlock = Space::MapBlock::world::fromBlock(static_cast<LocalWorld&>(world).getPlayer()->getPos());
for (auto it = regions.cbegin(); it != regions.cend();) {
bool remove = false;
@ -91,45 +91,45 @@ bool LocalDimension::setBlock(glm::ivec3 pos, unsigned int block) {
return true;
}
void LocalDimension::blockPlace(const Target &target, std::shared_ptr<Player> player) {
std::tuple<sol::optional<LuaItemStack>, sol::optional<glm::vec3>> res = game.getParser().safe_function(
game.getParser().core["block_place"], Api::Usertype::LocalPlayer(std::static_pointer_cast<LocalPlayer>(player)), Api::Usertype::Target(target));
void LocalDimension::blockPlace(const Target &target, PlayerPtr player) {
std::tuple<sol::optional<Api::Usertype::ItemStack>, sol::optional<glm::vec3>> res = game->getParser().safe_function(
game->getParser().core["block_place"], Api::Usertype::LocalPlayer(player.l()), Api::Usertype::Target(target));
// net->blockPlace(target);
auto stack = std::get<sol::optional<LuaItemStack>>(res);
auto stack = std::get<sol::optional<Api::Usertype::ItemStack>>(res);
if (!stack) return;
auto& inv = std::static_pointer_cast<LocalPlayer>(player)->getInventory();
if (inv.hasList(player->getWieldList()))
inv.getList(player->getWieldList()).setStack(player->getWieldIndex(), ItemStack(*stack, game));
auto inv = player.l()->getInventory();
if (inv->hasList(player->getWieldList()))
inv->getList(player->getWieldList())->setStack(player->getWieldIndex(), ItemStack(*stack, game));
}
void LocalDimension::blockInteract(const Target &target, std::shared_ptr<Player> player) {
game.getParser().safe_function(game.getParser().core["block_interact"],
Api::Usertype::LocalPlayer(std::static_pointer_cast<LocalPlayer>(player)), Api::Usertype::Target(target));
void LocalDimension::blockInteract(const Target &target, PlayerPtr player) {
game->getParser().safe_function(game->getParser().core["block_interact"],
Api::Usertype::LocalPlayer(player.l()), Api::Usertype::Target(target));
// net->blockInteract(target);
}
void LocalDimension::blockPlaceOrInteract(const Target &target, std::shared_ptr<Player> player) {
std::tuple<sol::optional<LuaItemStack>, sol::optional<glm::vec3>> res = game.getParser().safe_function(
game.getParser().core["block_interact_or_place"], Api::Usertype::LocalPlayer(std::static_pointer_cast<LocalPlayer>(player)), Api::Usertype::Target(target));
void LocalDimension::blockPlaceOrInteract(const Target &target, PlayerPtr player) {
std::tuple<sol::optional<Api::Usertype::ItemStack>, sol::optional<glm::vec3>> res = game->getParser().safe_function(
game->getParser().core["block_interact_or_place"], Api::Usertype::LocalPlayer(player.l()), Api::Usertype::Target(target));
// net->blockPlaceOrInteract(target);
auto stack = std::get<sol::optional<LuaItemStack>>(res);
auto stack = std::get<sol::optional<Api::Usertype::ItemStack>>(res);
if (!stack) return;
auto& inv = std::static_pointer_cast<LocalPlayer>(player)->getInventory();
if (inv.hasList(player->getWieldList()))
inv.getList(player->getWieldList()).setStack(player->getWieldIndex(), ItemStack(*stack, game));
auto inv = player.l()->getInventory();
if (inv->hasList(player->getWieldList()))
inv->getList(player->getWieldList())->setStack(player->getWieldIndex(), ItemStack(*stack, game));
}
double LocalDimension::blockHit(const Target &target, std::shared_ptr<Player> player) {
double LocalDimension::blockHit(const Target &target, PlayerPtr player) {
double timeout = 0, damage = 0;
sol::tie(damage, timeout) = game.getParser().safe_function(game.getParser().core["block_hit"],
Api::Usertype::LocalPlayer(std::static_pointer_cast<LocalPlayer>(player)), Api::Usertype::Target(target));
sol::tie(damage, timeout) = game->getParser().safe_function(game->getParser().core["block_hit"],
Api::Usertype::LocalPlayer(player.l()), Api::Usertype::Target(target));
// net->blockHit(target);
@ -189,7 +189,7 @@ void LocalDimension::serverEntityInfo(PacketView& p) {
luaEntity.setDisplayType(displayMode, displayArg1, displayArg2);
}
else {
auto entity = std::make_shared<ServerLocalLuaEntity>(id, static_cast<LocalSubgame&>(game), displayMode, displayArg1, displayArg2);
auto entity = std::make_shared<ServerLocalLuaEntity>(id, game, displayMode, displayArg1, displayArg2);
entity->entity->setPos(position);
entity->entity->setVisualOffset(visualOffset);
entity->entity->setRotateX(rotation.x);
@ -231,10 +231,6 @@ int LocalDimension::getMeshChunkCount() {
return static_cast<int>(renderElems.size());
}
LocalSubgame& LocalDimension::getGame() {
return static_cast<LocalSubgame&>(DimensionBase::getGame());
}
std::unordered_set<glm::ivec3, Vec::ivec3> LocalDimension::propogateAddNodes() {
auto updated = Dimension::propogateAddNodes();
for (auto& update : updated) attemptMeshChunk(getChunk(update));

View File

@ -24,16 +24,17 @@ public:
const static int MB_STORE_H = 6;
const static int MB_STORE_V = 4;
LocalDimension(LocalSubgame& game, LocalWorld& world, const std::string& identifier, unsigned int ind);
LocalDimension(SubgamePtr game, LocalWorld& world, const std::string& identifier, unsigned int ind);
void update(double delta) override;
void setChunk(std::shared_ptr<Chunk> chunk) override;
bool setBlock(glm::ivec3 pos, unsigned int block) override;
virtual void blockPlace(const Target &target, std::shared_ptr<Player> player) override;
virtual void blockPlaceOrInteract(const Target &target, std::shared_ptr<Player> player) override;
virtual void blockInteract(const Target &target, std::shared_ptr<Player> player) override;
virtual double blockHit(const Target &target, std::shared_ptr<Player> player) override;
virtual void blockPlace(const Target &target, PlayerPtr player) override;
virtual void blockPlaceOrInteract(const Target &target, PlayerPtr player) override;
virtual void blockInteract(const Target &target, PlayerPtr player) override;
virtual double blockHit(const Target &target, PlayerPtr player) override;
void setMeshChunk(std::shared_ptr<MeshChunk> chunk);
void removeMeshChunk(const glm::ivec3& pos);
@ -48,8 +49,6 @@ public:
void renderEntities(Renderer &renderer);
int getMeshChunkCount();
virtual LocalSubgame& getGame();
int lastMeshUpdates = 0;
std::vector<PlayerEntity> playerEntities;

View File

@ -11,15 +11,17 @@
#include "../def/ServerSubgame.h"
#include "../lua/usertype/Player.h"
#include "../lua/usertype/Target.h"
#include "../lua/usertype/LuaItemStack.h"
#include "../lua/usertype/ItemStack.h"
#include "../net/server/conn/ServerPlayer.h"
#include "../net/server/world/ServerWorld.h"
#include "../lua/usertype/ServerLuaEntity.h"
ServerDimension::ServerDimension(ServerSubgame& game, ServerWorld& world, const std::string& identifier, unsigned int ind) :
Dimension(game, world, identifier, ind) {}
ServerDimension::ServerDimension(SubgamePtr game, ServerWorld& world, const std::string& identifier, unsigned int ind) :
Dimension(game, static_cast<World&>(world), identifier, ind) {}
void ServerDimension::update(double delta) {
Dimension::update(delta);
//TODO: Thiss
// for (const auto& region : regions) {
// for (unsigned short i = 0; i < 64; i++) {
@ -52,37 +54,37 @@ bool ServerDimension::setBlock(glm::ivec3 pos, unsigned int block) {
return true;
}
void ServerDimension::blockPlace(const Target &target, std::shared_ptr<Player> player) {
std::tuple<sol::optional<LuaItemStack>, sol::optional<glm::vec3>> res = game.getParser().safe_function(
game.getParser().core["block_place"], Api::Usertype::ServerPlayer(std::static_pointer_cast<ServerPlayer>(player)), Api::Usertype::Target(target));
void ServerDimension::blockPlace(const Target &target, PlayerPtr player) {
std::tuple<sol::optional<Api::Usertype::ItemStack>, sol::optional<glm::vec3>> res = game->getParser().safe_function(
game->getParser().core["block_place"], Api::Usertype::ServerPlayer(player.s()), Api::Usertype::Target(target));
auto stack = std::get<sol::optional<LuaItemStack>>(res);
auto stack = std::get<sol::optional<Api::Usertype::ItemStack>>(res);
if (!stack) return;
auto& inv = std::static_pointer_cast<ServerPlayer>(player)->getInventory();
if (inv.hasList(player->getWieldList())) inv.getList(player->getWieldList()).setStack(player->getWieldIndex(), ItemStack(*stack, game));
auto inv = player->getInventory();
if (inv->hasList(player->getWieldList())) inv->getList(player->getWieldList())->setStack(player->getWieldIndex(), ItemStack(*stack, game));
}
void ServerDimension::blockInteract(const Target &target, std::shared_ptr<Player> player) {
game.getParser().safe_function(game.getParser().core["block_interact"],
Api::Usertype::LocalPlayer(std::static_pointer_cast<LocalPlayer>(player)), Api::Usertype::Target(target));
void ServerDimension::blockInteract(const Target &target, PlayerPtr player) {
game->getParser().safe_function(game->getParser().core["block_interact"],
Api::Usertype::LocalPlayer(player.s()), Api::Usertype::Target(target));
}
void ServerDimension::blockPlaceOrInteract(const Target &target, std::shared_ptr<Player> player) {
std::tuple<sol::optional<LuaItemStack>, sol::optional<glm::vec3>> res = game.getParser().safe_function(
game.getParser().core["block_interact_or_place"], Api::Usertype::LocalPlayer(std::static_pointer_cast<LocalPlayer>(player)), Api::Usertype::Target(target));
void ServerDimension::blockPlaceOrInteract(const Target &target, PlayerPtr player) {
std::tuple<sol::optional<Api::Usertype::ItemStack>, sol::optional<glm::vec3>> res = game->getParser().safe_function(
game->getParser().core["block_interact_or_place"], Api::Usertype::LocalPlayer(player.s()), Api::Usertype::Target(target));
auto stack = std::get<sol::optional<LuaItemStack>>(res);
auto stack = std::get<sol::optional<Api::Usertype::ItemStack>>(res);
if (!stack) return;
auto& inv = std::static_pointer_cast<LocalPlayer>(player)->getInventory();
if (inv.hasList(player->getWieldList())) inv.getList(player->getWieldList()).setStack(player->getWieldIndex(), ItemStack(*stack, game));
auto inv = player.s()->getInventory();
if (inv->hasList(player->getWieldList())) inv->getList(player->getWieldList())->setStack(player->getWieldIndex(), ItemStack(*stack, game));
}
double ServerDimension::blockHit(const Target &target, std::shared_ptr<Player> player) {
double ServerDimension::blockHit(const Target &target, PlayerPtr player) {
double timeout = 0, damage = 0;
sol::tie(damage, timeout) = game.getParser().safe_function(game.getParser().core["block_hit"],
Api::Usertype::LocalPlayer(std::static_pointer_cast<LocalPlayer>(player)), Api::Usertype::Target(target));
sol::tie(damage, timeout) = game->getParser().safe_function(game->getParser().core["block_hit"],
Api::Usertype::LocalPlayer(player.s()), Api::Usertype::Target(target));
return timeout;
}

View File

@ -15,17 +15,17 @@ class ServerLuaEntity;
class ServerDimension : public Dimension {
public:
ServerDimension(ServerSubgame& game, ServerWorld& world, const std::string& identifier, unsigned int ind);
ServerDimension(SubgamePtr game, ServerWorld& world, const std::string& identifier, unsigned int ind);
virtual void update(double delta) override;
void setChunk(std::shared_ptr<Chunk> chunk) override;
bool setBlock(glm::ivec3 pos, unsigned int block) override;
virtual void blockPlace(const Target &target, std::shared_ptr<Player> player) override;
virtual void blockPlaceOrInteract(const Target &target, std::shared_ptr<Player> player) override;
virtual void blockInteract(const Target &target, std::shared_ptr<Player> player) override;
virtual double blockHit(const Target &target, std::shared_ptr<Player> player) override;
virtual void blockPlace(const Target &target, PlayerPtr player) override;
virtual void blockPlaceOrInteract(const Target &target, PlayerPtr player) override;
virtual void blockInteract(const Target &target, PlayerPtr player) override;
virtual double blockHit(const Target &target, PlayerPtr player) override;
void addLuaEntity(std::shared_ptr<ServerLuaEntity>& entity);
void removeLuaEntity(std::shared_ptr<ServerLuaEntity>& entity);