Generalize Game class for use with Lua Api Modules

In the future, I would like to split item and block defs in two arrays,
and put all definitions inside a `defs` class.
master
Nicole Collings 2020-07-25 11:55:48 -07:00
parent d56d6f890a
commit 3de0c561e2
68 changed files with 412 additions and 313 deletions

View File

@ -12,7 +12,7 @@ zepha.register_item("base:hand", {
-- Register main and hand inventories
if zepha.server then
zepha.register_on("new_player", function(p)
zepha.bind("new_player", function(p)
local inv = p:get_inventory()
local main = inv:add_list("main", 30, 10)

View File

@ -1,9 +1,11 @@
-- Load Libraries
runfile(_PATH .. "modules/gui")
runfile(_PATH .. "modules/dump")
runfile(_PATH .. "modules/math")
runfile(_PATH .. "modules/table")
runfile(_PATH .. "modules/after")
runfile(_PATH .. "modules/vector")
runfile(_PATH .. "modules/gui")
runfile(_PATH .. "modules/callbacks")
-- Register base models (if not on main menu)
if zepha.client or zepha.server then runfile(_PATH .. "game/init") end

View File

@ -0,0 +1,16 @@
zepha.delayed_functions = {}
function zepha.after(fn, timeout)
table.insert(zepha.delayed_functions, {fn = fn, timeout = timeout, at = zepha.time.s()})
end
function zepha.__builtin.update_delayed_functions()
local time = zepha.time.s()
for k, v in pairs(zepha.delayed_functions) do
if v.at <= time then
local redo = v.fn()
if redo then v.at = time + v.timeout
else table.remove(zepha.delayed_functions, k) end
end
end
end

View File

@ -0,0 +1,14 @@
zepha.registered_callbacks = {}
function zepha.bind(event, fn)
if zepha.registered_callbacks[event] == nil then zepha.registered_callbacks[event] = {} end
table.insert(zepha.registered_callbacks[event], fn)
end
function zepha.trigger(event, ...)
if zepha.registered_callbacks[event] == nil then return nil end
for _, EVT_CALLBACK in pairs(zepha.registered_callbacks[event]) do
if (type(EVT_CALLBACK) == "function") then EVT_CALLBACK(...) end
end
end

View File

@ -235,9 +235,8 @@ set(ZEPHA_SRC
game/scene/menu/Subgame.h
game/scene/menu/SubgameConfig.h
game/scene/menu/MenuSandbox.cpp
game/scene/menu/MenuSandbox.h
lua/api/menu/mDelay.h
lua/api/menu/mSetGui.h
game/scene/menu/MenuSandbox.h
lua/api/menu/mSetGui.h
game/hud/GuiBuilder.cpp
game/hud/GuiBuilder.h
game/hud/GameGuiBuilder.cpp
@ -268,9 +267,8 @@ set(ZEPHA_SRC
lua/api/class/ServerLocalLuaEntity.cpp
lua/api/class/ServerLocalLuaEntity.h
lua/api/modules/register_item.h
lua/api/modules/register_biome.h
lua/api/modules/delay.h
lua/api/modules/register_block.h
lua/api/modules/register_biome.h
lua/api/modules/register_block.h
lua/api/modules/register_blockmodel.h
lua/api/modules/register_entity.h
game/scene/world/World.cpp
@ -292,8 +290,7 @@ set(ZEPHA_SRC
util/RIE.h
lua/api/class/ServerLuaPlayer.cpp
lua/api/class/ServerLuaPlayer.h
lua/api/modules/register_on.h
lua/api/functions/trigger_event.h
lua/api/functions/trigger_event.h
lua/parser/ServerModHandler.cpp
lua/parser/ServerModHandler.h
lua/parser/LocalModHandler.cpp
@ -319,6 +316,6 @@ set(ZEPHA_SRC
def/gen/MapGenProps.cpp
def/gen/MapGenProps.h
lua/api/class/LuaGuiElement.cpp
lua/api/class/LuaGuiElement.h world/Dimension.cpp world/Dimension.h world/fs/FileManipulator.cpp world/fs/FileManipulator.h def/item/BlockModel.cpp net/server/world/ServerPacketStream.cpp net/server/world/ServerPacketStream.h lua/register/CreateBlockModel.cpp lua/register/CreateBlockModel.h lua/customization/vec3.hpp)
lua/api/class/LuaGuiElement.h world/Dimension.cpp world/Dimension.h world/fs/FileManipulator.cpp world/fs/FileManipulator.h def/item/BlockModel.cpp net/server/world/ServerPacketStream.cpp net/server/world/ServerPacketStream.h lua/register/CreateBlockModel.cpp lua/register/CreateBlockModel.h lua/customization/vec3.hpp lua/api/modules/Base.h lua/api/modules/Register.cpp lua/api/modules/Register.h def/Game.h def/Game.cpp lua/api/modules/Base.cpp)
add_library (Zepha_Core ${ZEPHA_SRC})

View File

@ -4,24 +4,28 @@
#include "ClientGame.h"
ClientGame::ClientGame(const ClientGame &copy) : ClientGame(copy.tex_path) {}
#include "gen/LocalBiomeAtlas.h"
#include "LocalDefinitionAtlas.h"
#include "../lua/parser/LocalLuaParser.h"
ClientGame::ClientGame(const std::string& path) :
tex_path(path),
ClientGame::ClientGame(const std::string& texPath) :
texPath(texPath),
textures(2048),
parser(),
biomes(),
textures(2048),
defs(textures) {
lua(std::make_unique<LocalLuaParser>()),
biomes(std::make_unique<LocalBiomeAtlas>()),
defs(std::make_unique<LocalDefinitionAtlas>(textures)) {
textures.loadDirectory(tex_path);
textures.loadDirectory(texPath);
}
void ClientGame::init(LocalWorld &world, Player& player, ClientState& state) {
parser.init(*this, world, player, state);
lua->init(*this, world, player, state);
}
void ClientGame::update(double delta) {
parser.update(delta);
lua->update(delta);
textures.update();
}
ClientGame::~ClientGame() {}

View File

@ -7,32 +7,34 @@
#pragma once
#include "gen/MapGenProps.h"
#include "model/ModelStore.h"
#include "gen/LocalBiomeAtlas.h"
#include "texture/TextureAtlas.h"
#include "LocalDefinitionAtlas.h"
#include "../lua/parser/LocalLuaParser.h"
#include "Game.h"
#include "model/ModelStore.h"
#include "texture/TextureAtlas.h"
class Player;
class LocalWorld;
class ClientState;
class ClientGame {
class LocalLuaParser;
class LocalBiomeAtlas;
class LocalDefinitionAtlas;
class ClientGame : public Game {
public:
explicit ClientGame(const std::string& tex_path);
// This constructor is only valid for ClientGame objects!
ClientGame(const ClientGame& copy);
explicit ClientGame(const std::string& texPath);
~ClientGame();
void init(LocalWorld &world, Player& player, ClientState& state);
void update(double delta);
~ClientGame() = default;
std::string texPath;
std::string tex_path;
ModelStore models;
TextureAtlas textures;
TextureAtlas textures;
LocalLuaParser parser;
LocalDefinitionAtlas defs;
LocalBiomeAtlas biomes;
ModelStore models;
std::unique_ptr<LocalLuaParser> lua;
std::unique_ptr<LocalBiomeAtlas> biomes;
std::unique_ptr<LocalDefinitionAtlas> defs;
};

13
src/def/Game.cpp Normal file
View File

@ -0,0 +1,13 @@
//
// Created by aurailus on 2020-07-24.
//
#include "Game.h"
#include "gen/BiomeAtlas.h"
#include "DefinitionAtlas.h"
#include "../lua/LuaParser.h"
Game::Game() {}
Game::~Game() {}

21
src/def/Game.h Normal file
View File

@ -0,0 +1,21 @@
//
// Created by aurailus on 2020-07-24.
//
#pragma once
#include <memory>
class LuaParser;
class BiomeAtlas;
class DefinitionAtlas;
class Game {
public:
Game();
~Game();
std::unique_ptr<LuaParser> lua;
std::unique_ptr<BiomeAtlas> biomes;
std::unique_ptr<DefinitionAtlas> defs;
};

View File

@ -2,32 +2,32 @@
// Created by aurailus on 10/06/19.
//
#include <iostream>
#include <cute_files/cute_files.h>
#include "ServerGame.h"
#include "../util/Log.h"
#include "../def/gen/ServerBiomeAtlas.h"
#include "../def/ServerDefinitionAtlas.h"
#include "../net/server/conn/ClientList.h"
#include "../lua/parser/ServerLuaParser.h"
ServerGame::ServerGame(const std::string& subgame, unsigned int seed) :
subgamePath("subgames/" + subgame + "/"),
biomes(seed) {
if (subgame.empty()) {
std::cout << Log::err << "No subgame specified." << Log::endl;
exit(1);
}
else if (!cf_file_exists(subgamePath.data())) {
std::cout << Log::err << "Subgame '" << subgame << "' does not exist." << Log::endl;
exit(1);
}
defs(std::make_unique<ServerDefinitionAtlas>()),
biomes(std::make_unique<ServerBiomeAtlas>(seed)),
lua(std::make_unique<ServerLuaParser>()) {
if (subgame.empty()) throw std::runtime_error("No subgame specified.");
else if (!cf_file_exists(subgamePath.data())) throw std::runtime_error("Subgame does not exist.");
}
void ServerGame::init(ServerWorld &world) {
parser.init(*this, world, subgamePath);
lua->init(*this, world, subgamePath);
}
void ServerGame::update(double delta, ClientList& clients) {
parser.update(delta);
lua->update(delta);
}
ServerGame::~ServerGame() {}

View File

@ -4,25 +4,31 @@
#pragma once
#include "gen/ServerBiomeAtlas.h"
#include "ServerDefinitionAtlas.h"
#include "Game.h"
#include "../net/server/asset/AssetStorage.h"
#include "../lua/parser/ServerLuaParser.h"
class ServerWorld;
class ClientList;
class ServerGame {
class ServerLuaParser;
class ServerBiomeAtlas;
class ServerDefinitionAtlas;
class ServerGame : public Game {
public:
ServerGame(const std::string& subgame, unsigned int seed);
~ServerGame();
void init(ServerWorld& world);
void update(double delta, ClientList& clients);
std::string subgamePath;
ServerDefinitionAtlas defs;
ServerLuaParser parser;
ServerBiomeAtlas biomes;
AssetStorage assets;
AssetStorage assets;
std::unique_ptr<ServerLuaParser> lua;
std::unique_ptr<ServerBiomeAtlas> biomes;
std::unique_ptr<ServerDefinitionAtlas> defs;
};

View File

@ -8,6 +8,7 @@
#include "../../def/ClientGame.h"
#include "../../def/item/BlockDef.h"
#include "../scene/world/LocalWorld.h"
#include "../../def/LocalDefinitionAtlas.h"
Collidable::Collidable(LocalWorld &world, ClientGame& defs, const SelectionBox& collisionBox) :
world(world),
@ -67,7 +68,7 @@ bool Collidable::collidesAt(glm::vec3& pos, float stepUpMax) {
offset.z = collisionBox.a.z;
while (true) {
glm::vec3 offsetPos = glm::floor(pos + offset);
auto &def = game.defs.blockFromId(world.getBlock(offsetPos));
auto &def = game.defs->blockFromId(world.getBlock(offsetPos));
if (def.solid)
for (auto &cBox : def.cBoxes)
@ -99,7 +100,7 @@ bool Collidable::collidesAt(glm::vec3& pos, float stepUpMax) {
offset.z = collisionBox.a.z;
while (true) {
glm::vec3 offsetPos = glm::floor(pos + offset);
auto& def = game.defs.blockFromId(world.getBlock(offsetPos));
auto& def = game.defs->blockFromId(world.getBlock(offsetPos));
if (def.solid) {
for (auto &cBox : def.cBoxes) {

View File

@ -12,6 +12,8 @@
#include "../../def/item/BlockDef.h"
#include "components/basic/GuiText.h"
#include "../scene/world/LocalWorld.h"
#include "../../def/gen/LocalBiomeAtlas.h"
#include "../../def/LocalDefinitionAtlas.h"
#include "components/compound/GuiLabelledGraph.h"
DebugGui::DebugGui(glm::vec2 bufferSize, ClientGame& defs) :
@ -79,7 +81,7 @@ void DebugGui::positionElements(glm::vec2 bufferSize) {
get<GuiLabelledGraph>("gpuGraph")->setPos({bufferWidth - 254, 90 + 80});
}
void DebugGui::update(Player& player, LocalWorld& world, ClientGame& defs, double fps, int /*chunks*/, int drawCalls, int ssGen, int ssPack) {
void DebugGui::update(Player& player, LocalWorld& world, ClientGame& game, double fps, int /*chunks*/, int drawCalls, int ssGen, int ssPack) {
{ //Top Right Graphs
get<GuiLabelledGraph>("fpsGraph")->pushValue(static_cast<float>(fps));
@ -104,7 +106,7 @@ void DebugGui::update(Player& player, LocalWorld& world, ClientGame& defs, doubl
{ //Top-left Data
unsigned int biomeID = world.getBiome(glm::floor(player.getPos()));
std::string biome = defs.biomes.biomeFromId(biomeID).identifier;
std::string biome = game.biomes->biomeFromId(biomeID).identifier;
glm::vec3 playerPos = glm::floor(player.getPos());
glm::vec3 chunkPos = Space::Chunk::world::fromBlock(playerPos);
@ -133,8 +135,8 @@ void DebugGui::update(Player& player, LocalWorld& world, ClientGame& defs, doubl
str << "Biome: " << biome << std::endl << std::endl;
str << "Texture Slots: " << defs.textures.textureSlotsUsed << " / " << defs.textures.maxTextureSlots
<< " (" << round(defs.textures.textureSlotsUsed / static_cast<float>(defs.textures.maxTextureSlots) * 100) << "%)" << 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;
PointedThing thing = player.getPointedThing();
if (thing.thing == PointedThing::Thing::BLOCK) {
@ -149,7 +151,7 @@ void DebugGui::update(Player& player, LocalWorld& world, ClientGame& defs, doubl
faceDir == EVec::BACK ? "BACK" :
"NONE" ;
str << "Pointing At: " << defs.defs.blockFromId(thing.target.block.blockId).identifier << std::endl;
str << "Pointing At: " << game.defs->blockFromId(thing.target.block.blockId).identifier << std::endl;
str << "Pointed Position: " << vecToString(thing.target.block.pos) << std::endl;
str << "Pointed Face: " << face << std::endl;
}
@ -165,8 +167,8 @@ void DebugGui::update(Player& player, LocalWorld& world, ClientGame& defs, doubl
std::ostringstream crossText;
if (thing.thing == PointedThing::Thing::BLOCK) {
crossText << defs.defs.blockFromId(thing.target.block.blockId).name
<< " (" << defs.defs.blockFromId(thing.target.block.blockId).identifier << ")" << std::endl;
crossText << game.defs->blockFromId(thing.target.block.blockId).name
<< " (" << game.defs->blockFromId(thing.target.block.blockId).identifier << ")" << std::endl;
}
get<GuiText>("crosshairText")->setText(crossText.str());
}

View File

@ -18,7 +18,7 @@ public:
void changeVisibilityState(int state);
void positionElements(glm::vec2 bufferSize);
void update(Player& player, LocalWorld& world, ClientGame& defs, double fps, int chunks, int drawCalls, int ssGen, int ssPack);
void update(Player& player, LocalWorld& world, ClientGame& game, double fps, int chunks, int drawCalls, int ssGen, int ssPack);
private:
int displayMode;
};

View File

@ -9,9 +9,9 @@
#include "../basic/GuiInventoryItem.h"
#include "../../../../def/ClientGame.h"
#include "../../../../def/texture/Font.h"
#include "../../../../def/LocalDefinitionAtlas.h"
#include "../../../inventory/LocalInventoryList.h"
#include "../../../inventory/LocalInventoryRefs.h"
#include "../../../inventory/LocalInventoryList.h"
GuiInventoryList::GuiInventoryList(const std::string &key) : GuiContainer(key) {}
@ -152,7 +152,7 @@ void GuiInventoryList::drawContents() {
if (stack.id == 0) continue;
auto item = std::make_shared<GuiInventoryItem>("item_" + std::to_string(i) + "_" + std::to_string(j));
item->create(scale, stack.count, defs->defs.fromId(stack.id), f);
item->create(scale, stack.count, defs->defs->fromId(stack.id), f);
add(item);
item->setPos({padding.x + j * (16*scale.x+innerPadding.x/scale.x), padding.y + i * (16*scale.y+innerPadding.y/scale.y)});
}

View File

@ -7,13 +7,17 @@
#include "ConnectScene.h"
#include "../ClientState.h"
#include "../graph/Renderer.h"
#include "../../net/Packet.h"
#include "../../lua/LuaMod.h"
#include "../graph/Renderer.h"
#include "../../net/Address.h"
#include "../../net/PacketType.h"
#include "../../net/PacketView.h"
#include "../../def/gen/LocalBiomeAtlas.h"
#include "../../def/LocalDefinitionAtlas.h"
#include "../hud/components/basic/GuiText.h"
#include "../hud/components/basic/GuiRect.h"
#include "../../lua/parser/LocalLuaParser.h"
#include "../../net/server/asset/AssetType.h"
ConnectScene::ConnectScene(ClientState &state, Address addr) : Scene(state),
@ -88,7 +92,7 @@ void ConnectScene::update() {
auto statusText = components.get<GuiText>("statusText");
statusText->setText(statusText->getText() + "Received block index-identifier table.\n");
state.defs.defs.setIdentifiers(p.d.read<std::vector<std::string>>());
state.defs.defs->setIdentifiers(p.d.read<std::vector<std::string>>());
Packet resp(PacketType::BIOME_IDENTIFIER_LIST);
resp.sendTo(connection.getPeer(), PacketChannel::CONNECT);
@ -97,7 +101,7 @@ void ConnectScene::update() {
auto statusText = components.get<GuiText>("statusText");
statusText->setText(statusText->getText() + "Received biome index-identifier table.\nDownloading mods...\n");
state.defs.biomes.setIdentifiers(p.d.read<std::vector<std::string>>());
state.defs.biomes->setIdentifiers(p.d.read<std::vector<std::string>>());
connectState = State::MODS;
Packet resp(PacketType::MODS);
@ -118,10 +122,10 @@ void ConnectScene::update() {
if (p.type == PacketType::MODS) {
auto luaMod = LuaMod::fromPacket(p);
statusText->setText(statusText->getText() + "Received mod " + luaMod.config.name + ".\n");
state.defs.parser.getHandler().addLuaMod(std::move(luaMod));
state.defs.lua->getHandler().addLuaMod(std::move(luaMod));
}
else if (p.type == PacketType::MOD_ORDER) {
state.defs.parser.getHandler().setModsOrder(p.d.read<std::vector<std::string>>());
state.defs.lua->getHandler().setModsOrder(p.d.read<std::vector<std::string>>());
statusText->setText(statusText->getText() + "Done downloading mods.\nReceived the mods order.\nDownloading media...\n");

View File

@ -10,9 +10,9 @@
#include "../../net/PacketView.h"
GameScene::GameScene(ClientState& state) : Scene(state),
refs(*game.defs, net),
game(state.defs),
world(game, &net),
refs(game.defs, net),
net(state.connection, game, player),
player(world, game, state.renderer, refs),
debugGui(state.renderer.window.getSize(), game) {

View File

@ -14,7 +14,6 @@
#include "../../hud/components/basic/GuiContainer.h"
// Modules
#include "../../../lua/api/menu/mDelay.h"
#include "../../../lua/api/menu/mSetGui.h"
#include "../../../lua/api/menu/mStartGame.h"
@ -28,7 +27,6 @@ MenuSandbox::MenuSandbox(glm::ivec2 &win, ClientState& state, std::shared_ptr<Gu
void MenuSandbox::reset() {
container->remove("error");
builder.clear(true);
delayed_functions.clear();
core = {};
mod = {};
lua = sol::state {};
@ -45,7 +43,6 @@ void MenuSandbox::loadApi() {
ClientApi::gui_element(lua);
MenuApi::delay (core, delayed_functions);
MenuApi::set_gui (builder, win, lua, core);
MenuApi::start_game (state, core);
@ -71,7 +68,6 @@ void MenuSandbox::windowResized() {
}
void MenuSandbox::update(double delta) {
LuaParser::update(delta);
builder.update();
}

View File

@ -7,6 +7,7 @@
#include "../../../lua/LuaParser.h"
#include "../../hud/GuiBuilder.h"
#include "../../../lua/LuaMod.h"
class Subgame;
class AtlasRef;

View File

@ -9,10 +9,13 @@
#include "WorldInterpolationStream.h"
#include "../../../world/chunk/Chunk.h"
#include "../../../def/item/BlockDef.h"
#include "../../../net/client/ClientNetworkInterpreter.h"
#include "../../../def/gen/LocalBiomeAtlas.h"
#include "../../../def/LocalDefinitionAtlas.h"
#include "../../../lua/parser/LocalLuaParser.h"
#include "../../entity/engine/ParticleEntity.h"
#include "../../entity/engine/BlockCrackEntity.h"
#include "../../../lua/api/class/LocalLuaPlayer.h"
#include "../../../net/client/ClientNetworkInterpreter.h"
LocalWorld::LocalWorld(ClientGame& defs, ClientNetworkInterpreter* server) :
defs(defs),
@ -60,14 +63,14 @@ void LocalWorld::setBlock(glm::ivec3 pos, unsigned int block) {
void LocalWorld::blockPlace(glm::vec3 pos, unsigned int block) {
if (block == LocalDefinitionAtlas::AIR) {
auto def = defs.defs.blockFromId(getBlock(pos));
auto def = defs.defs->blockFromId(getBlock(pos));
if (def.callbacks.count(Callback::BREAK_CLIENT))
defs.parser.safe_function(def.callbacks[Callback::BREAK_CLIENT], pos);
defs.lua->safe_function(def.callbacks[Callback::BREAK_CLIENT], pos);
}
else {
auto def = defs.defs.blockFromId(block);
auto def = defs.defs->blockFromId(block);
if (def.callbacks.count(Callback::PLACE_CLIENT))
defs.parser.safe_function(def.callbacks[Callback::PLACE_CLIENT], pos);
defs.lua->safe_function(def.callbacks[Callback::PLACE_CLIENT], pos);
}
net->blockPlace(pos, block);
@ -79,10 +82,10 @@ void LocalWorld::blockBreak(glm::vec3 pos) {
}
void LocalWorld::blockInteract(PointedThing &thing) {
auto def = defs.defs.blockFromId(getBlock(thing.target.block.pos));
auto def = defs.defs->blockFromId(getBlock(thing.target.block.pos));
if (def.callbacks.count(Callback::INTERACT_CLIENT))
defs.parser.safe_function(def.callbacks[Callback::INTERACT_CLIENT], thing.target.block.pos);
defs.lua->safe_function(def.callbacks[Callback::INTERACT_CLIENT], thing.target.block.pos);
net->blockInteract(thing.target.block.pos);
}
@ -90,11 +93,11 @@ void LocalWorld::blockInteract(PointedThing &thing) {
double LocalWorld::blockHit(PointedThing& thing) {
glm::ivec3 pos = thing.target.block.pos;
auto& blockDef = defs.defs.blockFromId(getBlock(thing.target.block.pos));
auto& blockDef = defs.defs->blockFromId(getBlock(thing.target.block.pos));
double damage = 0, timeout = 0;
sol::tie(damage, timeout) = defs.parser.safe_function(defs.parser.core["get_hit_impact"],
defs.parser.core.get<LocalLuaPlayer>("player"), blockDef.identifier);
sol::tie(damage, timeout) = defs.lua->safe_function(defs.lua->core["get_hit_impact"],
defs.lua->core.get<LocalLuaPlayer>("player"), blockDef.identifier);
if (damage == 0) return timeout;

View File

@ -2,6 +2,8 @@
// Created by aurailus on 27/03/19.
//
#include <noise/noise.h>
#include "MeshGenStream.h"
#include "ChunkMeshDetails.h"
@ -86,7 +88,7 @@ void MeshGenStream::Thread::exec() {
auto& u = jobs[i];
if (!u.busy) continue;
ChunkMeshGenerator m(u.meshDetails, game.defs, game.biomes, u.thisChunk, u.adjacentChunks, offsetSamplers);
ChunkMeshGenerator m(u.meshDetails, *game.defs, *game.biomes, u.thisChunk, u.adjacentChunks, offsetSamplers);
empty = false;
u.busy = false;
}

View File

@ -13,6 +13,7 @@
#include "../../../def/item/BlockDef.h"
#include "../../../world/chunk/Chunk.h"
#include "../../inventory/LocalInventory.h"
#include "../../../def/LocalDefinitionAtlas.h"
#include "../../inventory/LocalInventoryList.h"
#include "../../../net/client/NetPlayerField.h"
@ -115,7 +116,7 @@ void Player::updateCamera() {
renderer.camera.setYaw(yaw);
renderer.camera.setPitch(pitch);
auto type = game.defs.fromId(wieldItem).type;
auto type = game.defs->fromId(wieldItem).type;
glm::vec3 eyesPos = {pos.x, pos.y + EYE_HEIGHT, pos.z};
renderer.camera.setPos(eyesPos);
@ -169,7 +170,7 @@ void Player::findPointedThing(Input &input) {
}
unsigned int blockID = blockChunk->getBlock(Space::Block::relative::toChunk(roundedPos));
auto& boxes = game.defs.blockFromId(blockID).sBoxes;
auto& boxes = game.defs->blockFromId(blockID).sBoxes;
for (auto& sBox : boxes) {
auto face = sBox.intersects(rayEnd, roundedPos);
@ -191,7 +192,7 @@ void Player::updateWireframe() {
wireframe.setVisible(false);
}
else if (pointedThing.thing == PointedThing::Thing::BLOCK) {
auto& boxes = game.defs.blockFromId(pointedThing.target.block.blockId).sBoxes;
auto& boxes = game.defs->blockFromId(pointedThing.target.block.blockId).sBoxes;
float distance = glm::distance(pos, glm::vec3(pointedThing.target.block.pos) + glm::vec3(0.5));
wireframe.updateMesh(boxes, 0.002f + distance * 0.0014f);
@ -210,10 +211,10 @@ void Player::interact(Input& input, double delta) {
breakTime += delta;
}
else if (input.mousePressed(GLFW_MOUSE_BUTTON_RIGHT)) {
auto& target = game.defs.blockFromId(world.getBlock(pointedThing.target.block.pos));
auto& target = game.defs->blockFromId(world.getBlock(pointedThing.target.block.pos));
if (target.hasInteraction()) world.blockInteract(pointedThing);
else if (wieldItem > DefinitionAtlas::AIR && game.defs.fromId(wieldItem).type == ItemDef::Type::BLOCK) {
else if (wieldItem > DefinitionAtlas::AIR && game.defs->fromId(wieldItem).type == ItemDef::Type::BLOCK) {
world.blockPlace(pointedThing.target.block.pos + SelectionBox::faceToOffset(pointedThing.target.block.face), wieldItem);
}
else {
@ -371,7 +372,7 @@ void Player::updateWieldAndHandItems() {
handItem = handList && handList->getLength() > 0 ? handList->getStack(0).id : 0;
wieldItem = wieldList && wieldList->getLength() > wieldIndex ? wieldList->getStack(wieldIndex).id : 0;
auto& model = game.defs.fromId(wieldItem <= DefinitionAtlas::AIR ? handItem : wieldItem).entityModel;
auto& model = game.defs->fromId(wieldItem <= DefinitionAtlas::AIR ? handItem : wieldItem).entityModel;
handItemModel.setModel(model);
}

View File

@ -95,8 +95,8 @@ private:
LocalInventoryRefs& refs;
unsigned int wieldIndex = 0;
unsigned int handItem = DefinitionAtlas::AIR;
unsigned int wieldItem = DefinitionAtlas::AIR;
unsigned int handItem = 1; // Air
unsigned int wieldItem = 1; // Air
float yaw = 0;
float pitch = 0;

View File

@ -7,6 +7,8 @@
#include "../../../net/PacketView.h"
#include "../../../def/ClientGame.h"
#include "../../../world/chunk/Chunk.h"
#include "../../../def/gen/LocalBiomeAtlas.h"
#include "../../../def/LocalDefinitionAtlas.h"
WorldInterpolationStream::WorldInterpolationStream(unsigned int seed, ClientGame& game) {
threads.reserve(THREADS);
@ -72,7 +74,7 @@ std::unique_ptr<std::vector<std::shared_ptr<Chunk>>> WorldInterpolationStream::u
}
WorldInterpolationStream::Thread::Thread(ClientGame& game, unsigned int seed) :
gen(game.defs, game.biomes, seed),
gen(*game.defs, *game.biomes, seed),
thread(std::bind(&WorldInterpolationStream::Thread::exec, this)) {}
void WorldInterpolationStream::Thread::exec() {

View File

@ -10,9 +10,7 @@
#include "../util/Log.h"
std::string ErrorFormatter::formatError(const std::string &fileName, int line, const std::string &stack,
std::string file, bool ansiColors) {
std::string ErrorFormatter::formatError(const std::string &fileName, int line, const std::string &stack, std::string file, bool ansiColors) {
const std::string red = (ansiColors ? Log::red : "");
const std::string unbl = (ansiColors ? Log::unbl : "");
const std::string endl = (ansiColors ? Log::endl : "\n");

View File

@ -2,21 +2,4 @@
// Created by aurailus on 11/06/19.
//
#include "LuaParser.h"
void LuaParser::update(double delta) {
// Execute delayed functions
// TODO: Experiment with storing delayed functions inside of Lua and test performance.
auto it = delayed_functions.begin();
while (it != delayed_functions.end()) {
DelayedFunction& f = *it;
f.timeout -= delta;
if (f.timeout <= 0) {
sol::optional<bool> res = f.function(sol::as_args(f.args));
if (res && *res) f.timeout = f.initial_timeout;
else { it = delayed_functions.erase(it); continue; }
}
it++;
}
}
#include "LuaParser.h"

View File

@ -13,18 +13,10 @@
class LuaParser {
public:
constexpr static double UPDATE_STEP {1 / 60.0};
virtual void update(double delta);
constexpr static double UPDATE_STEP {1. / 60.};
virtual void update(double delta) = 0;
sol::state lua;
sol::table core;
struct DelayedFunction {
sol::function function;
std::vector<sol::object> args;
float timeout;
float initial_timeout;
};
std::list<DelayedFunction> delayed_functions;
};

View File

@ -9,6 +9,7 @@
#include "../../../def/ClientGame.h"
#include "../../../def/item/BlockDef.h"
#include "../../../def/item/CraftItemDef.h"
#include "../../../def/LocalDefinitionAtlas.h"
void LocalLuaEntity::snap_pos(glm::vec3 pos) {
entity->setPos(pos);
@ -84,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.defs.fromStr(arg);
ItemDef& def = defs.defs->fromStr(arg);
if (def.type == ItemDef::Type::BLOCK)
entity->setModel(static_cast<BlockDef&>(def).entityModel);

View File

@ -7,9 +7,10 @@
#include "ServerLocalLuaEntity.h"
#include "../../../def/ItemDef.h"
#include "../../../def/ClientGame.h"
#include "../../../def/item/BlockDef.h"
#include "../../../def/item/CraftItemDef.h"
#include "../../../def/ClientGame.h"
#include "../../../def/LocalDefinitionAtlas.h"
ServerLocalLuaEntity::ServerLocalLuaEntity(unsigned int id, ClientGame &defs, const std::string &appearance,
const std::string &arg1, const std::string &arg2) :
@ -24,7 +25,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.defs.fromStr(arg2);
ItemDef& def = defs.defs->fromStr(arg2);
if (def.type == ItemDef::Type::BLOCK)
entity->setModel(static_cast<BlockDef&>(def).entityModel);

View File

@ -7,6 +7,7 @@
#include "../../LuaParser.h"
#include "../../../def/ItemDef.h"
#include "../../../def/ServerGame.h"
#include "../../../def/ServerDefinitionAtlas.h"
void ServerLuaEntity::snap_pos(glm::vec3 pos) {
entity->setPos(pos);
@ -82,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.defs.fromStr(arg);
ItemDef& def = defs.defs->fromStr(arg);
// if (def.index == 0) throw "Invalid gameobject to display";
if (def.type == ItemDef::Type::BLOCK)

View File

@ -9,15 +9,6 @@
namespace Api {
static void trigger_event(sol::state& lua) {
lua.script(R"(
zepha.__builtin.trigger_event = function(event, ...)
if zepha.registered_callbacks[event] == nil then return nil end
for _, EVENT_CALLBACK in pairs(zepha.registered_callbacks[event]) do
if (type(EVENT_CALLBACK) == "function") then
EVENT_CALLBACK(...)
end
end
end
)");
}
}

View File

@ -1,20 +0,0 @@
//
// Created by aurailus on 2019-12-12.
//
#pragma once
#include <list>
#include "../../Lua.h"
#include "../../LuaParser.h"
namespace MenuApi {
void delay(sol::table &core, std::list<LuaParser::DelayedFunction> &funcs) {
core.set_function("delay", [&](sol::function function, float delay, sol::variadic_args args) {
std::vector<sol::object> argsObject {};
for (auto arg : args) argsObject.push_back(arg);
funcs.push_back(LuaParser::DelayedFunction{function, argsObject, delay, delay});
});
}
}

View File

@ -0,0 +1,14 @@
//
// Created by aurailus on 2020-07-24.
//
#include "Base.h"
#include "../../../def/ServerGame.h"
#include "../../../lua/LuaParser.h"
Api::Module::Base::Base(Api::Module::State &state, Game &game, sol::table &core) :
state(state),
game(game),
core(core),
lua(game.lua->lua) {}

View File

@ -0,0 +1,30 @@
//
// Created by aurailus on 2020-07-23.
//
#pragma once
#include <functional>
#include "sol/forward.hpp"
class Game;
namespace Api {
namespace Module {
enum class State { CLIENT, SERVER };
class Base {
public:
Base(State& state, Game& game, sol::table& core);
virtual void bind() = 0;
protected:
Game& game;
State& state;
sol::state& lua;
sol::table& core;
};
}
}

View File

@ -0,0 +1,27 @@
//
// Created by aurailus on 2020-07-24.
//
#include "Register.h"
#include "../../Lua.h"
void Api::Module::Register::bind() {
createRegisterFn("block", "blocks");
createRegisterFn("biome", "biomes");
createRegisterFn("entity", "entities");
createRegisterFn("keybind", "keybinds");
createRegisterFn("blockmodel", "blockmodels");
}
void Api::Module::Register::createRegisterFn(const std::string &name, const std::string &table) {
core[table] = lua.create_table();
core.set_function("register_" + name, [=](sol::this_environment env, std::string identifier, sol::table data)
{ registerFn(table, static_cast<sol::environment>(env), identifier, data); });
}
void Api::Module::Register::registerFn(const std::string& table, sol::environment env, const std::string& identifier, const sol::table& data) {
std::cout << env.get<std::string>("_MODNAME");
core[table][identifier] = data;
}

View File

@ -0,0 +1,19 @@
//
// Created by aurailus on 2020-07-24.
//
#pragma once
#include "Base.h"
namespace Api::Module {
class Register : public Api::Module::Base {
public:
using Base::Base;
void bind() override;
protected:
void createRegisterFn(const std::string& name, const std::string& table);
void registerFn(const std::string& table, sol::environment env, const std::string& identifier, const sol::table& data);
};
}

View File

@ -1,20 +0,0 @@
//
// Created by aurailus on 2020-01-09.
//
#pragma once
#include "../../../lua/LuaParser.h"
namespace Api {
static void delay(sol::table& core, std::list<LuaParser::DelayedFunction>& funcs) {
core.set_function("delay", [&](sol::optional<sol::function> function, sol::optional<float> delay, sol::variadic_args args) {
if (!function) throw std::runtime_error("expected a function as the first argument.");
if (!delay) throw std::runtime_error("expected a number as the second argument.");
std::vector<sol::object> argsObject {};
for (auto arg : args) argsObject.push_back(arg);
funcs.push_back({*function, argsObject, *delay, *delay});
});
}
}

View File

@ -1,29 +0,0 @@
//
// Created by aurailus on 2020-02-17.
//
#pragma once
namespace Api {
static void register_on_s(sol::state& lua, sol::table& core, ServerLuaParser& parser) {
core["registered_callbacks"] = lua.create_table();
core["registered_callbacks"]["new_player"] = lua.create_table();
core["registered_callbacks"]["player_join"] = lua.create_table();
core["registered_callbacks"]["player_leave"] = lua.create_table();
core["registered_callbacks"]["place"] = lua.create_table();
core["registered_callbacks"]["break"] = lua.create_table();
core["registered_callbacks"]["after_place"] = lua.create_table();
core["registered_callbacks"]["after_break"] = lua.create_table();
lua.script(R"(
zepha.register_on = function(event, callback)
if type(event) ~= "string" then return nil end
if type(callback) ~= "function" then return nil end
if zepha.registered_callbacks[event] == nil then return nil end
table.insert(zepha.registered_callbacks[event], callback)
end
)");
}
}

View File

@ -21,7 +21,6 @@
#include "../api/usertype/cAnimationManager.h"
// Modules
#include "../api/modules/delay.h"
#include "../api/modules/register_block.h"
#include "../api/modules/register_blockmodel.h"
#include "../api/modules/register_biome.h"
@ -53,11 +52,10 @@ void LocalLuaParser::init(ClientGame& defs, LocalWorld& world, Player& player, C
}
void LocalLuaParser::update(double delta) {
LuaParser::update(delta);
this->delta += delta;
while (this->delta > static_cast<double>(UPDATE_STEP)) {
safe_function(core["__builtin"]["update_entities"], static_cast<double>(UPDATE_STEP));
safe_function(core["__builtin"]["update_delayed_functions"]);
this->delta -= static_cast<double>(UPDATE_STEP);
}
}
@ -84,8 +82,6 @@ void LocalLuaParser::loadApi(ClientGame &defs, LocalWorld &world, Player& player
core["player"] = LocalLuaPlayer(player);
// Modules
Api::delay (core, delayed_functions);
Api::register_block (lua, core);
Api::register_blockmodel (lua, core);
Api::register_biome (lua, core);
@ -93,9 +89,9 @@ void LocalLuaParser::loadApi(ClientGame &defs, LocalWorld &world, Player& player
Api::register_entity (lua, core);
Api::register_keybind (lua, core);
Api::get_block (core, defs.defs, world);
Api::set_block (core, defs.defs, world);
Api::remove_block (core, defs.defs, world);
Api::get_block (core, *defs.defs, world);
Api::set_block (core, *defs.defs, world);
Api::remove_block (core, *defs.defs, world);
Api::add_entity_c (lua, core, defs, world);
Api::remove_entity_c (lua, core, defs, world);

View File

@ -20,14 +20,12 @@
#include "../api/usertype/cItemStack.h"
// Modules
#include "../api/modules/delay.h"
#include "../api/modules/register_block.h"
#include "../api/modules/register_blockmodel.h"
#include "../api/modules/register_biome.h"
#include "../api/modules/register_item.h"
#include "../api/modules/register_entity.h"
#include "../api/modules/register_keybind.h"
#include "../api/modules/register_on.h"
#include "../api/modules/set_block.h"
#include "../api/modules/get_block.h"
#include "../api/modules/remove_block.h"
@ -56,11 +54,10 @@ void ServerLuaParser::init(ServerGame& defs, ServerWorld& world, const std::stri
}
void ServerLuaParser::update(double delta) {
LuaParser::update(delta);
this->delta += delta;
while (this->delta > static_cast<double>(UPDATE_STEP)) {
safe_function(core["__builtin"]["update_entities"], static_cast<double>(UPDATE_STEP));
safe_function(core["__builtin"]["update_delayed_functions"]);
this->delta -= static_cast<double>(UPDATE_STEP);
}
}
@ -80,15 +77,15 @@ void ServerLuaParser::playerConnected(std::shared_ptr<ServerClient> client) {
sol::object player = players[players.size()];
safe_function(core["__builtin"]["trigger_event"], "new_player", player);
safe_function(core["__builtin"]["trigger_event"], "player_join", player);
safe_function(core["trigger"], "new_player", player);
safe_function(core["trigger"], "player_join", player);
}
void ServerLuaParser::playerDisconnected(std::shared_ptr<ServerClient> client) {
for (auto& pair : core.get<sol::table>("players")) {
ServerLuaPlayer& p = pair.second.as<ServerLuaPlayer>();
if (p.get_cid() == client->cid) {
safe_function(core["__builtin"]["trigger_event"], "player_disconnect", p);
safe_function(core["trigger"], "player_disconnect", p);
p.is_player = false;
core.get<sol::table>("players")[pair.first] = sol::nil;
@ -113,19 +110,16 @@ void ServerLuaParser::loadApi(ServerGame &defs, ServerWorld &world) {
core["players"] = lua.create_table();
// Modules
Api::delay (core, delayed_functions);
Api::register_block (lua, core);
Api::register_blockmodel (lua, core);
Api::register_biome (lua, core);
Api::register_item (lua, core);
Api::register_entity (lua, core);
Api::register_keybind (lua, core);
Api::register_on_s (lua, core, *this);
Api::get_block (core, defs.defs, world);
Api::set_block (core, defs.defs, world);
Api::remove_block (core, defs.defs, world);
Api::get_block (core, *defs.defs, world);
Api::set_block (core, *defs.defs, world);
Api::remove_block (core, *defs.defs, world);
Api::add_entity_s (lua, core, defs, world);
Api::remove_entity_s (lua, core, defs, world);

View File

@ -2,17 +2,18 @@
// Created by aurailus on 2020-02-19.
//
#include <sstream>
#include <fstream>
#include <json/json.hpp>
#include <gzip/compress.hpp>
#include <stb_image/stb_image.h>
#include <cute_files/cute_files.h>
#include "ServerModHandler.h"
#include "../../def/ServerGame.h"
#include "../../net/Serializer.h"
#include "ServerModHandler.h"
void ServerModHandler::loadMods(ServerGame& defs, const std::string &path) {
auto modDirs = findModDirectories(path);
mods = initializeLuaMods(modDirs);

View File

@ -14,6 +14,8 @@
#include "../../def/ServerGame.h"
#include "../../def/gen/BiomeDef.h"
#include "../../def/item/BlockDef.h"
#include "../../def/gen/LocalBiomeAtlas.h"
#include "../../def/gen/ServerBiomeAtlas.h"
namespace RegisterBiomes {
static noise::module::Module* parseNoise(std::vector<noise::module::Module*>& modules, sol::table noise) {
@ -311,15 +313,15 @@ namespace RegisterBiomes {
// Create biome definition
BiomeDef* biomeDef = new BiomeDef(
identifier, biomes.size(),
temperature, humidity, roughness,
defs.blockFromStr(*bTop).index,
defs.blockFromStr(*bSoil).index,
defs.blockFromStr(*bRock).index,
heightmapModules,
volumeModules,
schematics,
glm::vec3(Util::hexToColorVec((*biomeTint)))
identifier, biomes.size(),
temperature, humidity, roughness,
defs.blockFromStr(*bTop).index,
defs.blockFromStr(*bSoil).index,
defs.blockFromStr(*bRock).index,
heightmapModules,
volumeModules,
schematics,
glm::vec3(Util::hexToColorVec((*biomeTint)))
);
// Add biome to biomes
@ -327,13 +329,13 @@ namespace RegisterBiomes {
}
}
static void server(sol::table& core, ServerGame& defs) {
registerBiomes(core.get<sol::table>("registered_biomes"), defs.defs, defs.biomes);
defs.biomes.generateVoronoi();
static void server(sol::table& core, ServerGame& game) {
registerBiomes(core.get<sol::table>("registered_biomes"), *game.defs, *game.biomes);
game.biomes->generateVoronoi();
}
static void client(sol::table& core, ClientGame& defs) {
registerBiomes(core.get<sol::table>("registered_biomes"), defs.defs, defs.biomes);
defs.biomes.generateVoronoi();
static void client(sol::table& core, ClientGame& game) {
registerBiomes(core.get<sol::table>("registered_biomes"), *game.defs, *game.biomes);
game.biomes->generateVoronoi();
}
};

View File

@ -14,6 +14,8 @@
#include "../../def/item/BlockModel.h"
#include "../../def/item/SelectionBox.h"
#include "../../def/item/CraftItemDef.h"
#include "../../def/LocalDefinitionAtlas.h"
#include "../../def/ServerDefinitionAtlas.h"
namespace RegisterBlocks {
@ -357,13 +359,13 @@ namespace RegisterBlocks {
}
}
static void server(sol::table& core, ServerGame& defs) {
static void server(sol::table& core, ServerGame& game) {
registerBlocks(core.get<sol::table>("registered_blocks"),
core.get<sol::table>("registered_blockmodels"), defs.defs, nullptr);
core.get<sol::table>("registered_blockmodels"), *game.defs, nullptr);
}
static void client(sol::table& core, ClientGame& defs) {
static void client(sol::table& core, ClientGame& game) {
registerBlocks(core.get<sol::table>("registered_blocks"),
core.get<sol::table>("registered_blockmodels"), defs.defs, &defs.textures);
core.get<sol::table>("registered_blockmodels"), *game.defs, &game.textures);
}
};

View File

@ -8,6 +8,8 @@
#include "../../def/ClientGame.h"
#include "../../def/ServerGame.h"
#include "../../def/gen/BiomeDef.h"
#include "../../def/LocalDefinitionAtlas.h"
#include "../../def/ServerDefinitionAtlas.h"
namespace RegisterItems {
static void registerItems(sol::table source, DefinitionAtlas& defs, TextureAtlas* atlas) {
@ -57,11 +59,11 @@ namespace RegisterItems {
}
}
static void server(sol::table& core, ServerGame& defs) {
registerItems(core.get<sol::table>("registered_items"), defs.defs, nullptr);
static void server(sol::table& core, ServerGame& game) {
registerItems(core.get<sol::table>("registered_items"), *game.defs, nullptr);
}
static void client(sol::table& core, ClientGame& defs) {
registerItems(core.get<sol::table>("registered_items"), defs.defs, &defs.textures);
static void client(sol::table& core, ClientGame& game) {
registerItems(core.get<sol::table>("registered_items"), *game.defs, &game.textures);
}
};

View File

@ -13,6 +13,8 @@
#include "../../util/Timer.h"
#include "../PacketChannel.h"
#include "../../def/item/BlockDef.h"
#include "../../def/ServerDefinitionAtlas.h"
#include "../../lua/parser/ServerLuaParser.h"
#include "../../lua/api/class/ServerLuaPlayer.h"
Server::Server(unsigned short port, const std::string& subgame) :
@ -22,7 +24,7 @@ Server::Server(unsigned short port, const std::string& subgame) :
defs(subgame, seed),
clientList(defs),
handler(port, 32),
refs(defs.defs, &clientList),
refs(*defs.defs, &clientList),
world(seed, defs, clientList) {
defs.init(world);
@ -129,39 +131,39 @@ void Server::handlePlayerPacket(ServerClient& client, PacketView& p) {
unsigned int worldBlock = (block == DefinitionAtlas::AIR ? world.getBlock(pos) : 0);
if (block == DefinitionAtlas::AIR) {
auto def = defs.defs.blockFromId(worldBlock);
auto def = defs.defs->blockFromId(worldBlock);
//TODO: stop casting to float vec3
if (def.callbacks.count(Callback::BREAK)) defs.parser.safe_function(def.callbacks[Callback::BREAK], glm::vec3(pos), ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "break", glm::vec3(pos), ServerLuaPlayer(client));
if (def.callbacks.count(Callback::BREAK)) defs.lua->safe_function(def.callbacks[Callback::BREAK], glm::vec3(pos), ServerLuaPlayer(client));
defs.lua->safe_function(defs.lua->core["trigger"], "break", glm::vec3(pos), ServerLuaPlayer(client));
}
else {
auto def = defs.defs.blockFromId(block);
auto def = defs.defs->blockFromId(block);
if (def.callbacks.count(Callback::PLACE))
defs.parser.safe_function(def.callbacks[Callback::PLACE], pos, ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "place", pos, ServerLuaPlayer(client));
defs.lua->safe_function(def.callbacks[Callback::PLACE], pos, ServerLuaPlayer(client));
defs.lua->safe_function(defs.lua->core["trigger"], "place", pos, ServerLuaPlayer(client));
}
world.setBlock(pos, block);
if (block == DefinitionAtlas::AIR) {
auto def = defs.defs.blockFromId(worldBlock);
auto def = defs.defs->blockFromId(worldBlock);
if (def.callbacks.count(Callback::AFTER_BREAK))
defs.parser.safe_function(def.callbacks[Callback::AFTER_BREAK], pos, ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "after_break", pos, ServerLuaPlayer(client));
defs.lua->safe_function(def.callbacks[Callback::AFTER_BREAK], pos, ServerLuaPlayer(client));
defs.lua->safe_function(defs.lua->core["trigger"], "after_break", pos, ServerLuaPlayer(client));
}
else {
auto def = defs.defs.blockFromId(block);
auto def = defs.defs->blockFromId(block);
if (def.callbacks.count(Callback::AFTER_PLACE))
defs.parser.safe_function(def.callbacks[Callback::AFTER_PLACE], pos, ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "after_place", pos, ServerLuaPlayer(client));
defs.lua->safe_function(def.callbacks[Callback::AFTER_PLACE], pos, ServerLuaPlayer(client));
defs.lua->safe_function(defs.lua->core["trigger"], "after_place", pos, ServerLuaPlayer(client));
}
break;
}
case PacketType::BLOCK_INTERACT: {
glm::ivec3 pos = p.d.read<glm::ivec3>();
auto def = defs.defs.blockFromId(world.getBlock(pos));
auto def = defs.defs->blockFromId(world.getBlock(pos));
if (def.callbacks.count(Callback::INTERACT))
defs.parser.safe_function(def.callbacks[Callback::INTERACT], pos, ServerLuaPlayer(client));
defs.lua->safe_function(def.callbacks[Callback::INTERACT], pos, ServerLuaPlayer(client));
break;
}
case PacketType::INV_WATCH: {

View File

@ -9,19 +9,23 @@
#include "../asset/AssetType.h"
#include "../conn/ServerClient.h"
#include "../../../def/ItemDef.h"
#include "../../../def/ServerGame.h"
#include "../../../def/gen/BiomeDef.h"
#include "../../../def/gen/ServerBiomeAtlas.h"
#include "../../../def/ServerDefinitionAtlas.h"
#include "../../../lua/parser/ServerLuaParser.h"
ServerConfig::ServerConfig(ServerGame &defs) : game(defs) {}
void ServerConfig::init() {
blockIdentifierList.reserve(static_cast<unsigned long>(game.defs.size()));
for (unsigned int i = 0; i < game.defs.size(); i++) {
blockIdentifierList.push_back(game.defs.fromId(i).identifier);
blockIdentifierList.reserve(static_cast<unsigned long>(game.defs->size()));
for (unsigned int i = 0; i < game.defs->size(); i++) {
blockIdentifierList.push_back(game.defs->fromId(i).identifier);
}
biomeIdentifierList.reserve(static_cast<unsigned long>(game.biomes.size()));
for (unsigned int i = 0; i < game.biomes.size(); i++) {
biomeIdentifierList.push_back(game.biomes.biomeFromId(i).identifier);
biomeIdentifierList.reserve(static_cast<unsigned long>(game.biomes->size()));
for (unsigned int i = 0; i < game.biomes->size(); i++) {
biomeIdentifierList.push_back(game.biomes->biomeFromId(i).identifier);
}
}
@ -34,7 +38,7 @@ bool ServerConfig::handlePacket(ServerClient& client, PacketView& r) {
case PacketType::SERVER_INFO: {
Serializer()
.append(game.biomes.seed)
.append(game.biomes->seed)
.packet(PacketType::SERVER_INFO)
.sendTo(client.peer, PacketChannel::CONNECT);
break;
@ -57,7 +61,7 @@ bool ServerConfig::handlePacket(ServerClient& client, PacketView& r) {
}
case PacketType::MODS: {
game.parser.sendModsPacket(client.peer);
game.lua->sendModsPacket(client.peer);
break;
}

View File

@ -4,8 +4,10 @@
#pragma once
#include "../../../def/ServerGame.h"
#include "../../PacketView.h"
class PacketView;
class ServerGame;
class ServerClient;
class ServerConfig {

View File

@ -11,6 +11,7 @@
#include "../../../util/Log.h"
#include "../../../def/ServerGame.h"
#include "../../client/NetPlayerField.h"
#include "../../../lua/parser/ServerLuaParser.h"
ClientList::ClientList(ServerGame& defs) :
defs(defs) {}
@ -19,7 +20,7 @@ void ClientList::handleConnect(ENetEvent e, InventoryRefs& refs) {
ENetPeer* peer = e.peer;
ENetAddress& addr = peer->address;
auto client = std::make_shared<ServerClient>(peer, addr, defs.defs, refs);
auto client = std::make_shared<ServerClient>(peer, addr, refs);
clients.push_back(client);
peer->data = client.get();
@ -31,7 +32,7 @@ void ClientList::handleDisconnect(ENetEvent e) {
for (unsigned int i = 0; i < clients.size(); i++) {
if (clients[i]->cid == cid) {
defs.parser.playerDisconnected(clients[i]);
defs.lua->playerDisconnected(clients[i]);
clients.erase(clients.begin() + i);
break;
}
@ -47,7 +48,7 @@ void ClientList::createPlayer(std::shared_ptr<ServerClient> c) {
c->getInventory()->createList("cursor", 1, 1);
defs.parser.playerConnected(c);
defs.lua->playerConnected(c);
Packet p(PacketType::THIS_PLAYER_INFO);
p.data = Serializer()

View File

@ -7,7 +7,8 @@
#include <vector>
#include "ServerClient.h"
#include "../../../lua/parser/ServerLuaParser.h"
class ServerGame;
class ClientList {
public:

View File

@ -11,7 +11,7 @@
#include "../../client/NetPlayerField.h"
#include "../../../game/inventory/InventoryRefs.h"
ServerClient::ServerClient(ENetPeer *peer, ENetAddress address, DefinitionAtlas& defs, InventoryRefs& refs) :
ServerClient::ServerClient(ENetPeer *peer, ENetAddress address, InventoryRefs& refs) :
peer(peer),
address(address),
cid(peer->connectID),

View File

@ -20,7 +20,7 @@ class ServerClient {
public:
const static int CHUNK_SEND_RANGE = 32;
ServerClient(ENetPeer* peer, ENetAddress address, DefinitionAtlas& defs, InventoryRefs& refs);
ServerClient(ENetPeer* peer, ENetAddress address, InventoryRefs& refs);
void setUsername(const std::string& name);

View File

@ -6,6 +6,8 @@
#include "../../../def/ServerGame.h"
#include "../../../world/chunk/Chunk.h"
#include "../../../def/gen/ServerBiomeAtlas.h"
#include "../../../def/ServerDefinitionAtlas.h"
ServerGenStream::ServerGenStream(unsigned int seed, ServerGame& game) {
threads.reserve(THREADS);
@ -51,7 +53,7 @@ std::unique_ptr<std::vector<ServerGenStream::FinishedBlockJob>> ServerGenStream:
}
ServerGenStream::Thread::Thread(ServerGame& game, unsigned int seed) :
gen(game.defs, game.biomes, seed),
gen(*game.defs, *game.biomes, seed),
thread(std::bind(&ServerGenStream::Thread::exec, this)) {}
void ServerGenStream::Thread::exec() {

View File

@ -19,6 +19,7 @@
#include "../../../world/chunk/Chunk.h"
#include "../../../world/chunk/MapBlock.h"
#include "../../../world/fs/FileManipulator.h"
#include "../../../def/ServerDefinitionAtlas.h"
#include "../../../lua/api/class/ServerLuaEntity.h"
ServerWorld::ServerWorld(unsigned int seed, ServerGame& game, ClientList& clients) :
@ -217,11 +218,11 @@ void ServerWorld::setBlock(glm::ivec3 pos, unsigned int block) {
auto oldBlock = getBlock(pos);
if (block == DefinitionAtlas::AIR) {
auto def = game.defs.blockFromId(oldBlock);
auto def = game.defs->blockFromId(oldBlock);
if (def.callbacks.count(Callback::DESTRUCT)) def.callbacks[Callback::DESTRUCT](pos);
}
else {
auto def = game.defs.blockFromId(block);
auto def = game.defs->blockFromId(block);
if (def.callbacks.count(Callback::CONSTRUCT)) def.callbacks[Callback::CONSTRUCT](pos);
}
@ -243,11 +244,11 @@ void ServerWorld::setBlock(glm::ivec3 pos, unsigned int block) {
}
if (block == DefinitionAtlas::AIR) {
auto def = game.defs.blockFromId(oldBlock);
auto def = game.defs->blockFromId(oldBlock);
if (def.callbacks.count(Callback::AFTER_DESTRUCT)) def.callbacks[Callback::AFTER_DESTRUCT](pos);
}
else {
auto def = game.defs.blockFromId(block);
auto def = game.defs->blockFromId(block);
if (def.callbacks.count(Callback::AFTER_CONSTRUCT)) def.callbacks[Callback::AFTER_CONSTRUCT](pos);
}
}

View File

@ -7,6 +7,7 @@
#include <string>
#include <sstream>
#include <iostream>
#include <functional>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
@ -251,5 +252,15 @@ namespace Util {
constexpr static uint64_t hash(const char * m) {
return (*m) ? mix(*m, hash(m + 1)) : 0;
}
template <class C, typename Ret, typename ... Ts>
std::function<Ret(Ts...)> bind_this(C* c, Ret (C::*m)(Ts...)) {
return [=](auto&&... args) { return (c->*m)(std::forward<decltype(args)>(args)...); };
}
template <class C, typename Ret, typename ... Ts>
std::function<Ret(Ts...)> bind_this(const C* c, Ret (C::*m)(Ts...) const) {
return [=](auto&&... args) { return (c->*m)(std::forward<decltype(args)>(args)...); };
}
};

View File

@ -9,13 +9,14 @@
#include "../world/chunk/Region.h"
#include "../game/graph/Renderer.h"
#include "../world/chunk/MapBlock.h"
#include "../def/LocalDefinitionAtlas.h"
#include "../lua/api/class/LocalLuaEntity.h"
#include "../game/scene/world/MeshGenStream.h"
#include "../game/scene/world/graph/MeshChunk.h"
#include "../game/scene/world/ChunkMeshDetails.h"
#include "../lua/api/class/ServerLocalLuaEntity.h"
LocalDimension::LocalDimension(ClientGame &game) : Dimension(game.defs),
LocalDimension::LocalDimension(ClientGame &game) : Dimension(*game.defs),
meshGenStream(std::make_shared<MeshGenStream>(game, *this)),
game(game) {}

View File

@ -13,6 +13,7 @@
class Renderer;
class MeshChunk;
class PacketView;
class MeshGenStream;
class ChunkRenderElem;
class LocalLuaEntity;

View File

@ -9,11 +9,12 @@
#include "chunk/MapBlock.h"
#include "../def/gen/MapGen.h"
#include "../def/ServerGame.h"
#include "../def/ServerDefinitionAtlas.h"
#include "../net/server/conn/ServerClient.h"
#include "../net/server/world/ServerWorld.h"
#include "../lua/api/class/ServerLuaEntity.h"
ServerDimension::ServerDimension(ServerGame &game) : Dimension(game.defs), game(game) {}
ServerDimension::ServerDimension(ServerGame &game) : Dimension(*game.defs), game(game) {}
void ServerDimension::update(const std::vector<std::shared_ptr<ServerClient>> &clients, glm::ivec2 discardRange) {
for (const auto& region : regions) {

View File

@ -52,7 +52,7 @@ local menu = zepha.build_gui(function()
}
end)
-- zepha.delay(function()
-- zepha.after(function()
-- menu:remove("buttonPlay")
-- menu:remove("buttonServers")
-- menu:get("sidebar"):append(function(m) return Gui.Text({
@ -75,7 +75,7 @@ menu(function()
end)
local tick = 0
zepha.delay(function()
zepha.after(function()
local i = 1
local part = particle_wrap:get(i)
tick = tick + 0.012

View File

@ -77,7 +77,7 @@ zepha.register_item("@aurailus:basictools:wooden_shovel", {
});
if zepha.server then
zepha.register_on("new_player", function(player)
zepha.bind("new_player", function(player)
local inv = player:get_inventory():get_list("hot_wheel_1");
-- inv:add_stack({"@aurailus:basictools:wooden_pickaxe", 1})
-- inv:add_stack({"@aurailus:basictools:wooden_hatchet", 1})

View File

@ -26,7 +26,7 @@ zepha.register_block("@aurailus:crazyblocks:inventory", {
})
if zepha.server then
zepha.register_on("new_player", function(player)
zepha.bind("new_player", function(player)
player:get_inventory():get_list("hot_wheel_1"):add_stack({"@aurailus:crazyblocks:stacker", 1})
player:get_inventory():get_list("hot_wheel_1"):add_stack({"@aurailus:crazyblocks:inventory", 1})
player:get_inventory():get_list("hot_wheel_1"):add_stack({"@aurailus:crazyblocks:box", 1})

View File

@ -12,7 +12,7 @@ local item = 1
local function position()
rotating = true
zepha.delay(function()
zepha.after(function()
currentRotation = currentRotation + (desiredRotation - currentRotation) / 2
for i, list in ipairs(api.lists) do

View File

@ -1,4 +1,4 @@
zepha.register_on("new_player", function(p)
zepha.bind("new_player", function(p)
local inv = p:get_inventory()
inv:add_list("hot_wheel_1", 5, 5)
inv:add_list("hot_wheel_2", 5, 5)
@ -21,7 +21,7 @@ zepha.register_on("new_player", function(p)
-- inv.allow_take = function() return 0 end
--
-- inv.allow_put = function(slot, item)
-- zepha.delay(function()
-- zepha.after(function()
-- -- This delay is necessary to avoid the engine overwriting it with nothing
-- inv:set_stack(slot, item)
-- end, 0)

View File

@ -77,7 +77,7 @@ zepha.register_entity("@aurailus:item_collection:dropped_item", {
self.object.pos = p.pos + V{0, 0.90, 0}
self.scooping = true
zepha.delay(function()
zepha.after(function()
p:get_inventory():get_list("main"):add_stack({self.item, 1})
zepha.remove_entity(self)
end, 2/20)

View File

@ -1,7 +1,7 @@
local get_yield = runfile("@aurailus:item_collection/get_yield")
if zepha.server then
zepha.register_on("break", function(pos, player)
zepha.bind("break", function(pos, player)
local yields = get_yield(pos)
if yields == nil then return end

View File

@ -1,7 +1,7 @@
local get_yield = runfile("@aurailus:item_collection/get_yield")
if zepha.server then
zepha.register_on("break", function(pos)
zepha.bind("break", function(pos)
local yields = get_yield(pos)
if yields == nil then return end

View File

@ -30,7 +30,7 @@
-- textures = {"zeus:default:light_blue"},
-- light_source = c / 2,
-- on_place_client = function(pos)
-- zepha.delay(function()
-- zepha.after(function()
-- target = target + 1
-- if target == 8 then target = 1 end
-- zepha.set_block(pos, "zeus:default:light_" .. tostring(target))

View File

@ -1,4 +1,4 @@
zepha.register_on("new_player", function(p)
zepha.bind("new_player", function(p)
local inv = p:get_inventory()
-- Resize the main inventory

View File

@ -23,7 +23,7 @@ zepha.register_block('zeus:kinetic:axle_0', {
end
end,
on_construct = function(pos)
zepha.delay(function()
zepha.after(function()
zepha.set_block(pos, "zeus:kinetic:axle_1")
end, 4)
end
@ -41,7 +41,7 @@ zepha.register_block('zeus:kinetic:axle_1', {
{0, 6/16, 6/16, 1, 10/16, 10/16}
},
on_construct = function(pos)
zepha.delay(function()
zepha.after(function()
zepha.set_block(pos, "zeus:kinetic:axle_2")
end, 4)
end
@ -59,7 +59,7 @@ zepha.register_block('zeus:kinetic:axle_2', {
{0, 6/16, 6/16, 1, 10/16, 10/16}
},
on_construct = function(pos)
zepha.delay(function()
zepha.after(function()
zepha.set_block(pos, "zeus:kinetic:axle_3")
end, 4)
end
@ -77,7 +77,7 @@ zepha.register_block('zeus:kinetic:axle_3', {
{0, 6/16, 6/16, 1, 10/16, 10/16}
},
on_construct = function(pos)
zepha.delay(function()
zepha.after(function()
zepha.set_block(pos, "zeus:kinetic:axle_0")
end, 4)
end