Overhaul of many classes to convert constructors to init lists + more

master
aurailus 2019-07-11 23:50:24 -07:00
parent 320c0cec0f
commit a5dc8ae45f
49 changed files with 384 additions and 258 deletions

6
.idea/other.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ClangdSettings">
<option name="clangWarnings" value="-Wno-unused-variable,-Wno-shadow,-Wshadow-field-in-constructor-modified,-Wshadow-ivar,-Wno-switch,-Wno-parentheses,-Wbitwise-op-parentheses,-Wdangling-else,-Wlogical-not-parentheses,-Wlogical-op-parentheses,-Woverloaded-shift-op-parentheses,-Wparentheses-equality,-Wshift-op-parentheses,-Werror=implicit-function-declaration,-Wno-unknown-pragmas" />
</component>
</project>

View File

@ -1,4 +1,4 @@
# Zeus Voxel Game
# Zeus Voxel Client
(c) 2018-2019 Benjamin Collings, All Rights Reserved.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 B

After

Width:  |  Height:  |  Size: 255 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 B

After

Width:  |  Height:  |  Size: 272 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 B

After

Width:  |  Height:  |  Size: 338 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 B

After

Width:  |  Height:  |  Size: 433 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 271 B

After

Width:  |  Height:  |  Size: 459 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 B

After

Width:  |  Height:  |  Size: 460 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 315 B

After

Width:  |  Height:  |  Size: 492 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 348 B

After

Width:  |  Height:  |  Size: 490 B

View File

@ -45,8 +45,8 @@ set(ZEUS_SRC_FILES
game/scene/world/Player.h
util/Ray.cpp
util/Ray.h
game/Game.cpp
game/Game.h
game/Client.cpp
game/Client.h
game/graph/scene/SceneManager.cpp
game/graph/scene/SceneManager.h
game/graph/scene/Scene.h
@ -166,6 +166,6 @@ set(ZEUS_SRC_FILES
api/client/LocalRegisterBlocks.h
api/server/ServerRegisterBlocks.cpp
api/server/ServerRegisterBlocks.h
server/conn/ServerClient.cpp server/config/ServerConfig.cpp server/config/ServerConfig.h util/net/PacketType.h)
server/conn/ServerClient.cpp server/config/ServerConfig.cpp server/config/ServerConfig.h util/net/PacketType.h util/net/NetState.h game/scene/ConnectScene.cpp game/scene/ConnectScene.h util/net/Address.cpp util/net/Address.h)
add_library (zeusCore ${ZEUS_SRC_FILES})

View File

@ -1,27 +1,88 @@
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#pragma ide diagnostic ignored "OCUnusedMacroInspection"
#define STB_IMAGE_IMPLEMENTATION
#define CUTE_FILES_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#pragma clang diagnostic pop
#include "game/Game.h"
#include "game/Client.h"
#include "server/Server.h"
#include "util/Log.h"
uint64_t constexpr mix(char m, uint64_t s) {
return ((s<<7) + ~(s>>3)) + ~m;
}
uint64_t constexpr hashStr(const char * m) {
return (*m) ? mix(*m, hashStr(m+1)) : 0;
}
int main(int argc, char* argv[]) {
std::cout << Log::info << "Zeus Engine Version 0.0.1 Pre-Alpha" << Log::endl;
enum class Mode {
NONE, CLIENT, SERVER, LOCAL_SERVER
};
std::string arg = "client";
if (argc >= 2) arg = argv[1];
//Collect arguments into `args` map
std::map<std::string, std::string> args;
for (int i = 1; i < argc; i++) {
if (arg == "client" || arg == "local") {
Game g(1366, 768, (arg == "local") ? argv[0] : nullptr);
std::string arg(argv[i]);
size_t equals = arg.find('=');
std::string first = (equals == -1) ? arg : arg.substr(0, equals);
if (args.count(first)) {
std::cout << Log::err << "Duplicate argument " << first << "." << Log::endl;
return -1;
}
if (equals == -1) args.emplace(first, "");
else {
if (equals == arg.length() - 1) {
std::cout << Log::err << "Empty equals-assignment " << first << "." << Log::endl;
return -1;
}
args.emplace(first, arg.substr(equals + 1, arg.length()));
}
}
if (arg == "server") {
Server s(12345);
Mode mode = Mode::NONE;
//Parse the arguments map
for (auto arg : args) {
switch (hashStr(arg.first.c_str())) {
default: {
std::cout << Log::err << "Invalid argument " << arg.first << "." << Log::endl;
return -1;
}
case hashStr("--mode"): {
if (arg.second == "client") mode = Mode::CLIENT;
else if (arg.second == "server") mode = Mode::SERVER;
else if (arg.second == "local" ) mode = Mode::LOCAL_SERVER;
else std::cout << Log::err << "Invalid mode argument." << Log::endl;
break;
}
}
}
//Start the game
switch (mode) {
default: {
std::cout << Log::err << "Mode not set." << Log::endl;
return -1;
}
case Mode::CLIENT: {
Client c(argv[0], 1366, 768);
break;
}
case Mode::LOCAL_SERVER: {
Client c(argv[0], 1366, 768);
break;
}
case Mode::SERVER: {
Server s(12345);
break;
}
}
return 0;
}
}
#pragma clang diagnostic pop

View File

@ -5,6 +5,7 @@
#include "LocalDefs.h"
LocalDefs::LocalDefs(std::string tex_path) :
tex_path(tex_path),
luaApi("/home/aurailus/CLion/Zeus/res/lua/") {
textureAtlas = TextureAtlas(1024);
@ -15,6 +16,10 @@ LocalDefs::LocalDefs(std::string tex_path) :
blockAtlas = LocalBlockAtlas();
}
LocalDefs::LocalDefs(const LocalDefs &copy) : LocalDefs(copy.tex_path) {
//Note: This constructor is only for *uninitialized* LocalDef objects!
}
void LocalDefs::init(LocalWorld &world) {
luaApi.init(*this, world);
}
@ -37,4 +42,4 @@ void LocalDefs::update(float delta) {
luaApi.update();
this->delta -= 48;
}
}
}

