Refactor LuaKeybindHandler, Error catching on keybinds and callbacks.

* Hotwheel implementation pt 1
master
Nicole Collings 2020-05-07 17:21:56 -07:00
parent 6add7becb4
commit 83dc74004e
34 changed files with 416 additions and 421 deletions

View File

@ -11,9 +11,9 @@ set(ZEPHA_SRC
game/graph/Camera.h
game/graph/Texture.cpp
game/graph/Texture.h
game/scene/world/graph/ChunkMeshGenerator.cpp
game/scene/world/graph/ChunkMeshGenerator.h
util/Timer.cpp
game/scene/world/graph/ChunkMeshGenerator.cpp
game/scene/world/graph/ChunkMeshGenerator.h
util/Timer.cpp
util/Timer.h
def/LocalDefinitionAtlas.cpp
def/LocalDefinitionAtlas.h
@ -82,8 +82,8 @@ set(ZEPHA_SRC
game/graph/frustum/FrustumAABB.h
server/world/ServerWorld.cpp
server/world/ServerWorld.h
server/world/ServerGenStream.cpp
server/world/ServerGenStream.h
server/world/ServerGenStream.cpp
server/world/ServerGenStream.h
game/scene/world/WorldInterpolationStream.cpp
game/scene/world/WorldInterpolationStream.h
util/Space.h
@ -144,7 +144,7 @@ set(ZEPHA_SRC
util/net/Address.h
game/scene/net/ServerConnection.cpp
game/scene/net/ServerConnection.h
game/scene/world/ChunkMeshDetails.h
game/scene/world/ChunkMeshDetails.h
game/hud/components/GuiComponent.cpp
game/hud/components/GuiComponent.h
game/hud/components/basic/GuiContainer.cpp
@ -201,10 +201,10 @@ set(ZEPHA_SRC
def/model/ModelStore.h
lua/api/modules/remove_entity.h
lua/api/functions/update_entities.h
lua/api/modules/register_keybind.h
lua/LuaInputManager.cpp
lua/LuaInputManager.h
lua/api/class/LocalLuaPlayer.cpp
lua/api/modules/register_keybind.h
lua/LuaKeybindHandler.cpp
lua/LuaKeybindHandler.h
lua/api/class/LocalLuaPlayer.cpp
lua/api/class/LocalLuaPlayer.h
game/entity/Collidable.cpp
game/entity/Collidable.h
@ -319,6 +319,20 @@ set(ZEPHA_SRC
game/inventory/InventoryList.h
lua/api/modules/time.h
util/net/PacketView.cpp
util/net/PacketView.h lua/api/modules/create_structure.h util/Any.h game/scene/world/graph/MeshFarMap.cpp game/scene/world/graph/MeshFarMap.h def/gen/MapGenProps.cpp def/gen/MapGenProps.h def/gen/FarMapGen.cpp def/gen/FarMapGen.h def/gen/FarMapJob.h game/scene/world/graph/FarMeshGenerator.cpp game/scene/world/graph/FarMeshGenerator.h game/scene/world/FarMapMeshDetails.h lua/api/class/LuaGuiElement.cpp lua/api/class/LuaGuiElement.h)
util/net/PacketView.h
lua/api/modules/create_structure.h
util/Any.h
game/scene/world/graph/MeshFarMap.cpp
game/scene/world/graph/MeshFarMap.h
def/gen/MapGenProps.cpp
def/gen/MapGenProps.h
def/gen/FarMapGen.cpp
def/gen/FarMapGen.h
def/gen/FarMapJob.h
game/scene/world/graph/FarMeshGenerator.cpp
game/scene/world/graph/FarMeshGenerator.h
game/scene/world/FarMapMeshDetails.h
lua/api/class/LuaGuiElement.cpp
lua/api/class/LuaGuiElement.h)
add_library (Zepha_Core ${ZEPHA_SRC})

View File

@ -4,7 +4,6 @@
#include "ClientGame.h"
//Note: This constructor is only for *uninitialized* LocalDef objects!
ClientGame::ClientGame(const ClientGame &copy) : ClientGame(copy.tex_path) {}
ClientGame::ClientGame(const std::string& path) :
@ -18,11 +17,11 @@ ClientGame::ClientGame(const std::string& path) :
textures.loadDirectory(tex_path);
}
void ClientGame::init(LocalWorld &world, Player& player) {
parser.init(*this, world, player);
void ClientGame::init(LocalWorld &world, Player& player, ClientState& state) {
parser.init(*this, world, player, state);
}
void ClientGame::update(double delta, bool* keys) {
parser.update(delta, keys);
void ClientGame::update(double delta) {
parser.update(delta);
textures.update();
}

View File

@ -1,4 +1,7 @@
//
// The ClientGame class stores all of the subgame data for the client.
// This data is used when in the GameScene. It is initialized when the client joins a game and cleared when they exit it.
// The data within is in an undefined state until the init method is called.
// Created by aurailus on 18/04/19.
//
@ -11,13 +14,16 @@
#include "LocalDefinitionAtlas.h"
#include "../lua/parser/LocalLuaParser.h"
class ClientState;
class ClientGame {
public:
explicit ClientGame(const std::string& tex_path);
// This constructor is only valid for ClientGame objects!
ClientGame(const ClientGame& copy);
void init(LocalWorld &world, Player& player);
void update(double delta, bool* keys);
void init(LocalWorld &world, Player& player, ClientState& state);
void update(double delta);
~ClientGame() = default;

View File

@ -18,7 +18,6 @@ Renderer::Renderer(glm::ivec2 win) :
blur (win, 1),
light (win, 2) {
window.initialize();
camera.create(window.getSize().x, window.getSize().y, glm::vec3(0, 1, 0));
ssao.createFromFile("./assets/shader/post/passThrough.vs", "./assets/shader/post/ssaoCalc.fs");

View File

@ -2,94 +2,143 @@
// Created by aurailus on 09/04/19.
//
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include "Input.h"
Input::Input() {
for (bool& key : keysDown) key = false;
for (bool& key : keysPressed) key = false;
for (bool& key : keysReleased) key = false;
#include "Window.h"
leftDown = false;
rightDown = false;
leftPressed = false;
rightPressed = false;
leftReleased = false;
rightReleased = false;
Input::Input() {
for (bool& key : keysDown) key = false;
for (bool& key : keysPressed) key = false;
for (bool& key : keysReleased) key = false;
for (bool& key : keysNew) key = false;
}
void Input::update(bool* keys) {
for (bool &key : keysPressed) key = false;
void Input::init(GLFWwindow *window, glm::ivec2* winDimensions) {
this->window = window;
this->winDimensions = winDimensions;
glfwSetKeyCallback(window, keyCallback);
}
void Input::setCallback(std::function<void(bool, int)> callback) {
this->callback = callback;
}
void Input::update() {
for (bool &key : keysPressed) key = false;
for (bool &key : keysReleased) key = false;
for (int i = 0; i < 1024; i++) {
bool key = keys[i];
bool key = keysNew[i];
if (key) {
if (!keysDown[i]) keysPressed[i] = true;
if (!keysDown[i]) {
keysPressed[i] = true;
if (callback) callback(true, i);
}
keysDown[i] = true;
}
else {
if (!keysReleased[i]) keysReleased[i] = true;
if (keysDown[i]) {
keysReleased[i] = true;
if (callback) callback(false, i);
}
keysDown[i] = false;
}
}
leftPressed = false;
leftReleased = false;
for (auto& s : mouseState) {
s.pressed = false;
s.released = false;
}
rightPressed = false;
rightReleased = false;
}
updateMouse(0);
updateMouse(1);
updateMouse(2);
void Input::updateLeftMouse(bool down) {
if (down) {
if (!leftDown) leftPressed = true;
leftDown = true;
if (glfwGetWindowAttrib(window, GLFW_FOCUSED) == GL_FALSE) {
mouseIsLocked = false;
delta = {};
}
else {
if (leftDown) leftReleased = true;
leftDown = false;
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
if (!mouseIsLocked) {
if (!forceMouseUnlocked && mousePressed(GLFW_MOUSE_BUTTON_LEFT)) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
glfwSetCursorPos(window, winDimensions->x / 2, winDimensions->y / 2);
mouseIsLocked = true;
}
}
else {
delta = {mouseX - (winDimensions->x / 2), -(mouseY - (winDimensions->y / 2))};
glfwSetCursorPos(window, winDimensions->x / 2, winDimensions->y / 2);
}
}
}
void Input::updateRightMouse(bool down) {
if (down) {
if (!rightDown) rightPressed = true;
rightDown = true;
}
else {
if (rightDown) rightReleased = true;
rightDown = false;
}
}
bool Input::isKeyDown(int key) {
bool Input::keyDown(int key) {
return keysDown[key];
}
bool Input::isKeyPressed(int key) {
bool Input::keyPressed(int key) {
return keysPressed[key];
}
bool Input::isKeyReleased(int key) {
bool Input::keyReleased(int key) {
return keysReleased[key];
}
bool Input::isMouseDown(int button) {
if (button == GLFW_MOUSE_BUTTON_LEFT) return leftDown;
else if (button == GLFW_MOUSE_BUTTON_RIGHT) return rightDown;
return false;
bool Input::mouseDown(int button) {
return mouseState[button].down;
}
bool Input::isMousePressed(int button) {
if (button == GLFW_MOUSE_BUTTON_LEFT) return leftPressed;
else if (button == GLFW_MOUSE_BUTTON_RIGHT) return rightPressed;
return false;
bool Input::mousePressed(int button) {
return mouseState[button].pressed;
}
bool Input::isMouseReleased(int button) {
if (button == GLFW_MOUSE_BUTTON_LEFT) return leftReleased;
else if (button == GLFW_MOUSE_BUTTON_RIGHT) return rightReleased;
return false;
bool Input::mouseReleased(int button) {
return mouseState[button].released;
}
void Input::updateMouse(int button) {
if (glfwGetMouseButton(window, button) == GLFW_PRESS) {
if (!mouseState[button].down) mouseState[button].pressed = true;
mouseState[button].down = true;
}
else {
if (mouseState[button].down) mouseState[button].released = true;
mouseState[button].down = false;
}
}
void Input::keyCallback(GLFWwindow* window, int key, int code, int action, int mode) {
auto w = static_cast<Window*>(glfwGetWindowUserPointer(window));
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE);
if (key > 0 && key < 1024) {
if (action == GLFW_PRESS) w->input.keysNew[key] = true;
else if (action == GLFW_RELEASE) w->input.keysNew[key] = false;
}
}
void Input::lockMouse(bool lock) {
forceMouseUnlocked = !lock;
mouseIsLocked = lock;
glfwSetCursorPos(window, winDimensions->x / 2, winDimensions->y / 2);
glfwSetInputMode(window, GLFW_CURSOR, (mouseIsLocked ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL));
delta = {};
}
glm::ivec2 Input::mousePos() {
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
return glm::ivec2 { static_cast<int>(xPos), static_cast<int>(yPos) };
}
glm::vec2 Input::mouseDelta() {
return delta;
}

View File

@ -4,26 +4,47 @@
#pragma once
#include <array>
#include <glm/vec2.hpp>
#include <functional>
class Input {
public:
Input();
void init(GLFWwindow* window, glm::ivec2* winDimensions);
void setCallback(std::function<void(bool, int)> callback);
void update(bool* keys);
void updateLeftMouse(bool down);
void updateRightMouse(bool down);
void update();
bool isKeyDown(int key);
bool isKeyPressed(int key);
bool isKeyReleased(int key);
bool keyDown(int key);
bool keyPressed(int key);
bool keyReleased(int key);
bool isMouseDown(int button);
bool isMousePressed(int button);
bool isMouseReleased(int button);
bool mouseDown(int button);
bool mousePressed(int button);
bool mouseReleased(int button);
void lockMouse(bool lock);
glm::ivec2 mousePos();
glm::vec2 mouseDelta();
private:
void updateMouse(int key);
static void keyCallback(GLFWwindow* window, int key, int code, int action, int mode);
GLFWwindow* window = nullptr;
glm::ivec2* winDimensions = nullptr;
bool keysNew[1024] {false};
bool keysDown[1024] {false};
bool keysPressed[1024] {false};
bool keysReleased[1024] {false};
bool leftPressed, leftDown, leftReleased;
bool rightReleased, rightDown, rightPressed;
struct mouse { bool down = false; bool pressed = false; bool released = false; };
std::array<mouse, 3> mouseState {};
glm::vec2 delta;
bool mouseIsLocked = false;
bool forceMouseUnlocked = false;
std::function<void(bool, int)> callback = nullptr;
};

View File

@ -3,98 +3,69 @@
//
#include <iostream>
#include "Window.h"
#include "../../../util/Log.h"
Window::Window() : Window({800, 600}) {};
Window::Window(glm::ivec2 win) :
win(win),
center(win.x / 2, win.y / 2) {}
win(win), center(win.x / 2, win.y / 2) {
int Window::initialize() {
//Initialize GLFW
if (!glfwInit()) {
printf("GLFW init failed\n");
std::cout << Log::err << "Failed to initialize GLFW context." << Log::endl;
glfwTerminate();
return 1;
exit(1);
}
//Version 3.3
// Version 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
//Compatibility - No Backwards compat, only forwards
// Compatibility - No Backwards compat, only forwards
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
//Create the window
mainWindow = glfwCreateWindow(win.x, win.y, "Zepha", nullptr, nullptr);
handCursor = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
if (!mainWindow) {
printf("GLFW window failed\n");
// Create the window
if (!(mainWindow = glfwCreateWindow(win.x, win.y, "Zepha", nullptr, nullptr))) {
std::cout << Log::err << "Failed to initialize GLFW window." << Log::endl;
glfwTerminate();
return 1;
exit(1);
}
glfwGetFramebufferSize(mainWindow, &win.x, &win.y);
//Set context for GLEW to our window
glfwMakeContextCurrent(mainWindow);
//Allow modern extension features
glewExperimental = GL_TRUE;
//Initialize GLEW
handCursor = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
// Initialize GLEW
GLenum error;
if ((error = glewInit()) != GLEW_OK) {
printf("GLEW init failed.");
fprintf(stderr, "Error: %s\n", glewGetErrorString(error));
std::cout << Log::err << "GLEW Encountered a fatal error:\n" << glewGetErrorString(error) << Log::endl;
glfwDestroyWindow(mainWindow);
glfwTerminate();
return 1;
exit(1);
}
glEnable(GL_DEPTH_TEST);
//Setup viewport (draw) size
glViewport(0, 0, win.x, win.y);
// Setup callbacks
glfwSetWindowUserPointer(mainWindow, this);
glfwSetKeyCallback(mainWindow, handleKeys);
glfwSetWindowSizeCallback(mainWindow, handleResize);
glfwSetInputMode(mainWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
glfwSetScrollCallback(mainWindow, scrollCallback);
glfwSetWindowSizeCallback(mainWindow, resizeCallback);
glfwSetInputMode(mainWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
glfwMaximizeWindow(mainWindow);
return 0;
input.init(mainWindow, &this->win);
}
void Window::update() {
double mouseX, mouseY;
if (glfwGetWindowAttrib(mainWindow, GLFW_FOCUSED) == GL_FALSE) {
mouseIsLocked = false;
delta = {};
}
else {
glfwGetCursorPos(mainWindow, &mouseX, &mouseY);
if (!mouseIsLocked) {
if (!forceMouseUnlocked && input.isMousePressed(GLFW_MOUSE_BUTTON_LEFT)) {
glfwSetInputMode(mainWindow, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
glfwSetCursorPos(mainWindow, center.x, center.y);
mouseIsLocked = true;
}
}
else {
delta = {mouseX - center.x, center.y - mouseY};
glfwSetCursorPos(mainWindow, center.x, center.y);
}
}
input.update(keys);
input.updateLeftMouse(glfwGetMouseButton(mainWindow, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS);
input.updateRightMouse(glfwGetMouseButton(mainWindow, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS);
input.update();
}
bool Window::shouldClose() {
@ -117,58 +88,26 @@ glm::ivec2 Window::getSize() {
return win;
}
glm::ivec2 Window::getMousePos() {
double xPos, yPos;
glfwGetCursorPos(mainWindow, &xPos, &yPos);
return glm::ivec2 {static_cast<int>(xPos), static_cast<int>(yPos)};
}
glm::vec2 Window::getDelta() {
return delta;
}
void Window::lockMouse(bool lock) {
forceMouseUnlocked = !lock;
mouseIsLocked = lock;
glfwSetCursorPos(mainWindow, center.x, center.y);
glfwSetInputMode(mainWindow, GLFW_CURSOR, (mouseIsLocked ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL));
delta = {};
}
void Window::setCursorHand(bool hand) {
glfwSetCursor(mainWindow, hand ? handCursor : nullptr);
}
void Window::scrollCallback(GLFWwindow* window, double xO, double yO) {
auto w = static_cast<Window*>(glfwGetWindowUserPointer(window));
}
void Window::resizeCallback(GLFWwindow* window, int width, int height) {
auto w = static_cast<Window*>(glfwGetWindowUserPointer(window));
glfwGetFramebufferSize(window, &w->win.x, &w->win.y);
glViewport(0, 0, w->win.x, w->win.y);
w->center = glm::ivec2(w->win.x / 2, w->win.y / 2);
for (auto& cb : w->resizeCallbacks) cb.second(w->win);
}
Window::~Window() {
glfwDestroyWindow(mainWindow);
glfwTerminate();
}
void Window::handleKeys(GLFWwindow* glfwWindow, int key, int, int action, int) {
auto window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(glfwWindow, GL_TRUE);
}
if (key > 0 && key < 1024) {
if (action == GLFW_PRESS) {
window->keys[key] = true;
}
else if (action == GLFW_RELEASE) {
window->keys[key] = false;
}
}
}
void Window::handleResize(GLFWwindow *glfwWindow, int, int) {
auto window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
glfwGetFramebufferSize(glfwWindow, &window->win.x, &window->win.y);
glViewport(0, 0, window->win.x, window->win.y);
window->center.x = window->win.x / 2;
window->center.y = window->win.y / 2;
for (auto& cb : window->resizeCallbacks) cb.second(window->win);
}
}

View File

@ -5,11 +5,11 @@
#pragma once
#include <map>
#include <cstdio>
#include <functional>
#include <glm/vec2.hpp>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/vec2.hpp>
#include "Input.h"
class Window {
@ -17,8 +17,6 @@ public:
Window();
Window(glm::ivec2 win);
int initialize();
void update();
bool shouldClose();
void swapBuffers();
@ -27,32 +25,24 @@ public:
void removeResizeCallback(const std::string& identifier);
glm::ivec2 getSize();
glm::ivec2 getMousePos();
glm::vec2 getDelta();
void lockMouse(bool lock);
void setCursorHand(bool hand);
~Window();
Input input;
bool keys[1024] {};
GLFWwindow* mainWindow = nullptr;
private:
GLFWwindow *mainWindow = nullptr;
static void scrollCallback(GLFWwindow* window, double xO, double yO);
static void resizeCallback(GLFWwindow* window, int width, int height);
GLFWcursor* handCursor = nullptr;
glm::ivec2 win;
glm::ivec2 center;
glm::vec2 delta;
bool mouseIsLocked = false;
bool forceMouseUnlocked = false;
bool keys[1024] {};
std::map<std::string, std::function<void(glm::ivec2)>> resizeCallbacks;
//Static so that GLFW can run callback
static void handleKeys(GLFWwindow* glfwWindow, int key, int code, int action, int mode);
static void handleResize(GLFWwindow* glfwWindow, int width, int height);
GLFWcursor* handCursor = nullptr;
};

View File

@ -28,7 +28,7 @@ void GameGui::update(double delta) {
hudBuilder.update();
menuBuilder.update();
handList->setPos((renderer.window.getMousePos() - glm::ivec2(24)) / 3 * 3);
handList->setPos((renderer.window.input.mousePos() - glm::ivec2(24)) / 3 * 3);
menuRoot->handleMouseInput(renderer.window);
}

View File

@ -72,11 +72,13 @@ void GuiComponent::setCallback(GuiComponent::CallbackType type, const callback&
}
void GuiComponent::handleMouseInput(Window &window) {
window.setCursorHand(mouseActivity(window.getMousePos()));
if (window.input.isMousePressed(GLFW_MOUSE_BUTTON_LEFT)) clickEvent(true, true, window.getMousePos());
if (window.input.isMouseReleased(GLFW_MOUSE_BUTTON_LEFT)) clickEvent(true, false, window.getMousePos());
if (window.input.isMousePressed(GLFW_MOUSE_BUTTON_RIGHT)) clickEvent(false, true, window.getMousePos());
if (window.input.isMouseReleased(GLFW_MOUSE_BUTTON_RIGHT)) clickEvent(false, false, window.getMousePos());
auto mousePos = window.input.mousePos();
window.setCursorHand(mouseActivity(mousePos));
if (window.input.mousePressed(GLFW_MOUSE_BUTTON_LEFT)) clickEvent(true, true, mousePos);
if (window.input.mouseReleased(GLFW_MOUSE_BUTTON_LEFT)) clickEvent(true, false, mousePos);
if (window.input.mousePressed(GLFW_MOUSE_BUTTON_RIGHT)) clickEvent(false, true, mousePos);
if (window.input.mouseReleased(GLFW_MOUSE_BUTTON_RIGHT)) clickEvent(false, false, mousePos);
}
bool GuiComponent::mouseActivity(glm::ivec2 pos) {

View File

@ -19,20 +19,20 @@ GameScene::GameScene(ClientState& state) : Scene(state),
world.init(&player);
net.init(&world, std::bind(&LocalInventoryRefs::packetReceived, refs, ph::_1));
game.init(world, player);
game.init(world, player, state);
state.renderer.window.addResizeCallback("gamescene", std::bind(&DebugGui::bufferResized, debugGui, ph::_1));
state.renderer.setClearColor(148, 194, 240);
state.renderer.window.lockMouse(true);
state.renderer.window.input.lockMouse(true);
}
void GameScene::update() {
Window& window = state.renderer.window;
player.update(window.input, state.delta, window.getDelta());
game .update(state.delta, state.renderer.window.keys);
refs .update(state.delta, net);
net .update();
player.update(window.input, state.delta, window.input.mouseDelta());
game.update(state.delta);
refs.update(state.delta, net);
net.update();
for (auto entity : entities) entity->update(state.delta);
@ -41,13 +41,13 @@ void GameScene::update() {
net.serverSideChunkGens = 0;
net.recvPackets = 0;
if (window.input.isKeyPressed(GLFW_KEY_F1)) {
if (window.input.keyPressed(GLFW_KEY_F1)) {
hudVisible = !hudVisible;
debugGui.changeVisibilityState(hudVisible ? debugVisible ? 0 : 2 : 1);
player.setHudVisible(hudVisible);
}
if (window.input.isKeyPressed(GLFW_KEY_F3)) {
if (window.input.keyPressed(GLFW_KEY_F3)) {
debugVisible = !debugVisible;
debugGui.changeVisibilityState(hudVisible ? debugVisible ? 0 : 2 : 1);
}

View File

@ -9,7 +9,7 @@
LuaErrorScene::LuaErrorScene(ClientState &state, const std::string &err) : Scene(state), err(err) {
state.renderer.setClearColor(0, 0, 0);
state.renderer.window.lockMouse(false);
state.renderer.window.input.lockMouse(false);
Font f(state.defs.textures, state.defs.textures["font"]);
glm::ivec2 win = state.renderer.window.getSize();

View File

@ -9,7 +9,7 @@ MainMenuScene::MainMenuScene(ClientState& state) :
sandbox(sandboxArea, state, sandboxContainer) {
state.renderer.setClearColor(0, 0, 0);
state.renderer.window.lockMouse(false);
state.renderer.window.input.lockMouse(false);
Font f(state.defs.textures, state.defs.textures["font"]);
win = state.renderer.window.getSize();

View File

@ -57,13 +57,13 @@ void LocalWorld::localSetBlock(glm::ivec3 pos, unsigned int block) {
if (block == LocalDefinitionAtlas::AIR) {
auto def = defs.defs.blockFromId(getBlock(pos));
if (def.callbacks.count(Callback::BREAK_CLIENT)) {
def.callbacks[Callback::BREAK_CLIENT](defs.parser.luaVec(pos));
defs.parser.safe_function(def.callbacks[Callback::BREAK_CLIENT], defs.parser.luaVec(pos));
}
}
else {
auto def = defs.defs.blockFromId(block);
if (def.callbacks.count(Callback::PLACE_CLIENT)) {
def.callbacks[Callback::PLACE_CLIENT](defs.parser.luaVec(pos));
defs.parser.safe_function(def.callbacks[Callback::PLACE_CLIENT], defs.parser.luaVec(pos));
}
}

View File

@ -38,7 +38,7 @@ void Player::update(Input &input, double delta, glm::vec2 mouseDelta) {
void Player::moveAndLook(Input &input, double delta, glm::vec2 mouseDelta) {
//Position movement
bool sprinting = input.isKeyDown(GLFW_KEY_LEFT_CONTROL);
bool sprinting = input.keyDown(GLFW_KEY_LEFT_CONTROL);
double moveSpeed = BASE_MOVE_SPEED * delta * (sprinting ? 1.6 : 1);
float friction = 0.3f;
@ -48,7 +48,7 @@ void Player::moveAndLook(Input &input, double delta, glm::vec2 mouseDelta) {
friction = 0.15f;
}
else {
if (input.isKeyDown(GLFW_KEY_SPACE) && isOnGround()) vel.y = JUMP_VEL;
if (input.keyDown(GLFW_KEY_SPACE) && isOnGround()) vel.y = JUMP_VEL;
}
//Calculate movement vector from camera angle.
@ -58,14 +58,14 @@ void Player::moveAndLook(Input &input, double delta, glm::vec2 mouseDelta) {
glm::vec3 mod {0, 0, 0};
if (input.isKeyDown(GLFW_KEY_W)) mod += frontFlat;
if (input.isKeyDown(GLFW_KEY_S)) mod -= frontFlat;
if (input.isKeyDown(GLFW_KEY_D)) mod += rightFlat;
if (input.isKeyDown(GLFW_KEY_A)) mod -= rightFlat;
if (input.keyDown(GLFW_KEY_W)) mod += frontFlat;
if (input.keyDown(GLFW_KEY_S)) mod -= frontFlat;
if (input.keyDown(GLFW_KEY_D)) mod += rightFlat;
if (input.keyDown(GLFW_KEY_A)) mod -= rightFlat;
if (flying) {
if (input.isKeyDown(GLFW_KEY_SPACE)) mod.y += 1;
if (input.isKeyDown(GLFW_KEY_LEFT_SHIFT)) mod.y -= 1;
if (input.keyDown(GLFW_KEY_SPACE)) mod.y += 1;
if (input.keyDown(GLFW_KEY_LEFT_SHIFT)) mod.y -= 1;
}
else {
if (!isOnGround()) vel.y = std::fmax(vel.y - 0.0085, -3);
@ -195,7 +195,7 @@ void Player::updateWireframe() {
void Player::breakBlock(Input& input, double delta) {
if (pointedThing.thing == PointedThing::Thing::BLOCK) {
if (input.isMouseDown(GLFW_MOUSE_BUTTON_LEFT)) {
if (input.mouseDown(GLFW_MOUSE_BUTTON_LEFT)) {
if (breakInterval == 0) {
world.damageBlock(pointedThing.target.block.pos, BLOCK_DAMAGE);
}
@ -207,7 +207,7 @@ void Player::breakBlock(Input& input, double delta) {
if (breakInterval > BLOCK_INTERVAL) breakInterval = 0;
}
if (input.isMousePressed(GLFW_MOUSE_BUTTON_RIGHT)) {
if (input.mousePressed(GLFW_MOUSE_BUTTON_RIGHT)) {
world.localSetBlock(pointedThing.target.block.pos + SelectionBox::faceToOffset(pointedThing.target.block.face), activeBlock);
}
}
@ -278,12 +278,12 @@ void Player::setActiveBlock(const std::string& block) {
void Player::showMenu(std::shared_ptr<LuaGuiElement> root) {
gameGui.showMenu(root);
renderer.window.lockMouse(false);
renderer.window.input.lockMouse(false);
}
void Player::closeMenu() {
gameGui.closeMenu();
renderer.window.lockMouse(true);
renderer.window.input.lockMouse(true);
}
bool Player::isInMenu() {

View File

@ -1,52 +0,0 @@
//
// Created by aurailus on 14/10/19.
//
#include "LuaInputManager.h"
#include "../util/Util.h"
#include <GLFW/glfw3.h>
#include <iostream>
LuaInputManager::LuaInputManager() {
for (bool& key : keysDown) key = false;
for (bool& key : keysPressed) key = false;
for (bool& key : keysReleased) key = false;
for (auto &callback : callbacksDown) callback = {};
for (auto &callback : callbacksUp) callback = {};
}
void LuaInputManager::update(bool* keys) {
for (unsigned short i = 0; i < 1024; i++) {
bool key = keys[i];
if (key) {
if (!keysDown[i]) keysPressed[i] = true;
keysDown[i] = true;
}
else {
if (keysDown[i]) keysReleased[i] = true;
keysDown[i] = false;
}
}
}
void LuaInputManager::triggerKeybinds() {
for (unsigned short i = 0; i < 1024; i++) {
if (keysPressed[i]) {
for (auto& cb : callbacksDown[i]) cb();
keysPressed[i] = false;
}
if (keysReleased[i]) {
for (auto& cb : callbacksUp[i]) cb();
keysReleased[i] = false;
}
}
}
void LuaInputManager::bindOnDown(unsigned short key, const sol::function &cb) {
callbacksDown[key].push_back(cb);
}
void LuaInputManager::bindOnUp(unsigned short key, const sol::function &cb) {
callbacksUp[key].push_back(cb);
}

View File

@ -1,25 +0,0 @@
//
// Created by aurailus on 14/10/19.
//
#pragma once
#include <sol2/sol.hpp>
class LuaInputManager {
public:
LuaInputManager();
void update(bool* keys);
void triggerKeybinds();
void bindOnDown(unsigned short key, const sol::function& cb);
void bindOnUp(unsigned short key, const sol::function& cb);
private:
bool keysDown[1024] {};
bool keysPressed[1024] {};
bool keysReleased[1024] {};
std::array<std::vector<sol::function>, 1024> callbacksDown {};
std::array<std::vector<sol::function>, 1024> callbacksUp {};
};

View File

@ -0,0 +1,25 @@
//
// Created by aurailus on 14/10/19.
//
#include "LuaKeybindHandler.h"
#include "parser/LocalLuaParser.h"
LuaKeybindHandler::LuaKeybindHandler(LocalLuaParser* parser): parser(parser) {
for (auto &callback : callbacksDown) callback = {};
for (auto &callback : callbacksUp) callback = {};
}
void LuaKeybindHandler::keybindHandler(bool state, int i) {
if (state) for (auto& cb : callbacksDown[i]) parser->safe_function(cb);
else for (auto& cb : callbacksUp[i]) parser->safe_function(cb);
}
void LuaKeybindHandler::bindOnDown(unsigned short key, const sol::function &cb) {
callbacksDown[key].push_back(cb);
}
void LuaKeybindHandler::bindOnUp(unsigned short key, const sol::function &cb) {
callbacksUp[key].push_back(cb);
}

View File

@ -0,0 +1,27 @@
//
// A simple class that stores Lua callbacks for keybinds. Has a callback function (keybindHandler)
// that is given to the Input object and called when a keyboard key changes state.
// Created by aurailus on 14/10/19.
//
#pragma once
#include <sol2/sol.hpp>
class LocalLuaParser;
class LuaKeybindHandler {
public:
LuaKeybindHandler(LocalLuaParser* parser);
LuaKeybindHandler(const LuaKeybindHandler& o) = delete;
void bindOnDown(unsigned short key, const sol::function& cb);
void bindOnUp(unsigned short key, const sol::function& cb);
void keybindHandler(bool state, int i);
private:
std::array<std::vector<sol::function>, 1024> callbacksDown {};
std::array<std::vector<sol::function>, 1024> callbacksUp {};
const LocalLuaParser* parser;
};

View File

@ -5,7 +5,9 @@
#include "LuaParser.h"
void LuaParser::update(double delta) {
//Loop through and call delayed functions
// 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;

View File

@ -1,35 +1,18 @@
//
// The LuaParser superclass for both the Client and Server Parsers.
// This contains some shared functions, structs, and variables used by both subclasses.
// Created by aurailus on 11/06/19.
// The Lua API superclass for both the client and the server.
// This class contains platform agnostic functions and structures for both of the APIs.
//
//
#pragma once
#include <list>
#include <iostream>
#include <glm/vec3.hpp>
#include <sol2/sol.hpp>
#include "../util/Log.h"
class LuaParser {
public:
constexpr static double UPDATE_STEP {1 / 60.0};
// static inline void override_panic(sol::optional<std::string> message) {
// std::cout << Log::err << "Zepha has panicked! Error:" << Log::endl;
// if (message) std::cout << Log::err << message.value() << Log::endl;
// }
struct DelayedFunction {
sol::function function;
std::vector<sol::object> args;
float timeout;
float initial_timeout;
};
virtual void update(double delta);
sol::table luaVec(glm::vec3 vec);
@ -38,6 +21,12 @@ public:
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

@ -5,6 +5,7 @@
#pragma once
#include <sol2/sol.hpp>
#include "../../../def/DefinitionAtlas.h"
#include "../../../game/scene/world/World.h"

View File

@ -2,13 +2,14 @@
// Created by aurailus on 17/12/18.
//
#include "LocalLuaParser.h"
#include "../ErrorFormatter.h"
#include "../register/RegisterBlocks.h"
#include "../register/RegisterItems.h"
#include "../register/RegisterBiomes.h"
#include "../register/RegisterKeybinds.h"
#include "LocalLuaParser.h"
#include "../../game/ClientState.h"
// Usertypes
#include "../api/class/LuaGuiElement.h"
@ -38,26 +39,26 @@
#include "../api/functions/trigger_event.h"
#include "../api/functions/update_entities.h"
void LocalLuaParser::init(ClientGame& defs, LocalWorld& world, Player& player) {
LocalLuaParser::LocalLuaParser(): keybinds(this) {}
void LocalLuaParser::init(ClientGame& defs, LocalWorld& world, Player& player, ClientState& state) {
lua.open_libraries(sol::lib::base, sol::lib::string, sol::lib::math, sol::lib::table);
loadApi(defs, world, player);
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(defs);
}
void LocalLuaParser::update(double delta, bool* keys) {
void LocalLuaParser::update(double delta) {
LuaParser::update(delta);
this->delta += delta;
while (this->delta > static_cast<double>(UPDATE_STEP)) {
manager.triggerKeybinds();
safe_function(core["__builtin"]["update_entities"], static_cast<double>(UPDATE_STEP));
this->delta -= static_cast<double>(UPDATE_STEP);
}
manager.update(keys);
}
LocalModHandler& LocalLuaParser::getHandler() {
@ -114,10 +115,10 @@ void LocalLuaParser::registerDefs(ClientGame &defs) {
RegisterBlocks ::client(core, defs);
RegisterItems ::client(core, defs);
RegisterBiomes ::client(core, defs);
RegisterKeybinds::client(core, manager);
RegisterKeybinds::client(core, keybinds);
}
sol::protected_function_result LocalLuaParser::errorCallback(sol::protected_function_result errPfr) {
sol::protected_function_result LocalLuaParser::errorCallback(sol::protected_function_result errPfr) const {
sol::error err = errPfr;
std::string errString = err.what();

View File

@ -4,23 +4,26 @@
#pragma once
#include "LocalModHandler.h"
#include "../LuaMod.h"
#include "../LuaParser.h"
#include "../LuaInputManager.h"
#include "LocalModHandler.h"
#include "../LuaKeybindHandler.h"
class ClientGame;
class ClientState;
class LocalWorld;
class Player;
class LocalLuaParser : public LuaParser {
public:
void init(ClientGame& defs, LocalWorld& world, Player& player);
void update(double delta, bool* keys);
LocalLuaParser();
void init(ClientGame& defs, LocalWorld& world, Player& player, ClientState& state);
void update(double delta);
LocalModHandler& getHandler();
template<typename... Args> void safe_function(sol::protected_function f, Args... args) {
template<typename... Args> void safe_function(sol::protected_function f, Args... args) const {
auto res = f(args...);
if (!res.valid()) errorCallback(res);
}
@ -28,10 +31,10 @@ private:
void loadApi(ClientGame& defs, LocalWorld& world, Player& player);
void registerDefs(ClientGame &defs);
sol::protected_function_result errorCallback(sol::protected_function_result errPfr);
sol::protected_function_result errorCallback(sol::protected_function_result errPfr) const;
sol::protected_function_result runFileSandboxed(std::string file);
LuaInputManager manager;
LuaKeybindHandler keybinds;
LocalModHandler handler;
double delta = 0;
};

View File

@ -5,13 +5,13 @@
#include <gzip/compress.hpp>
#include <enet/enet.h>
#include "ServerLuaParser.h"
#include "../ErrorFormatter.h"
#include "../register/RegisterBlocks.h"
#include "../register/RegisterItems.h"
#include "../register/RegisterBiomes.h"
#include "ServerLuaParser.h"
// Usertypes
#include "../api/usertype/sServerPlayer.h"
#include "../api/usertype/sLuaEntity.h"

View File

@ -4,12 +4,15 @@
#pragma once
#include "ServerModHandler.h"
#include <enet/enet.h>
#include "../LuaParser.h"
#include "../../server/conn/ServerClient.h"
#include "ServerModHandler.h"
class ServerGame;
class ServerWorld;
class ServerClient;
class ServerLuaParser : public LuaParser {
public:

View File

@ -10,7 +10,7 @@
#include "../../def/gen/BiomeDef.h"
namespace RegisterKeybinds {
static void registerKeybinds(sol::table source, LuaInputManager& manager) {
static void registerKeybinds(sol::table source, LuaKeybindHandler& keybinds) {
// Register all of the items in the zepha.registered_keybinds table
for (auto keybindRef : source) {
@ -27,8 +27,8 @@ namespace RegisterKeybinds {
auto onPress = keybindTbl.get<sol::optional<sol::function>>("on_press");
auto onRelease = keybindTbl.get<sol::optional<sol::function>>("on_release");
if (onPress) manager.bindOnDown(def, *onPress);
if (onRelease) manager.bindOnUp(def, *onRelease);
if (onPress) keybinds.bindOnDown(def, *onPress);
if (onRelease) keybinds.bindOnUp(def, *onRelease);
}
}
@ -36,7 +36,7 @@ namespace RegisterKeybinds {
// registerItems(core.get<sol::table>("registered_items"), defs.defs, nullptr);
// }
static void client(sol::table& core, LuaInputManager& manager) {
static void client(sol::table& core, LuaKeybindHandler& manager) {
registerKeybinds(core.get<sol::table>("registered_keybinds"), manager);
}
};

View File

@ -125,32 +125,42 @@ void Server::handlePlayerPacket(ServerClient& client, PacketView& p) {
if (block == DefinitionAtlas::AIR) {
auto def = defs.defs.blockFromId(worldBlock);
if (def.callbacks.count(Callback::BREAK)) def.callbacks[Callback::BREAK](defs.parser.luaVec(pos), ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "break",
defs.parser.luaVec(pos), ServerLuaPlayer(client));
if (def.callbacks.count(Callback::BREAK)) {
defs.parser.safe_function(def.callbacks[Callback::BREAK],
defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"],
"break", defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
else {
auto def = defs.defs.blockFromId(block);
if (def.callbacks.count(Callback::PLACE)) def.callbacks[Callback::PLACE](defs.parser.luaVec(pos), ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "place",
defs.parser.luaVec(pos), ServerLuaPlayer(client));
if (def.callbacks.count(Callback::PLACE)) {
defs.parser.safe_function(def.callbacks[Callback::PLACE],
defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"],
"place", defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
world.setBlock(pos, block);
if (block == DefinitionAtlas::AIR) {
auto def = defs.defs.blockFromId(worldBlock);
if (def.callbacks.count(Callback::AFTER_BREAK)) def.callbacks[Callback::AFTER_BREAK](
defs.parser.luaVec(pos), ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "after_break",
defs.parser.luaVec(pos), ServerLuaPlayer(client));
if (def.callbacks.count(Callback::AFTER_BREAK)) {
defs.parser.safe_function(def.callbacks[Callback::AFTER_BREAK],
defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"],
"after_break", defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
else {
auto def = defs.defs.blockFromId(block);
if (def.callbacks.count(Callback::AFTER_PLACE)) def.callbacks[Callback::AFTER_PLACE](
defs.parser.luaVec(pos), ServerLuaPlayer(client));
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"], "after_place",
defs.parser.luaVec(pos), ServerLuaPlayer(client));
if (def.callbacks.count(Callback::AFTER_PLACE)) {
defs.parser.safe_function(def.callbacks[Callback::AFTER_PLACE],
defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
defs.parser.safe_function(defs.parser.core["__builtin"]["trigger_event"],
"after_place", defs.parser.luaVec(pos), ServerLuaPlayer(client));
}
break;
}

View File

@ -5,6 +5,7 @@
#include "ServerConfig.h"
#include "../asset/AssetType.h"
#include "../conn/ServerClient.h"
#include "../../util/net/PacketView.h"
#include "../../util/net/Serializer.h"

View File

@ -0,0 +1,29 @@
local root = zepha.player:get_hud():get("hot_wheel_root")
local lists = {
root:get("list_1"),
root:get("list_2"),
root:get("list_3"),
root:get("list_4"),
root:get("list_5"),
root:get("list_6")
}
local offset = 0
local function select(n)
offset = n - 1
for i,list in ipairs(lists) do
list.list = "hot_wheel_" .. tostring((i + offset - 1) % 6 + 1)
end
root:get("numbers").background = "@aurailus:hot_wheel:circle_numbers_" .. (offset + 1)
zepha.player:set_selected_block(zepha.player:get_inventory():get_list("hot_wheel_" .. ((offset + 2) % 6 + 1)):get_stack(1).name)
end
for i = 1, 6 do
zepha.register_keybind("@aurailus:hot_wheel:select_slot_" .. i, {
description = "Select Slot " .. i,
default = zepha.keys[tostring(i)],
on_press = function() select(i) end
})
end

View File

@ -1,2 +1,8 @@
runfile(_PATH .. "register")
runfile(_PATH .. "menu")
if zepha.server then
runfile(_PATH .. "register")
end
if zepha.client then
runfile(_PATH .. "ui")
runfile(_PATH .. "keys")
end

View File

@ -1,5 +1,3 @@
if zepha.client then return end
zepha.register_on("new_player", function(p)
local inv = p:get_inventory()
inv:add_list("hot_wheel_1", 5, 5)

View File

@ -1,18 +1,13 @@
if zepha.server then return end
local hud = zepha.player:get_hud()
hud:append(function() return Gui.Rect {
key = "hot_wheel_root",
size = { 140, 80 },
position = { "0%", "100%" },
position_anchor = { "-10%", "110%" },
-- background = "#966"
} end)
local root = hud:get("hot_wheel_root")
root(function(e)
e:append(Gui.Rect {
Gui.Rect {
size = { 80, 80 },
background = "@aurailus:hot_wheel:hot_wheel_circle",
@ -38,13 +33,6 @@ root(function(e)
source = "current_player",
list = "hot_wheel_2",
},
-- Gui.InventoryList {
-- position = { 6, 16 },
-- slot_spacing = { 2, 2 },
-- length = 1,
-- source = "current_player",
-- list = "hot_wheel_3",
-- },
Gui.InventoryList {
key = "list_4",
position = { 52, 43 },
@ -68,10 +56,9 @@ root(function(e)
length = 1,
source = "current_player",
list = "hot_wheel_6",
},
})
e:append(Gui.Rect {
}
},
Gui.Rect {
size = { 100, 18 },
position = { 52, 19 },
background = "@aurailus:hot_wheel:hot_wheel_line",
@ -84,34 +71,5 @@ root(function(e)
source = "current_player",
list = "hot_wheel_3",
}
})
end)
local lists = {
root:get("list_1"),
root:get("list_2"),
root:get("list_3"),
root:get("list_4"),
root:get("list_5"),
root:get("list_6")
}
local offset = 0
local function select(n)
offset = n - 1
for i,list in ipairs(lists) do
list.list = "hot_wheel_" .. tostring((i + offset - 1) % 6 + 1)
end
root:get("numbers").background = "@aurailus:hot_wheel:circle_numbers_" .. (offset + 1)
zepha.player:set_selected_block(zepha.player:get_inventory():get_list("hot_wheel_" .. ((offset + 2) % 6 + 1)):get_stack(1).name)
end
for i = 1, 6 do
zepha.register_keybind("@aurailus:hot_wheel:select_slot_" .. i, {
description = "Select Slot " .. i,
default = zepha.keys[tostring(i)],
on_press = function() select(i) end
})
end
}
} end)

View File

@ -28,7 +28,7 @@ zepha.register_entity("zeus:default:raven", {
}
if (self.targeting) {
self.object.pos = v(
self.object.pos = V(
self.object.pos.x + 0.08 * math.sin(math.rad(self.object.yaw)),
self.object.pos.y,
self.object.pos.z + 0.08 * math.cos(math.rad(self.object.yaw))
@ -46,6 +46,6 @@ zepha.register_keybind("zeus:default:spawn_raven", {
description = "Spawn Raven",
default = zepha.keys.z,
on_press = fn() {
zepha.add_entity("zeus:default:raven", vector.add(zepha.player.pos, v(0, 1.7, 0)))
zepha.add_entity("zeus:default:raven", vector.add(zepha.player.pos, V(0, 1.7, 0)))
}
})