Apply new Code Styling to all files.

This commit is contained in:
Auri 2020-11-08 22:57:34 -08:00
parent 4915a8130b
commit e49ab18617
322 changed files with 14205 additions and 13136 deletions

4
.idea/misc.xml generated
View File

@ -6,14 +6,12 @@
<file path="$PROJECT_DIR$/src" />
<file path="$PROJECT_DIR$/test" />
</sourceRoots>
<libraryRoots>
<file path="$PROJECT_DIR$/lib" />
</libraryRoots>
<excludeRoots>
<file path="$PROJECT_DIR$/.github" />
<file path="$PROJECT_DIR$/.idea" />
<file path="$PROJECT_DIR$/Libraries" />
<file path="$PROJECT_DIR$/cmake-build-install" />
<file path="$PROJECT_DIR$/lib" />
<file path="$PROJECT_DIR$/worlds" />
<file path="$PROJECT_DIR$/worlds/world" />
</excludeRoots>

View File

@ -21,7 +21,8 @@
/**
* Main entrance point to the program. (Am I really describing what the main function is?)
* Intentionally kept minimal to allow for testing. Real startup logic is done in StartGame. *
* Intentionally kept minimal to allow for testing. Real startup logic is done in StartGame.
*
* @param argc - Argument array length
* @param argv - Argument array
* @returns - A numerical value indicating exit status.

View File

@ -11,7 +11,9 @@
#include "client/Client.h"
#include "server/Server.h"
enum class Mode { CLIENT, SERVER };
enum class Mode {
CLIENT, SERVER
};
/**
@ -23,7 +25,6 @@ enum class Mode { CLIENT, SERVER };
*/
std::map<std::string, std::string> ParseArgs(int argc, char* argv[]) {
//Collect arguments into `args` map
std::map<std::string, std::string> args;
for (int i = 1; i < argc; i++) {
@ -67,8 +68,7 @@ int StartGame(int argc, char* argv[]) {
for (auto arg : ParseArgs(argc, argv)) {
switch (Util::hash(arg.first.c_str())) {
default:
throw std::runtime_error("Invalid argument '" + arg.first + "'.");
default: throw std::runtime_error("Invalid argument '" + arg.first + "'.");
case Util::hash("--mode"):
if (arg.second == "client") mode = Mode::CLIENT;
@ -80,16 +80,13 @@ int StartGame(int argc, char* argv[]) {
// addr.host = arg.second;
// break;
case Util::hash("--port"):
port = static_cast<unsigned short>(stoi(arg.second));
case Util::hash("--port"): port = static_cast<unsigned short>(stoi(arg.second));
break;
case Util::hash("--subgame"):
subgame = arg.second;
case Util::hash("--subgame"): subgame = arg.second;
break;
case Util::hash("--noascii"):
ascii = false;
case Util::hash("--noascii"): ascii = false;
break;
}
}
@ -104,15 +101,8 @@ int StartGame(int argc, char* argv[]) {
"\t\t(____)(____)(__) \\_)(_/\\_/\\_/\n" << std::endl;
}
switch (mode) {
case Mode::CLIENT: {
Client c({1366, 768});
break; }
case Mode::SERVER: {
Server s(port, subgame);
break; }
}
if (mode == Mode::CLIENT) Client({ 1366, 768 });
else Server(port, subgame);
return 0;
}

View File

@ -18,6 +18,7 @@ class LocalServerInstance;
class Client {
public:
Client(const Client& o) = delete;
explicit Client(glm::ivec2 window);
double getDelta();

View File

@ -11,25 +11,36 @@
class Input {
public:
Input();
void init(GLFWwindow* window, glm::ivec2* winDimensions);
void setCallback(std::function<void(bool, int)> callback);
void update();
bool keyDown(int key);
bool keyPressed(int key);
bool keyReleased(int key);
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);
static void scrollCallback(GLFWwindow* window, double, double yO);
GLFWwindow* window = nullptr;
@ -40,7 +51,11 @@ private:
bool keysPressed[1024]{ false };
bool keysReleased[1024]{ false };
struct mouse { bool down = false; bool pressed = false; bool released = false; };
struct mouse {
bool down = false;
bool pressed = false;
bool released = false;
};
std::array<mouse, 3> mouseState{};
glm::vec2 delta;

View File

@ -7,9 +7,11 @@
#include <string>
#ifndef _WIN32
#include <thread>
#include <zconf.h>
#include <signal.h>
#endif
class LocalServerInstance {
@ -17,9 +19,11 @@ public:
LocalServerInstance(const std::string& path, unsigned short port, const std::string& subgame);
bool start();
void stop();
~LocalServerInstance();
private:
std::string path;
std::string subgame;

View File

@ -13,16 +13,21 @@
class Window {
public:
Window();
Window(glm::ivec2 win);
void update();
bool shouldClose();
void swapBuffers();
void addResizeCallback(const std::string& identifier, std::function<void(glm::ivec2)> cb);
void removeResizeCallback(const std::string& identifier);
glm::ivec2 getSize();
void setCursorHand(bool hand);
~Window();
@ -31,6 +36,7 @@ public:
GLFWwindow* mainWindow = nullptr;
private:
static void scrollCallback(GLFWwindow* window, double xO, double yO);
static void resizeCallback(GLFWwindow* window, int width, int height);
GLFWcursor* handCursor = nullptr;

View File

@ -50,7 +50,8 @@ void ClientNetworkInterpreter::update() {
}
auto player = world.getPlayer();
if (player) Serializer()
if (player)
Serializer()
.appendE(NetField::POS).append(player->getPos())
.appendE(NetField::VEL).append(player->getVel())
.appendE(NetField::LOOK_PITCH).append(player->getPitch())
@ -62,40 +63,43 @@ void ClientNetworkInterpreter::receivedPacket(std::unique_ptr<PacketView> p) {
switch (p->type) {
default:
std::cout << Log::err << "Received unknown packet of type " << static_cast<int>(p->type)
<< ". Is the server on a different protocol version?" << Log::endl; break;
<< ". Is the server on a different protocol version?" << Log::endl;
break;
case Packet::Type::SERVER_INFO:
serverSideChunkGens = p->d.read<unsigned int>(); break;
case Packet::Type::SERVER_INFO:serverSideChunkGens = p->d.read<unsigned int>();
break;
case Packet::Type::THIS_PLAYER_INFO:
world.getPlayer()->handleAssertion(p->d); break;
case Packet::Type::THIS_PLAYER_INFO:world.getPlayer()->handleAssertion(p->d);
break;
case Packet::Type::PLAYER_ENT_INFO:
world.handlePlayerEntPacket(std::move(p)); break;
case Packet::Type::PLAYER_ENT_INFO:world.handlePlayerEntPacket(std::move(p));
break;
case Packet::Type::CHUNK:
case Packet::Type::MAPBLOCK:
world.handleWorldPacket(std::move(p)); break;
case Packet::Type::MAPBLOCK:world.handleWorldPacket(std::move(p));
break;
case Packet::Type::BLOCK_SET: {
auto pos = p->d.read<glm::ivec3>();
auto block = p->d.read<unsigned int>();
world.getActiveDimension()->setBlock(pos, block);
break; }
break;
}
case Packet::Type::ENTITY_INFO:
world.getActiveDimension().l()->serverEntitiesInfo(p->d); break;
case Packet::Type::ENTITY_INFO:world.getActiveDimension().l()->serverEntitiesInfo(p->d);
break;
case Packet::Type::ENTITY_REMOVED:
world.getActiveDimension().l()->serverEntitiesRemoved(p->d); break;
case Packet::Type::ENTITY_REMOVED:world.getActiveDimension().l()->serverEntitiesRemoved(p->d);
break;
case Packet::Type::INV_DATA:
onInvPacket(std::move(p)); break;
case Packet::Type::INV_DATA:onInvPacket(std::move(p));
break;
case Packet::Type::INV_INVALID: {
std::string source = p->d.read<std::string>();
std::string list = p->d.read<std::string>();
throw std::runtime_error("Invalid inventory " + source + ":" + list + " was request by client."); }
throw std::runtime_error("Invalid inventory " + source + ":" + list + " was request by client.");
}
}
}
@ -129,7 +133,8 @@ void ClientNetworkInterpreter::invUnwatch(const std::string& inv, const std::str
.sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}
void ClientNetworkInterpreter::invInteract(const std::string &inv, const std::string &list, bool primary, unsigned short ind) {
void ClientNetworkInterpreter::invInteract(const std::string& inv, const std::string& list, bool primary,
unsigned short ind) {
Serializer().append<unsigned short>(primary).append(inv).append(list).append<unsigned short>(ind)
.packet(Packet::Type::INV_INTERACT).sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}

View File

@ -13,28 +13,41 @@
#include "client/conn/ServerConnection.h"
class Model;
class Target;
class LocalWorld;
class PacketView;
class LocalPlayer;
class LocalSubgame;
enum class NetPlayerField;
class ClientNetworkInterpreter {
public:
ClientNetworkInterpreter(const ClientNetworkInterpreter& other) = delete;
ClientNetworkInterpreter(ServerConnection& connection, LocalWorld& world);
void init(std::function<void(std::unique_ptr<PacketView>)> invCallback);
void update();
void blockHit(const Target& target);
void blockPlace(const Target& target);
void blockInteract(const Target& target);
void blockPlaceOrInteract(const Target& target);
void invWatch(const std::string& inv, const std::string& list);
void invUnwatch(const std::string& inv, const std::string& list);
void invInteract(const std::string& inv, const std::string& list, bool primary, unsigned short ind);
void sendPacket(const Packet& packet, Packet::Channel channel);

View File

@ -23,10 +23,13 @@ public:
ServerConnection() = default;
void attemptConnect(Address addr);
State getConnectionStatus();
void disconnect();
void processConnecting();
bool pollEvents(ENetEvent* event);
ENetPeer* getPeer();

View File

@ -13,6 +13,7 @@ public:
ParticleEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, BlockDef& block);
void update(double delta, glm::vec3 player);
void draw(Renderer& renderer) override;
float time = 0;

View File

@ -8,7 +8,8 @@
class PlayerEntity : public DrawableEntity {
public:
PlayerEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, unsigned int id, const std::shared_ptr<Model>& model) :
PlayerEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, unsigned int id, const std::shared_ptr<Model>& model)
:
DrawableEntity(game, dim, model), Entity(game, dim), id(id) {
setPos(pos);
}

View File

@ -44,21 +44,33 @@ void WireframeEntity::buildMesh(const std::vector<SelectionBox>& boxes) {
this->model->fromMesh(std::move(mesh));
}
void WireframeEntity::createBox(glm::vec3 a, glm::vec3 b, float x, float y, float z, float xSize, float ySize, float zSize) {
void
WireframeEntity::createBox(glm::vec3 a, glm::vec3 b, float x, float y, float z, float xSize, float ySize, float zSize) {
float hw = (width / 2.0f);
float w = width;
glm::vec3 c = color;
std::vector<EntityVertex> myVerts{
/*0*/ {{x - hw + a.x, y - hw + a.y, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*1*/ {{x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*2*/ {{x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*3*/ {{x - hw + a.x, y - hw + a.y, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*0*/
{{ x - hw + a.x, y - hw + a.y, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false, { 0, 1, 0 }, {}, {}},
/*1*/{{ x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*2*/
{{ x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*3*/{{ x - hw + a.x, y - hw + a.y, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*4*/ {{x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*5*/ {{x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*6*/ {{x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*7*/ {{x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*4*/{{ x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*5*/
{{ x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*6*/{{ x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 },
{ 1, 1, 1 }, false, { 0, 1, 0 }, {}, {}},
/*7*/
{{ x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
};
std::vector<unsigned int> myInds{

View File

@ -16,11 +16,13 @@ public:
color(color) {};
void updateMesh(const std::vector<SelectionBox>& boxes, float width);
private:
std::vector<EntityVertex> vertices{};
std::vector<unsigned int> indices{};
void buildMesh(const std::vector<SelectionBox>& boxes);
void createBox(glm::vec3 a, glm::vec3 b, float x, float y, float z, float xSize, float ySize, float zSize);
glm::vec3 color{};

View File

@ -13,30 +13,37 @@
class Camera {
public:
Camera();
void create(float buffWidth, float buffHeight, glm::vec3 up);
void changeWindowDimensions(glm::vec2 size);
glm::vec3 getPos();
void setPos(glm::vec3 pos);
void setYaw(double yaw);
void setPitch(double pitch);
glm::mat4 getProjectionMatrix();
glm::mat4 getOrthographicMatrix();
glm::mat4 getViewMatrix();
glm::vec3 getFront();
glm::vec3 getRight();
glm::vec2 getBufferDimensions();
bool inFrustum(glm::vec3& p);
int inFrustum(FrustumAABB& b);
~Camera();
private:
//Window Size
glm::vec2 bufferDimensions;
@ -66,6 +73,7 @@ private:
double pitch;
void createMatrices();
void update();
};

View File

@ -9,12 +9,15 @@ class Renderer;
class Drawable {
public:
virtual void update(double delta) {};
virtual void draw(Renderer& renderer) {};
virtual bool isVisible() { return visible; }
virtual void setVisible(bool visible) { this->visible = visible; }
virtual ~Drawable() = default;
protected:
bool visible = true;
};

View File

@ -13,12 +13,15 @@ public:
void draw(Renderer& renderer) override;
void addDrawable(Drawable* drawable);
void removeDrawable(Drawable* drawable);
void clearDrawables();
std::vector<Drawable*>& getChildren();
~DrawableGroup() override;
protected:
std::vector<Drawable*> children{};
};

View File

@ -9,13 +9,17 @@
#include <glm/vec4.hpp>
class AtlasRef;
class TextureAtlas;
class Font {
public:
Font() = default;
Font(TextureAtlas& atlas, std::shared_ptr<AtlasRef> tex);
unsigned int getCharWidth(char c);
glm::vec4 getCharUVs(char c);
const static unsigned int amountOfChars = 95;

View File

@ -46,7 +46,8 @@ int Model::fromSerialized(const SerializedModel& model, const std::vector<std::s
this->textures = textures;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFileFromMemory(model.data.data(), model.data.length(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals, "B3D");
const aiScene* scene = importer.ReadFileFromMemory(model.data.data(), model.data.length(),
aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals, "B3D");
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cout << Log::err << "ERROR::ASSIMP::" << importer.GetErrorString() << Log::endl;
@ -206,7 +207,8 @@ void Model::loadAnimations(const aiScene *scene) {
channel.scaleKeys.reserve(aiChannel->mNumScalingKeys);
for (unsigned int k = 0; k < aiChannel->mNumScalingKeys; k++) {
aiVectorKey* key = &aiChannel->mScalingKeys[k];
channel.scaleKeys.emplace_back(key->mTime, glm::vec3{key->mValue.x, key->mValue.y, key->mValue.z});
channel.scaleKeys.emplace_back(key->mTime,
glm::vec3{ key->mValue.x, key->mValue.y, key->mValue.z });
}
}
}
@ -229,7 +231,8 @@ void Model::calcBoneHeirarchy(aiNode *node, const aiScene *scene, int parentBone
for (unsigned int i = 0; i < node->mNumChildren; i++) calcBoneHeirarchy(node->mChildren[i], scene, index);
}
void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds, std::vector<glm::mat4>& transforms) {
void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds,
std::vector<glm::mat4>& transforms) {
AnimChannel* channel = nullptr;
for (auto& i : animation.channels) {
if (i.index == bone.index) {
@ -240,7 +243,8 @@ void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 p
glm::mat4 boneTransformation(1.0f);
if (channel) {
glm::mat4 position = glm::translate(glm::mat4(1.0), calcBoneVal<glm::vec3>(animTime, bounds, channel->positionKeys, {},
glm::mat4 position = glm::translate(glm::mat4(1.0),
calcBoneVal<glm::vec3>(animTime, bounds, channel->positionKeys, {},
[](const glm::vec3& a, const glm::vec3& b, float factor) { return glm::mix(a, b, factor); }));
glm::mat4 scale = glm::scale(glm::mat4(1.0), calcBoneVal<glm::vec3>(animTime, bounds, channel->scaleKeys, {},
[](const glm::vec3& a, const glm::vec3& b, float factor) { return glm::mix(a, b, factor); }));
@ -258,5 +262,6 @@ void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 p
glm::mat4 globalTransformation = parentTransform * boneTransformation;
transforms[bone.index] = globalInverseTransform * globalTransformation * bone.offsetMatrix;
for (auto& child : bone.children) calcBoneTransformation(animTime, *child, globalTransformation, bounds, transforms);
for (auto& child : bone.children)
calcBoneTransformation(animTime, *child, globalTransformation, bounds, transforms);
}

View File

@ -16,6 +16,7 @@
#include "client/graph/mesh/EntityMesh.h"
class AtlasRef;
class SerializedModel;
class Model {
@ -23,7 +24,9 @@ public:
Model() = default;
void fromMesh(std::unique_ptr<EntityMesh> mesh);
int fromFile(const std::string& path, const std::vector<std::shared_ptr<AtlasRef>>& texture);
int fromSerialized(const SerializedModel& model, const std::vector<std::shared_ptr<AtlasRef>>& texture);
void getTransformsByFrame(double frame, glm::ivec2 bounds, std::vector<glm::mat4>& transforms);
@ -34,13 +37,18 @@ public:
std::vector<std::unique_ptr<EntityMesh>> meshes;
private:
void loadModelMeshes(aiNode* node, const aiScene* scene);
void loadMeshAndBone(aiMesh* mesh, std::unique_ptr<EntityMesh>& target);
void loadAnimations(const aiScene* scene);
void calcBoneHeirarchy(aiNode* node, const aiScene* scene, int parentBoneIndex);
void calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds, std::vector<glm::mat4>& transforms);
template <typename T> static inline T calcBoneVal(
void calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds,
std::vector<glm::mat4>& transforms);
template<typename T>
static inline T calcBoneVal(
double animTime, glm::ivec2 bounds, const std::vector<std::pair<double, T>>& keysArray,
const T& def, std::function<T(const T& a, const T& b, float factor)> merge) {

View File

@ -12,6 +12,7 @@
class ModelAnimation {
public:
ModelAnimation() = default;
explicit ModelAnimation(const std::string& name);
std::string name = "";

View File

@ -11,6 +11,7 @@
class ModelBone {
public:
ModelBone() = default;
ModelBone(unsigned int index, int parent, const std::string& name);
std::string name{};

View File

@ -23,7 +23,8 @@ Renderer::Renderer(glm::ivec2 win) :
ssao.createFromFile("../assets/shader/post/passThrough.vs", "../assets/shader/post/ssaoCalc.fs");
blur.createFromFile("../assets/shader/post/passThrough.vs", "../assets/shader/post/ssaoBlur.fs");
light.createFromFile("../assets/shader/post/passThrough.vs", "../assets/shader/post/deferredLighting.fs");
world.createFromFile("../assets/shader/world/world.vs", "../assets/shader/world/world.fs", "../assets/shader/world/world.gs");
world.createFromFile("../assets/shader/world/world.vs", "../assets/shader/world/world.fs",
"../assets/shader/world/world.gs");
entity.createFromFile("../assets/shader/world/entity.vs", "../assets/shader/world/entity.fs");
guiShader = Shader();
@ -70,7 +71,8 @@ void Renderer::beginChunkDeferredCalls() {
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
glViewport(0, 0, static_cast<int>(world.windowSize.x * world.bufferScale), static_cast<int>(world.windowSize.y * world.bufferScale));
glViewport(0, 0, static_cast<int>(world.windowSize.x * world.bufferScale),
static_cast<int>(world.windowSize.y * world.bufferScale));
glBindFramebuffer(GL_FRAMEBUFFER, light.gBuffer);
glClear(GL_DEPTH_BUFFER_BIT);
@ -194,7 +196,8 @@ void Renderer::setModelMatrix(const glm::mat4& modelMatrix) {
void Renderer::setBones(std::vector<glm::mat4>& transforms) {
if (transforms.empty()) return;
currentShader->setArr((currentShader == &entity ? entity.uniforms.bones : gu.bones), static_cast<GLsizei>(transforms.size()), transforms.at(0));
currentShader->setArr((currentShader == &entity ? entity.uniforms.bones : gu.bones),
static_cast<GLsizei>(transforms.size()), transforms.at(0));
}
void Renderer::setClipBounds(glm::vec4 bounds) {

View File

@ -19,25 +19,35 @@
class Renderer {
public:
Renderer();
Renderer(glm::ivec2 win);
void update(double delta);
void beginChunkDeferredCalls();
void beginEntityDeferredCalls();
void endDeferredCalls();
void beginGUIDrawCalls();
void swapBuffers();
void setShader(Shader& s);
void setClearColor(unsigned char r, unsigned char g, unsigned char b);
static void toggleDepthTest(bool enable);
static void clearDepthBuffer();
void setModelMatrix(const glm::mat4& modelMatrix);
void setBones(std::vector<glm::mat4>& transforms);
void setClipBounds(glm::vec4 bounds);
void enableTexture(Texture* texture);
Window window;

View File

@ -10,13 +10,18 @@
class Texture {
public:
Texture() = default;
explicit Texture(const std::string& file);
void loadFromFile(std::string file);
void loadFromBytes(unsigned char* bytes, int width, int height, GLint interpolation = GL_NEAREST, GLint repeatMode = GL_CLAMP_TO_EDGE);
void loadFromBytes(unsigned char* bytes, int width, int height, GLint interpolation = GL_NEAREST,
GLint repeatMode = GL_CLAMP_TO_EDGE);
void updateTexture(int x, int y, int width, int height, unsigned char* bytes);
void use(GLuint position = 0);
void clear();
~Texture();

View File

@ -14,6 +14,7 @@ class ChunkVertex;
class ChunkMesh : public Mesh {
public:
ChunkMesh() = default;
ChunkMesh(const ChunkMesh& o) { throw std::runtime_error("No copy constructor for ChunkMeshes"); };
void create(const std::vector<ChunkVertex>& vertices, const std::vector<unsigned int>& indices);

View File

@ -5,6 +5,7 @@
#include <vector>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/normal.hpp>
#include "ChunkMeshGenerator.h"
@ -21,8 +22,10 @@
#include "game/atlas/LocalBiomeAtlas.h"
#include "game/atlas/LocalDefinitionAtlas.h"
ChunkMeshGenerator::ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefinitionAtlas& defs, LocalBiomeAtlas& biomes,
std::shared_ptr<Chunk> chunk, std::array<std::shared_ptr<Chunk>, 6> adjacent, std::array<NoiseSample, 3>& blockOffsets) :
ChunkMeshGenerator::ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefinitionAtlas& defs,
LocalBiomeAtlas& biomes,
std::shared_ptr<Chunk> chunk, std::array<std::shared_ptr<Chunk>, 6> adjacent,
std::array<NoiseSample, 3>& blockOffsets) :
meshDetails(meshDetails),
adjacent(adjacent),
biomes(biomes),
@ -57,24 +60,33 @@ ChunkMeshGenerator::ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefin
for (auto& mod : model.meshMods) {
switch (mod.first) {
default: break;
case MeshMod::OFFSET_X: vis.x += blockOffsets[0].get(vis / 16.f) * mod.second; break;
case MeshMod::OFFSET_Y: vis.y += blockOffsets[1].get(vis / 16.f) * mod.second; break;
case MeshMod::OFFSET_Z: vis.z += blockOffsets[2].get(vis / 16.f) * mod.second; break;
case MeshMod::OFFSET_X: vis.x += blockOffsets[0].get(vis / 16.f) * mod.second;
break;
case MeshMod::OFFSET_Y: vis.y += blockOffsets[1].get(vis / 16.f) * mod.second;
break;
case MeshMod::OFFSET_Z: vis.z += blockOffsets[2].get(vis / 16.f) * mod.second;
break;
}
}
glm::ivec3 pos = { off.x - 1, off.y, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::XNEG)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::XNEG)], biomeTint, getLightAt(pos));
pos = { off.x + 1, off.y, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::XPOS)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::XPOS)], biomeTint, getLightAt(pos));
pos = { off.x, off.y - 1, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::YNEG)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::YNEG)], biomeTint, getLightAt(pos));
pos = { off.x, off.y + 1, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::YPOS)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::YPOS)], biomeTint, getLightAt(pos));
pos = { off.x, off.y, off.z - 1 };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::ZNEG)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::ZNEG)], biomeTint, getLightAt(pos));
pos = { off.x, off.y, off.z + 1 };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::ZPOS)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::ZPOS)], biomeTint, getLightAt(pos));
addFaces(vis, model.parts[static_cast<int>(EVec::NO_CULL)], biomeTint, getLightAt(vis));
}
@ -111,7 +123,9 @@ glm::vec4 ChunkMeshGenerator::getLightAt(const glm::ivec3& pos) {
return chunk->getLight(Space::Block::index(pos));
}
void ChunkMeshGenerator::addFaces(const glm::vec3 &offset, const std::vector<MeshPart> &meshParts, const glm::vec3& tint, glm::vec4 light) {
void
ChunkMeshGenerator::addFaces(const glm::vec3& offset, const std::vector<MeshPart>& meshParts, const glm::vec3& tint,
glm::vec4 light) {
for (const MeshPart& mp : meshParts) {
glm::vec3 modData = {};
@ -122,8 +136,7 @@ void ChunkMeshGenerator::addFaces(const glm::vec3 &offset, const std::vector<Mes
case ShaderMod::ROTATE_Y:
case ShaderMod::ROTATE_Z:
case ShaderMod::SWAY_ATTACHED:
case ShaderMod::SWAY_FULL_BLOCK:
modData = { Util::packFloat((offset - 8.f) / 8.f), mp.modValue, 0 };
case ShaderMod::SWAY_FULL_BLOCK:modData = { Util::packFloat((offset - 8.f) / 8.f), mp.modValue, 0 };
break;
}

View File

@ -9,11 +9,17 @@
#include <memory>
class Chunk;
class MeshPart;
class BlockDef;
class NoiseSample;
class LocalBiomeAtlas;
class ChunkMeshDetails;
class LocalDefinitionAtlas;
class ChunkMeshGenerator {
@ -21,11 +27,14 @@ public:
ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefinitionAtlas& defs, LocalBiomeAtlas& biomes,
std::shared_ptr<Chunk> chunk, std::array<std::shared_ptr<Chunk>, 6> adjacent,
std::array<NoiseSample, 3>& blockOffsets);
private:
inline BlockDef& getBlockAt(const glm::ivec3& pos);
inline glm::vec4 getLightAt(const glm::ivec3& pos);
void addFaces(const glm::vec3 &offset, const std::vector<MeshPart> &meshParts, const glm::vec3& tint, glm::vec4 light);
void
addFaces(const glm::vec3& offset, const std::vector<MeshPart>& meshParts, const glm::vec3& tint, glm::vec4 light);
LocalDefinitionAtlas& defs;
LocalBiomeAtlas& biomes;

View File

@ -10,7 +10,9 @@ class Renderer;
struct ChunkRenderElem {
virtual void draw(Renderer& renderer) = 0;
virtual glm::vec3 getPos() = 0;
// Used to determine if the RenderElem should be deleted.
// Bool is if the RenderElem should be kept alive.
// True = keep, False = remove

View File

@ -13,9 +13,13 @@
class EntityMesh : public Mesh {
public:
EntityMesh() = default;
EntityMesh(const EntityMesh& o);
void create(const std::vector<EntityVertex>& vertices, const std::vector<unsigned int>& indices);
~EntityMesh() = default;
private:
void initModel();

View File

@ -10,6 +10,7 @@
class EntityVertex {
public:
EntityVertex() = default;
EntityVertex(glm::vec3 position, glm::vec4 colorData, glm::vec3 colorBlend, float useTex, glm::vec3 normal,
glm::ivec4 boneIDs, glm::vec4 boneWeights) : position(position), colorData(colorData),
colorBlend(colorBlend), useTex(useTex), normal(normal), boneIDs(boneIDs), boneWeights(boneWeights) {};

View File

@ -11,11 +11,14 @@ public:
Mesh() = default;
void cleanup();
virtual void draw() const;
~Mesh();
protected:
void genArrays(GLuint vboLength, GLuint iboLength, const void* verticesPtr, const void* indicesPtr);
void createVertexAttrib(GLuint offset, GLuint size, GLenum type, GLsizei stride, const void* pointer);
GLuint VAO = 0;

View File

@ -11,18 +11,23 @@
#include "client/graph/Drawable.h"
class ChunkMesh;
class ChunkVertex;
class MeshChunk : public ChunkRenderElem, Drawable {
public:
MeshChunk() = default;
void create(std::vector<ChunkVertex>& vertices, std::vector<unsigned int>& indices);
void draw(Renderer& renderer) override;
bool updateChunkUse(glm::vec3 chunk, bool used) override;
void setPos(glm::vec3 pos);
glm::vec3 getPos() override;
private:
std::shared_ptr<ChunkMesh> mesh = nullptr;
glm::vec3 pos{};

View File

@ -18,7 +18,8 @@ void BlurShader::postCreate() {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glGenTextures(1, &colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
@ -30,7 +31,8 @@ void BlurShader::windowResized(glm::ivec2 windowSize) {
this->windowSize = windowSize;
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}

View File

@ -11,6 +11,7 @@
class BlurShader : public Shader {
public:
explicit BlurShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);

View File

@ -11,6 +11,7 @@
class EntityGeometryShader : public Shader {
public:
explicit EntityGeometryShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
struct Uniforms {

View File

@ -28,7 +28,8 @@ void LightingShader::postCreate() {
glGenTextures(1, &gPosition);
glBindTexture(GL_TEXTURE_2D, gPosition);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@ -37,14 +38,16 @@ void LightingShader::postCreate() {
glGenTextures(1, &gNormal);
glBindTexture(GL_TEXTURE_2D, gNormal);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0);
glGenTextures(1, &gColorSpec);
glBindTexture(GL_TEXTURE_2D, gColorSpec);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x), static_cast<int>(windowSize.y), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x), static_cast<int>(windowSize.y), 0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gColorSpec, 0);
@ -55,7 +58,8 @@ void LightingShader::postCreate() {
glGenRenderbuffers(1, &rDepth);
glBindRenderbuffer(GL_RENDERBUFFER, rDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale));
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale));
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rDepth);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
@ -72,22 +76,26 @@ void LightingShader::windowResized(glm::ivec2 windowSize) {
glBindFramebuffer(GL_FRAMEBUFFER, gBuffer);
glBindTexture(GL_TEXTURE_2D, gPosition);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gPosition, 0);
glBindTexture(GL_TEXTURE_2D, gNormal);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0);
glBindTexture(GL_TEXTURE_2D, gColorSpec);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gColorSpec, 0);
unsigned int attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);
glBindRenderbuffer(GL_RENDERBUFFER, rDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale));
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale));
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rDepth);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

View File

@ -11,6 +11,7 @@
class LightingShader : public Shader {
public:
explicit LightingShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);

View File

@ -61,7 +61,8 @@ void SSAOShader::postCreate() {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glGenTextures(1, &colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
@ -73,7 +74,8 @@ void SSAOShader::windowResized(glm::ivec2 windowSize) {
this->windowSize = windowSize;
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}

View File

@ -12,6 +12,7 @@
class SSAOShader : public Shader {
public:
explicit SSAOShader(glm::ivec2 windowSize, float bufferScale, unsigned int kernelCount);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);

View File

@ -14,7 +14,8 @@ void Shader::createFromString(std::string& vertexSource, std::string& fragmentSo
compileShader(vertexSource, fragmentSource);
}
void Shader::createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile) {
void
Shader::createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile) {
compileShader(readFile(vertexFile), readFile(fragmentFile),
geoFile == "" ? "" : readFile(geoFile));
postCreate();
@ -84,7 +85,8 @@ void Shader::setArr(int loc, unsigned int count, glm::mat4 &start) {
glUniformMatrix4fv(loc, count, GL_FALSE, glm::value_ptr(start));
}
void Shader::compileShader(const std::string& vertexSource, const std::string& fragmentSource, const std::string& geoSource) {
void Shader::compileShader(const std::string& vertexSource, const std::string& fragmentSource,
const std::string& geoSource) {
shaderID = glCreateProgram();
if (!shaderID) throw std::runtime_error("Failed to create shader program.");
@ -128,7 +130,8 @@ void Shader::addShader(GLuint program, const std::string& shaderCode, GLenum sha
if (!result) {
glGetShaderInfoLog(shader, sizeof(eLog), nullptr, eLog);
std::string shaderTypeName = (shaderType == GL_VERTEX_SHADER) ? "vertex" : (shaderType == GL_FRAGMENT_SHADER) ? "fragment" : "geometry";
std::string shaderTypeName = (shaderType == GL_VERTEX_SHADER) ? "vertex" : (shaderType == GL_FRAGMENT_SHADER)
? "fragment" : "geometry";
throw std::runtime_error("Failed to compile the " + shaderTypeName + " shader. Error:\n" + eLog);
}

View File

@ -12,20 +12,28 @@
class Shader {
public:
void createFromString(std::string& vertexSource, std::string& fragmentSource, const std::string& geoSource = "");
void createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile = "");
void
createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile = "");
virtual void postCreate() {};
int get(const std::string& name);
void use();
static void clearShader();
void set(int loc, unsigned int val);
void set(int loc, int val);
void set(int loc, float val);
void set(int loc, glm::vec3 val);
void set(int loc, glm::vec4 val);
void set(int loc, glm::mat4 val);
void setArr(int loc, unsigned int count, glm::mat4& start);
@ -37,7 +45,9 @@ public:
private:
static std::string readFile(const std::string& fileLocation);
void compileShader(const std::string& vertexSource, const std::string& fragmentSource, const std::string& geoSource = "");
void compileShader(const std::string& vertexSource, const std::string& fragmentSource,
const std::string& geoSource = "");
static void addShader(unsigned int program, const std::string& shaderCode, GLenum shaderType);
void checkActive();

View File

@ -32,12 +32,17 @@ void WorldGeometryShader::postCreate() {
void WorldGeometryShader::windowResized(glm::ivec2 windowSize) {
this->windowSize = windowSize;
}
void WorldGeometryShader::updateSwayMap(double delta) {
swayOffset += delta * 2.8;
for (int i = 0; i < 16 * 16; i++) {
swayData[i*4] = static_cast<unsigned char>((fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset))) + 1) / 2.f * 255.f);
swayData[i*4+1] = static_cast<unsigned char>((fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 50))) + 1) / 2.f * 255.f);
swayData[i*4+2] = static_cast<unsigned char>((fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 100))) + 1) / 2.f * 255.f);
swayData[i * 4] = static_cast<unsigned char>(
(fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset))) + 1) / 2.f * 255.f);
swayData[i * 4 + 1] = static_cast<unsigned char>(
(fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 50))) + 1) / 2.f * 255.f);
swayData[i * 4 + 2] = static_cast<unsigned char>(
(fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 100))) + 1) / 2.f *
255.f);
}
swayTex.updateTexture(0, 0, 16, 16, &swayData[0]);
}

View File

@ -14,9 +14,11 @@
class WorldGeometryShader : public Shader {
public:
explicit WorldGeometryShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);
void updateSwayMap(double delta);
struct Uniforms {

View File

@ -78,10 +78,12 @@ void DebugGui::positionElements(glm::vec2 bufferSize) {
get<GuiLabelledGraph>("gpuGraph")->setPos({ bufferWidth - 254, 90 + 80 });
}
void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chunks*/, int drawCalls, int ssGen, int ssPack) {
void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chunks*/, int drawCalls, int ssGen,
int ssPack) {
Target target = player->getTarget();
auto& onBiomeDef = game->getBiomes().biomeFromId(world.l()->getActiveDimension()->getBiome(glm::floor(player->getPos())));
auto& onBiomeDef = game->getBiomes().biomeFromId(
world.l()->getActiveDimension()->getBiome(glm::floor(player->getPos())));
auto& targetedBlockDef = game->getDefs().blockFromId(world.l()->getActiveDimension()->getBlock(target.pos));
/* Top-right Graphs */ {
@ -128,10 +130,13 @@ void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chu
str << "C: " << vecToString(posOffsetFromChunk) << " [" << vecToString(chunkPos) << "]" << std::endl;
str << "M: " << vecToString(posOffsetFromBlock) << " [" << vecToString(mapBlockPos) << "]" << std::endl;
str << "R: " << vecToString(posOffsetFromRegion) << " [" << vecToString(regionPos) << "]" << std::endl << std::endl;
str << "R: " << vecToString(posOffsetFromRegion) << " [" << vecToString(regionPos) << "]" << std::endl
<< std::endl;
str << "Texture Slots: " << game.l()->textures.textureSlotsUsed << " / " << game.l()->textures.maxTextureSlots
<< " (" << round(game.l()->textures.textureSlotsUsed / static_cast<float>(game.l()->textures.maxTextureSlots) * 100) << "%)" << std::endl << std::endl;
<< " ("
<< round(game.l()->textures.textureSlotsUsed / static_cast<float>(game.l()->textures.maxTextureSlots) * 100)
<< "%)" << std::endl << std::endl;
str << "Biome: " << onBiomeDef.identifier << " [" << onBiomeDef.index << "]" << std::endl << std::endl;
@ -157,8 +162,10 @@ void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chu
}
/* Crosshair Text */ {
if (target.type == Target::Type::BLOCK) get<GuiText>("crosshairText")->setText(targetedBlockDef.name + " (" +
targetedBlockDef.identifier + ") [" + std::to_string(targetedBlockDef.index) + "]");
if (target.type == Target::Type::BLOCK)
get<GuiText>("crosshairText")->setText(targetedBlockDef.name + " (" +
targetedBlockDef.identifier + ") [" +
std::to_string(targetedBlockDef.index) + "]");
else get<GuiText>("crosshairText")->setText("");
}
}

View File

@ -9,7 +9,9 @@
#include "util/CovariantPtr.h"
class LocalPlayer;
class LocalSubgame;
class LocalWorld;
class DebugGui : public GuiContainer {
@ -17,10 +19,13 @@ public:
DebugGui(glm::vec2 bufferSize, SubgamePtr game, WorldPtr world);
void bufferResized(glm::vec2 bufferSize);
void changeVisibilityState(int state);
void positionElements(glm::vec2 bufferSize);
void update(std::shared_ptr<LocalPlayer> player, double fps, int chunks, int drawCalls, int ssGen, int ssPack);
private:
int displayMode;

View File

@ -10,21 +10,29 @@
class GameGui {
public:
explicit GameGui(InventoryRefsPtr refs, glm::vec2 bufferSize, SubgamePtr defs, Renderer& renderer);
void winResized(glm::ivec2 win);
void update(double delta);
void setVisible(bool visible);
bool isVisible();
void showMenu(std::shared_ptr<LuaGuiElement> root);
void closeMenu();
const bool isInMenu() const;
void setHud(std::shared_ptr<LuaGuiElement> hud);
std::shared_ptr<LuaGuiElement> getHud();
void drawHud(Renderer& renderer);
void drawMenu(Renderer& renderer);
private:
SubgamePtr defs;
Renderer& renderer;

View File

@ -15,6 +15,7 @@ public:
defs(defs), refs(refs), GuiBuilder(defs.l()->textures, defs.l()->models, root) {};
std::shared_ptr<GuiComponent> createComponent(LuaGuiElement& elem, glm::ivec2 bounds) override;
private:
InventoryRefsPtr refs;
SubgamePtr defs;

View File

@ -57,17 +57,13 @@ std::shared_ptr<GuiComponent> GuiBuilder::createComponent(LuaGuiElement& elem, g
c = body;
break;
}
case Util::hash("Rect"):
c = GuiRect::fromSerialized(elem, textures, bounds);
case Util::hash("Rect"):c = GuiRect::fromSerialized(elem, textures, bounds);
break;
case Util::hash("Button"):
c = GuiImageButton::fromSerialized(elem, textures, bounds);
case Util::hash("Button"):c = GuiImageButton::fromSerialized(elem, textures, bounds);
break;
case Util::hash("Text"):
c = GuiText::fromSerialized(elem, textures, bounds);
case Util::hash("Text"):c = GuiText::fromSerialized(elem, textures, bounds);
break;
case Util::hash("Model"):
c = GuiModel::fromSerialized(elem, textures, models, bounds);
case Util::hash("Model"):c = GuiModel::fromSerialized(elem, textures, models, bounds);
break;
}

View File

@ -13,18 +13,27 @@ class GuiContainer;
class GuiBuilder {
public:
struct ComponentCallbacks { GuiComponent::callback left {}, right {}, hover {}; };
struct ComponentCallbacks {
GuiComponent::callback left{}, right{}, hover{};
};
GuiBuilder(TextureAtlas& textures, ModelStore& models, std::shared_ptr<GuiContainer> root);
void setGuiRoot(std::shared_ptr<LuaGuiElement> menu);
void update();
void build(glm::ivec2 winBounds = {});
void clear(bool deleteRoot = true);
~GuiBuilder();
protected:
void create(LuaGuiElement& element, std::shared_ptr<GuiComponent> parent, glm::ivec2 bounds);
virtual std::shared_ptr<GuiComponent> createComponent(LuaGuiElement& elem, glm::ivec2 bounds);
static void clearCallbacks(std::shared_ptr<GuiComponent> component);
void elementUpdated();

View File

@ -15,10 +15,13 @@ class Window;
class GuiComponent : public Drawable {
public:
enum class CallbackType { PRIMARY, SECONDARY, HOVER };
enum class CallbackType {
PRIMARY, SECONDARY, HOVER
};
typedef std::function<void(bool, glm::ivec2)> callback;
GuiComponent() = default;
explicit GuiComponent(const std::string& key);
virtual void update(double delta) override;
@ -26,18 +29,27 @@ public:
const std::string& getKey();
virtual glm::ivec2 getPos();
virtual void setPos(glm::ivec2 pos);
virtual glm::vec2 getScale();
virtual void setScale(glm::vec2 scale);
virtual glm::vec4 getPadding();
virtual void setPadding(glm::vec4 padding);
void setOverflows(bool overflows);
void setVisible(bool visible) override;
virtual void setCallback(CallbackType type, const callback& cb);
void handleMouseInput(Window& window);
template<class T> std::shared_ptr<T> get(const std::string &key) {
template<class T>
std::shared_ptr<T> get(const std::string& key) {
for (auto& it : children) {
if (it.get()->key == key) {
return std::static_pointer_cast<T>(it);
@ -47,16 +59,20 @@ public:
};
std::shared_ptr<GuiComponent> insert(unsigned int index, std::shared_ptr<GuiComponent> component);
std::shared_ptr<GuiComponent> add(std::shared_ptr<GuiComponent> component);
std::list<std::shared_ptr<GuiComponent>> getChildren();
void remove(const std::string& key);
void empty();
void draw(Renderer& renderer) override;
protected:
bool mouseActivity(glm::ivec2 pos);
bool clickEvent(bool left, bool state, glm::ivec2 pos);
std::string key = "";

View File

@ -73,18 +73,23 @@ namespace SerialGui {
}
}
template <typename T> static T calcNumbers(const T in, glm::ivec2 multiple = {}) {};
template<typename T>
static T calcNumbers(const T in, glm::ivec2 multiple = {}) {};
template <typename T> static T get(const LuaGuiElement& elem, const std::string& req, glm::ivec2 multiple = {}) {
template<typename T>
static T get(const LuaGuiElement& elem, const std::string& req, glm::ivec2 multiple = {}) {
if (!elem.has<T>(req)) return T{};
return calcNumbers<T>(elem.get<T>(req), multiple);
}
template <> glm::vec2 calcNumbers<glm::vec2>(const glm::vec2 in, glm::ivec2 multiple) {
template<>
glm::vec2 calcNumbers<glm::vec2>(const glm::vec2 in, glm::ivec2 multiple) {
return { convertNum(in.x, multiple.x), convertNum(in.y, multiple.y) };
}
template <> glm::vec4 calcNumbers<glm::vec4>(const glm::vec4 in, glm::ivec2 multiple) {
return {convertNum(in.x, multiple.x), convertNum(in.y, multiple.y), convertNum(in.z, multiple.x), convertNum(in.w, multiple.y)};
template<>
glm::vec4 calcNumbers<glm::vec4>(const glm::vec4 in, glm::ivec2 multiple) {
return { convertNum(in.x, multiple.x), convertNum(in.y, multiple.y), convertNum(in.z, multiple.x),
convertNum(in.w, multiple.y) };
}
};

View File

@ -9,6 +9,7 @@
class GuiContainer : public GuiComponent {
public:
GuiContainer() = default;
explicit GuiContainer(const std::string& key);
void draw(Renderer& renderer) override;

View File

@ -70,7 +70,8 @@ void GuiGraph::buildHistogramMesh() {
float xOffset = 0;
for (float num : history) {
float distFromPointer = (xOffset <= insertionPoint) ? insertionPoint - xOffset : insertionPoint + length - xOffset;
float distFromPointer = (xOffset <= insertionPoint) ? insertionPoint - xOffset : insertionPoint + length -
xOffset;
float age = std::round((90 - (distFromPointer / length) * 90)) / 100.0f;
float h = num / maxVal;
@ -78,9 +79,12 @@ void GuiGraph::buildHistogramMesh() {
auto columnVerts = std::vector<EntityVertex>{
{{ xOffset, -h, 0 }, { uv.x + age * uv.z, uv.y + sec * uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{xOffset + 1,-h, 0}, {uv.x + (age+0.01f) * uv.z, uv.y + sec * uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{xOffset + 1, 0, 0}, {uv.x + (age+0.01f) * uv.z, uv.y + (sec+0.10f) * uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{xOffset, 0, 0}, {uv.x + age * uv.z, uv.y + (sec+0.10f) * uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{ xOffset + 1, -h, 0 }, { uv.x + (age + 0.01f) * uv.z, uv.y + sec * uv.w, 0, 1 }, { 1, 1, 1 }, true, {},
{}, {}},
{{ xOffset + 1, 0, 0 }, { uv.x + (age + 0.01f) * uv.z, uv.y + (sec + 0.10f) * uv.w, 0, 1 }, { 1, 1, 1 },
true, {}, {}, {}},
{{ xOffset, 0, 0 }, { uv.x + age * uv.z, uv.y + (sec + 0.10f) * uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {},
{}},
};
vertices.insert(vertices.end(), columnVerts.begin(), columnVerts.end());

View File

@ -11,12 +11,17 @@ class AtlasRef;
class GuiGraph : public GuiComponent {
public:
GuiGraph() = default;
GuiGraph(const std::string& key);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, unsigned int length, float maxValue, bool editInPlace);
void
create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, unsigned int length, float maxValue,
bool editInPlace);
void setMax(float max);
void pushValue(float value);
private:
void buildHistogramMesh();

View File

@ -7,11 +7,13 @@
#include "GuiContainer.h"
class ItemDef;
class Font;
class GuiInventoryItem : public GuiContainer {
public:
GuiInventoryItem() = default;
GuiInventoryItem(const std::string& key);
void create(glm::vec2 scale, unsigned short itemCount, ItemDef& def, Font font);

View File

@ -13,7 +13,8 @@
GuiModel::GuiModel(const std::string& key) : GuiComponent(key) {}
std::shared_ptr<GuiModel> GuiModel::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds) {
std::shared_ptr<GuiModel>
GuiModel::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds) {
glm::vec2 pos = SerialGui::get<glm::vec2>(elem, "position", bounds);
glm::vec2 scale = SerialGui::get<glm::vec2>(elem, "scale");
glm::vec2 anim_range = SerialGui::get<glm::vec2>(elem, "anim_range");

View File

@ -9,27 +9,36 @@
#include "GuiContainer.h"
class LocalSubgame;
class ModelStore;
class TextureAtlas;
class LuaGuiElement;
class GuiModel : public GuiComponent {
public:
GuiModel() = default;
GuiModel(const std::string& key);
static std::shared_ptr<GuiModel> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds);
static std::shared_ptr<GuiModel>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds);
void create(glm::vec2 scale, std::shared_ptr<Model> model);
void update(double delta) override;
void animate(glm::vec2 range);
void setRotationX(float x);
void setRotationY(float x);
void setRotationZ(float x);
void draw(Renderer& renderer) override;
protected:
float depth = 300;
};

View File

@ -7,20 +7,28 @@
#include "client/gui/GuiComponent.h"
class AtlasRef;
class LocalSubgame;
class TextureAtlas;
class LuaGuiElement;
class GuiRect : public GuiComponent {
public:
GuiRect() = default;
GuiRect(const std::string& key);
static std::shared_ptr<GuiRect> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
static std::shared_ptr<GuiRect>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
void create(glm::vec2 scale, glm::vec4 padding, glm::vec4 color);
void create(glm::vec2 scale, glm::vec4 padding, glm::vec4 tl, glm::vec4 tr, glm::vec4 bl, glm::vec4 br);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, glm::vec4 tint);
protected:

View File

@ -80,10 +80,14 @@ void GuiText::setText(std::string text) {
if (lineWidth > maxLineWidth) maxLineWidth = lineWidth;
if (bgcolor.w != 0) {
textVertices.emplace_back(glm::vec3 {-1, yOffset - 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {-1, yOffset + h + 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {lineWidth + 1, yOffset + h + 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {lineWidth + 1, yOffset - 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3{ -1, yOffset - 1, 0 }, bgcolor, glm::vec3(1), 0.f, glm::vec3{},
glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ -1, yOffset + h + 1, 0 }, bgcolor, glm::vec3(1), 0.f,
glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ lineWidth + 1, yOffset + h + 1, 0 }, bgcolor, glm::vec3(1),
0.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ lineWidth + 1, yOffset - 1, 0 }, bgcolor, glm::vec3(1), 0.f,
glm::vec3{}, glm::ivec4{}, glm::vec4{});
textIndices.emplace_back(indOffset);
textIndices.emplace_back(indOffset + 1);
@ -145,10 +149,14 @@ void GuiText::setText(std::string text) {
yOffset -= 1;
}
textVertices.emplace_back(glm::vec3 {xOffset, yOffset, 0}, glm::vec4 {charUVs.x, charUVs.y, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {xOffset, yOffset + h, 0}, glm::vec4 {charUVs.x, charUVs.w, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {xOffset + charWidth, yOffset + h, 0}, glm::vec4 {charUVs.z, charUVs.w, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {xOffset + charWidth, yOffset, 0}, glm::vec4 {charUVs.z, charUVs.y, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3{ xOffset, yOffset, 0 }, glm::vec4{ charUVs.x, charUVs.y, 0, color.w },
c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ xOffset, yOffset + h, 0 },
glm::vec4{ charUVs.x, charUVs.w, 0, color.w }, c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ xOffset + charWidth, yOffset + h, 0 },
glm::vec4{ charUVs.z, charUVs.w, 0, color.w }, c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ xOffset + charWidth, yOffset, 0 },
glm::vec4{ charUVs.z, charUVs.y, 0, color.w }, c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textIndices.emplace_back(indOffset);
textIndices.emplace_back(indOffset + 1);

View File

@ -9,21 +9,26 @@
#include "client/graph/Font.h"
class TextureAtlas;
class LuaGuiElement;
class GuiText : public GuiComponent {
public:
GuiText() = default;
explicit GuiText(const std::string& key);
static std::shared_ptr<GuiText> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
static std::shared_ptr<GuiText>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
void create(glm::vec2 scale, glm::vec4 padding, glm::vec4 bgcolor, glm::vec4 color, Font font);
unsigned int getWidth();
void setText(std::string text);
std::string getText();
private:
Font font;
glm::vec4 bgcolor{};

View File

@ -11,7 +11,8 @@
GuiImageButton::GuiImageButton(const std::string& key) : GuiRect(key) {}
std::shared_ptr<GuiImageButton> GuiImageButton::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds) {
std::shared_ptr<GuiImageButton>
GuiImageButton::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds) {
glm::vec2 pos = SerialGui::get<glm::vec2>(elem, "position", bounds);
glm::vec2 offset = SerialGui::get<glm::vec2>(elem, "position_anchor");
glm::vec2 size = SerialGui::get<glm::vec2>(elem, "size", bounds);
@ -45,7 +46,8 @@ std::shared_ptr<GuiImageButton> GuiImageButton::fromSerialized(const LuaGuiEleme
// Texture Constructor
// Creates a GuiImageButton object with two textures
// defined by the 'texture' & 'hoverTexture' reference.
void GuiImageButton::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, std::shared_ptr<AtlasRef> hoverTexture) {
void GuiImageButton::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture,
std::shared_ptr<AtlasRef> hoverTexture) {
this->hoverTexture = hoverTexture;
GuiRect::create(scale, padding, texture);

View File

@ -9,14 +9,19 @@
class GuiImageButton : public GuiRect {
public:
GuiImageButton() = default;
GuiImageButton(const std::string& key);
static std::shared_ptr<GuiImageButton> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
static std::shared_ptr<GuiImageButton>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, std::shared_ptr<AtlasRef> hoverTexture);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture,
std::shared_ptr<AtlasRef> hoverTexture);
void setCallback(CallbackType type, const callback& cb) override;
private:
void rebuild(bool hover);
std::shared_ptr<AtlasRef> hoverTexture = nullptr;
};

View File

@ -137,7 +137,8 @@ void GuiInventoryList::drawContents() {
auto item = std::make_shared<GuiInventoryItem>("item_" + std::to_string(i) + "_" + std::to_string(j));
item->create(scale, stack.count, defs->getDefs().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)});
item->setPos({ padding.x + j * (16 * scale.x + innerPadding.x / scale.x),
padding.y + i * (16 * scale.y + innerPadding.y / scale.y) });
}
}

View File

@ -9,14 +9,19 @@
#include "util/CovariantPtr.h"
class LocalSubgame;
class LuaGuiElement;
class LocalInventoryRefs;
class LocalInventoryList;
class GuiInventoryList : public GuiContainer {
public:
GuiInventoryList() = default;
GuiInventoryList(const std::string& key);
~GuiInventoryList() override;
static std::shared_ptr<GuiInventoryList> fromSerialized(const LuaGuiElement& elem,
@ -29,8 +34,11 @@ public:
void setCallback(CallbackType type, const callback& cb) override;
void hoverEvent(bool hovered, glm::ivec2 pos);
void interactEvent(glm::ivec2 pos, bool primary);
void drawContents();
private:
std::shared_ptr<GuiRect> hoverRect = std::make_shared<GuiRect>("hover_rect");
std::shared_ptr<std::function<void()>> myCallback = nullptr;

View File

@ -22,12 +22,14 @@ void GuiLabelledGraph::create(glm::vec2 scale, glm::vec4 padding, const std::str
this->graphTextureRef = std::move(graphTextureRef);
auto background = std::make_shared<GuiRect>("background");
background->create(scale, {}, {0.1, 0.1, 0.1, 0.2}, {0.1, 0.1, 0.1, 0.2}, {0.1, 0.1, 0.1, 0.7}, {0.1, 0.1, 0.1, 0.7});
background->create(scale, {}, { 0.1, 0.1, 0.1, 0.2 }, { 0.1, 0.1, 0.1, 0.2 }, { 0.1, 0.1, 0.1, 0.7 },
{ 0.1, 0.1, 0.1, 0.7 });
add(background);
background->setPos({ 0, 0 });
auto graph = std::make_shared<GuiGraph>("graph");
graph->create({scale.x / (graphLength + GRAPH_PAD_X), scale.y * 0.4}, {}, this->graphTextureRef, graphLength, graphScale, true);
graph->create({ scale.x / (graphLength + GRAPH_PAD_X), scale.y * 0.4 }, {}, this->graphTextureRef, graphLength,
graphScale, true);
add(graph);
graph->setPos({ GRAPH_PAD_X, GRAPH_PAD_Y });

View File

@ -14,6 +14,7 @@
class GuiLabelledGraph : public GuiContainer {
public:
GuiLabelledGraph() = default;
GuiLabelledGraph(const std::string& key);
void create(glm::vec2 scale, glm::vec4 padding, const std::string& title,
@ -21,6 +22,7 @@ public:
std::shared_ptr<AtlasRef> graphTextureRef, Font font);
void pushValue(float value);
private:
std::string title;

View File

@ -189,7 +189,8 @@ sol::protected_function_result MenuSandbox::errorCallback(sol::protected_functio
std::string fileName = errString.substr(0, lineNumStart);
int lineNum = std::stoi(errString.substr(lineNumStart + 1, lineNumEnd - lineNumStart - 1));
for (const LuaMod::File& file : mod.files) if (file.path == fileName)
for (const LuaMod::File& file : mod.files)
if (file.path == fileName)
throw std::runtime_error(ErrorFormatter::formatError(fileName, lineNum, errString, file.file));
throw std::out_of_range("Error thrown outside of handled files. [2]");

View File

@ -10,28 +10,37 @@
#include "client/gui/GuiBuilder.h"
class Client;
class Subgame;
class AtlasRef;
class SubgameDef;
class GuiContainer;
class MenuSandbox : LuaParser {
public:
MenuSandbox(glm::ivec2& window, Client& client, std::shared_ptr<GuiContainer> container);
void load(const SubgameDef& subgame);
void update(double delta) override;
void windowResized();
using LuaParser::update;
private:
void reset();
void loadApi();
void loadAndRunMod(const std::string& modPath);
void showError(const std::string& what, const std::string& subgame);
sol::protected_function_result runFileSandboxed(const std::string& file);
virtual sol::protected_function_result errorCallback(sol::protected_function_result r) const override;
LuaMod mod{};

View File

@ -54,15 +54,12 @@ void ConnectScene::update() {
client.game->textures.update();
switch (connectState) {
default:
throw std::runtime_error("Invalid connection state.");
default:throw std::runtime_error("Invalid connection state.");
case State::DONE:
case State::FAILED_CONNECT:
break;
case State::FAILED_CONNECT:break;
case State::CONNECTING:
handleConnecting();
case State::CONNECTING:handleConnecting();
break;
case State::PROPERTIES: {
@ -105,7 +102,8 @@ void ConnectScene::update() {
}
else if (p.type == Packet::Type::BIOME_IDENTIFIER_LIST) {
auto statusText = components.get<GuiText>("statusText");
statusText->setText(statusText->getText() + "Received biome index-identifier table.\nDownloading mods...\n");
statusText->setText(
statusText->getText() + "Received biome index-identifier table.\nDownloading mods...\n");
client.game->getBiomes().setIdentifiers(p.d.read<std::vector<std::string>>());
@ -133,7 +131,8 @@ void ConnectScene::update() {
else if (p.type == Packet::Type::MOD_ORDER) {
client.game->getParser().getHandler().setModsOrder(p.d.read<std::vector<std::string>>());
statusText->setText(statusText->getText() + "Done downloading mods.\nReceived the mods order.\nDownloading media...\n");
statusText->setText(
statusText->getText() + "Done downloading mods.\nReceived the mods order.\nDownloading media...\n");
connectState = State::MEDIA;
Packet resp(Packet::Type::MEDIA);
@ -201,20 +200,16 @@ void ConnectScene::handleConnecting() {
auto statusText = components.get<GuiText>("statusText");
switch (connection.getConnectionStatus()) {
default:
throw std::runtime_error("Uncaught connection error.");
default:throw std::runtime_error("Uncaught connection error.");
case ServerConnection::State::ENET_ERROR:
throw std::runtime_error("Enet Initialization error.");
case ServerConnection::State::ENET_ERROR:throw std::runtime_error("Enet Initialization error.");
break;
case ServerConnection::State::FAILED_CONNECT:
connectState = State::FAILED_CONNECT;
case ServerConnection::State::FAILED_CONNECT:connectState = State::FAILED_CONNECT;
statusText->setText(statusText->getText() + "\nFailed to connect :(\n");
break;
case ServerConnection::State::ATTEMPTING_CONNECT:
connection.processConnecting();
case ServerConnection::State::ATTEMPTING_CONNECT:connection.processConnecting();
dotsTime += client.getDelta();
if (dotsTime > 1) {
@ -224,8 +219,7 @@ void ConnectScene::handleConnecting() {
break;
case ServerConnection::State::CONNECTED:
connectState = State::PROPERTIES;
case ServerConnection::State::CONNECTED:connectState = State::PROPERTIES;
statusText->setText(statusText->getText() + " Connected!~\n");
resp.sendTo(connection.getPeer(), Packet::Channel::CONNECT);

View File

@ -9,6 +9,7 @@
#include "client/gui/basic/GuiContainer.h"
class ServerConnection;
class Address;
class ConnectScene : public Scene {
@ -26,7 +27,9 @@ public:
ConnectScene(Client& state, Address addr);
void update() override;
void draw() override;
void cleanup() override;
void handleConnecting();

View File

@ -13,6 +13,7 @@
#include "client/conn/ClientNetworkInterpreter.h"
class LocalSubgame;
class Drawable;
class GameScene : public Scene {
@ -20,6 +21,7 @@ public:
GameScene(Client& client);
void update() override;
void draw() override;
void cleanup() override;

View File

@ -13,7 +13,9 @@ public:
LuaErrorScene(Client& client, const std::string& err);
void update() override;
void draw() override;
void cleanup() override;
private:

View File

@ -141,7 +141,10 @@ void MainMenuScene::findSubgames() {
while (subgamesDir.has_next) {
cf_file_t subgameFolder;
cf_read_file(&subgamesDir, &subgameFolder);
if (!subgameFolder.is_dir || strncmp(subgameFolder.name, ".", 1) == 0) { cf_dir_next(&subgamesDir); continue; }
if (!subgameFolder.is_dir || strncmp(subgameFolder.name, ".", 1) == 0) {
cf_dir_next(&subgamesDir);
continue;
}
try {
bool hasConf = false, hasIcon = false, hasMods = false;
@ -160,20 +163,29 @@ void MainMenuScene::findSubgames() {
}
cf_dir_close(&subgame);
if (!hasConf) throw std::runtime_error(std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a conf.json.");
if (!hasMods) throw std::runtime_error(std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a 'mods' directory.");
if (!hasConf)
throw std::runtime_error(
std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a conf.json.");
if (!hasMods)
throw std::runtime_error(
std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a 'mods' directory.");
nlohmann::json j{};
try {
std::ifstream(std::string(subgameFolder.path) + "/conf.json") >> j;
} catch (...) { throw std::runtime_error(std::string(subgameFolder.name) + "/conf.json is not a valid JSON object."); }
}
catch (...) {
throw std::runtime_error(std::string(subgameFolder.name) + "/conf.json is not a valid JSON object.");
}
if (!j.is_object())
throw std::runtime_error(std::string(subgameFolder.name) + "/conf.json is not a valid JSON object.");
if (!j["name"].is_string() || j["name"] == "")
throw std::runtime_error("The 'name' property in " + std::string(subgameFolder.name) + "/conf.json is missing or invalid.");
throw std::runtime_error(
"The 'name' property in " + std::string(subgameFolder.name) + "/conf.json is missing or invalid.");
if (!j["version"].is_string() || j["version"] == "")
throw std::runtime_error("The 'version' property in " + std::string(subgameFolder.name) + "/conf.json is missing or invalid.");
throw std::runtime_error("The 'version' property in " + std::string(subgameFolder.name) +
"/conf.json is missing or invalid.");
std::string name = j["name"];
std::string description = (j["description"].is_string() ? j["description"] : "");
@ -192,7 +204,8 @@ void MainMenuScene::findSubgames() {
}
cf_dir_close(&subgamesDir);
std::sort(subgames.begin(), subgames.end(), [](SubgameDef& a, SubgameDef& b) { return a.config.name < b.config.name; });
std::sort(subgames.begin(), subgames.end(),
[](SubgameDef& a, SubgameDef& b) { return a.config.name < b.config.name; });
}
void MainMenuScene::positionElements() {

View File

@ -16,11 +16,14 @@ public:
explicit MainMenuScene(Client& client);
void update() override;
void draw() override;
void cleanup() override;
private:
void positionElements();
void findSubgames();
static constexpr float GS = 3;

View File

@ -14,7 +14,9 @@ public:
explicit Scene(Client& client) : client(client) {}
virtual void update() = 0;
virtual void draw() = 0;
virtual void cleanup() = 0;
virtual ~Scene() = default;

View File

@ -11,9 +11,11 @@
class SceneManager {
public:
void setScene(std::unique_ptr<Scene> scene);
const Scene& getScene();
void update();
void cleanupScene();
~SceneManager();

View File

@ -87,7 +87,8 @@ void MeshGenStream::Thread::exec() {
auto& u = jobs[i];
if (!u.busy) continue;
ChunkMeshGenerator m(u.meshDetails, game.getDefs(), game.getBiomes(), u.thisChunk, u.adjacentChunks, offsetSamplers);
ChunkMeshGenerator m(u.meshDetails, game.getDefs(), game.getBiomes(), u.thisChunk, u.adjacentChunks,
offsetSamplers);
empty = false;
u.busy = false;
}

View File

@ -15,6 +15,7 @@
#include "world/gen/NoiseSample.h"
class Chunk;
class LocalSubgame;
class LocalDimension;
@ -25,6 +26,7 @@ public:
static const int THREAD_QUEUE_SIZE = 16;
explicit MeshGenStream(SubgamePtr game, LocalDimension& dimension);
~MeshGenStream();
void queue(glm::ivec3 pos, bool priority = false);
@ -44,6 +46,7 @@ public:
struct Thread {
explicit Thread(LocalSubgame& defs, std::array<NoiseSample, 3>& offsetSampler);
void exec();
LocalSubgame& game;

View File

@ -15,7 +15,9 @@
#include "util/CovariantPtr.h"
class Chunk;
class LocalSubgame;
class PacketView;
class WorldInterpolationStream {
@ -27,6 +29,7 @@ public:
// Queue parsing of packet `p`.
void queuePacket(std::unique_ptr<PacketView> p);
// Queue interpolation of Mapblock at `pos`.
// bool queuePosition(glm::vec3 pos);
// Returns a vector of BlockChunks that have finished processing,
@ -34,6 +37,7 @@ public:
std::unique_ptr<std::vector<std::shared_ptr<Chunk>>> update();
~WorldInterpolationStream();
private:
// enum class JobType {
// EMPTY,
@ -54,6 +58,7 @@ private:
struct Thread {
explicit Thread(LocalSubgame& game, LocalWorld& world, unsigned int seed);
void run();
bool kill = false;

View File

@ -17,7 +17,9 @@
#include "game/atlas/LocalDefinitionAtlas.h"
class Client;
class LocalWorld;
class LocalPlayer;
class LocalSubgame : public Subgame {
@ -25,10 +27,13 @@ public:
explicit LocalSubgame(const std::string& baseAssets);
void init(WorldPtr world, PlayerPtr player, Client& client);
void update(double delta);
LocalDefinitionAtlas& getDefs() override { return *defs; };
LocalBiomeAtlas& getBiomes() override { return *biomes; };
LocalLuaParser& getParser() override { return *lua; };
ModelStore models;

View File

@ -14,20 +14,25 @@
#include "game/atlas/ServerDefinitionAtlas.h"
class ServerWorld;
class ServerClients;
class ServerSubgame : public Subgame {
public:
ServerSubgame(const std::string& subgame, unsigned int seed);
~ServerSubgame();
void init(WorldPtr world);
void update(double delta);
std::string subgamePath;
ServerDefinitionAtlas& getDefs() override { return *defs; };
ServerBiomeAtlas& getBiomes() override { return *biomes; };
ServerLuaParser& getParser() override { return *lua; };
AssetStorage assets;

View File

@ -5,13 +5,18 @@
#pragma once
class World;
class LuaParser;
class BiomeAtlas;
class DefinitionAtlas;
class Subgame {
public:
virtual DefinitionAtlas& getDefs() = 0;
virtual BiomeAtlas& getBiomes() = 0;
virtual LuaParser& getParser() = 0;
};

View File

@ -16,7 +16,8 @@ BiomeDef& BiomeAtlas::biomeFromId(unsigned int index) {
}
BiomeDef& BiomeAtlas::biomeFromStr(const std::string& identifier) {
if (defTable.count(identifier) <= 0) throw std::runtime_error("Undefined biome identifier " + identifier + " requested.");
if (defTable.count(identifier) <= 0)
throw std::runtime_error("Undefined biome identifier " + identifier + " requested.");
return *defs.at(static_cast<unsigned long>(defTable.at(identifier)));
}

View File

@ -13,10 +13,13 @@ class BiomeDef;
class BiomeAtlas {
public:
BiomeAtlas() = default;
virtual void registerBiome(BiomeDef* def) = 0;
BiomeDef& biomeFromId(unsigned int index);
BiomeDef& biomeFromStr(const std::string& identifier);
std::vector<BiomeDef*> biomesFromTag(const std::string& tag);
unsigned int size();

View File

@ -15,7 +15,8 @@ ItemDef& DefinitionAtlas::fromId(unsigned int id) const {
ItemDef& DefinitionAtlas::fromStr(const std::string& identifier) const {
if (identifier == "") return *defs.at(AIR);
if (defTable.count(identifier) <= 0) throw std::runtime_error("Undefined definition identifier " + identifier + " requested.");
if (defTable.count(identifier) <= 0)
throw std::runtime_error("Undefined definition identifier " + identifier + " requested.");
return *defs.at(static_cast<unsigned long>(defTable.at(identifier)));
}

View File

@ -9,7 +9,9 @@
#include <unordered_map>
class ItemDef;
class BlockDef;
class CraftItemDef;
class DefinitionAtlas {
@ -17,12 +19,16 @@ public:
virtual void registerDef(ItemDef* def) = 0;
ItemDef& fromId(unsigned int index) const;
ItemDef& fromStr(const std::string& identifier) const;
//Specializations that throw an error upon an invalid usertype.
BlockDef& blockFromId(unsigned int index) const;
BlockDef& blockFromStr(const std::string& identifier) const;
CraftItemDef& craftItemFromId(unsigned int index) const;
CraftItemDef& craftItemFromStr(const std::string& identifier) const;
unsigned int size();
@ -31,6 +37,7 @@ public:
const static unsigned int AIR = 1;
~DefinitionAtlas();
protected:
std::vector<ItemDef*> defs;
std::unordered_map<std::string, unsigned int> defTable;

View File

@ -25,7 +25,8 @@ void LocalBiomeAtlas::setIdentifiers(const std::vector<std::string>& identifiers
}
void LocalBiomeAtlas::registerBiome(BiomeDef* def) {
if (!defTable.count(def->identifier)) throw std::runtime_error("Client/Server biome desync: " + def->identifier + ".");
if (!defTable.count(def->identifier))
throw std::runtime_error("Client/Server biome desync: " + def->identifier + ".");
def->index = defTable[def->identifier];
defs[def->index] = def;
}

View File

@ -9,6 +9,8 @@
class LocalBiomeAtlas : public BiomeAtlas {
public:
LocalBiomeAtlas();
void registerBiome(BiomeDef* def) override;
void setIdentifiers(const std::vector<std::string>& identifiers);
};

View File

@ -44,7 +44,8 @@ void LocalDefinitionAtlas::setIdentifiers(const std::vector<std::string>& identi
}
void LocalDefinitionAtlas::registerDef(ItemDef* def) {
if (!defTable.count(def->identifier)) throw std::runtime_error("Client/Server definition desync: " + def->identifier + ".");
if (!defTable.count(def->identifier))
throw std::runtime_error("Client/Server definition desync: " + def->identifier + ".");
def->index = defTable[def->identifier];
defs[def->index] = def;
}

View File

@ -11,6 +11,7 @@ class TextureAtlas;
class LocalDefinitionAtlas : public DefinitionAtlas {
public:
LocalDefinitionAtlas(TextureAtlas& atlas);
void registerDef(ItemDef* def) override;
void setIdentifiers(const std::vector<std::string>& identifiers);

View File

@ -9,6 +9,7 @@
class ServerBiomeAtlas : public BiomeAtlas {
public:
ServerBiomeAtlas(unsigned int seed);
void registerBiome(BiomeDef* def) override;
unsigned int seed;

View File

@ -9,5 +9,6 @@
class ServerDefinitionAtlas : public DefinitionAtlas {
public:
ServerDefinitionAtlas();
void registerDef(ItemDef* def) override;
};

View File

@ -45,7 +45,8 @@ std::vector<std::shared_ptr<AtlasRef>> TextureAtlas::loadDirectory(const std::st
cf_read_file(&dir, &file);
if (!file.is_dir && strcmp(file.ext, ".png") == 0) {
refs.push_back(loadImage(file.path, std::string(file.name).substr(0, std::string(file.name).size() - 4), base));
refs.push_back(
loadImage(file.path, std::string(file.name).substr(0, std::string(file.name).size() - 4), base));
}
if (recursive && file.is_dir && strncmp(file.name, ".", 1) != 0) {
@ -93,7 +94,8 @@ glm::vec4 TextureAtlas::sampleTexturePixel(const std::shared_ptr<AtlasRef> &atla
};
}
std::shared_ptr<AtlasRef> TextureAtlas::addImage(unsigned char *data, const std::string& name, bool base, int texWidth, int texHeight) {
std::shared_ptr<AtlasRef>
TextureAtlas::addImage(unsigned char* data, const std::string& name, bool base, int texWidth, int texHeight) {
std::shared_ptr<AtlasRef> ref;
if (textures.count(name) != 0) ref = textures[name];
@ -139,9 +141,12 @@ std::shared_ptr<AtlasRef> TextureAtlas::generateCrackImage(const std::string& na
for (int i = 0; i < base.width * base.height; i++) {
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);
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);
}
auto ref = addImage(base.data, name + "_crack_" + std::to_string(crackLevel), false, base.width, base.height);
@ -185,7 +190,8 @@ std::shared_ptr<AtlasRef> TextureAtlas::generateTexture(std::string req) {
if (paramName == "crop") {
if (params.size() != 5) throw std::runtime_error("crop() requires 5 parameters.");
glm::ivec4 loc = {atof(params[0].data()), atof(params[1].data()), atof(params[2].data()), atof(params[3].data())};
glm::ivec4 loc = { atof(params[0].data()), atof(params[1].data()), atof(params[2].data()),
atof(params[3].data()) };
std::shared_ptr<AtlasRef> src = operator[](params[4]);
auto data = getBytesAtPos({ src->pos.x + loc.x, src->pos.y + loc.y }, { loc.z, loc.w }).data;

View File

@ -23,17 +23,23 @@ public:
};
TextureAtlas() = default;
explicit TextureAtlas(unsigned int width, unsigned int height = 0);
void update();
std::vector<std::shared_ptr<AtlasRef>> loadDirectory(const std::string& path, bool base = true, bool recursive = true);
std::vector<std::shared_ptr<AtlasRef>>
loadDirectory(const std::string& path, bool base = true, bool recursive = true);
std::shared_ptr<AtlasRef> loadImage(const std::string& path, const std::string& name, bool base = false);
glm::vec4 sampleTexturePixel(const std::shared_ptr<AtlasRef>& atlasRef, glm::vec2 pixel);
std::shared_ptr<AtlasRef> operator[](const std::string& name);
std::shared_ptr<AtlasRef> addImage(unsigned char *data, const std::string& name, bool base, int texWidth, int texHeight);
std::shared_ptr<AtlasRef>
addImage(unsigned char* data, const std::string& name, bool base, int texWidth, int texHeight);
std::shared_ptr<AtlasRef> generateCrackImage(const std::string& name, unsigned short crackLevel);
glm::ivec2 pixelSize{};
@ -48,10 +54,13 @@ private:
std::shared_ptr<AtlasRef> generateTexture(std::string req);
RawTexData getBytesOfTex(const std::string& name);
RawTexData getBytesAtPos(glm::ivec2 pos, glm::ivec2 dims);
glm::vec2 findImageSpace(int w, int h);
void createMissingImage();
void updateAtlas(int tileX, int tileY, int texWidth, int texHeight, unsigned char* data);
void deleteImage(std::shared_ptr<AtlasRef> ref);

View File

@ -19,6 +19,7 @@ public:
BlockDef() : ItemDef{ "", "", 0, 0, ItemDef::Type::BLOCK } {};
void createModel();
bool hasInteraction();
BlockModel model;

View File

@ -12,7 +12,8 @@ CraftItemDef::CraftItemDef(const std::string &identifier, const std::string &nam
CraftItemDef(identifier, 0, name, maxStackSize, textures, textureRefs) {}
CraftItemDef::CraftItemDef(const std::string& identifier, unsigned int index, const std::string& name,
unsigned short maxStackSize, const std::vector<std::string>& textures, const std::vector<std::shared_ptr<AtlasRef>>& textureRefs) :
unsigned short maxStackSize, const std::vector<std::string>& textures,
const std::vector<std::shared_ptr<AtlasRef>>& textureRefs) :
ItemDef{ identifier, name, index, maxStackSize, ItemDef::Type::CRAFTITEM },
textures(textures),
@ -30,7 +31,8 @@ void CraftItemDef::createModel(TextureAtlas& atlas) {
for (unsigned int i = 0; i <= 1; i++) {
float xx = xo * (i == 1 ? -1 : 1);
std::vector<EntityVertex> myVerts = {
{{xx, -0.5, -0.5}, {ref->uv.x, ref->uv.w, 0, 1}, {1, 1, 1}, true, {(i == 1 ? -1 : 1), 0, 0}, {}, {}},
{{ xx, -0.5, -0.5 }, { ref->uv.x, ref->uv.w, 0, 1 }, { 1, 1, 1 }, true, { (i == 1 ? -1 : 1), 0, 0 }, {},
{}},
{{ xx, 0.5, -0.5 }, { ref->uv.x, ref->uv.y, 0, 1 }, { 1, 1, 1 }, true, { (i == 1 ? -1 : 1), 0, 0 }, {}, {}},
{{ xx, 0.5, 0.5 }, { ref->uv.z, ref->uv.y, 0, 1 }, { 1, 1, 1 }, true, { (i == 1 ? -1 : 1), 0, 0 }, {}, {}},
{{ xx, -0.5, 0.5 }, { ref->uv.z, ref->uv.w, 0, 1 }, { 1, 1, 1 }, true, { (i == 1 ? -1 : 1), 0, 0 }, {}, {}}
@ -53,7 +55,8 @@ void CraftItemDef::createModel(TextureAtlas& atlas) {
{{ xo, 0.5 - off.y, -0.5 + off.x + 0.0625 }, col, { 1, 1, 1 }, false, { 0, 1, 0 }, {}, {}},
{{ xo, 0.5 - off.y, -0.5 + off.x }, col, { 1, 1, 1 }, false, { 0, 1, 0 }, {}, {}}};
vertices.insert(vertices.end(), myVerts.begin(), myVerts.end());
std::vector<unsigned int> myInds = {indOffset, indOffset+1, indOffset+2, indOffset+2, indOffset+3, indOffset};
std::vector<unsigned int> myInds = { indOffset, indOffset + 1, indOffset + 2, indOffset + 2, indOffset + 3,
indOffset };
indices.insert(indices.end(), myInds.begin(), myInds.end());
indOffset += 4;
}
@ -65,7 +68,8 @@ void CraftItemDef::createModel(TextureAtlas& atlas) {
{{ xo, 0.5 - off.y - 0.0625, -0.5 + off.x + 0.0625 }, col, { 1, 1, 1 }, false, { 0, -1, 0 }, {}, {}},
{{ xo, 0.5 - off.y - 0.0625, -0.5 + off.x }, col, { 1, 1, 1 }, false, { 0, -1, 0 }, {}, {}}};
vertices.insert(vertices.end(), myVerts.begin(), myVerts.end());
std::vector<unsigned int> myInds = {indOffset, indOffset+3, indOffset+2, indOffset+2, indOffset+1, indOffset};
std::vector<unsigned int> myInds = { indOffset, indOffset + 3, indOffset + 2, indOffset + 2, indOffset + 1,
indOffset };
indices.insert(indices.end(), myInds.begin(), myInds.end());
indOffset += 4;
}
@ -77,7 +81,8 @@ void CraftItemDef::createModel(TextureAtlas& atlas) {
{{ xo, 0.5 - off.y, -0.5 + off.x }, col, { 1, 1, 1 }, false, { 0, 0, 1 }, {}, {}},
{{ xo, 0.5 - off.y - 0.0625, -0.5 + off.x }, col, { 1, 1, 1 }, false, { 0, 0, 1 }, {}, {}}};
vertices.insert(vertices.end(), myVerts.begin(), myVerts.end());
std::vector<unsigned int> myInds = {indOffset, indOffset+1, indOffset+2, indOffset+2, indOffset+3, indOffset};
std::vector<unsigned int> myInds = { indOffset, indOffset + 1, indOffset + 2, indOffset + 2, indOffset + 3,
indOffset };
indices.insert(indices.end(), myInds.begin(), myInds.end());
indOffset += 4;
}
@ -89,7 +94,8 @@ void CraftItemDef::createModel(TextureAtlas& atlas) {
{{ xo, 0.5 - off.y, -0.5 + off.x + 0.0625 }, col, { 1, 1, 1 }, false, { 0, 0, -1 }, {}, {}},
{{ xo, 0.5 - off.y - 0.0625, -0.5 + off.x + 0.0625 }, col, { 1, 1, 1 }, false, { 0, 0, -1 }, {}, {}}};
vertices.insert(vertices.end(), myVerts.begin(), myVerts.end());
std::vector<unsigned int> myInds = {indOffset, indOffset+3, indOffset+2, indOffset+2, indOffset+1, indOffset};
std::vector<unsigned int> myInds = { indOffset, indOffset + 3, indOffset + 2, indOffset + 2, indOffset + 1,
indOffset };
indices.insert(indices.end(), myInds.begin(), myInds.end());
indOffset += 4;
}

View File

@ -9,16 +9,19 @@
#include "ItemDef.h"
class AtlasRef;
class TextureAtlas;
class CraftItemDef : public ItemDef {
public:
CraftItemDef() = default;
CraftItemDef(const std::string& identifier, const std::string& name, unsigned short maxStackSize,
const std::vector<std::string>& textures, const std::vector<std::shared_ptr<AtlasRef>>& textureRefs);
CraftItemDef(const std::string& identifier, unsigned int index, const std::string& name,
unsigned short maxStackSize, const std::vector<std::string>& textures, const std::vector<std::shared_ptr<AtlasRef>>& textureRefs);
unsigned short maxStackSize, const std::vector<std::string>& textures,
const std::vector<std::shared_ptr<AtlasRef>>& textureRefs);
void createModel(TextureAtlas& atlas);

View File

@ -3,6 +3,7 @@
//
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/normal.hpp>
#include "MeshPart.h"

View File

@ -11,7 +11,9 @@
class SelectionBox {
public:
SelectionBox() = default;
SelectionBox(glm::vec3 a, glm::vec3 b) : a(a), b(b) {};
SelectionBox& operator=(const SelectionBox& s) = default;
bool operator==(const SelectionBox& o) {
@ -32,12 +34,18 @@ public:
vec -= blockOffset; //Normalize Vector Position
if (std::abs(vec.y - b.y) < THRESH && vec.x > a.x && vec.x < b.x && vec.z > a.z && vec.z < b.z) return EVec::TOP;
if (std::abs(vec.y - a.y) < THRESH && vec.x > a.x && vec.x < b.x && vec.z > a.z && vec.z < b.z) return EVec::BOTTOM;
if (std::abs(vec.z - a.z) < THRESH && vec.x > a.x && vec.x < b.x && vec.y > a.y && vec.y < b.y) return EVec::FRONT;
if (std::abs(vec.z - b.z) < THRESH && vec.x > a.x && vec.x < b.x && vec.y > a.y && vec.y < b.y) return EVec::BACK;
if (std::abs(vec.x - b.x) < THRESH && vec.z > a.z && vec.z < b.z && vec.y > a.y && vec.y < b.y) return EVec::RIGHT;
if (std::abs(vec.x - a.x) < THRESH && vec.z > a.z && vec.z < b.z && vec.y > a.y && vec.y < b.y) return EVec::LEFT;
if (std::abs(vec.y - b.y) < THRESH && vec.x > a.x && vec.x < b.x && vec.z > a.z && vec.z < b.z)
return EVec::TOP;
if (std::abs(vec.y - a.y) < THRESH && vec.x > a.x && vec.x < b.x && vec.z > a.z && vec.z < b.z)
return EVec::BOTTOM;
if (std::abs(vec.z - a.z) < THRESH && vec.x > a.x && vec.x < b.x && vec.y > a.y && vec.y < b.y)
return EVec::FRONT;
if (std::abs(vec.z - b.z) < THRESH && vec.x > a.x && vec.x < b.x && vec.y > a.y && vec.y < b.y)
return EVec::BACK;
if (std::abs(vec.x - b.x) < THRESH && vec.z > a.z && vec.z < b.z && vec.y > a.y && vec.y < b.y)
return EVec::RIGHT;
if (std::abs(vec.x - a.x) < THRESH && vec.z > a.z && vec.z < b.z && vec.y > a.y && vec.y < b.y)
return EVec::LEFT;
return EVec::NONE;
}

Some files were not shown because too many files have changed in this diff Show More