Merge branch 'MihailRis:main' into main

This commit is contained in:
Astazium 2026-09-20 12:36:56 +03:00 • committed by GitHub
commit 2c3c217fef
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
71 changed files with 3978 additions and 786 deletions

View file

@ -25,6 +25,7 @@ endif()
find_package(ZLIB REQUIRED)
find_package(PNG REQUIRED)
find_package(CURL REQUIRED)
find_package(OpenSSL 3.0 REQUIRED COMPONENTS Crypto)
find_package(glfw3 REQUIRED)
find_package(Freetype REQUIRED)
if(NOT APPLE)
@ -86,12 +87,13 @@ target_link_libraries(
ZLIB::ZLIB
PNG::PNG
CURL::libcurl
OpenSSL::Crypto
OpenAL::OpenAL
Vorbis::vorbis
Vorbis::vorbisfile
luajit::luajit
Freetype::Freetype
PUBLIC glm::glm # Need public for src/delegates.hpp, which including to
PUBLIC luajit::luajit
glm::glm # Need public for src/delegates.hpp, which including to
# main.cpp
)

View file

@ -46,7 +46,8 @@ Skeleton::Skeleton(std::shared_ptr<const SkeletonConfig> config)
flags(config ? config->getBones().size() : 0),
textures(),
modelOverrides(config ? config->getBones().size() : 0),
visible(true) {
visible(true),
boneTints(config ? config->getBones().size() : 0, glm::vec4(1.0f)) {
if (config == nullptr) {
return;
}
@ -99,6 +100,7 @@ void Skeleton::setConfig(std::shared_ptr<const SkeletonConfig> rigConfig) {
modelOverrides.resize(bonesCount);
flags.resize(bonesCount);
boneTints.resize(bonesCount, glm::vec4(1.0f));
for (size_t i = 0; i < bonesCount; i++) {
flags[i].visible = true;
@ -175,6 +177,7 @@ void SkeletonConfig::render(
const Assets& assets,
ModelBatch& batch,
Skeleton& skeleton,
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
@ -201,16 +204,24 @@ void SkeletonConfig::render(
if (auto foundOverride = modelOverride.model.lock()) {
model = foundOverride.get();
}
if (model) {
batch.draw(
skeleton.calculated.matrices[i],
skeleton.tint,
model,
&skeleton.textures
);
} else if (!node->model.name.empty()) {
node->model.updateFlag = true;
}
if (model == nullptr) {
if (!node->model.name.empty()) {
node->model.updateFlag = true;
}
continue;
}
batch.draw(
skeleton.calculated.matrices[i],
skeleton.tint * skeleton.boneTints[i],
lightingMode == ModelLightingMode::SOLID
? position - glm::vec3(
skeleton.calculated.matrices[i] *
glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)
)
: glm::vec3(),
model,
&skeleton.textures
);
}
}

View file

@ -11,6 +11,7 @@
#include "typedefs.hpp"
#include "data/dv_fwd.hpp"
#include "util/Interpolation.hpp"
#include "util/EnumMetadata.hpp"
class Assets;
class ModelBatch;
@ -19,6 +20,16 @@ namespace model {
struct Model;
}
enum class ModelLightingMode {
BONE_BASED,
SOLID,
};
VC_ENUM_METADATA(ModelLightingMode)
{"bone-based", ModelLightingMode::BONE_BASED},
{"solid", ModelLightingMode::SOLID},
VC_ENUM_END
namespace rigging {
struct Skeleton;
class SkeletonConfig;
@ -85,7 +96,8 @@ namespace rigging {
std::unordered_map<std::string, std::string> textures;
std::vector<ModelReference> modelOverrides;
bool visible;
glm::vec3 tint {1.0f, 1.0f, 1.0f};
glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f};
std::vector<glm::vec4> boneTints;
util::VecInterpolation<3, float> interpolation {false};
@ -131,6 +143,7 @@ namespace rigging {
const Assets& assets,
ModelBatch& batch,
Skeleton& skeleton,
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale

View file

@ -94,4 +94,8 @@ template<> void ContentUnitLoader<EntityDef>::loadUnit(
root.at("mass").get(def.mass);
root.at("elasticity").get(def.elasticity);
root.at("step-height").get(def.stepHeight);
std::string lightingModeName;
root.at("lighting-mode").get(lightingModeName);
ModelLightingModeMeta.getItem(lightingModeName, def.lightingMode);
}

1247
src/crypto/Crypto.cpp Normal file

File diff suppressed because it is too large Load diff

185
src/crypto/Crypto.hpp Normal file
View file

@ -0,0 +1,185 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace crypto {
constexpr int API_VERSION = 1;
using Bytes = std::vector<std::uint8_t>;
enum class ErrorCode {
InvalidArgument,
InvalidKey,
InvalidSignature,
AuthenticationFailed,
UnsupportedAlgorithm,
OutputTooLarge,
InvalidState,
BackendError
};
class Error : public std::runtime_error {
public:
Error(ErrorCode code, const std::string& message);
ErrorCode code() const noexcept;
const char* codeName() const noexcept;
private:
ErrorCode errorCode;
};
struct KeyPair {
Bytes privateKey;
Bytes publicKey;
};
struct Features {
bool sha256;
bool sha384;
bool sha512;
bool md5;
bool hmac;
bool ed25519;
bool ecdsa;
bool rsa;
bool x25519;
bool p256;
bool aes128Gcm;
bool aes256Gcm;
bool chacha20Poly1305;
bool random;
bool hkdf;
bool pbkdf2;
bool scrypt;
};
class HashContext {
public:
explicit HashContext(std::string_view hash);
~HashContext();
HashContext(HashContext&&) noexcept;
HashContext& operator=(HashContext&&) noexcept;
HashContext(const HashContext&) = delete;
HashContext& operator=(const HashContext&) = delete;
void update(std::string_view data);
Bytes final();
void reset();
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
Bytes digest(std::string_view hash, std::string_view data);
Bytes hmac(
std::string_view hash, std::string_view key, std::string_view data
);
KeyPair ed25519KeyPair();
Bytes ed25519Public(std::string_view privateKey);
Bytes ed25519Sign(std::string_view privateKey, std::string_view message);
bool ed25519Verify(
std::string_view publicKey,
std::string_view message,
std::string_view signature
);
bool ecdsaVerify(
std::string_view curve,
std::string_view publicKey,
std::string_view message,
std::string_view signature,
std::string_view hash
);
KeyPair ecdsaKeyPair(std::string_view curve);
Bytes ecdsaPublic(std::string_view curve, std::string_view privateKey);
Bytes ecdsaSign(
std::string_view curve,
std::string_view privateKey,
std::string_view message,
std::string_view hash
);
bool rsaPkcs1Verify(
std::string_view hash,
std::string_view modulus,
std::string_view exponent,
std::string_view message,
std::string_view signature
);
bool rsaPssVerify(
std::string_view hash,
std::string_view modulus,
std::string_view exponent,
std::string_view message,
std::string_view signature,
int saltLength
);
KeyPair x25519KeyPair();
Bytes x25519Public(std::string_view privateKey);
Bytes x25519(std::string_view privateKey, std::string_view peerPublicKey);
Bytes p256Public(std::string_view privateKey);
Bytes p256Shared(
std::string_view privateKey, std::string_view peerPublicKey
);
Bytes aesGcmEncrypt(
std::string_view key,
std::string_view nonce,
std::string_view aad,
std::string_view plaintext
);
Bytes aesGcmDecrypt(
std::string_view key,
std::string_view nonce,
std::string_view aad,
std::string_view ciphertextWithTag
);
Bytes chacha20Poly1305Encrypt(
std::string_view key,
std::string_view nonce,
std::string_view aad,
std::string_view plaintext
);
Bytes chacha20Poly1305Decrypt(
std::string_view key,
std::string_view nonce,
std::string_view aad,
std::string_view ciphertextWithTag
);
Bytes randomBytes(std::size_t length);
bool constantTimeEqual(std::string_view left, std::string_view right);
Bytes hkdfExtract(
std::string_view hash, std::string_view salt, std::string_view ikm
);
Bytes hkdfExpand(
std::string_view hash,
std::string_view prk,
std::string_view info,
std::size_t length
);
Bytes pbkdf2(
std::string_view hash,
std::string_view password,
std::string_view salt,
std::uint32_t iterations,
std::size_t length
);
Bytes scrypt(
std::string_view password,
std::string_view salt,
std::uint64_t n,
std::uint64_t r,
std::uint64_t p,
std::size_t length,
std::uint64_t maxMemory = 0
);
const char* backendVersion();
Features features();
}

View file

@ -117,6 +117,13 @@ std::shared_ptr<Texture> Framebuffer::getSharedTexture() const {
return texture;
}
std::unique_ptr<ImageData> Framebuffer::readData() const {
if (!texture) {
return nullptr;
}
return texture->readData();
}
uint Framebuffer::getWidth() const {
return width;
}

View file

@ -6,6 +6,7 @@
#include <memory>
class Texture;
class ImageData;
class Framebuffer : public Bindable {
uint fbo;
@ -36,6 +37,8 @@ public:
std::shared_ptr<Texture> getSharedTexture() const;
std::unique_ptr<ImageData> readData() const;
/// @brief Get framebuffer width
uint getWidth() const;
/// @brief Get framebuffer height

View file

@ -161,7 +161,7 @@ void BlockWrapsRenderer::draw(const DrawContext& pctx) {
u64id_t BlockWrapsRenderer::add(
const glm::ivec3& position,
const std::string& texture,
const glm::vec3& tint,
const glm::vec4& tint,
float emission
) {
u64id_t id = nextWrapper++;

View file

@ -20,7 +20,7 @@ class DrawContext;
struct BlockWrapper {
glm::ivec3 position;
std::array<std::string, 6> textureFaces {};
std::array<glm::vec3, 6> tints {};
std::array<glm::vec4, 6> tints {};
float emission = 0.0f;
// --- render cache ---
@ -56,7 +56,7 @@ public:
u64id_t add(
const glm::ivec3& position,
const std::string& texture,
const glm::vec3& tint,
const glm::vec4& tint,
float emission
);

View file

@ -357,20 +357,30 @@ void BlocksRenderer::blockCustomModel(
const auto& vcoord = vertex.coord - 0.5f;
glm::vec4 aoColor {1.0f, 1.0f, 1.0f, 1.0f};
if (shading && ao) {
if (shading) {
const float eps = 0.05f;
auto p = coord + vcoord.x * X + vcoord.y * Y + vcoord.z * Z +
r * 0.5f + t * 0.5f + n * eps;
auto p1 = p + n * eps;
auto p2 = p + n * 0.5f;
aoColor = pickSoftLight(p1.x, p1.y, p1.z, glm::ivec3(r), glm::ivec3(t));
if (!block.lightPassing) {
aoColor = glm::max(
aoColor,
pickSoftLight(
p2.x, p2.y, p2.z, glm::ivec3(r), glm::ivec3(t)
)
);
r * 0.5f + t * 0.5f + n * eps;
if (ao) {
auto p1 = p + n * eps;
auto p2 = p + n * 0.5f;
aoColor = pickSoftLight(p1.x, p1.y, p1.z, glm::ivec3(r), glm::ivec3(t));
if (!block.lightPassing) {
aoColor = glm::max(
aoColor,
pickSoftLight(
p2.x, p2.y, p2.z, glm::ivec3(r), glm::ivec3(t)
)
);
}
} else {
aoColor = pickLight(glm::floor(p + 0.5f) + 0.5f);
if (!block.lightPassing) {
aoColor = glm::max(
aoColor,
pickLight(glm::floor(p + n + 0.5f) + 0.5f)
);
}
}
}
this->vertex(

View file

@ -30,6 +30,7 @@ void HandsRenderer::render(const Camera& camera) {
assets,
modelBatch,
skeleton,
ModelLightingMode::SOLID,
glm::mat3(1.0f),
glm::vec3(),
glm::vec3(1.0f)

View file

@ -82,12 +82,75 @@ inline glm::vec4 do_tint(float value) {
return {value, value, value, 1.0f};
}
void MainBatch::quad(
const glm::vec3& pos,
const glm::vec3& right,
const glm::vec3& up,
const glm::vec3& normal,
const glm::vec2& size,
const glm::vec4& light,
const glm::vec4& tint,
const UVRegion& subregion,
float emission
) {
prepare(6);
vertex(
pos - right * size.x * 0.5f - up * size.y * 0.5f,
{subregion.u1, subregion.v1},
light,
tint,
normal,
emission
);
vertex(
pos + right * size.x * 0.5f - up * size.y * 0.5f,
{subregion.u2, subregion.v1},
light,
tint,
normal,
emission
);
vertex(
pos + right * size.x * 0.5f + up * size.y * 0.5f,
{subregion.u2, subregion.v2},
light,
tint,
normal,
emission
);
vertex(
pos - right * size.x * 0.5f - up * size.y * 0.5f,
{subregion.u1, subregion.v1},
light,
tint,
normal,
emission
);
vertex(
pos + right * size.x * 0.5f + up * size.y * 0.5f,
{subregion.u2, subregion.v2},
light,
tint,
normal,
emission
);
vertex(
pos - right * size.x * 0.5f + up * size.y * 0.5f,
{subregion.u1, subregion.v2},
light,
tint,
normal,
emission
);
}
void MainBatch::cube(
const glm::vec3& coord,
const glm::vec3& size,
const UVRegion(&texfaces)[6],
const glm::vec4& lights,
const glm::vec3 tints[],
const glm::vec4 tints[],
float emission,
uint8_t cullingBits
) {

View file

@ -17,30 +17,20 @@ class Chunks;
struct MainBatchVertex {
glm::vec3 position;
glm::vec2 uv;
glm::vec3 tint;
glm::vec4 tint;
std::array<uint8_t, 4> color;
std::array<uint8_t, 4> normal;
static constexpr VertexAttribute ATTRIBUTES[] = {
{VertexAttribute::Type::FLOAT, false, 3},
{VertexAttribute::Type::FLOAT, false, 2},
{VertexAttribute::Type::FLOAT, false, 3},
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::UNSIGNED_BYTE, true, 4},
{VertexAttribute::Type::UNSIGNED_BYTE, true, 4},
{{}, 0}};
};
class MainBatch {
std::unique_ptr<MainBatchVertex[]> const buffer;
size_t const capacity;
size_t index;
UVRegion region {0.0f, 0.0f, 1.0f, 1.0f};
std::unique_ptr<Mesh<MainBatchVertex>> mesh;
std::unique_ptr<Texture> blank;
const Texture* texture = nullptr;
public:
/// xyz, uv, color, compressed lights
@ -63,7 +53,7 @@ public:
const glm::vec3& pos,
const glm::vec2& uv,
const glm::vec4& light,
const glm::vec3& tint,
const glm::vec4& tint,
const glm::vec3& normal,
float emission
) {
@ -84,76 +74,36 @@ public:
index++;
}
inline void quad(
void quad(
const glm::vec3& pos,
const glm::vec3& right,
const glm::vec3& up,
const glm::vec3& normal,
const glm::vec2& size,
const glm::vec4& light,
const glm::vec3& tint,
const glm::vec4& tint,
const UVRegion& subregion,
float emission = 0.0f
) {
prepare(6);
vertex(
pos - right * size.x * 0.5f - up * size.y * 0.5f,
{subregion.u1, subregion.v1},
light,
tint,
normal,
emission
);
vertex(
pos + right * size.x * 0.5f - up * size.y * 0.5f,
{subregion.u2, subregion.v1},
light,
tint,
normal,
emission
);
vertex(
pos + right * size.x * 0.5f + up * size.y * 0.5f,
{subregion.u2, subregion.v2},
light,
tint,
normal,
emission
);
vertex(
pos - right * size.x * 0.5f - up * size.y * 0.5f,
{subregion.u1, subregion.v1},
light,
tint,
normal,
emission
);
vertex(
pos + right * size.x * 0.5f + up * size.y * 0.5f,
{subregion.u2, subregion.v2},
light,
tint,
normal,
emission
);
vertex(
pos - right * size.x * 0.5f + up * size.y * 0.5f,
{subregion.u1, subregion.v2},
light,
tint,
normal,
emission
);
}
);
void cube(
const glm::vec3& coord,
const glm::vec3& size,
const UVRegion(&texfaces)[6],
const glm::vec4& lights,
const glm::vec3 tints[],
const glm::vec4 tints[],
float emission,
uint8_t cullingBits = 0xFF
);
private:
std::unique_ptr<MainBatchVertex[]> const buffer;
size_t const capacity;
size_t index;
UVRegion region {0.0f, 0.0f, 1.0f, 1.0f};
std::unique_ptr<Mesh<MainBatchVertex>> mesh;
std::unique_ptr<Texture> blank;
const Texture* texture = nullptr;
};

View file

@ -61,8 +61,8 @@ void ModelBatch::draw(
const model::Mesh& mesh,
const glm::mat4& matrix,
const glm::mat3& rotation,
glm::vec3 tint,
const texture_names_map* varTextures,
const glm::vec4& tint,
const TextureNamesMap* varTextures,
bool backlight
) {
setTexture(mesh.texture, varTextures);
@ -72,7 +72,7 @@ void ModelBatch::draw(
glm::vec4 lights(1, 1, 1, 0);
if (mesh.shading) {
glm::vec3 gpos = matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
gpos += lightsOffset;
gpos += lightsOffset + localLightsOffset;
lights = MainBatch::sampleLight(gpos, chunks, backlight);
}
for (size_t i = 0; i < vcount / 3; i++) {
@ -97,14 +97,21 @@ void ModelBatch::draw(
}
}
void ModelBatch::draw(glm::mat4 matrix,
glm::vec3 tint,
const model::Model* model,
const texture_names_map* varTextures) {
void ModelBatch::draw(
const glm::mat4& matrix,
const glm::vec4& tint,
const glm::vec3& lightSampleOffset,
const model::Model* model,
const TextureNamesMap* varTextures
) {
for (const auto& mesh : model->meshes) {
entries.push_back({
matrix, extract_rotation(matrix), tint, &mesh, varTextures
});
entries.push_back(DrawEntry {
matrix,
extract_rotation(matrix),
tint,
lightSampleOffset,
&mesh,
varTextures});
}
}
@ -116,6 +123,7 @@ void ModelBatch::render() {
);
bool backlight = settings.graphics.backlight.get();
for (auto& entry : entries) {
localLightsOffset = entry.lightSampleOffset;
draw(
*entry.mesh,
entry.matrix,
@ -124,6 +132,7 @@ void ModelBatch::render() {
entry.varTextures,
backlight
);
localLightsOffset = {};
}
batch->flush();
entries.clear();
@ -134,7 +143,7 @@ void ModelBatch::setLightsOffset(const glm::vec3& offset) {
}
void ModelBatch::setTexture(const std::string& name,
const texture_names_map* varTextures) {
const TextureNamesMap* varTextures) {
if (varTextures && !name.empty() && name.at(0) == '$') {
const auto& found = varTextures->find(name);
if (found == varTextures->end()) {

View file

@ -18,37 +18,9 @@ namespace model {
struct Model;
}
using texture_names_map = std::unordered_map<std::string, std::string>;
using TextureNamesMap = std::unordered_map<std::string, std::string>;
class ModelBatch {
const Assets& assets;
const Chunks& chunks;
const EngineSettings& settings;
glm::vec3 lightsOffset {};
static inline glm::vec3 SUN_VECTOR {0.411934f, 0.863868f, -0.279161f};
std::unique_ptr<MainBatch> batch;
void draw(const model::Mesh& mesh,
const glm::mat4& matrix,
const glm::mat3& rotation,
glm::vec3 tint,
const texture_names_map* varTextures,
bool backlight);
void setTexture(const std::string& name,
const texture_names_map* varTextures);
struct DrawEntry {
glm::mat4 matrix;
glm::mat3 rotation;
glm::vec3 tint;
const model::Mesh* mesh;
const texture_names_map* varTextures;
};
std::vector<DrawEntry> entries;
public:
ModelBatch(
size_t capacity,
@ -58,11 +30,47 @@ public:
);
~ModelBatch();
void draw(glm::mat4 matrix,
glm::vec3 tint,
const model::Model* model,
const texture_names_map* varTextures);
void draw(
const glm::mat4& matrix,
const glm::vec4& tint,
const glm::vec3& lightSampleOffset,
const model::Model* model,
const TextureNamesMap* varTextures
);
void render();
void setLightsOffset(const glm::vec3& offset);
private:
const Assets& assets;
const Chunks& chunks;
const EngineSettings& settings;
glm::vec3 lightsOffset {};
glm::vec3 localLightsOffset {};
static inline glm::vec3 SUN_VECTOR {0.411934f, 0.863868f, -0.279161f};
std::unique_ptr<MainBatch> batch;
void draw(
const model::Mesh& mesh,
const glm::mat4& matrix,
const glm::mat3& rotation,
const glm::vec4& tint,
const TextureNamesMap* varTextures,
bool backlight
);
void setTexture(const std::string& name,
const TextureNamesMap* varTextures);
struct DrawEntry {
glm::mat4 matrix;
glm::mat3 rotation;
glm::vec4 tint;
glm::vec3 lightSampleOffset;
const model::Mesh* mesh;
const TextureNamesMap* varTextures;
};
std::vector<DrawEntry> entries;
};

View file

@ -160,7 +160,7 @@ void ParticlesRenderer::renderParticle(
-camera.front,
preset.size * scale,
light,
glm::vec3(1.0f),
glm::vec4(1.0f),
particle.region,
preset.lighting ? 0.0f : 1.0f
);

View file

@ -151,7 +151,7 @@ void PrecipitationRenderer::render(
glm::cross(glm::vec3(0, 1, 0), face.right),
FACE_SIZE,
light_at(chunks, pos.x, y, pos.z),
glm::vec3(1.0f),
glm::vec4(1.0f),
calc_uv(pos, face.right, timer, weather)
);
}

View file

@ -374,6 +374,14 @@ std::shared_ptr<gui::Frame> GUI::getActiveFrame() const {
return activeFrame;
}
std::shared_ptr<gui::Frame> GUI::getFrame(const std::string& id) {
const auto& found = frames.find(id);
if (found == frames.end()) {
return nullptr;
}
return found->second;
}
void GUI::remove(UINode* node) noexcept {
container->remove(node);
}

View file

@ -137,6 +137,8 @@ namespace gui {
std::shared_ptr<Frame> getActiveFrame() const;
std::shared_ptr<Frame> getFrame(const std::string& id);
/// @brief Remove node from the main container
void remove(UINode* node) noexcept;

View file

@ -66,3 +66,10 @@ const std::string& gui::Frame::getOutputTexture() const {
const std::string& gui::Frame::getFrameId() const {
return frameId;
}
std::unique_ptr<ImageData> gui::Frame::takeScreenshot() const {
if (fbo == nullptr) {
return nullptr;
}
return fbo->readData();
}

View file

@ -4,6 +4,7 @@
class Framebuffer;
class UiDocument;
class ImageData;
namespace gui {
class Frame final : public Container {
@ -18,6 +19,8 @@ namespace gui {
const std::string& getOutputTexture() const;
const std::string& getFrameId() const;
std::unique_ptr<ImageData> takeScreenshot() const;
private:
std::string frameId;
std::unique_ptr<Framebuffer> fbo;

View file

@ -25,6 +25,7 @@ extern const luaL_Reg byteutillib[];
extern const luaL_Reg cameralib[];
extern const luaL_Reg consolelib[];
extern const luaL_Reg corelib[];
extern const luaL_Reg cryptolib[];
extern const luaL_Reg entitylib[];
extern const luaL_Reg filelib[];
extern const luaL_Reg generationlib[];
@ -93,3 +94,4 @@ namespace lua {
}
void initialize_libs_extends(lua::State* L);
void initialize_cryptolib(lua::State* L);

View file

@ -147,8 +147,19 @@ static int l_set_visible(lua::State* L) {
return 0;
}
static glm::vec4 to_color(lua::State* L, int idx) {
if (lua::objlen(L, idx) > 3) {
return lua::tovec4(L, idx);
}
return glm::vec4(lua::tovec3(L, idx), 1.0f);
}
static int l_get_color(lua::State* L) {
if (auto skeleton = get_skeleton(L)) {
if (lua::isnumber(L, 2)) {
auto index = index_range_check(*skeleton, lua::tointeger(L, 2));
return lua::pushvec(L, skeleton->boneTints[index]);
}
return lua::pushvec(L, skeleton->tint);
}
return 0;
@ -156,7 +167,13 @@ static int l_get_color(lua::State* L) {
static int l_set_color(lua::State* L) {
if (auto skeleton = get_skeleton(L)) {
skeleton->tint = lua::tovec3(L, 2);
auto color = to_color(L, 2);
if (lua::isnumber(L, 3)) {
auto index = index_range_check(*skeleton, lua::tointeger(L, 3));
skeleton->boneTints[index] = color;
} else {
skeleton->tint = color;
}
}
return 0;
}

View file

@ -10,7 +10,11 @@ static int l_wrap(lua::State* L) {
auto position = lua::tovec3(L, 1);
std::string texture = lua::require_string(L, 2);
float emission = lua::isnumber(L, 3) ? lua::tonumber(L, 3) : 1.0f;
glm::vec3 tint = lua::istable(L, 4) ? lua::tovec3(L, 4) : glm::vec3(1.0f);
glm::vec4 tint =
lua::istable(L, 4)
? (lua::objlen(L, 4) > 3 ? lua::tovec4(L, 4)
: glm::vec4(lua::tovec3(L, 4), 1.0f))
: glm::vec4(1.0f);
return lua::pushinteger(
L,
@ -72,9 +76,12 @@ static int l_set_tints(lua::State* L) {
if (auto wrapper = renderer->blockWraps->get(lua::tointeger(L, 1))) {
for (int i = 0; i < wrapper->textureFaces.size(); i++) {
if (lua::isnil(L, 2 + i)) {
wrapper->tints[i] = glm::vec3(1.0f);
wrapper->tints[i] = glm::vec4(1.0f);
} else {
wrapper->tints[i] = lua::tovec3(L, 2 + i);
wrapper->tints[i] =
lua::objlen(L, 2 + i) > 3
? lua::tovec4(L, 2 + i)
: glm::vec4(lua::tovec3(L, 2 + i), 1.0f);
}
}
}

View file

@ -0,0 +1,540 @@
#include <climits>
#include <cstdint>
#include <new>
#include <stdexcept>
#include <string>
#include <string_view>
#include "api_lua.hpp"
#include "crypto/Crypto.hpp"
namespace {
using HashContext = crypto::HashContext;
constexpr const char* HASH_CONTEXT_METATABLE =
"voxelcore.crypto.HashContext";
int pushBytes(lua::State* L, const crypto::Bytes& value) {
return lua::pushlstring(L, value.data(), value.size());
}
int pushFailure(lua::State* L, bool nil, const char* error) {
nil ? lua::pushnil(L) : lua::pushboolean(L, false);
lua::pushstring(L, error);
return 2;
}
int pushKeyPair(lua::State* L, const crypto::KeyPair& keyPair) {
pushBytes(L, keyPair.privateKey);
pushBytes(L, keyPair.publicKey);
return 2;
}
template <typename Operation>
int verify(lua::State* L, Operation operation) {
try {
if (operation()) return lua::pushboolean(L, true);
return pushFailure(L, false, "invalid_signature");
} catch (const crypto::Error& error) {
return pushFailure(L, false, error.codeName());
} catch (const std::exception& error) {
return pushFailure(L, false, "backend_error");
}
}
template <typename Operation>
int decrypt(lua::State* L, Operation operation) {
try {
return pushBytes(L, operation());
} catch (const crypto::Error& error) {
return pushFailure(L, true, error.codeName());
} catch (const std::exception& error) {
return pushFailure(L, true, "backend_error");
}
}
std::size_t requireSize(lua::State* L, int index, const char* name) {
if (lua::type(L, index) != LUA_TNUMBER) {
throw std::runtime_error(std::string(name) + " must be a number");
}
const lua::Number number = lua::tonumber(L, index);
const lua::Integer value = lua::tointeger(L, index);
if (number != static_cast<lua::Number>(value)) {
throw std::runtime_error(std::string(name) + " must be an integer");
}
if (value < 0) {
throw std::runtime_error(
std::string(name) + " must be non-negative"
);
}
return static_cast<std::size_t>(value);
}
int requireInt(lua::State* L, int index, const char* name) {
if (lua::type(L, index) != LUA_TNUMBER) {
throw std::runtime_error(std::string(name) + " must be a number");
}
const lua::Number number = lua::tonumber(L, index);
const lua::Integer value = lua::tointeger(L, index);
if (number != static_cast<lua::Number>(value)) {
throw std::runtime_error(std::string(name) + " must be an integer");
}
if (value < INT_MIN || value > INT_MAX) {
throw std::runtime_error(std::string(name) + " is out of range");
}
return static_cast<int>(value);
}
int hash(lua::State* L, std::string_view name) {
lua::check_argc(L, 1);
return pushBytes(L, crypto::digest(name, lua::require_lstring(L, 1)));
}
int l_sha256(lua::State* L) {
return hash(L, "SHA256");
}
int l_sha384(lua::State* L) {
return hash(L, "SHA384");
}
int l_sha512(lua::State* L) {
return hash(L, "SHA512");
}
int l_md5(lua::State* L) {
return hash(L, "MD5");
}
int l_hash(lua::State* L) {
lua::check_argc(L, 2);
return pushBytes(
L,
crypto::digest(
lua::require_lstring(L, 1), lua::require_lstring(L, 2)
)
);
}
crypto::HashContext* requireHashContext(lua::State* L) {
return static_cast<crypto::HashContext*>(
luaL_checkudata(L, 1, HASH_CONTEXT_METATABLE)
);
}
int l_hash_context_gc(lua::State* L) {
requireHashContext(L)->~HashContext();
return 0;
}
int l_hash_context_update(lua::State* L) {
lua::check_argc(L, 2);
requireHashContext(L)->update(lua::require_lstring(L, 2));
lua::pushvalue(L, 1);
return 1;
}
int l_hash_context_final(lua::State* L) {
lua::check_argc(L, 1);
return pushBytes(L, requireHashContext(L)->final());
}
int l_hash_context_reset(lua::State* L) {
lua::check_argc(L, 1);
requireHashContext(L)->reset();
lua::pushvalue(L, 1);
return 1;
}
void ensureHashContextMetatable(lua::State* L) {
if (luaL_newmetatable(L, HASH_CONTEXT_METATABLE)) {
lua::pushcfunction(L, lua::wrap<l_hash_context_gc>);
lua::setfield(L, "__gc");
lua::pushcfunction(L, lua::wrap<l_hash_context_update>);
lua::setfield(L, "update");
lua::pushcfunction(L, lua::wrap<l_hash_context_final>);
lua::setfield(L, "final");
lua::pushcfunction(L, lua::wrap<l_hash_context_reset>);
lua::setfield(L, "reset");
lua::pushvalue(L, -1);
lua::setfield(L, "__index");
}
lua::pop(L);
}
int l_hash_new(lua::State* L) {
lua::check_argc(L, 1);
const auto name = lua::require_lstring(L, 1);
ensureHashContextMetatable(L);
void* memory = lua_newuserdata(L, sizeof(crypto::HashContext));
new (memory) crypto::HashContext(name);
luaL_getmetatable(L, HASH_CONTEXT_METATABLE);
lua_setmetatable(L, -2);
return 1;
}
int l_hmac(lua::State* L) {
lua::check_argc(L, 3);
return pushBytes(
L,
crypto::hmac(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
lua::require_lstring(L, 3)
)
);
}
int l_ed25519_verify(lua::State* L) {
lua::check_argc(L, 3);
const auto key = lua::require_lstring(L, 1);
const auto message = lua::require_lstring(L, 2);
const auto signature = lua::require_lstring(L, 3);
return verify(L, [=] {
return crypto::ed25519Verify(key, message, signature);
});
}
int l_ed25519_keypair(lua::State* L) {
lua::check_argc(L, 0);
return pushKeyPair(L, crypto::ed25519KeyPair());
}
int l_ed25519_public(lua::State* L) {
lua::check_argc(L, 1);
return pushBytes(L, crypto::ed25519Public(lua::require_lstring(L, 1)));
}
int l_ed25519_sign(lua::State* L) {
lua::check_argc(L, 2);
return pushBytes(
L,
crypto::ed25519Sign(
lua::require_lstring(L, 1), lua::require_lstring(L, 2)
)
);
}
int l_ecdsa_verify(lua::State* L) {
lua::check_argc(L, 5);
const auto curve = lua::require_lstring(L, 1);
const auto key = lua::require_lstring(L, 2);
const auto message = lua::require_lstring(L, 3);
const auto signature = lua::require_lstring(L, 4);
const auto hashName = lua::require_lstring(L, 5);
return verify(L, [=] {
return crypto::ecdsaVerify(
curve, key, message, signature, hashName
);
});
}
int l_ecdsa_keypair(lua::State* L) {
lua::check_argc(L, 1);
return pushKeyPair(L, crypto::ecdsaKeyPair(lua::require_lstring(L, 1)));
}
int l_ecdsa_public(lua::State* L) {
lua::check_argc(L, 2);
return pushBytes(
L,
crypto::ecdsaPublic(
lua::require_lstring(L, 1), lua::require_lstring(L, 2)
)
);
}
int l_ecdsa_sign(lua::State* L) {
lua::check_argc(L, 4);
return pushBytes(
L,
crypto::ecdsaSign(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
lua::require_lstring(L, 3),
lua::require_lstring(L, 4)
)
);
}
int l_rsa_pkcs1_verify(lua::State* L) {
lua::check_argc(L, 5);
const auto hashName = lua::require_lstring(L, 1);
const auto modulus = lua::require_lstring(L, 2);
const auto exponent = lua::require_lstring(L, 3);
const auto message = lua::require_lstring(L, 4);
const auto signature = lua::require_lstring(L, 5);
return verify(L, [=] {
return crypto::rsaPkcs1Verify(
hashName, modulus, exponent, message, signature
);
});
}
int l_rsa_pss_verify(lua::State* L) {
lua::check_argc(L, 6);
const auto hashName = lua::require_lstring(L, 1);
const auto modulus = lua::require_lstring(L, 2);
const auto exponent = lua::require_lstring(L, 3);
const auto message = lua::require_lstring(L, 4);
const auto signature = lua::require_lstring(L, 5);
const int saltLength = requireInt(L, 6, "salt_length");
return verify(L, [=] {
return crypto::rsaPssVerify(
hashName, modulus, exponent, message, signature, saltLength
);
});
}
int l_x25519_public(lua::State* L) {
lua::check_argc(L, 1);
return pushBytes(L, crypto::x25519Public(lua::require_lstring(L, 1)));
}
int l_x25519_keypair(lua::State* L) {
lua::check_argc(L, 0);
return pushKeyPair(L, crypto::x25519KeyPair());
}
int l_x25519(lua::State* L) {
lua::check_argc(L, 2);
return pushBytes(
L,
crypto::x25519(
lua::require_lstring(L, 1), lua::require_lstring(L, 2)
)
);
}
int l_p256_public(lua::State* L) {
lua::check_argc(L, 1);
return pushBytes(L, crypto::p256Public(lua::require_lstring(L, 1)));
}
int l_p256_keypair(lua::State* L) {
lua::check_argc(L, 0);
return pushKeyPair(L, crypto::ecdsaKeyPair("P-256"));
}
int l_p256_shared(lua::State* L) {
lua::check_argc(L, 2);
return pushBytes(
L,
crypto::p256Shared(
lua::require_lstring(L, 1), lua::require_lstring(L, 2)
)
);
}
int l_aes_gcm_encrypt(lua::State* L) {
lua::check_argc(L, 4);
return pushBytes(
L,
crypto::aesGcmEncrypt(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
lua::require_lstring(L, 3),
lua::require_lstring(L, 4)
)
);
}
int l_aes_gcm_decrypt(lua::State* L) {
lua::check_argc(L, 4);
const auto key = lua::require_lstring(L, 1);
const auto nonce = lua::require_lstring(L, 2);
const auto aad = lua::require_lstring(L, 3);
const auto ciphertext = lua::require_lstring(L, 4);
return decrypt(L, [=] {
return crypto::aesGcmDecrypt(key, nonce, aad, ciphertext);
});
}
int l_chacha20_poly1305_encrypt(lua::State* L) {
lua::check_argc(L, 4);
return pushBytes(
L,
crypto::chacha20Poly1305Encrypt(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
lua::require_lstring(L, 3),
lua::require_lstring(L, 4)
)
);
}
int l_chacha20_poly1305_decrypt(lua::State* L) {
lua::check_argc(L, 4);
const auto key = lua::require_lstring(L, 1);
const auto nonce = lua::require_lstring(L, 2);
const auto aad = lua::require_lstring(L, 3);
const auto ciphertext = lua::require_lstring(L, 4);
return decrypt(L, [=] {
return crypto::chacha20Poly1305Decrypt(key, nonce, aad, ciphertext);
});
}
int l_random_bytes(lua::State* L) {
lua::check_argc(L, 1);
return pushBytes(L, crypto::randomBytes(requireSize(L, 1, "length")));
}
int l_constant_time_equal(lua::State* L) {
lua::check_argc(L, 2);
return lua::pushboolean(
L,
crypto::constantTimeEqual(
lua::require_lstring(L, 1), lua::require_lstring(L, 2)
)
);
}
int l_hkdf_extract(lua::State* L) {
lua::check_argc(L, 3);
return pushBytes(
L,
crypto::hkdfExtract(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
lua::require_lstring(L, 3)
)
);
}
int l_hkdf_expand(lua::State* L) {
lua::check_argc(L, 4);
return pushBytes(
L,
crypto::hkdfExpand(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
lua::require_lstring(L, 3),
requireSize(L, 4, "length")
)
);
}
int l_pbkdf2(lua::State* L) {
lua::check_argc(L, 5);
const auto iterations = requireSize(L, 4, "iterations");
if (iterations == 0 || iterations > UINT32_MAX) {
throw std::runtime_error(
"iterations must be between 1 and 4294967295"
);
}
return pushBytes(
L,
crypto::pbkdf2(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
lua::require_lstring(L, 3),
static_cast<std::uint32_t>(iterations),
requireSize(L, 5, "length")
)
);
}
int l_scrypt(lua::State* L) {
const auto argc = lua::check_argc(L, 6, 7);
const auto maxMemory =
argc == 7 ? requireSize(L, 7, "max_memory") : std::size_t {0};
return pushBytes(
L,
crypto::scrypt(
lua::require_lstring(L, 1),
lua::require_lstring(L, 2),
requireSize(L, 3, "n"),
requireSize(L, 4, "r"),
requireSize(L, 5, "p"),
requireSize(L, 6, "length"),
maxMemory
)
);
}
void setFeature(lua::State* L, const char* name, bool available) {
lua::pushboolean(L, available);
lua::setfield(L, name);
}
int l_features(lua::State* L) {
lua::check_argc(L, 0);
const auto features = crypto::features();
lua::createtable(L, 0, 26);
lua::pushstring(L, "OpenSSL");
lua::setfield(L, "backend");
lua::pushstring(L, crypto::backendVersion());
lua::setfield(L, "backend_version");
lua::pushinteger(L, crypto::API_VERSION);
lua::setfield(L, "api_version");
setFeature(L, "sha256", features.sha256);
setFeature(L, "sha384", features.sha384);
setFeature(L, "sha512", features.sha512);
setFeature(L, "md5", features.md5);
setFeature(L, "hmac", features.hmac);
setFeature(L, "streaming_hash", features.sha256);
setFeature(L, "ed25519", features.ed25519);
setFeature(L, "ed25519_verify", features.ed25519);
setFeature(L, "ecdsa", features.ecdsa);
setFeature(L, "ecdsa_verify", features.ecdsa);
setFeature(L, "rsa_pkcs1_verify", features.rsa);
setFeature(L, "rsa_pss_verify", features.rsa);
setFeature(L, "x25519", features.x25519);
setFeature(L, "p256", features.p256);
setFeature(L, "aes_128_gcm", features.aes128Gcm);
setFeature(L, "aes_256_gcm", features.aes256Gcm);
setFeature(L, "aes_gcm", features.aes128Gcm && features.aes256Gcm);
setFeature(L, "chacha20_poly1305", features.chacha20Poly1305);
setFeature(L, "random_bytes", features.random);
setFeature(L, "constant_time_equal", true);
setFeature(L, "hkdf", features.hkdf);
setFeature(L, "pbkdf2", features.pbkdf2);
setFeature(L, "scrypt", features.scrypt);
return 1;
}
}
const luaL_Reg cryptolib[] = {
{"sha256", lua::wrap<l_sha256>},
{"sha384", lua::wrap<l_sha384>},
{"sha512", lua::wrap<l_sha512>},
{"md5", lua::wrap<l_md5>},
{"hash", lua::wrap<l_hash>},
{"hash_new", lua::wrap<l_hash_new>},
{"hmac", lua::wrap<l_hmac>},
{"ed25519_keypair", lua::wrap<l_ed25519_keypair>},
{"ed25519_public", lua::wrap<l_ed25519_public>},
{"ed25519_sign", lua::wrap<l_ed25519_sign>},
{"ed25519_verify", lua::wrap<l_ed25519_verify>},
{"ecdsa_keypair", lua::wrap<l_ecdsa_keypair>},
{"ecdsa_public", lua::wrap<l_ecdsa_public>},
{"ecdsa_sign", lua::wrap<l_ecdsa_sign>},
{"ecdsa_verify", lua::wrap<l_ecdsa_verify>},
{"rsa_pkcs1_verify", lua::wrap<l_rsa_pkcs1_verify>},
{"rsa_pss_verify", lua::wrap<l_rsa_pss_verify>},
{"x25519_keypair", lua::wrap<l_x25519_keypair>},
{"x25519_public", lua::wrap<l_x25519_public>},
{"x25519", lua::wrap<l_x25519>},
{"x25519_shared", lua::wrap<l_x25519>},
{"p256_keypair", lua::wrap<l_p256_keypair>},
{"p256_public", lua::wrap<l_p256_public>},
{"p256_shared", lua::wrap<l_p256_shared>},
{"aes_gcm_encrypt", lua::wrap<l_aes_gcm_encrypt>},
{"aes_gcm_decrypt", lua::wrap<l_aes_gcm_decrypt>},
{"chacha20_poly1305_encrypt", lua::wrap<l_chacha20_poly1305_encrypt>},
{"chacha20_poly1305_decrypt", lua::wrap<l_chacha20_poly1305_decrypt>},
{"random_bytes", lua::wrap<l_random_bytes>},
{"constant_time_equal", lua::wrap<l_constant_time_equal>},
{"hkdf_extract", lua::wrap<l_hkdf_extract>},
{"hkdf_expand", lua::wrap<l_hkdf_expand>},
{"pbkdf2", lua::wrap<l_pbkdf2>},
{"scrypt", lua::wrap<l_scrypt>},
{"features", lua::wrap<l_features>},
{NULL, NULL}
};
void initialize_cryptolib(lua::State* L) {
ensureHashContextMetatable(L);
if (lua::getglobal(L, "crypto")) {
lua::pushinteger(L, crypto::API_VERSION);
lua::setfield(L, "API_VERSION");
lua::pop(L);
}
}

View file

@ -25,6 +25,7 @@
#include "items/Inventories.hpp"
#include "util/stringutil.hpp"
#include "world/Level.hpp"
#include "window/Window.hpp"
#include "../usertypes/lua_type_canvas.hpp"
using namespace gui;
@ -1218,7 +1219,26 @@ static int l_get_active_frame(lua::State* L) {
return lua::pushstring(L, frame->getId());
}
static int l_screenshot(lua::State* L) {
if (engine->isHeadless()) {
return 0;
}
std::unique_ptr<ImageData> image;
if (lua::isstring(L, 1)) {
auto& gui = engine->getGUI();
auto frame = gui.getFrame(lua::require_string(L, 1));
if (frame == nullptr) {
return 0;
}
image = frame->takeScreenshot();
} else {
image = engine->getWindow().takeScreenshot();
}
return lua::newuserdata<lua::LuaCanvas>(L, nullptr, std::move(image));
}
const luaL_Reg guilib[] = {
{"screenshot", lua::wrap<l_screenshot>},
{"get_viewport", lua::wrap<l_gui_getviewport>},
{"getattr", lua::wrap<l_gui_getattr>},
{"setattr", lua::wrap<l_gui_setattr>},

View file

@ -3,6 +3,7 @@
#include "engine/Engine.hpp"
#include "network/Network.hpp"
#include "devtools/Project.hpp"
#include "util/stringutil.hpp"
#include <variant>
#include <utility>
@ -27,7 +28,7 @@ struct ResponseEventDto {
int status;
bool binary;
int requestId;
std::vector<char> bytes;
network::HttpResponse response;
};
enum NetworkDatagramSide {
@ -85,74 +86,55 @@ static std::vector<std::string> read_headers(lua::State* L, int index) {
static int request_id = 1;
static int perform_get(lua::State* L, network::Network& network, bool binary) {
std::string url(lua::require_lstring(L, 1));
auto headers = read_headers(L, 2);
static int l_request(lua::State* L, network::Network& network) {
network::HttpRequest request {};
request.url = lua::require_lstring(L, 1);
int currentRequestId = request_id++;
network.get(
url,
[currentRequestId, binary](std::vector<char> bytes) {
push_event(NetworkEvent(
RESPONSE,
ResponseEventDto {
200, binary, currentRequestId, std::move(bytes)}
));
},
[currentRequestId, binary](int code, std::vector<char> bytes) {
push_event(NetworkEvent(
RESPONSE,
ResponseEventDto {
code, binary, currentRequestId, std::move(bytes)}
));
},
std::move(headers)
);
return lua::pushinteger(L, currentRequestId);
}
static int l_get(lua::State* L, network::Network& network) {
return perform_get(L, network, false);
}
static int l_get_binary(lua::State* L, network::Network& network) {
return perform_get(L, network, true);
}
static int l_post(lua::State* L, network::Network& network) {
std::string url(lua::require_lstring(L, 1));
auto data = lua::tovalue(L, 2);
std::string string;
if (data.isString()) {
string = data.asString();
} else {
string = json::stringify(data, false);
if (!lua::istable(L, 2)) {
throw std::runtime_error("table expected as argument #2");
}
if (lua::getfield(L, "method", 2)) {
request.method = lua::require_string(L, -1);
lua::pop(L);
}
if (lua::getfield(L, "headers", 2)) {
request.headers = read_headers(L, -1);
lua::pop(L);
}
if (lua::getfield(L, "body", 2)) {
if (lua::type(L, -1) == LUA_TCDATA) {
request.body = lua::bytearray_as_string(L, -1);
} else {
request.body = lua::require_lstring(L, -1);
}
lua::pop(L);
}
if (lua::getfield(L, "follow_location", 2)) {
request.followLocation = lua::toboolean(L, -1);
lua::pop(L);
}
if (lua::getfield(L, "timeout_ms", 2)) {
request.timeoutMs = lua::tointeger(L, -1);
lua::pop(L);
}
if (lua::getfield(L, "verify_ssl", 2)) {
request.verifySSL = lua::toboolean(L, -1);
lua::pop(L);
}
auto headers = read_headers(L, 3);
int currentRequestId = request_id++;
request.onResponse = [currentRequestId](network::HttpResponse response) {
push_event(NetworkEvent(
RESPONSE,
ResponseEventDto {
response.status,
false,
currentRequestId,
std::move(response)}
));
};
network.post(
url,
string,
[currentRequestId](std::vector<char> bytes) {
push_event(NetworkEvent(
RESPONSE,
ResponseEventDto {
200, false, currentRequestId, std::move(bytes)}
));
},
[currentRequestId](int code, std::vector<char> bytes) {
push_event(NetworkEvent(
RESPONSE,
ResponseEventDto {
code, false, currentRequestId, std::move(bytes)}
));
},
std::move(headers)
);
network.request(std::move(request));
return lua::pushinteger(L, currentRequestId);
}
@ -519,11 +501,31 @@ static int l_pull_events(lua::State* L) {
lua::pushinteger(L, dto.requestId);
lua::rawseti(L, 3);
lua::createtable(L, 0, 2);
lua::pushinteger(L, dto.response.status);
lua::setfield(L, "status");
if (dto.binary) {
lua::create_bytearray(L, dto.bytes.data(), dto.bytes.size());
lua::create_bytearray(
L, dto.response.body.data(), dto.response.body.size()
);
} else {
lua::pushlstring(L, std::string_view(dto.bytes.data(), dto.bytes.size()));
lua::pushlstring(
L,
std::string_view(
dto.response.body.data(), dto.response.body.size()
)
);
}
lua::setfield(L, "body");
lua::createtable(L, dto.response.headers.size(), 0);
for (int i = 0; i < dto.response.headers.size(); i++) {
lua::pushlstring(L, dto.response.headers[i]);
lua::rawseti(L, i + 1);
}
lua::setfield(L, "headers");
lua::rawseti(L, 4);
break;
}
@ -562,9 +564,7 @@ int wrap(lua_State* L) {
}
const luaL_Reg networklib[] = {
{"__get", wrap<l_get>},
{"__get_binary", wrap<l_get_binary>},
{"__post", wrap<l_post>},
{"__request", wrap<l_request>},
{"get_total_upload", wrap<l_get_total_upload>},
{"get_total_download", wrap<l_get_total_download>},
{"find_free_port", wrap<l_find_free_port>},

View file

@ -53,6 +53,8 @@ static void create_libs(State* L, StateType stateType) {
openlib(L, "bjson", bjsonlib);
openlib(L, "block", blocklib);
openlib(L, "byteutil", byteutillib);
openlib(L, "crypto", cryptolib);
initialize_cryptolib(L);
openlib(L, "file", filelib);
openlib(L, "generation", generationlib);
openlib(L, "item", itemlib);

View file

@ -4,7 +4,7 @@
#define NOMINMAX
#include <curl/curl.h>
#include <queue>
#include <algorithm>
using namespace network;
@ -23,97 +23,96 @@ static size_t write_callback(
return size * nmemb;
}
enum class RequestType {
GET, POST
};
static size_t header_callback(
char* buffer, size_t size, size_t nitems, void* userdata
) {
auto* headers = static_cast<std::vector<std::string>*>(userdata);
size_t len = size * nitems;
std::string header(buffer, len);
struct Request {
RequestType type;
std::string url;
OnResponse onResponse;
OnReject onReject;
long maxSize;
bool followLocation = false;
std::string data;
while (!header.empty() &&
(header.back() == '\r' || header.back() == '\n')) {
header.pop_back();
}
headers->push_back(std::move(header));
return len;
}
struct ProcessingRequest {
CURLM* multiHandle;
CURL* curl;
HttpRequest request;
std::vector<char> buffer;
std::vector<std::string> headers;
ProcessingRequest(CURLM* multiHandle) : multiHandle(multiHandle) {
curl = curl_easy_init();
}
ProcessingRequest(const ProcessingRequest&) = delete;
ProcessingRequest& operator=(const ProcessingRequest&) = delete;
ProcessingRequest(ProcessingRequest&& other) noexcept
: multiHandle(other.multiHandle),
curl(other.curl),
request(std::move(other.request)),
buffer(std::move(other.buffer)),
headers(std::move(other.headers)) {
other.curl = nullptr;
other.multiHandle = nullptr;
}
ProcessingRequest& operator=(ProcessingRequest&& other) noexcept {
if (this != &other) {
if (curl) {
curl_multi_remove_handle(multiHandle, curl);
curl_easy_cleanup(curl);
}
multiHandle = other.multiHandle;
curl = other.curl;
request = std::move(other.request);
buffer = std::move(other.buffer);
headers = std::move(other.headers);
other.curl = nullptr;
other.multiHandle = nullptr;
}
return *this;
}
~ProcessingRequest() {
if (curl) {
curl_multi_remove_handle(multiHandle, curl);
curl_easy_cleanup(curl);
}
}
};
class CurlRequests : public Requests {
CURLM* multiHandle;
CURL* curl;
std::vector<std::unique_ptr<ProcessingRequest>> requests;
size_t totalUpload = 0;
size_t totalDownload = 0;
OnResponse onResponse;
OnReject onReject;
std::vector<char> buffer;
std::string url;
std::queue<Request> requests;
public:
CurlRequests(CURLM* multiHandle, CURL* curl)
: multiHandle(multiHandle), curl(curl) {
CurlRequests(CURLM* multiHandle) : multiHandle(multiHandle) {
}
virtual ~CurlRequests() {
curl_multi_remove_handle(multiHandle, curl);
curl_easy_cleanup(curl);
requests.clear();
curl_multi_cleanup(multiHandle);
}
void get(
const std::string& url,
OnResponse onResponse,
OnReject onReject,
std::vector<std::string> headers,
long maxSize
) override {
Request request {
RequestType::GET,
url,
onResponse,
onReject,
maxSize,
true,
"",
std::move(headers)};
void request(HttpRequest request) override {
processRequest(std::move(request));
}
void post(
const std::string& url,
const std::string& data,
OnResponse onResponse,
OnReject onReject=nullptr,
std::vector<std::string> headers = {},
long maxSize=0
) override {
Request request {
RequestType::POST,
url,
onResponse,
onReject,
maxSize,
false,
"",
std::move(headers)};
request.data = data;
processRequest(std::move(request));
}
void processRequest(HttpRequest request) {
auto entry = std::make_unique<ProcessingRequest>(multiHandle);
auto curl = entry->curl;
void processRequest(Request request) {
if (!url.empty()) {
requests.push(request);
return;
}
onResponse = request.onResponse;
onReject = request.onReject;
url = request.url;
buffer.clear();
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, request.type == RequestType::POST);
curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, request.method.c_str());
curl_slist* hs = nullptr;
@ -121,22 +120,25 @@ public:
hs = curl_slist_append(hs, header.c_str());
}
switch (request.type) {
case RequestType::GET:
break;
case RequestType::POST:
hs = curl_slist_append(hs, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request.data.length());
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, request.data.c_str());
break;
default:
throw std::runtime_error("not implemented");
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(request.body.length()));
if (!request.body.empty()) {
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, request.body.data());
}
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, static_cast<long>(request.verifySSL));
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, static_cast<long>(request.verifySSL));
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, request.followLocation);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, static_cast<long>(request.followLocation));
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &entry->buffer);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &entry->headers);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/7.81.0");
if (request.timeoutMs > 0) {
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, request.timeoutMs);
}
#ifndef NDEBUG
// curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
#endif
if (request.maxSize == 0) {
curl_easy_setopt(
curl, CURLOPT_MAXFILESIZE, std::numeric_limits<long>::max()
@ -144,69 +146,105 @@ public:
} else {
curl_easy_setopt(curl, CURLOPT_MAXFILESIZE, request.maxSize);
}
curl_multi_add_handle(multiHandle, curl);
int running;
CURLMcode res = curl_multi_perform(multiHandle, &running);
if (res != CURLM_OK) {
auto message = curl_multi_strerror(res);
logger.error() << message << " (" << url << ")";
if (onReject) {
onReject(HTTP_BAD_GATEWAY, {});
{
CURLMcode res = curl_multi_add_handle(multiHandle, curl);
if (res != CURLM_OK) {
auto message = curl_multi_strerror(res);
logger.error() << message << " (" << request.url << ")";
if (request.onResponse) {
request.onResponse({0, {}, {}});
}
return;
}
url = "";
}
{
int running;
CURLMcode res = curl_multi_perform(multiHandle, &running);
if (res != CURLM_OK) {
auto message = curl_multi_strerror(res);
logger.error() << message << " (" << request.url << ")";
if (request.onResponse) {
request.onResponse({0, {}, {}});
}
return;
}
}
entry->request = std::move(request);
requests.push_back(std::move(entry));
}
void update() override {
int messagesLeft;
int running;
CURLMsg* msg;
CURLMcode res = curl_multi_perform(multiHandle, &running);
if (res != CURLM_OK) {
if (CURLMcode res = curl_multi_poll(
multiHandle,
nullptr,
0,
0,
nullptr
)) {
auto message = curl_multi_strerror(res);
logger.error() << message << " (" << url << ")";
if (onReject) {
onReject(HTTP_BAD_GATEWAY, {});
}
curl_multi_remove_handle(multiHandle, curl);
url = "";
logger.error() << message;
return;
}
if ((msg = curl_multi_info_read(multiHandle, &messagesLeft)) != nullptr) {
if(msg->msg == CURLMSG_DONE) {
curl_multi_remove_handle(multiHandle, curl);
}
int response;
curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &response);
if (response == HTTP_OK) {
long size;
if (!curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &size)) {
totalUpload += size;
}
if (!curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &size)) {
totalDownload += size;
}
totalDownload += buffer.size();
if (onResponse) {
onResponse(std::move(buffer));
}
} else {
logger.error()
<< "response code " << response << " (" << url << ")"
<< (buffer.empty()
? ""
: std::to_string(buffer.size()) + " byte(s)");
totalDownload += buffer.size();
if (onReject) {
onReject(response, std::move(buffer));
}
}
url = "";
int messagesLeft;
int running;
if (CURLMcode res = curl_multi_perform(multiHandle, &running)) {
auto message = curl_multi_strerror(res);
logger.error() << message;
return;
}
if (url.empty() && !requests.empty()) {
auto request = std::move(requests.front());
requests.pop();
processRequest(std::move(request));
CURLMsg* msg = curl_multi_info_read(multiHandle, &messagesLeft);
if (msg == nullptr || msg->msg != CURLMSG_DONE) {
return;
}
auto curl = msg->easy_handle;
auto found = std::find_if(
requests.begin(),
requests.end(),
[curl](const std::unique_ptr<ProcessingRequest>& entry) {
return entry && entry->curl == curl;
}
);
if (requests.empty() || found == requests.end()) {
logger.error() << "could not find request for cURL handle";
return;
}
auto entry = std::move(*found);
auto& req = entry->request;
requests.erase(found);
long response = -1;
CURLcode result = msg->data.result;
curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &response);
auto headers = std::move(entry->headers);
if (response == 0) {
auto message = std::string(curl_easy_strerror(result));
logger.error() << message << " (" << req.url << ")";
if (req.onResponse) {
req.onResponse(
{static_cast<int>(response),
std::move(headers),
std::vector<char>(
message.data(), message.data() + message.size()
)}
);
}
} else {
long size;
if (!curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &size)) {
totalUpload += size;
}
if (!curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &size)) {
totalDownload += size;
}
totalDownload += entry->buffer.size();
if (req.onResponse) {
req.onResponse({
static_cast<int>(response),
std::move(headers),
std::move(entry->buffer),
});
}
}
}
@ -219,16 +257,11 @@ public:
}
static std::unique_ptr<CurlRequests> create() {
auto curl = curl_easy_init();
if (curl == nullptr) {
throw std::runtime_error("could not initialzie cURL");
}
auto multiHandle = curl_multi_init();
if (multiHandle == nullptr) {
curl_easy_cleanup(curl);
throw std::runtime_error("could not initialzie cURL-multi");
throw std::runtime_error("could not initialize cURL-multi");
}
return std::make_unique<CurlRequests>(multiHandle, curl);
return std::make_unique<CurlRequests>(multiHandle);
}
};

View file

@ -51,27 +51,8 @@ Network::Network(std::unique_ptr<Requests> requests)
Network::~Network() = default;
void Network::get(
const std::string& url,
OnResponse onResponse,
OnReject onReject,
std::vector<std::string> headers,
long maxSize
) {
requests->get(url, onResponse, onReject, std::move(headers), maxSize);
}
void Network::post(
const std::string& url,
const std::string& fieldsData,
OnResponse onResponse,
OnReject onReject,
std::vector<std::string> headers,
long maxSize
) {
requests->post(
url, fieldsData, onResponse, onReject, std::move(headers), maxSize
);
void Network::request(HttpRequest request) {
requests->request(std::move(request));
}
Connection* Network::getConnection(u64id_t id, bool includePrivate) {

View file

@ -68,22 +68,7 @@ namespace network {
Network(std::unique_ptr<Requests> requests);
~Network();
void get(
const std::string& url,
OnResponse onResponse,
OnReject onReject = nullptr,
std::vector<std::string> headers = {},
long maxSize=0
);
void post(
const std::string& url,
const std::string& fieldsData,
OnResponse onResponse,
OnReject onReject = nullptr,
std::vector<std::string> headers = {},
long maxSize=0
);
void request(HttpRequest request);
[[nodiscard]] Connection* getConnection(u64id_t id, bool includePrivate);
[[nodiscard]] Server* getServer(u64id_t id, bool includePrivate) const;

View file

@ -10,33 +10,38 @@
#include <mutex>
namespace network {
using OnResponse = std::function<void(std::vector<char>)>;
using OnReject = std::function<void(int, std::vector<char>)>;
struct HttpResponse;
using OnResponse = std::function<void(HttpResponse)>;
using ConnectCallback = std::function<void(u64id_t, u64id_t)>;
using ConnectErrorCallback = std::function<void(u64id_t, std::string)>;
using ServerDatagramCallback = std::function<void(u64id_t sid, const std::string& addr, int port, const char* buffer, size_t length)>;
using ClientDatagramCallback = std::function<void(u64id_t cid, const char* buffer, size_t length)>;
struct HttpRequest {
std::string method;
std::string url;
std::string body;
std::vector<std::string> headers;
OnResponse onResponse;
bool followLocation = false;
bool verifySSL = true;
long maxSize = -1;
long timeoutMs = 0;
};
struct HttpResponse {
int status;
std::vector<std::string> headers;
std::vector<char> body;
};
class Requests {
public:
virtual ~Requests() {}
virtual void get(
const std::string& url,
OnResponse onResponse,
OnReject onReject=nullptr,
std::vector<std::string> headers = {},
long maxSize=0
) = 0;
virtual void post(
const std::string& url,
const std::string& data,
OnResponse onResponse,
OnReject onReject=nullptr,
std::vector<std::string> headers = {},
long maxSize=0
) = 0;
virtual void request(HttpRequest request) = 0;
[[nodiscard]] virtual size_t getTotalUpload() const = 0;
[[nodiscard]] virtual size_t getTotalDownload() const = 0;

View file

@ -485,6 +485,7 @@ void Entities::render(
if (eid.uid == fpsEntity) {
continue;
}
const auto& def = eid.def;
const auto& pos = transform.pos;
const auto& size = transform.size;
if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) {
@ -494,7 +495,13 @@ void Entities::render(
const auto& rigConfig = skeleton.config;
if (rigConfig) {
rigConfig->render(
assets, batch, skeleton, transform.rot, pos, size
assets,
batch,
skeleton,
def.lightingMode,
transform.rot,
pos,
size
);
}
}

View file

@ -14,4 +14,5 @@ void EntityDef::cloneTo(EntityDef& dst) {
dst.elasticity = elasticity;
dst.stepHeight = stepHeight;
dst.save = save;
dst.lightingMode = lightingMode;
}

View file

@ -8,10 +8,7 @@
#include "data/dv.hpp"
#include "maths/aabb.hpp"
#include "physics/Hitbox.hpp"
namespace rigging {
class SkeletonConfig;
}
#include "animation/rigging.hpp"
struct ComponentInstance {
std::string component;
@ -42,6 +39,9 @@ struct EntityDef {
/// @brief Solid entity material material
std::string material;
/// @brief Model lighting mode
ModelLightingMode lightingMode = ModelLightingMode::SOLID;
/// @brief Can the entity be interacted with cursor (on_attack, on_use)
bool selectable = true;

View file

@ -543,6 +543,14 @@ static std::basic_string<CharT> upper_case(const std::basic_string<CharT>& str)
return result;
}
std::string util::lower_case(const std::string& str) {
return ::lower_case(str);
}
std::string util::upper_case(const std::string& str) {
return ::upper_case(str);
}
std::wstring util::lower_case(const std::wstring& str) {
return ::lower_case(str);
}

View file

@ -101,6 +101,8 @@ namespace util {
std::string capitalized(const std::string& str);
std::string lower_case(const std::string& str);
std::string upper_case(const std::string& str);
std::wstring lower_case(const std::wstring& str);
std::wstring upper_case(const std::wstring& str);
std::wstring capitalized(const std::wstring& str);