View File

@ -12,6 +12,7 @@
class LocalDefs {
public:
explicit LocalDefs(std::string tex_path);
LocalDefs(const LocalDefs& copy);
LocalBlockAtlas& blocks();
TextureAtlas& textures();
@ -24,6 +25,8 @@ public:
private:
float delta = 0;
std::string tex_path;
TextureAtlas textureAtlas;
LocalBlockAtlas blockAtlas;
LocalLuaParser luaApi;

View File

@ -224,8 +224,9 @@ std::shared_ptr<AtlasRef> TextureAtlas::generateCrackImage(std::string &name, un
RawTexData crack = getSubImageBytes(crackStr);
for (int i = 0; i < base.width * base.height; i++) {
float alpha = crack.data[i * 4 + 3] / 255.f * (crackLevel / 16.f + 0.5f);
// float alpha = crack.data[i * 4 + 3] / 255.f * (crackLevel / 16.f + 0.5f);
float alpha = crack.data[i * 4 + 3] / 255.f;
base.data[i * 4 + 0] = static_cast<unsigned char>(base.data[i * 4 + 0] * (1 - alpha) + crack.data[i * 4 + 0] * alpha);
base.data[i * 4 + 1] = static_cast<unsigned char>(base.data[i * 4 + 1] * (1 - alpha) + crack.data[i * 4 + 1] * alpha);
base.data[i * 4 + 2] = static_cast<unsigned char>(base.data[i * 4 + 2] * (1 - alpha) + crack.data[i * 4 + 2] * alpha);

55
src/game/Client.cpp Normal file
View File

@ -0,0 +1,55 @@
//
// Created by aurailus on 06/01/19.
//
#include "Client.h"
Client::Client(char* path, int width, int height) :
renderer(width, height),
state {renderer, LocalDefs("../res/tex"), 0, 0} {
// Start Local Server
// if (path != nullptr) {
// int pid = fork();
// if (pid == 0) {
// char *arr[] =
// {(char*)"", (char*)"-iconic", (char*)"-e", path, (char*)"--mode=server", (char*)nullptr};
//
// execvp("xterm", arr);
// } else {
// serverPID = pid;
// }
// }
std::unique_ptr<Scene> scene = std::make_unique<MenuScene>(state);
sceneManager.setScene(std::move(scene));
while (!renderer.getWindow().shouldClose()) loop();
}
void Client::loop() {
Timer t("Client Loop");
if (!startedGame && timeElapsed > 1) {
// std::unique_ptr<Scene> scene = std::make_unique<ConnectScene>(state);
std::unique_ptr<Scene> scene = std::make_unique<GameScene>(state);
sceneManager.setScene(std::move(scene));
startedGame = true;
}
double now = glfwGetTime();
state.deltaTime = now - timeElapsed;
timeElapsed = now;
glfwPollEvents();
sceneManager.update();
renderer.update(state.deltaTime);
state.fps = 1000.0 / (t.elapsedNs() / 1000000.0);
}
Client::~Client() {
if (serverPID != 0) kill(serverPID, SIGKILL);
sceneManager.cleanupScene();
}

View File

@ -5,35 +5,32 @@
#ifndef ZEUS_CLIENT_H
#define ZEUS_CLIENT_H
#include <zconf.h>
#include <signal.h>
#include "ClientState.h"
#include "graph/Renderer.h"
#include "graph/scene/SceneManager.h"
#include "../util/Timer.h"
#include "scene/GameScene.h"
#include "scene/MenuScene.h"
#include "../util/Timer.h"
class Game {
class Client {
public:
Game();
Game(int width, int height, char* path);
~Game();
Client(char* path, int width, int height);
~Client();
private:
void loop();
void cleanup();
Renderer renderer;
ClientState state;
Renderer* renderer;
ClientState* state;
SceneManager sceneManager;
int local_server_pid = 0;
int count = 0;
double timeElapsed = 0.0f;
bool startedGame = false;
int serverPID = 0;
};

View File

@ -6,12 +6,16 @@
#define ZEUS_CLIENTSTATE_H
#include "graph/Renderer.h"
#include "scene/net/ServerConnection.h"
#include "../def/LocalDefs.h"
struct ClientState {
Renderer* renderer;
Renderer& renderer;
LocalDefs defs;
// ServerConnection connection;
double fps = 0;
double deltaTime;
double deltaTime = 0;
};
#endif //ZEUS_CLIENTSTATE_H

View File

@ -1,77 +0,0 @@
//
// Created by aurailus on 06/01/19.
//
#include <zconf.h>
#include <signal.h>
#include "Game.h"
Game::Game() = default;
Game::Game(int width, int height, char* path) :
renderer(new Renderer(width, height)) {
//Start Local Server
if (path != nullptr) {
int pid = fork();
if (pid == 0) {
char *arr[] = {
(char*) "xterm",
(char*) "-iconic",
(char*) "-e",
path,
(char*) "server",
(char*) nullptr};
execvp("xterm", arr);
} else {
local_server_pid = pid;
}
}
//Create ClientState struct
state = new ClientState {
.renderer = renderer,
.fps = 0,
.deltaTime = 0
};
//Start the Main Menu
Scene* m = new GameScene(state);
sceneManager.setScene(m);
while (!renderer->getWindow()->getShouldClose()) loop();
}
void Game::loop() {
//VSync 1 = On, 0 = Off
glfwSwapInterval(1);
Timer t("Game Loop");
double now = glfwGetTime();
state->deltaTime = now - timeElapsed;
timeElapsed = now;
glfwPollEvents();
sceneManager.update();
state->renderer->update(state->deltaTime);
state->fps = 1000 / (t.elapsedNs() / 1000000.0);
}
void Game::cleanup() {
if (local_server_pid != 0) {
kill(local_server_pid, SIGKILL);
}
sceneManager.cleanupScene();
delete state;
delete renderer;
}
Game::~Game() {
cleanup();
}

View File

@ -144,6 +144,9 @@ void Renderer::createGUIShader() {
}
void Renderer::update(double delta) {
//VSync 1 = On, 0 = Off
glfwSwapInterval(1);
window.update();
elapsedTime += delta;
@ -278,12 +281,12 @@ void Renderer::swapBuffers() {
window.swapBuffers();
}
Window *Renderer::getWindow() {
return &window;
Window& Renderer::getWindow() {
return window;
}
Camera *Renderer::getCamera() {
return &camera;
Camera& Renderer::getCamera() {
return camera;
}
void Renderer::renderQuad() {

View File

@ -36,8 +36,8 @@ public:
void setModelMatrix(const glm::mat4& modelMatrix);
void enableTexture(Texture* texture);
Window* getWindow();
Camera* getCamera();
Window& getWindow();
Camera& getCamera();
~Renderer();

View File

@ -10,19 +10,15 @@
class Scene {
public:
explicit Scene(ClientState* state) {
this->state = state;
};
explicit Scene(ClientState& state) : state(state) {}
virtual void update() {};
virtual void draw() {};
virtual void cleanup() {};
virtual void update() = 0;
virtual void draw() = 0;
virtual void cleanup() = 0;
virtual ~Scene() = default;
ClientState* state;
ClientState& state;
};

View File

@ -4,28 +4,23 @@
#include "SceneManager.h"
SceneManager::SceneManager() {
scene = nullptr;
};
void SceneManager::update() {
scene->update();
scene->draw();
}
void SceneManager::setScene(Scene* scene) {
void SceneManager::setScene(std::unique_ptr<Scene> scene) {
if (this->scene != nullptr) cleanupScene();
this->scene = scene;
this->scene = std::move(scene);
}
Scene* SceneManager::getScene() {
return scene;
Scene& SceneManager::getScene() {
return *scene;
}
void SceneManager::cleanupScene() {
if (scene != nullptr) {
scene->cleanup();
delete scene;
scene = nullptr;
}
}

View File

@ -6,21 +6,21 @@
#define ZEUS_SCENEMANAGER_H
#include "Scene.h"
#include <memory>
class SceneManager {
public:
SceneManager();
SceneManager() = default;
void setScene(Scene* scene);
Scene* getScene();
void setScene(std::unique_ptr<Scene> scene);
Scene& getScene();
void update();
void cleanupScene();
~SceneManager();
private:
Scene* scene;
std::unique_ptr<Scene> scene = nullptr;
};

View File

@ -20,7 +20,7 @@ Window::Window(GLint windowWidth, GLint windowHeight) {
int Window::initialize() {
//Initialize GLFW
if (!glfwInit()) {
printf("GLFW init failed");
printf("GLFW init failed\n");
glfwTerminate();
return 1;
}
@ -33,15 +33,11 @@ int Window::initialize() {
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
//MSAA
// glfwWindowHint(GLFW_SAMPLES, 4);
// glEnable(GL_MULTISAMPLE);
//Create the window
mainWindow = glfwCreateWindow(width, height, "Zeus", nullptr, nullptr);
if (!mainWindow) {
printf("GLFW window failed");
printf("GLFW window failed\n");
glfwTerminate();
return 1;
}
@ -148,8 +144,8 @@ glm::vec2 Window::getSize() {
return {bufferWidth, bufferHeight};
}
bool Window::getShouldClose() {
return (bool)glfwWindowShouldClose(mainWindow);
bool Window::shouldClose() {
return static_cast<bool>(glfwWindowShouldClose(mainWindow));
}
void Window::swapBuffers() {

View File

@ -23,7 +23,7 @@ public:
glm::vec2 getSize();
bool resized;
bool getShouldClose();
bool shouldClose();
double getDeltaX();
double getDeltaY();

View File

@ -0,0 +1,5 @@
//
// Created by aurailus on 11/07/19.
//
#include "ConnectScene.h"

View File

@ -0,0 +1,14 @@
//
// Created by aurailus on 11/07/19.
//
#ifndef ZEUS_CONNECTSCENE_H
#define ZEUS_CONNECTSCENE_H
#include "../graph/scene/Scene.h"
class ConnectScene : public Scene {
// ConnectScene(ClientState& state, Address addr);
};
#endif //ZEUS_CONNECTSCENE_H

View File

@ -4,15 +4,15 @@
#include "GameScene.h"
GameScene::GameScene(ClientState* state) : Scene(state),
defs("../res/tex"),
server("127.0.0.1", 12345, defs.textures()),
GameScene::GameScene(ClientState& state) : Scene(state),
defs(state.defs),
server("127.0.0.1", 12345, defs),
world(defs, &playerPos, &server),
player(world, defs, *state->renderer->getCamera()),
player(world, defs, state.renderer.getCamera()),
gameGui(state->renderer->getCamera()->getBufferDimensions()),
debugGui(state->renderer->getCamera()->getBufferDimensions(), &defs.textures().getAtlasTexture()) {
gameGui (state.renderer.getCamera().getBufferDimensions()),
debugGui(state.renderer.getCamera().getBufferDimensions(), &defs.textures().getAtlasTexture()) {
defs.init(world);
world.init();
@ -27,44 +27,44 @@ GameScene::GameScene(ClientState* state) : Scene(state),
void GameScene::update() {
defs.update(static_cast<float>(state->deltaTime) * 1000);
defs.update(static_cast<float>(state.deltaTime) * 1000);
defs.textures().update();
server.update(player);
auto window = state->renderer->getWindow();
Window& window = state.renderer.getWindow();
playerPos = player.getPos();
player.update(window->input, state->deltaTime, window->getDeltaX(), window->getDeltaY());
player.update(window.input, state.deltaTime, window.getDeltaX(), window.getDeltaY());
if (state->renderer->resized) {
debugGui.bufferResized(state->renderer->getCamera()->getBufferDimensions());
gameGui.bufferResized(state->renderer->getCamera()->getBufferDimensions());
if (state.renderer.resized) {
debugGui.bufferResized(state.renderer.getCamera().getBufferDimensions());
gameGui.bufferResized(state.renderer.getCamera().getBufferDimensions());
state->renderer->resized = false;
state.renderer.resized = false;
}
for (auto &chunkPacket : server.chunkPackets) world.loadChunkPacket(chunkPacket);
server.chunkPackets.clear();
debugGui.update(player, world, defs, state->fps, world.getMeshChunkCount(), drawCalls, server.serverSideChunkGens, server.recvPackets);
debugGui.update(player, world, defs, state.fps, world.getMeshChunkCount(), drawCalls, server.serverSideChunkGens, server.recvPackets);
server.recvPackets = 0;
world.update(state->deltaTime);
world.update(state.deltaTime);
if (window->input.isKeyPressed(GLFW_KEY_F1)) {
if (window.input.isKeyPressed(GLFW_KEY_F1)) {
hudVisible = !hudVisible;
debugGui.changeVisibilityState(hudVisible ? debugVisible ? 0 : 2 : 1);
gameGui.setVisible(hudVisible);
}
if (window->input.isKeyPressed(GLFW_KEY_F3)) {
if (window.input.isKeyPressed(GLFW_KEY_F3)) {
debugVisible = !debugVisible;
debugGui.changeVisibilityState(hudVisible ? debugVisible ? 0 : 2 : 1);
}
}
void GameScene::draw() {
auto &renderer = *state->renderer;
auto &camera = *renderer.getCamera();
Renderer& renderer = state.renderer;
Camera& camera = renderer.getCamera();
renderer.beginChunkDeferredCalls();

View File

@ -19,14 +19,14 @@
class GameScene : public Scene {
public:
explicit GameScene(ClientState* state);
explicit GameScene(ClientState& state);
void update() override;
void draw() override;
void cleanup() override;
public:
LocalDefs defs;
LocalDefs& defs;
glm::vec3 playerPos;

View File

@ -4,7 +4,7 @@
#include "MenuScene.h"
MenuScene::MenuScene(ClientState *state) : Scene(state) {
MenuScene::MenuScene(ClientState& state) : Scene(state) {
fontTexture = new Texture((char*)"../res/tex/gui/font.png");
auto alphaText = new TextEntity(fontTexture);
@ -31,15 +31,15 @@ void MenuScene::update() {
}
void MenuScene::draw() {
state->renderer->beginChunkDeferredCalls();
state->renderer->endDeferredCalls();
state->renderer->beginGUIDrawCalls();
state.renderer.beginChunkDeferredCalls();
state.renderer.endDeferredCalls();
state.renderer.beginGUIDrawCalls();
for (auto &element : entities) {
element->draw(*state->renderer);
element->draw(state.renderer);
}
state->renderer->swapBuffers();
state.renderer.swapBuffers();
}
void MenuScene::cleanup() {

View File

@ -5,17 +5,15 @@
#ifndef ZEUS_MENUSCENE_H
#define ZEUS_MENUSCENE_H
#include "../../game/ClientState.h"
#include "../../game/graph/scene/Scene.h"
#include "../entity/hud/TextEntity.h"
class MenuScene : public Scene {
public:
explicit MenuScene(ClientState* state);
explicit MenuScene(ClientState& state);
void update() override;
void draw() override;
void cleanup() override;
@ -23,7 +21,6 @@ public:
private:
Texture* fontTexture;
std::vector<Entity*> entities;
// DebugGui gui;
};

View File

@ -5,13 +5,13 @@
#include "ServerConnection.h"
ServerConnection::ServerConnection(std::string address, unsigned short port, TextureAtlas &atlas) :
ServerConnection::ServerConnection(std::string address, unsigned short port, LocalDefs& defs) :
port(port),
address(std::move(address)) {
playerFrontTex = atlas.getTextureRef("player_front");
playerBackTex = atlas.getTextureRef("player_back");
shadowTex = atlas.getTextureRef("player_shadow");
playerFrontTex = defs.textures().getTextureRef("player_front");
playerBackTex = defs.textures().getTextureRef("player_back");
shadowTex = defs.textures().getTextureRef("player_shadow");
entities = new DrawableGroup();
}
@ -23,7 +23,7 @@ void ServerConnection::init(std::vector<Drawable *> &entities, LocalWorld *world
handler = NetHandler(address, port, 3, 3000);
if (handler.getState() != NetHandler::CLIENT) {
if (handler.getState() != NetState::CLIENT) {
exit(EXIT_FAILURE);
}
}

View File

@ -19,7 +19,7 @@
class ServerConnection {
public:
ServerConnection(std::string address, unsigned short port, TextureAtlas& atlas);
ServerConnection(std::string address, unsigned short port, LocalDefs& defs);
void init(std::vector<Drawable*> &entities, LocalWorld* world);
void update(Player &player);

View File

@ -14,6 +14,7 @@ Server::Server(unsigned short port) :
defs.init(world);
world.init();
config.init();
while (alive) update();
}

View File

@ -3,14 +3,30 @@
//
#include "ServerConfig.h"
#include "../../util/net/PacketChannel.h"
ServerConfig::ServerConfig(ServerDefs &defs) :
defs(defs) {
}
void ServerConfig::handlePacket(ServerClient &client, Packet &p) {
if (p.type == PacketType::MOD_DATA) {
return;
void ServerConfig::init() {
identifierList.reserve(static_cast<unsigned long>(defs.blocks().definitionsSize()));
for (int i = 0; i < defs.blocks().definitionsSize(); i++) {
identifierList.push_back(defs.blocks().fromIndex(i).getIdentifier());
}
}
void ServerConfig::handlePacket(ServerClient &client, Packet &r) {
if (r.type == PacketType::IDENTIFIER_LIST) {
Packet p(PacketType::IDENTIFIER_LIST);
Serializer::encodeInt(p.data, static_cast<int>(identifierList.size()));
for (auto& str : identifierList) {
Serializer::encodeString(p.data, str);
}
p.sendTo(client.getPeer(), PacketChannel::CONNECT_DATA);
}
}

View File

@ -13,9 +13,12 @@ class ServerConfig {
public:
explicit ServerConfig(ServerDefs& defs);
void init();
void handlePacket(ServerClient &client, Packet& p);
private:
ServerDefs& defs;
std::vector<std::string> identifierList {};
};
#endif //ZEUS_SERVERCONFIG_H

View File

@ -3,11 +3,14 @@
//
#include "Timer.h"
#include "Log.h"
Timer::Timer(const char* name) {
this->name = name;
start = std::chrono::high_resolution_clock::now();
}
Timer::Timer() :
start(std::chrono::high_resolution_clock::now()) {}
Timer::Timer(const char* name) :
name(name), hasName(true),
start(std::chrono::high_resolution_clock::now()) {}
long Timer::elapsedNs() {
auto finish = std::chrono::high_resolution_clock::now();
@ -15,15 +18,29 @@ long Timer::elapsedNs() {
return elapsed;
};
void Timer::printElapsedNs() {
printf("%s took %ld ns.\n", this->name, elapsedNs());
if (!name) {
std::cout << Log::err << "Timer without name called print function." << Log::endl;
return;
}
printf("%s took %ld ns.\n", this->name, elapsedNs());
}
void Timer::printElapsedMs() {
printf("%s took %.2f ms.\n", this->name, elapsedNs() / (double)1000000);
if (!name) {
std::cout << Log::err << "Timer without name called print function." << Log::endl;
return;
}
printf("%s took %.2f ms.\n", this->name, elapsedNs() / 1000000.);
}
void Timer::printElapsedSeconds() {
printf("%s took %.2f secs.\n", this->name, elapsedNs() / (double)1000000 / (double)1000);
if (!name) {
std::cout << Log::err << "Timer without name called print function." << Log::endl;
return;
}
printf("%s took %.2f secs.\n", this->name, elapsedNs() / 1000000. / 1000.);
}

View File

@ -10,15 +10,17 @@
class Timer {
public:
explicit Timer();
explicit Timer(const char* name);
long elapsedNs();
void printElapsedNs();
void printElapsedMs();
void printElapsedSeconds(); //Seconds
void printElapsedSeconds();
private:
const char* name;
bool hasName = false;
const char* name = nullptr;
std::chrono::high_resolution_clock::time_point start;
};

5
src/util/net/Address.cpp Normal file
View File

@ -0,0 +1,5 @@
//
// Created by aurailus on 11/07/19.
//
#include "Address.h"

14
src/util/net/Address.h Normal file
View File

@ -0,0 +1,14 @@
//
// Created by aurailus on 11/07/19.
//
#ifndef ZEUS_ADDRESS_H
#define ZEUS_ADDRESS_H
class Address {
};
#endif //ZEUS_ADDRESS_H

View File

@ -25,43 +25,43 @@ NetHandler::NetHandler(unsigned short port, short max_clients) {
}
void NetHandler::initServer(unsigned short port, short max_clients) {
state = HOST;
state = NetState::HOST;
if (enet_initialize() != 0) {
fprintf(stderr, "[FATAL] Failed to Initialize ENet.\n");
state = ERROR;
state = NetState::ERROR;
return;
}
address.host = ENET_HOST_ANY;
address.port = port;
host = enet_host_create(&address, (size_t)max_clients, PacketChannel::CHANNELS, 0, 0);
host = enet_host_create(&address, (size_t)max_clients, PACKET_CHANNELS, 0, 0);
peer = nullptr;
if (host == nullptr) {
fprintf(stderr, "[FATAL] Failed to create ENet host.\n");
state = ERROR;
state = NetState::ERROR;
return;
}
std::cout << Log::info << "Server Started. Listening for clientList." << Log::endl;
std::cout << Log::info << "Server Started. Listening for clients." << Log::endl;
}
void NetHandler::initClient(std::string host_address, unsigned short host_port, int attempts, int timeout) {
state = FAILED_CONNECT;
state = NetState::FAILED_CONNECT;
if (enet_initialize() != 0) {
fprintf(stderr, "[FATAL] Failed to Initialize ENet.\n");
state = ERROR;
state = NetState::ERROR;
return;
}
host = enet_host_create(nullptr, 1, PacketChannel::CHANNELS, 0, 0);
host = enet_host_create(nullptr, 1, PACKET_CHANNELS, 0, 0);
if (host == nullptr) {
fprintf(stderr, "[FATAL] Failed to create ENet client.\n");
state = ERROR;
state = NetState::ERROR;
return;
}
@ -71,11 +71,11 @@ void NetHandler::initClient(std::string host_address, unsigned short host_port,
int attempt = 0;
while (attempt++ < attempts) {
peer = enet_host_connect(host, &address, PacketChannel::CHANNELS, 0);
peer = enet_host_connect(host, &address, PACKET_CHANNELS, 0);
if (peer == nullptr) {
fprintf(stderr, "[FATAL] Failed to find ENet peer.\n");
state = ERROR;
state = NetState::ERROR;
return;
}
@ -83,7 +83,7 @@ void NetHandler::initClient(std::string host_address, unsigned short host_port,
if (enet_host_service(host, &event, (enet_uint32)timeout) > 0 && event.type == ENET_EVENT_TYPE_CONNECT) {
std::cout << Log::info << "Connected to "
<< event.peer->address.host << ":" << event.peer->address.port << "." << Log::endl;
state = CLIENT;
state = NetState::CLIENT;
break;
} else {
enet_peer_reset(peer);
@ -93,7 +93,7 @@ void NetHandler::initClient(std::string host_address, unsigned short host_port,
}
}
if (state == FAILED_CONNECT) {
if (state == NetState::FAILED_CONNECT) {
std::cout << Log::err << "Failed to connect to peer." << Log::endl;
return;
}
@ -103,7 +103,7 @@ bool NetHandler::update(ENetEvent *event) {
return enet_host_service(host, event, 0) > 0;
}
int NetHandler::getState() {
NetState NetHandler::getState() {
return state;
}
@ -112,14 +112,14 @@ ENetPeer* NetHandler::getPeer() {
}
void NetHandler::disconnect() {
if (state == CLIENT) {
if (state == NetState::CLIENT) {
std::cout << Log::info << "Disconnecting from host." << Log::endl;
enet_peer_disconnect(peer, 0);
enet_host_flush(host);
}
if (state != HOST) {
if (state != NetState::HOST) {
enet_host_destroy(host);
state = CLOSED;
state = NetState::CLOSED;
}
}
@ -128,7 +128,7 @@ NetHandler::~NetHandler() {
if (host != nullptr) {
disconnect();
}
if (getState() != UNINITIALIZED) {
if (getState() != NetState::UNINITIALIZED) {
enet_deinitialize();
}
}

View File

@ -10,6 +10,7 @@
#include <enet/enet.h>
#include "PacketChannel.h"
#include "../Log.h"
#include "NetState.h"
class NetHandler {
public:
@ -20,7 +21,7 @@ public:
void disconnect();
int getState();
NetState getState();
ENetPeer* getPeer();
bool update(ENetEvent* event);
@ -30,23 +31,14 @@ private:
void initClient(std::string host_address, unsigned short host_port, int connection_attempts, int connection_timeout);
bool initialized = false; //Not default constructed.
int state = UNINITIALIZED;
NetState state = NetState::UNINITIALIZED;
ENetPeer* peer;
ENetHost* host;
ENetAddress address;
public:
// States
enum {
UNINITIALIZED,
FAILED_CONNECT,
ERROR,
CLIENT,
HOST,
CLOSED
};
const static int PACKET_CHANNELS = 12;
};
#endif //ZEUS_NETHANDLER_H

19
src/util/net/NetState.h Normal file
View File

@ -0,0 +1,19 @@
//
// Created by aurailus on 11/07/19.
//
#ifndef ZEUS_NETSTATE_H
#define ZEUS_NETSTATE_H
enum class NetState {
UNINITIALIZED,
FAILED_CONNECT,
ERROR,
CLIENT,
HOST,
CLOSED
};
#endif //ZEUS_NETSTATE_H

View File

@ -4,9 +4,7 @@
#include "Packet.h"
Packet::Packet(PacketType p) {
this->type = p;
}
Packet::Packet(PacketType type) : type(type) {}
Packet::Packet(ENetPacket *packet) {
std::string packetData(packet->data, packet->data + packet->dataLength);
@ -24,12 +22,12 @@ ENetPacket* Packet::toENetPacket() {
return enet;
}
void Packet::sendTo(ENetPeer *peer, int channel) {
void Packet::sendTo(ENetPeer *peer, PacketChannel channel) {
ENetPacket* enet = toENetPacket();
enet_peer_send(peer, (enet_uint8)channel, enet);
enet_peer_send(peer, static_cast<enet_uint8>(channel), enet);
}
void Packet::sendTo(const ENetPeer &peer, int channel) {
void Packet::sendTo(const ENetPeer &peer, PacketChannel channel) {
ENetPacket* enet = toENetPacket();
enet_peer_send(const_cast<ENetPeer*>(&peer), (enet_uint8)channel, enet);
enet_peer_send(const_cast<ENetPeer*>(&peer), static_cast<enet_uint8>(channel), enet);
}

View File

@ -14,20 +14,22 @@
#include "Serializer.h"
#include "PacketType.h"
#include "PacketChannel.h"
struct Packet {
class Packet {
public:
Packet() = default;
explicit Packet(PacketType p);
explicit Packet(PacketType type);
explicit Packet(ENetPacket* packet);
ENetPacket* toENetPacket();
void sendTo(ENetPeer* peer, int channel);
void sendTo(const ENetPeer &peer, int channel);
void sendTo(ENetPeer* peer, PacketChannel channel);
void sendTo(const ENetPeer &peer, PacketChannel channel);
~Packet() = default;
PacketType type = PacketType::UNDEFINED;
std::string data;
~Packet() = default;
};

View File

@ -5,20 +5,16 @@
#ifndef ZEUS_PACKETCHANNEL_H
#define ZEUS_PACKETCHANNEL_H
struct PacketChannel {
const static int CHANNELS = 12;
enum {
UNDEFINED = -1,
KEEP_ALIVE,
AUTHENTICATE,
PLAYER_INFO,
ENTITY_INFO,
CHUNKS,
SERVER_INFO,
BLOCK_UPDATES
};
enum class PacketChannel {
UNDEFINED = -1,
KEEP_ALIVE,
AUTHENTICATE,
CONNECT_DATA,
PLAYER_INFO,
ENTITY_INFO,
CHUNKS,
SERVER_INFO,
BLOCK_UPDATES,
};

View File

@ -10,7 +10,7 @@ enum class PacketType {
UNDEFINED = 0,
HANDSHAKE,
AUTHENTICATE,
MOD_DATA,
IDENTIFIER_LIST,
PLAYER_INFO,
ENTITY_INFO,
CHUNK_INFO,

View File

@ -82,7 +82,7 @@ int Dimension::render(Renderer &renderer) {
for (auto &chunk : meshChunks) {
FrustumAABB bbox(chunk->getPos() * glm::vec3(TransPos::CHUNK_SIZE), glm::vec3(TransPos::CHUNK_SIZE));
if (renderer.getCamera()->inFrustum(bbox) != Frustum::OUTSIDE) {
if (renderer.getCamera().inFrustum(bbox) != Frustum::OUTSIDE) {
chunk->draw(renderer);
count++;
}