Merge pull request #1072 from MihailRis/dev
Some checks are pending
x86-64 AppImage / build-appimage (ubuntu-22.04) (push) Waiting to run
Build / Build (push) Waiting to run
Macos Build / build-dmg (push) Waiting to run
Windows Build (CLang) / build-windows (clang, windows-latest) (push) Waiting to run
MSVC Build / build-windows (windows-2022) (push) Waiting to run

0.33 development
This commit is contained in:
MihailRis 2026-11-04 16:23:46 +03:00 • committed by GitHub
commit 97c790350d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
216 changed files with 6838 additions and 2590 deletions

View file

@ -28,9 +28,6 @@ find_package(CURL REQUIRED)
find_package(OpenSSL 3.0 REQUIRED COMPONENTS Crypto)
find_package(glfw3 REQUIRED)
find_package(Freetype REQUIRED)
if(NOT APPLE)
find_package(EnTT REQUIRED)
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
find_package(vorbis REQUIRED)

View file

@ -88,6 +88,7 @@ void Skeleton::deserialize(const dv::value& root) {
dv::get_mat(posearr[i], pose.matrices[i]);
}
}
boundsDirty = true;
}
void Skeleton::setConfig(std::shared_ptr<const SkeletonConfig> rigConfig) {
@ -105,6 +106,7 @@ void Skeleton::setConfig(std::shared_ptr<const SkeletonConfig> rigConfig) {
for (size_t i = 0; i < bonesCount; i++) {
flags[i].visible = true;
}
boundsDirty = true;
}
static void get_all_nodes(std::vector<Bone*>& nodes, Bone* node) {
@ -160,17 +162,87 @@ void SkeletonConfig::update(
const glm::vec3& position,
const glm::vec3& scale
) const {
if (skeleton.interpolation.isEnabled()) {
const auto& interpolation = skeleton.interpolation;
update(
0,
skeleton,
root.get(),
build_matrix(rotation, interpolation.getCurrent(), scale)
);
} else {
update(0, skeleton, root.get(), build_matrix(rotation, position, scale));
glm::vec3 pos = position;
const auto& interpolation = skeleton.interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) {
pos = interpolation.getCurrent();
}
glm::mat3 rot = rotation;
const auto& rotationInterpolation = skeleton.rotationInterpolation;
if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) {
rot = glm::mat3_cast(rotationInterpolation.getCurrent());
}
update(0, skeleton, root.get(), build_matrix(rot, pos, scale));
}
static float max_component(const glm::vec3& v) {
return glm::max(glm::abs(v.x), glm::max(glm::abs(v.y), glm::abs(v.z)));
}
static float farthest_corner_distance(
const glm::mat4& matrix, const AABB& aabb, const glm::vec3& origin
) {
glm::vec3 center = glm::vec3(matrix * glm::vec4(aabb.center(), 1.0f));
glm::vec3 halfSize = aabb.size() * 0.5f;
glm::vec3 extent = glm::abs(glm::vec3(matrix[0])) * halfSize.x +
glm::abs(glm::vec3(matrix[1])) * halfSize.y +
glm::abs(glm::vec3(matrix[2])) * halfSize.z;
return glm::length(glm::abs(center - origin) + extent);
}
void SkeletonConfig::processModels(
const Assets& assets,
Skeleton& skeleton,
const glm::vec3& position,
const glm::vec3& scale,
ModelBatch* batch,
ModelLightingMode lightingMode,
bool translucent
) const {
float radius = 0.0f;
bool pending = false;
for (size_t i = 0; i < nodes.size(); i++) {
auto* node = nodes[i];
if (!skeleton.flags[i].visible) {
continue;
}
node->model.refresh(assets);
auto model = node->model.model.lock(); // TODO: cache model pointer during frame
auto& modelOverride = skeleton.modelOverrides.at(i);
if (modelOverride.updateFlag) {
modelOverride.refresh(assets);
}
if (auto foundOverride = modelOverride.model.lock()) {
model = std::move(foundOverride);
}
if (model == nullptr) {
if (!node->model.name.empty()) {
node->model.updateFlag = true;
pending = true;
}
continue;
}
const auto& matrix = skeleton.calculated.matrices[i];
radius = glm::max(
radius, farthest_corner_distance(matrix, model->getBounds(), position)
);
if (batch == nullptr) {
continue;
}
batch->draw(
matrix,
skeleton.tint * skeleton.boneTints[i],
lightingMode == ModelLightingMode::SOLID
? position - glm::vec3(matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f))
: glm::vec3(),
model,
&skeleton.textures,
translucent
);
}
float maxScale = max_component(scale);
skeleton.boundsRadius = maxScale > 0.0f ? radius / maxScale : radius;
skeleton.boundsDirty = pending;
}
void SkeletonConfig::render(
@ -180,7 +252,8 @@ void SkeletonConfig::render(
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
const glm::vec3& scale,
bool translucent
) const {
if (skeleton.config->root == nullptr) {
return;
@ -190,39 +263,31 @@ void SkeletonConfig::render(
if (!skeleton.visible) {
return;
}
for (size_t i = 0; i < nodes.size(); i++) {
auto* node = nodes[i];
if (!skeleton.flags[i].visible) {
continue;
}
node->model.refresh(assets);
auto model = node->model.model.lock().get(); // TODO: cache model pointer during frame
auto& modelOverride = skeleton.modelOverrides.at(i);
if (modelOverride.updateFlag) {
modelOverride.refresh(assets);
}
if (auto foundOverride = modelOverride.model.lock()) {
model = foundOverride.get();
}
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
);
processModels(
assets, skeleton, position, scale, &batch, lightingMode, translucent
);
}
void SkeletonConfig::updateBounds(
const Assets& assets,
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
) const {
if (skeleton.config->root == nullptr) {
return;
}
update(skeleton, rotation, position, scale);
processModels(
assets,
skeleton,
position,
scale,
nullptr,
ModelLightingMode::SOLID,
false
);
}
const Bone* SkeletonConfig::find(std::string_view str) const {

View file

@ -97,10 +97,15 @@ namespace rigging {
std::vector<ModelReference> modelOverrides;
bool visible;
bool culled = false;
/// @brief Bounding radius of visible models around entity position,
/// divided by the largest scale component
float boundsRadius = 0.0f;
bool boundsDirty = true;
glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f};
std::vector<glm::vec4> boneTints;
util::VecInterpolation<3, float> interpolation {false};
util::RotationInterpolation rotationInterpolation {false};
Skeleton(std::shared_ptr<const SkeletonConfig> config);
@ -126,6 +131,16 @@ namespace rigging {
size_t update(
size_t index, Skeleton& skeleton, Bone* node, const glm::mat4& matrix
) const;
void processModels(
const Assets& assets,
Skeleton& skeleton,
const glm::vec3& position,
const glm::vec3& scale,
ModelBatch* batch,
ModelLightingMode lightingMode,
bool translucent
) const;
public:
SkeletonConfig(
const std::string& name,
@ -147,6 +162,15 @@ namespace rigging {
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale,
bool translucent = false
) const;
void updateBounds(
const Assets& assets,
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
) const;

View file

@ -19,8 +19,14 @@
#include "util/ThreadPool.hpp"
#include "voxels/Block.hpp"
#include <algorithm>
#include <cctype>
#include <map>
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>
namespace fs = std::filesystem;
@ -151,24 +157,14 @@ static std::string assets_def_folder(AssetType tag) {
return "<error>";
}
void AssetsLoader::processPreload(
AssetType tag, const std::string& name, const dv::value& map
static std::shared_ptr<AssetCfg> create_preload_config(
AssetType tag, const dv::value& map
) {
std::string defFolder = assets_def_folder(tag);
std::string path = defFolder + "/" + name;
if (map == nullptr) {
add(tag, path, name, nullptr, true);
return;
}
std::shared_ptr<AssetCfg> config = nullptr;
map.at("path").get(path);
logger.debug() << "processing preload " << util::quote(name)
<< " path: " << util::quote(path);
switch (tag) {
case AssetType::SOUND: {
bool keepPCM = false;
config = std::make_shared<SoundCfg>(map.at("keep-pcm").get(keepPCM));
break;
map.at("keep-pcm").get(keepPCM);
return std::make_shared<SoundCfg>(keepPCM);
}
case AssetType::ATLAS: {
std::string typeName = "atlas";
@ -177,44 +173,295 @@ void AssetsLoader::processPreload(
if (typeName == "separate") {
type = AtlasType::SEPARATE;
}
config = std::make_shared<AtlasCfg>(type);
break;
return std::make_shared<AtlasCfg>(type);
}
case AssetType::POST_EFFECT: {
bool advanced = false;
map.at("advanced").get(advanced);
config = std::make_shared<PostEffectCfg>(advanced);
break;
return std::make_shared<PostEffectCfg>(advanced);
}
case AssetType::MODEL: {
bool squashed = false;
map.at("squash").get(squashed);
config = std::make_shared<ModelCfg>(squashed);
break;
return std::make_shared<ModelCfg>(squashed);
}
case AssetType::FONT: {
int size = DEFAULT_FONT_SIZE;
map.at("size").get(size);
config = std::make_unique<FontCfg>(size);
break;
return std::make_shared<FontCfg>(size);
}
default:
break;
return nullptr;
}
}
static bool is_pattern(const std::string& name) {
return name.find('*') != std::string::npos;
}
static bool match_wildcard(std::string_view pattern, std::string_view str) {
size_t p = 0;
size_t s = 0;
size_t starPos = std::string_view::npos;
size_t starMatch = 0;
while (s < str.length()) {
if (p < pattern.length() && pattern[p] == '*') {
starPos = p++;
starMatch = s;
} else if (p < pattern.length() && pattern[p] == str[s]) {
p++;
s++;
} else if (starPos != std::string_view::npos) {
p = starPos + 1;
s = ++starMatch;
} else {
return false;
}
}
while (p < pattern.length() && pattern[p] == '*') {
p++;
}
return p == pattern.length();
}
static std::vector<std::string> split_pattern(const std::string& pattern) {
if (pattern.find("**") != std::string::npos) {
throw std::runtime_error(
"'**' is not supported in preload pattern " + util::quote(pattern)
);
}
std::vector<std::string> segments;
size_t start = 0;
while (start < pattern.length()) {
size_t end = pattern.find('/', start);
if (end == std::string::npos) {
end = pattern.length();
}
if (end > start) {
auto segment = pattern.substr(start, end - start);
if (segment == "." || segment == "..") {
throw std::runtime_error(
"relative segments are not allowed in preload pattern " +
util::quote(pattern)
);
}
segments.push_back(std::move(segment));
}
start = end + 1;
}
return segments;
}
static void glob(
const io::path& folder,
const std::vector<std::string>& segments,
size_t index,
const std::string& relative,
bool directories,
std::vector<std::string>& out
) {
const auto& segment = segments[index];
bool last = index + 1 == segments.size();
auto visit = [&](const std::string& name) {
io::path path = folder / name;
std::string rel = relative.empty() ? name : relative + "/" + name;
if (!last) {
if (io::is_directory(path)) {
glob(path, segments, index + 1, rel, directories, out);
}
} else if (directories ? io::is_directory(path)
: io::is_regular_file(path)) {
out.push_back(std::move(rel));
}
};
if (!is_pattern(segment)) {
visit(segment);
return;
}
if (!io::is_directory(folder)) {
return;
}
for (const auto& entry : io::directory_iterator(folder)) {
auto name = entry.name();
if (match_wildcard(segment, name)) {
visit(name);
}
}
}
static std::vector<std::string> asset_search_folders(AssetType tag) {
if (tag == AssetType::ANIMATION) {
return {ANIMATION_FOLDER, ANIMATION_FOLDER_ALIAS};
}
return {assets_def_folder(tag)};
}
static std::vector<std::string> asset_extensions(AssetType tag) {
switch (tag) {
case AssetType::ANIMATION:
return {".vca"};
case AssetType::FONT:
return {".png", ".ttf", ".otf"};
case AssetType::MODEL:
return {".vec3", ".obj", ".xml", ".vcm"};
case AssetType::POST_EFFECT:
return {".glsl"};
case AssetType::SHADER:
return {".glslv", ".glslf"};
case AssetType::SKELETON:
return {".json"};
case AssetType::SOUND:
return {".ogg", ".wav"};
case AssetType::TEXTURE:
return {".png"};
default:
return {};
}
}
static std::optional<std::string> strip_index_suffix(const std::string& stem) {
size_t pos = stem.rfind('_');
if (pos == std::string::npos || pos + 1 == stem.length()) {
return std::nullopt;
}
for (size_t i = pos + 1; i < stem.length(); i++) {
if (!std::isdigit(static_cast<unsigned char>(stem[i]))) {
return std::nullopt;
}
}
return stem.substr(0, pos);
}
struct PreloadMatch {
std::string name;
std::string path;
};
/// @brief Resolve asset name for a file matched by preload pattern
/// @param folder asset type folder the file was found in
/// @param relative file path relative to the folder
/// @return std::nullopt if the file is not a loadable asset of the type
static std::optional<PreloadMatch> resolve_preload_file(
AssetType tag, const io::path& folder, const std::string& relative
) {
io::path file = relative;
std::string extension = file.extension();
const auto& extensions = asset_extensions(tag);
if (std::find(extensions.begin(), extensions.end(), extension) ==
extensions.end()) {
return std::nullopt;
}
std::string base = relative.substr(0, relative.length() - extension.length());
std::string defFolder = assets_def_folder(tag);
if (tag == AssetType::FONT) {
if (extension != ".png") {
return PreloadMatch {base, defFolder + "/" + relative};
}
auto fontName = strip_index_suffix(base);
if (!fontName || !io::exists(folder / (*fontName + "_0.png"))) {
return std::nullopt;
}
base = std::move(*fontName);
} else if (tag == AssetType::SOUND) {
auto soundName = strip_index_suffix(base);
if (soundName && (io::exists(folder / (*soundName + extension)) ||
io::exists(folder / (*soundName + "_0" + extension)))) {
base = std::move(*soundName);
}
}
return PreloadMatch {base, defFolder + "/" + base};
}
static std::vector<PreloadMatch> find_preload_matches(
AssetType tag, const io::path& packFolder, const std::string& pattern
) {
auto segments = split_pattern(pattern);
if (segments.empty()) {
return {};
}
bool directories = pattern.back() == '/' || tag == AssetType::ATLAS;
if (directories && tag != AssetType::ATLAS) {
throw std::runtime_error(
"directory pattern " + util::quote(pattern) +
" is not applicable to assets of type " + assets_def_folder(tag)
);
}
std::map<std::string, std::string> found;
for (const auto& searchFolder : asset_search_folders(tag)) {
io::path folder = packFolder / searchFolder;
std::vector<std::string> files;
glob(folder, segments, 0, "", directories, files);
for (const auto& relative : files) {
if (directories) {
found.try_emplace(relative, assets_def_folder(tag) + "/" + relative);
continue;
}
if (auto match = resolve_preload_file(tag, folder, relative)) {
found.try_emplace(std::move(match->name), std::move(match->path));
}
}
}
std::vector<PreloadMatch> matches;
matches.reserve(found.size());
for (auto& [name, path] : found) {
matches.push_back(PreloadMatch {name, std::move(path)});
}
return matches;
}
void AssetsLoader::processPreload(
AssetType tag,
const std::string& name,
const dv::value& map,
const io::path& packFolder
) {
std::shared_ptr<AssetCfg> config =
map == nullptr ? nullptr : create_preload_config(tag, map);
if (is_pattern(name)) {
if (map != nullptr && map.has("path")) {
throw std::runtime_error(
"'path' cannot be used with preload pattern " + util::quote(name)
);
}
auto matches = find_preload_matches(tag, packFolder, name);
if (matches.empty()) {
logger.warning() << "preload pattern " << util::quote(name)
<< " matches nothing in " << packFolder.string();
}
for (const auto& match : matches) {
logger.debug() << "processing preload " << util::quote(match.name)
<< " path: " << util::quote(match.path);
add(tag, match.path, match.name, config, true);
}
return;
}
std::string path = assets_def_folder(tag) + "/" + name;
if (map != nullptr) {
map.at("path").get(path);
logger.debug() << "processing preload " << util::quote(name)
<< " path: " << util::quote(path);
}
add(tag, path, name, std::move(config), true);
}
void AssetsLoader::processPreloadList(AssetType tag, const dv::value& list) {
void AssetsLoader::processPreloadList(
AssetType tag, const dv::value& list, const io::path& packFolder
) {
if (list == nullptr) {
return;
}
for (const auto& value : list) {
switch (value.getType()) {
case dv::value_type::string:
processPreload(tag, value.asString(), nullptr);
processPreload(tag, value.asString(), nullptr, packFolder);
break;
case dv::value_type::object:
processPreload(tag, value["name"].asString(), value);
processPreload(tag, value["name"].asString(), value, packFolder);
break;
default:
throw std::runtime_error("invalid entry type");
@ -224,15 +471,17 @@ void AssetsLoader::processPreloadList(AssetType tag, const dv::value& list) {
void AssetsLoader::processPreloadConfig(const io::path& file) {
auto root = io::read_json(file);
processPreloadList(AssetType::ANIMATION, root["animation"]);
processPreloadList(AssetType::ATLAS, root["atlases"]);
processPreloadList(AssetType::FONT, root["fonts"]);
processPreloadList(AssetType::MODEL, root["models"]);
processPreloadList(AssetType::POST_EFFECT, root["post-effects"]);
processPreloadList(AssetType::SHADER, root["shaders"]);
processPreloadList(AssetType::SKELETON, root["skeletons"]);
processPreloadList(AssetType::SOUND, root["sounds"]);
processPreloadList(AssetType::TEXTURE, root["textures"]);
io::path folder = file.parent();
processPreloadList(AssetType::ANIMATION, root["animations"], folder);
processPreloadList(AssetType::ANIMATION, root["animation"], folder);
processPreloadList(AssetType::ATLAS, root["atlases"], folder);
processPreloadList(AssetType::FONT, root["fonts"], folder);
processPreloadList(AssetType::MODEL, root["models"], folder);
processPreloadList(AssetType::POST_EFFECT, root["post-effects"], folder);
processPreloadList(AssetType::SHADER, root["shaders"], folder);
processPreloadList(AssetType::SKELETON, root["skeletons"], folder);
processPreloadList(AssetType::SOUND, root["sounds"], folder);
processPreloadList(AssetType::TEXTURE, root["textures"], folder);
// layouts are loaded automatically
}

View file

@ -149,9 +149,14 @@ private:
AssetsLoadInfo& assetsLoadInfo;
void processPreload(
AssetType tag, const std::string& name, const dv::value& map
AssetType tag,
const std::string& name,
const dv::value& map,
const io::path& packFolder
);
void processPreloadList(
AssetType tag, const dv::value& list, const io::path& packFolder
);
void processPreloadList(AssetType tag, const dv::value& list);
void processPreloadConfig(const io::path& file);
void processPreloadConfigs(const Content* content);
};

View file

@ -44,6 +44,18 @@ static bool load_animated_texture(
Atlas* dstAtlas
);
static io::path find_animation(const ResPaths& paths, const std::string& filename) {
auto path = paths.find(filename + ".vca");
const auto prefix = ANIMATION_FOLDER + "/";
if (io::is_regular_file(path) || filename.rfind(prefix, 0) != 0) {
return path;
}
auto alias = paths.find(
ANIMATION_FOLDER_ALIAS + "/" + filename.substr(prefix.length()) + ".vca"
);
return io::is_regular_file(alias) ? alias : path;
}
assetload::postfunc assetload::animation(
AssetsLoader& loader,
const ResPaths& paths,
@ -51,7 +63,7 @@ assetload::postfunc assetload::animation(
const std::string& name,
const std::shared_ptr<AssetCfg>&
) {
auto path = paths.find(filename + ".vca");
auto path = find_animation(paths, filename);
loader.attachToFile(path, {name, AssetType::ANIMATION});
if (io::is_regular_file(path)) {

View file

@ -262,6 +262,18 @@ std::unique_ptr<Sound> audio::create_sound(
}
std::unique_ptr<PCMStream> audio::open_PCM_stream(const io::path& file) {
if (!io::exists(file)) {
io::path candidate = file.string() + ".wav";
if (io::exists(candidate)) {
return wav::create_stream(candidate);
}
candidate = file.string() + ".ogg";
if (io::exists(candidate)) {
return ogg::create_stream(candidate);
}
throw std::runtime_error("file not found '" + file.string() + "'");
}
std::string ext = file.extension();
if (ext == ".wav" || ext == ".WAV") {
return wav::create_stream(file);

View file

@ -134,6 +134,7 @@ public:
auto model = std::make_unique<Model>();
buildMeshes(*model);
model->clean();
model->calcBounds();
return model;
}
};

View file

@ -469,6 +469,7 @@ static VcmModel load_model(const xmlelement& root) {
perform_element(*elem, builder, ctx);
}
model.calcBounds();
vcmModel.parts["root"] = std::move(model);
vcmModel.skeleton = SkeletonConfig(
"",

View file

@ -6,7 +6,12 @@
#include <string>
inline constexpr int ENGINE_VERSION_MAJOR = 0;
inline constexpr int ENGINE_VERSION_MINOR = 32;
inline constexpr int ENGINE_VERSION_MINOR = 33;
#ifdef VC_VERSION_PATCH
inline constexpr int ENGINE_VERSION_PATCH = VC_VERSION_PATCH;
#else
inline constexpr int ENGINE_VERSION_PATCH = 0;
#endif
#ifdef NDEBUG
inline constexpr bool ENGINE_DEBUG_BUILD = false;
@ -14,7 +19,13 @@ inline constexpr bool ENGINE_DEBUG_BUILD = false;
inline constexpr bool ENGINE_DEBUG_BUILD = true;
#endif // NDEBUG
inline const std::string ENGINE_VERSION_STRING = "0.32";
inline const std::string ENGINE_VERSION_STRING =
std::to_string(ENGINE_VERSION_MAJOR) + "." +
std::to_string(ENGINE_VERSION_MINOR)
#ifdef VC_VERSION_PATCH
+ "." + std::to_string(ENGINE_VERSION_PATCH)
#endif
;
inline constexpr uint MAX_SUBPROCESSES = 1;
inline constexpr uint MAX_SUBPROCESS_DEPTH = 2;
@ -75,7 +86,8 @@ inline constexpr int DEFAULT_FONT_SIZE = 16;
inline constexpr int DEFAULT_PRE_RENDER_FONT_PAGES = 1; // must be at least 1
inline const std::string ANIMATION_FOLDER = "animation";
inline const std::string ANIMATION_FOLDER = "animations";
inline const std::string ANIMATION_FOLDER_ALIAS = "animation";
inline const std::string FONTS_FOLDER = "fonts";
inline const std::string LAYOUTS_FOLDER = "layouts";
inline const std::string MODELS_FOLDER = "models";

View file

@ -1,5 +1,8 @@
#include "ContentBuilder.hpp"
#include "core_defs.hpp"
#include "util/stringutil.hpp"
ContentBuilder::~ContentBuilder() = default;
void ContentBuilder::add(std::unique_ptr<ContentPackRuntime> pack) {
@ -19,6 +22,11 @@ std::unique_ptr<Content> ContentBuilder::build() {
for (const std::string& name : blocks.names) {
Block& def = *blocks.defs[name];
// Filling auto fields
if (def.caption.empty()) {
def.caption = util::id_to_caption(def.name);
}
// Generating runtime info
def.rt.id = blockDefsIndices.size();
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
@ -31,39 +39,50 @@ std::unique_ptr<Content> ContentBuilder::build() {
variant.culling == CullingMode::OPTIONAL;
};
auto prepareHitboxes = [&def](Variant& variant) {
if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {
auto& rotated = variant.rt.hitboxes[i];
rotated.clear();
rotated.reserve(variant.hitboxes.size());
for (AABB aabb : variant.hitboxes) {
def.rotations.variants[i].transform(aabb);
aabb.fix();
rotated.push_back(aabb);
}
}
} else {
variant.rt.hitboxes[0] = variant.hitboxes;
}
};
const float EPSILON = 0.01f;
auto isFullHitbox = [&def, EPSILON](const Variant& variant) {
return !variant.hitboxes.empty() &&
glm::i8vec3(variant.hitboxes[0].size() + EPSILON) == def.size;
};
bool fullHitboxes;
if (def.variants) {
fullHitboxes = true;
for (auto& variant : def.variants->variants) {
variant.rt.solid = isSolid(variant) || def.explictlySolid;
prepareHitboxes(variant);
fullHitboxes = fullHitboxes && isFullHitbox(variant);
}
def.defaults = def.variants->variants.at(0);
} else {
def.defaults.rt.solid = isSolid(def.defaults) || def.explictlySolid;
prepareHitboxes(def.defaults);
fullHitboxes = isFullHitbox(def.defaults);
}
def.rt.solid = def.defaults.rt.solid;
const float EPSILON = 0.01f;
def.rt.solid = def.rt.solid &&
def.obstacle &&
(glm::i8vec3(def.hitboxes[0].size() + EPSILON) == def.size);
def.rt.solid = def.defaults.rt.solid && def.obstacle && fullHitboxes;
def.rt.extended = def.size.x > 1 || def.size.y > 1 || def.size.z > 1;
if (def.material.empty()) {
defaults.at("block-material").get(def.material);
}
if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {
def.rt.hitboxes[i].reserve(def.hitboxes.size());
for (AABB aabb : def.hitboxes) {
def.rotations.variants[i].transform(aabb);
aabb.fix();
def.rt.hitboxes[i].push_back(aabb);
}
}
} else {
def.rt.hitboxes[0] = def.hitboxes;
}
blockDefsIndices.push_back(&def);
groups->insert(def.defaults.drawGroup); // FIXME: variants
}
@ -72,6 +91,11 @@ std::unique_ptr<Content> ContentBuilder::build() {
for (const std::string& name : items.names) {
ItemDef& def = *items.defs[name];
// Filling auto fields
if (def.caption.empty()) {
def.caption = util::id_to_caption(def.name);
}
// Generating runtime info
def.rt.id = itemDefsIndices.size();
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
@ -105,8 +129,17 @@ std::unique_ptr<Content> ContentBuilder::build() {
// Now, it's time to resolve foreign keys
for (Block* def : blockDefsIndices) {
def->rt.pickingItem = content->items.require(def->pickingItem).rt.id;
def->rt.surfaceReplacement = content->blocks.require(def->surfaceReplacement).rt.id;
def->rt.pickingItem =
content->items
.require(
def->pickingItem.empty()
? (def->hidden ? CORE_EMPTY
: def->name + BLOCK_ITEM_SUFFIX)
: def->pickingItem
)
.rt.id;
def->rt.surfaceReplacement =
content->blocks.require(def->surfaceReplacement).rt.id;
if (def->properties == nullptr) {
def->properties = dv::object();
}
@ -123,6 +156,13 @@ std::unique_ptr<Content> ContentBuilder::build() {
def->properties["script-file"] = def->scriptFile;
}
for (EntityDef* def : entityDefsIndices) {
if (def->properties == nullptr) {
def->properties = dv::object();
}
def->properties["name"] = def->name;
}
for (auto& [name, def] : content->generators.getDefs()) {
def->prepare(content.get());
}

View file

@ -38,16 +38,21 @@ public:
T& create(const std::string& id, bool* created = nullptr) {
auto found = defs.find(id);
if (found != defs.end()) {
if (created) *created = false;
if (created) {
*created = false;
}
return *found->second;
}
if (created) *created = true;
if (created) {
*created = true;
}
checkIdentifier(id);
allNames[id] = type;
names.push_back(id);
defs[id] = std::make_unique<T>(id);
return *defs[id];
}
// Only fetch existing definition, return null otherwise.
T* get(const std::string& id) {
auto found = defs.find(id);

View file

@ -180,7 +180,8 @@ void ContentUnitLoader<DefT>::loadUnit(
auto configFile = folder / (defsDir + "/" + name + ".json");
if (io::exists(configFile)) {
try {
loadUnit(def, full, configFile);
dv::value root = io::read_json(configFile);
loadUnit(def, full, std::move(root));
} catch (const std::runtime_error& err) {
throw std::runtime_error(
"file " + util::quote(configFile.string()) + ": " +
@ -286,12 +287,15 @@ void ContentLoader::loadContent(const dv::value& root) {
};
ContentUnitLoader<Block>(*pack, builder.blocks, "blocks",
[this](Block& def) {
[this](const Block& def) {
if (!def.hidden) {
bool created;
auto& item = builder.items.create(def.name + BLOCK_ITEM_SUFFIX, &created);
auto& item = builder.items.create(
def.name + BLOCK_ITEM_SUFFIX, &created
);
item.generated = true;
item.caption = def.caption;
item.caption = def.caption.empty() ? util::id_to_caption(def.name)
: def.caption;
item.iconType = ItemIconType::BLOCK;
item.icon = def.name;
item.placingBlock = def.name;

View file

@ -42,6 +42,21 @@ static void perform_user_block_fields(
layout = StructLayout::create(fields);
}
static AABB load_hitbox(const dv::value& box) {
if (box.size() < 6) {
throw std::runtime_error("hitbox requires 6 elements");
}
AABB aabb;
aabb.a = glm::vec3(
box[0].asNumber(), box[1].asNumber(), box[2].asNumber()
);
aabb.b = glm::vec3(
box[3].asNumber(), box[4].asNumber(), box[5].asNumber()
);
aabb.b += aabb.a;
return aabb;
}
static void load_variant(
Variant& variant, const dv::value& root, const std::string& name
) {
@ -86,12 +101,22 @@ static void load_variant(
logger.error() << "unknown culling mode: " << cullingModeName;
}
root.at("draw-group").get(variant.drawGroup);
if (auto found = root.at("hitboxes")) {
const auto& boxarr = *found;
variant.hitboxes.clear();
variant.hitboxes.reserve(boxarr.size());
for (uint i = 0; i < boxarr.size(); i++) {
variant.hitboxes.push_back(load_hitbox(boxarr[i]));
}
} else if (auto found = root.at("hitbox")) {
variant.hitboxes = {load_hitbox(*found)};
}
}
template<> void ContentUnitLoader<Block>::loadUnit(
Block& def, const std::string& name, const io::path& file
Block& def, const std::string& name, dv::value root
) {
auto root = io::read_json(file);
process_properties(def, name, root);
process_tags(def, root);
@ -100,7 +125,7 @@ template<> void ContentUnitLoader<Block>::loadUnit(
auto parentDef = builder.get(parentName);
if (parentDef == nullptr) {
throw std::runtime_error(
"Failed to find parent(" + parentName + ") for " + name
"failed to find parent(" + parentName + ") for " + name
);
}
parentDef->cloneTo(def);
@ -120,7 +145,7 @@ template<> void ContentUnitLoader<Block>::loadUnit(
stateBased.at("offset").get(offset);
stateBased.at("bits").get(bitsCount);
if (offset < 0 || bitsCount <= 0 || offset + bitsCount > 8) {
throw std::runtime_error("Invalid state-based bits configuration");
throw std::runtime_error("invalid state-based bits configuration");
}
def.variants = std::make_unique<Variants>();
@ -136,6 +161,13 @@ template<> void ContentUnitLoader<Block>::loadUnit(
def.variants->variants.push_back(def.defaults);
}
}
} else if (def.variants) {
auto& variants = def.variants->variants;
variants.at(0) = def.defaults;
for (int i = 1; i < variants.size(); i++) {
load_variant(variants.at(i), root, name);
}
}
root.at("material").get(def.material);
@ -158,34 +190,6 @@ template<> void ContentUnitLoader<Block>::loadUnit(
def.rotatable = false;
}
// block hitbox AABB [x, y, z, width, height, depth]
if (auto found = root.at("hitboxes")) {
const auto& boxarr = *found;
def.hitboxes.resize(boxarr.size());
for (uint i = 0; i < boxarr.size(); i++) {
const auto& box = boxarr[i];
auto& hitboxesIndex = def.hitboxes[i];
hitboxesIndex.a = glm::vec3(
box[0].asNumber(), box[1].asNumber(), box[2].asNumber()
);
hitboxesIndex.b = glm::vec3(
box[3].asNumber(), box[4].asNumber(), box[5].asNumber()
);
hitboxesIndex.b += hitboxesIndex.a;
}
} else if (auto found = root.at("hitbox")) {
const auto& box = *found;
AABB aabb;
aabb.a = glm::vec3(
box[0].asNumber(), box[1].asNumber(), box[2].asNumber()
);
aabb.b = glm::vec3(
box[3].asNumber(), box[4].asNumber(), box[5].asNumber()
);
aabb.b += aabb.a;
def.hitboxes = {aabb};
}
// block light emission [r, g, b] where r,g,b in range [0..15]
if (auto found = root.at("emission")) {
const auto& emissionarr = *found;
@ -219,11 +223,19 @@ template<> void ContentUnitLoader<Block>::loadUnit(
);
}
// should variant modify hitbox?
if (def.defaults.model.type == BlockModelType::BLOCK &&
(def.size.x != 1 || def.size.y != 1 || def.size.z != 1)) {
def.defaults.model.type = BlockModelType::AABB;
def.hitboxes = {AABB(def.size)};
if (def.size.x != 1 || def.size.y != 1 || def.size.z != 1) {
auto applySize = [&def](Variant& variant) {
if (variant.model.type == BlockModelType::BLOCK) {
variant.model.type = BlockModelType::AABB;
variant.hitboxes = {AABB(def.size)};
}
};
applySize(def.defaults);
if (def.variants) {
for (auto& variant : def.variants->variants) {
applySize(variant);
}
}
}
// grounding behaviour
@ -243,6 +255,7 @@ template<> void ContentUnitLoader<Block>::loadUnit(
root.at("sky-light-passing").get(def.skyLightPassing);
root.at("shadeless").get(def.shadeless);
root.at("ambient-occlusion").get(def.ambientOcclusion);
root.at("uv-lock").get(def.uvLock);
root.at("breakable").get(def.breakable);
root.at("selectable").get(def.selectable);
root.at("grounded").get(def.grounded);

View file

@ -25,7 +25,7 @@ public:
postFunc(std::move(postFunc)) {
}
void loadUnit(DefT& def, const std::string& full, const std::string& name);
void loadUnit(DefT& def, const std::string& name, const io::path& file);
void loadUnit(DefT& def, const std::string& name, dv::value root);
void loadDefs(const dv::value& root);
private:
const ContentPack& pack;

View file

@ -1,5 +1,6 @@
#define VC_ENABLE_REFLECTION
#include "ContentUnitLoader.hpp"
#include "ContentLoadingCommons.hpp"
#include "../ContentBuilder.hpp"
#include "coders/json.hpp"
@ -13,9 +14,9 @@
static debug::Logger logger("entity-content-loader");
template<> void ContentUnitLoader<EntityDef>::loadUnit(
EntityDef& def, const std::string& name, const io::path& file
EntityDef& def, const std::string& name, dv::value root
) {
auto root = io::read_json(file);
process_properties(def, name, root);
if (root.has("parent")) {
const auto& parentName = root["parent"].asString();
@ -94,6 +95,7 @@ template<> void ContentUnitLoader<EntityDef>::loadUnit(
root.at("mass").get(def.mass);
root.at("elasticity").get(def.elasticity);
root.at("step-height").get(def.stepHeight);
root.at("translucent").get(def.translucent);
std::string lightingModeName;
root.at("lighting-mode").get(lightingModeName);

View file

@ -15,9 +15,8 @@ static debug::Logger logger("item-content-loader");
template<> void ContentUnitLoader<ItemDef>::loadUnit(
ItemDef& def, const std::string& name, const io::path& file
ItemDef& def, const std::string& name, dv::value root
) {
auto root = io::read_json(file);
process_properties(def, name, root);
process_tags(def, root);

View file

@ -39,7 +39,7 @@ void corecontent::setup(Input* input, ContentBuilder& builder) {
for (uint i = 0; i < 6; i++) {
block.defaults.textureFaces[i] = "obstacle";
}
block.hitboxes = {AABB()};
block.defaults.hitboxes = {AABB()};
block.breakable = false;
ItemDef& item = builder.items.create(CORE_OBSTACLE+".item");
item.iconType = ItemIconType::BLOCK;
@ -55,7 +55,7 @@ void corecontent::setup(Input* input, ContentBuilder& builder) {
block.defaults.drawGroup = -1;
block.skyLightPassing = true;
block.lightPassing = true;
block.hitboxes = {AABB()};
block.defaults.hitboxes = {AABB()};
block.obstacle = false;
ItemDef& item = builder.items.create(CORE_STRUCT_AIR+".item");
item.iconType = ItemIconType::BLOCK;

View file

@ -28,6 +28,7 @@ void cmd::start_stdin_cmd_reader(Engine& engine) {
if (line.empty()) {
continue;
}
logger.debug() << "input received: " << line;
engine.postRunnable([line, &interpreter] () {
try {
auto result = interpreter.execute(line);

View file

@ -42,8 +42,7 @@ WindowControl::Result WindowControl::initialize() {
#endif
title += "VoxelCore v";
if (buildName.empty()) {
title += std::to_string(ENGINE_VERSION_MAJOR) + "." +
std::to_string(ENGINE_VERSION_MINOR);
title += ENGINE_VERSION_STRING;
} else {
title += buildName;
}

View file

@ -1,6 +1,6 @@
#include "ContentGfxCache.hpp"
#include <string>
#define GLM_ENABLE_EXPERIMENTAL
#include "UiDocument.hpp"
#include "assets/Assets.hpp"
@ -8,13 +8,80 @@
#include "content/ContentPack.hpp"
#include "graphics/core/Atlas.hpp"
#include "maths/UVRegion.hpp"
#include "maths/util.hpp"
#include "voxels/Block.hpp"
#include "debug/Logger.hpp"
#include "core_defs.hpp"
#include "settings.hpp"
#include <cmath>
#include <optional>
#include <string>
#include <vector>
#include <stdexcept>
static debug::Logger logger("content-gfx-cache");
static void unrotate_triangle_uv(
const glm::vec3 (&coords)[3], glm::vec2 (&uvs)[3], const glm::vec3& normal
) {
glm::vec3 absN = glm::abs(normal);
if (glm::max(absN.x, glm::max(absN.y, absN.z)) < 0.999f) {
return;
}
glm::vec2 d1 = uvs[1] - uvs[0];
glm::vec2 d2 = uvs[2] - uvs[0];
float det = d1.x * d2.y - d2.x * d1.y;
if (std::abs(det) < 1e-6f) {
return;
}
glm::vec3 e1 = coords[1] - coords[0];
glm::vec3 e2 = coords[2] - coords[0];
glm::vec3 pu = (e1 * d2.y - e2 * d1.y) / det;
glm::vec3 pv = (e2 * d1.x - e1 * d2.x) / det;
if (glm::length2(pu) < 1e-6f || glm::length2(pv) < 1e-6f) {
return;
}
pu = glm::normalize(pu);
pv = glm::normalize(pv);
glm::vec3 cu;
glm::vec3 cv;
util::uv_by_normal(normal, cu, cv);
glm::mat2 uvTransform(
std::round(glm::dot(pu, cu)), std::round(glm::dot(pu, cv)),
std::round(glm::dot(pv, cu)), std::round(glm::dot(pv, cv))
);
if (std::abs(std::abs(glm::determinant(uvTransform)) - 1.0f) > 1e-3f) {
return;
}
for (auto& uv : uvs) {
uv = uvTransform * (uv - 0.5f) + 0.5f;
}
}
static void unrotate_mesh_uv(model::Mesh& mesh, const CoordSystem& orient) {
glm::vec3 X = orient.axes[0];
glm::vec3 Y = orient.axes[1];
glm::vec3 Z = orient.axes[2];
for (size_t j = 0; j + 2 < mesh.vertices.size(); j += 3) {
glm::vec3 pos[3];
glm::vec2 uv[3];
for (int i = 0; i < 3; i++) {
auto origin = mesh.vertices[j + i].coord - 0.5f;
pos[i] = origin.x * X + origin.y * Y + origin.z * Z;
uv[i] = mesh.vertices[j + i].uv;
}
const auto& normal = mesh.vertices[j].normal;
unrotate_triangle_uv(pos, uv, normal.x * X + normal.y * Y + normal.z * Z);
for (int i = 0; i < 3; i++) {
mesh.vertices[j + i].uv = uv[i];
}
}
}
ContentGfxCache::ContentGfxCache(
const Content& content,
const Assets& assets,
@ -51,11 +118,14 @@ void ContentGfxCache::refreshVariant(
sideregions[index + 1] = atlas.get(texOpaque);
}
if (variant.model.type == BlockModelType::CUSTOM) {
auto model = assets.require<model::Model>(variant.model.name);
const auto& srcModel = assets.require<model::Model>(variant.model.name);
for (auto& mesh : model.meshes) {
std::vector<std::optional<UVRegion>> regions;
regions.reserve(srcModel.meshes.size());
for (const auto& mesh : srcModel.meshes) {
size_t pos = mesh.texture.find(':');
if (pos == std::string::npos) {
regions.emplace_back(std::nullopt);
continue;
}
std::string texture = mesh.texture.substr(pos+1);
@ -63,13 +133,28 @@ void ContentGfxCache::refreshVariant(
if (found != optionalTextures.end()) {
texture = found->second;
}
if (auto region = atlas.getIf(texture)) {
regions.emplace_back(atlas.getIf(texture));
}
bool uvLock = def.uvLock && def.rotatable;
int rotationsCount = uvLock ? def.rotations.variantsCount : 1;
for (int rotation = 0; rotation < rotationsCount; rotation++) {
model::Model model = srcModel;
for (size_t i = 0; i < model.meshes.size(); i++) {
auto& mesh = model.meshes[i];
const auto& region = regions[i];
if (!region) {
continue;
}
if (uvLock) {
unrotate_mesh_uv(mesh, def.rotations.variants[rotation]);
}
for (auto& vertex : mesh.vertices) {
vertex.uv = region->apply(vertex.uv);
}
}
models[modelKey(def.rt.id, variantIndex, rotation)] = std::move(model);
}
models[modelKey(def.rt.id, variantIndex)] = std::move(model);
}
}
@ -101,8 +186,13 @@ void ContentGfxCache::refresh() {
ContentGfxCache::~ContentGfxCache() = default;
const model::Model& ContentGfxCache::getModel(blockid_t id, uint8_t variant) const {
const auto& found = models.find(modelKey(id, variant));
const model::Model& ContentGfxCache::getModel(
blockid_t id, uint8_t variant, uint8_t rotation
) const {
auto found = models.find(modelKey(id, variant, rotation));
if (found == models.end() && rotation != 0) {
found = models.find(modelKey(id, variant, 0));
}
if (found == models.end()) {
throw std::runtime_error("model not found");
}

View file

@ -2,13 +2,12 @@
#include "typedefs.hpp"
#include <memory>
#include <stdexcept>
#include <unordered_map>
#include "maths/UVRegion.hpp"
#include "graphics/commons/Model.hpp"
#include <memory>
#include <unordered_map>
class Content;
class Assets;
class Atlas;
@ -17,28 +16,9 @@ struct UVRegion;
struct Variant;
struct GraphicsSettings;
inline constexpr int GFXC_MAX_VARIANTS = 16;
inline constexpr int GFXC_SIDES = 6;
class ContentGfxCache {
const Content& content;
const Assets& assets;
const GraphicsSettings& settings;
// array of block sides uv regions (6 per block)
std::unique_ptr<UVRegion[]> sideregions;
std::unordered_map<uint64_t, model::Model> models;
static inline uint64_t modelKey(blockid_t id, uint8_t variant) {
return (uint64_t(id) << 8) | uint64_t(variant & 0xFF);
}
void refreshVariant(
const Block& def,
const Variant& variant,
uint8_t variantIndex,
const Atlas& atlas
);
static constexpr int GFXC_MAX_VARIANTS = 16;
static constexpr int GFXC_SIDES = 6;
public:
ContentGfxCache(
const Content& content,
@ -50,16 +30,44 @@ public:
static inline size_t getRegionIndex(
blockid_t id, uint8_t variant, int side, bool opaque
) {
return ((id * GFXC_SIDES + side) * GFXC_MAX_VARIANTS + variant) * 2 + opaque;
return ((id * GFXC_SIDES + side) * GFXC_MAX_VARIANTS + variant) * 2 +
opaque;
}
inline const UVRegion& getRegion(blockid_t id, uint8_t variant, int side, bool dense) const {
inline const UVRegion& getRegion(
blockid_t id, uint8_t variant, int side, bool dense
) const {
return sideregions[getRegionIndex(id, variant, side, !dense)];
}
const model::Model& getModel(blockid_t id, uint8_t variant) const;
const model::Model& getModel(
blockid_t id, uint8_t variant, uint8_t rotation = 0
) const;
void refresh(const Block& block, const Atlas& atlas);
void refresh();
private:
const Content& content;
const Assets& assets;
const GraphicsSettings& settings;
// array of block sides uv regions (6 per block)
std::unique_ptr<UVRegion[]> sideregions;
std::unordered_map<uint64_t, model::Model> models;
static inline uint64_t modelKey(
blockid_t id, uint8_t variant, uint8_t rotation = 0
) {
return (uint64_t(id) << 16) | (uint64_t(rotation & 0xFF) << 8) |
uint64_t(variant & 0xFF);
}
void refreshVariant(
const Block& def,
const Variant& variant,
uint8_t variantIndex,
const Atlas& atlas
);
};

View file

@ -143,9 +143,11 @@ std::shared_ptr<InventoryView> Hud::createHotbar() {
auto inventory = player.getInventory();
auto& content = frontend.getLevel().content;
int size = player.getHotbarSize();
SlotLayout slotLayout(-1, glm::vec2(), false, false, nullptr, nullptr, nullptr);
InventoryBuilder builder(gui);
builder.addGrid(10, 10, glm::vec2(), glm::vec4(4), true, slotLayout);
builder.addGrid(size, size, glm::vec2(), glm::vec4(4), true, slotLayout);
auto view = builder.build();
view->setId("hud.hotbar");
view->setOrigin(glm::vec2(view->getSize().x/2, 0));
@ -177,7 +179,25 @@ Hud::Hud(Engine& engine, LevelFrontend& frontend, Player& player)
contentAccessPanel->setScrollable(true);
contentAccessPanel->setId("hud.content-access-panel");
hotbarView = createHotbar();
auto hotbarLayout =
frontend.getLevel().content.getDefaults()["hotbar-layout"].asString("");
if (hotbarLayout.empty()) {
hotbarView = createHotbar();
} else {
hotbarDocument = &assets.require<UiDocument>(hotbarLayout);
hotbarView =
std::dynamic_pointer_cast<InventoryView>(hotbarDocument->getRoot());
if (hotbarView == nullptr) {
throw std::runtime_error(
"hotbar UI root element must be 'inventory'"
);
}
hotbarView->bind(player.getInventory(), &frontend.getLevel().content);
hotbarView->setInteractive(false);
if (hotbarView->getPositionFunc() == nullptr) {
hotbarView->setOrigin(glm::vec2(hotbarView->getSize().x / 2, 0));
}
}
darkOverlay = guiutil::create(
gui,
"<container size='4000' color='#00000080' z-index='-1' visible='false'/>"
@ -229,6 +249,7 @@ Hud::~Hud() {
for (auto& element : elements) {
onRemove(element);
}
hotbarView->unbind();
gui.remove(hotbarView);
gui.remove(darkOverlay);
gui.remove(inventoryDropArea);
@ -263,12 +284,13 @@ void Hud::processInput(bool visible) {
}
void Hud::updateHotbarControl() {
int size = player.getHotbarSize();
int scroll = input.getScroll();
if (!inventoryOpen && scroll) {
int slot = player.getChosenSlot();
slot = (slot - scroll) % 10;
slot = (slot - scroll) % size;
if (slot < 0) {
slot += 10;
slot += size;
}
player.setChosenSlot(slot);
}
@ -277,11 +299,12 @@ void Hud::updateHotbarControl() {
i <= static_cast<int>(Keycode::NUM_9);
i++
) {
if (input.jpressed(static_cast<Keycode>(i))) {
player.setChosenSlot(i - static_cast<int>(Keycode::NUM_1));
int slot = i - static_cast<int>(Keycode::NUM_1);
if (slot < size && input.jpressed(static_cast<Keycode>(i))) {
player.setChosenSlot(slot);
}
}
if (input.jpressed(Keycode::NUM_0)) {
if (size > 9 && input.jpressed(Keycode::NUM_0)) {
player.setChosenSlot(9);
}
}
@ -375,7 +398,16 @@ void Hud::update(bool visible) {
contentAccessPanel->setVisible(inventoryView != nullptr && showContentPanel);
contentAccessPanel->setSize(glm::vec2(caSize.x, windowSize.y));
contentAccess->setMinSize(glm::vec2(1, windowSize.y));
hotbarView->setVisible(visible && !(secondUI && !inventoryView));
if (hotbarDocument == nullptr &&
static_cast<int>(hotbarView->getSlotsCount()) !=
player.getHotbarSize()) {
gui.remove(hotbarView);
hotbarView = createHotbar();
gui.add(hotbarView);
}
hotbarView->setVisible(
visible && hotbarVisible && !(secondUI && !inventoryView)
);
darkOverlay->setVisible(isMenuOpen);
inventoryDropArea->setVisible(inventoryOpen);
menu.setVisible(isMenuOpen);
@ -404,8 +436,16 @@ void Hud::openInventory(bool playerInventory) {
if (playerInventory) {
auto& content = frontend.getLevel().content;
auto inventory = player.getInventory();
auto inventoryDocument = assets.get<UiDocument>("core:inventory");
auto layout = content.getDefaults()["inventory-layout"].asString(
"core:inventory"
);
auto inventoryDocument = &assets.require<UiDocument>(layout);
inventoryView = std::dynamic_pointer_cast<InventoryView>(inventoryDocument->getRoot());
if (inventoryView == nullptr) {
throw std::runtime_error(
"player inventory UI root element must be 'inventory'"
);
}
inventoryView->bind(inventory, &content);
add(HudElement(HudElementMode::INVENTORY, inventoryDocument, inventoryView, false));
}
@ -700,7 +740,9 @@ void Hud::updateElementsPosition(const glm::uvec2& viewport) {
if (exchangeSlot != nullptr) {
exchangeSlot->setPos(input.getCursor().pos);
}
hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65));
if (hotbarView->getPositionFunc() == nullptr) {
hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65));
}
hotbarView->setSelected(player.getChosenSlot());
}
@ -790,6 +832,14 @@ void Hud::setAllowPause(bool flag) {
allowPause = flag;
}
void Hud::setHotbarVisible(bool flag) {
hotbarVisible = flag;
}
bool Hud::isHotbarVisible() const {
return hotbarVisible;
}
bool Hud::isOpen(const std::string& layoutid) const {
for (const auto& element : elements) {
auto doc = element.getDocument();

View file

@ -89,6 +89,10 @@ class Hud : public util::ObjectsKeeper {
std::shared_ptr<gui::InventoryView> contentAccess;
/// @brief Player inventory hotbar
std::shared_ptr<gui::InventoryView> hotbarView;
/// @brief Hotbar layout set by 'hotbar-layout', nullptr for built-in
UiDocument* hotbarDocument = nullptr;
/// @brief Hotbar is not hidden by scripts
bool hotbarVisible = true;
/// @brief Debug info and control panel (F3 key)
std::shared_ptr<gui::UINode> debugPanel;
/// @brief Overlay used in pause mode
@ -219,6 +223,10 @@ public:
void setAllowPause(bool flag);
void setHotbarVisible(bool flag);
bool isHotbarVisible() const;
bool isOpen(const std::string& layoutid) const;
static bool showGeneratorMinimap;

View file

@ -79,7 +79,9 @@ UiDocument* menus::show(
auto documentPtr = UiDocument::read(
engine.getGUI(),
scripting::get_root_environment(),
scripting::create_doc_environment(
scripting::get_root_environment(), fullname, true
),
fullname,
file,
"core:layouts/" + name

View file

@ -85,10 +85,30 @@ LevelScreen::LevelScreen(
};
keepAlive(settings.graphics.backlight.observe(resetChunks));
keepAlive(settings.graphics.softLighting.observe(resetChunks));
keepAlive(settings.graphics.denseRender.observe([=](bool flag) {
resetChunks(flag);
keepAlive(settings.graphics.denseRender.observe([=](bool) {
resetChunks(false);
frontend->getContentGfxCache().refresh();
}));
auto graphics = &settings.graphics;
auto shadowsMeshing = std::make_shared<bool>(
graphics->shadowsQuality.get() > 0 && graphics->advancedRender.get()
);
auto updateShadowsMeshing = [=]() {
bool enabled =
graphics->shadowsQuality.get() > 0 && graphics->advancedRender.get();
if (enabled == *shadowsMeshing) {
return;
}
*shadowsMeshing = enabled;
resetChunks(false);
frontend->getContentGfxCache().refresh();
};
keepAlive(settings.graphics.shadowsQuality.observe([=](int) {
updateShadowsMeshing();
}));
keepAlive(settings.graphics.advancedRender.observe([=](bool) {
updateShadowsMeshing();
}));
keepAlive(settings.camera.fov.observe([=](double value) {
player->fpCamera->setFov(glm::radians(value));
}));

View file

@ -3,6 +3,7 @@
#include "Model.hpp"
#include <algorithm>
#include <limits>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/matrix_decompose.hpp>
@ -168,6 +169,25 @@ void Mesh::translate(const glm::vec3& offset) {
}
}
void Model::calcBounds() {
glm::vec3 min(std::numeric_limits<float>::max());
glm::vec3 max(std::numeric_limits<float>::lowest());
for (const auto& mesh : meshes) {
for (const auto& vertex : mesh.vertices) {
min = glm::min(min, vertex.coord);
max = glm::max(max, vertex.coord);
}
}
if (min.x > max.x) {
min = max = glm::vec3(0.0f);
}
bounds = AABB(min, max);
}
const AABB& Model::getBounds() const {
return bounds;
}
void Model::clean() {
meshes.erase(
std::remove_if(meshes.begin(), meshes.end(),

View file

@ -5,6 +5,7 @@
#include <glm/glm.hpp>
#include "maths/UVRegion.hpp"
#include "maths/aabb.hpp"
namespace model {
struct Vertex {
@ -82,6 +83,7 @@ namespace model {
struct Model {
std::vector<Mesh> meshes;
AABB bounds {glm::vec3(0.0f), glm::vec3(0.0f)};
/// @brief Add mesh to the model
/// @param texture texture name
@ -96,6 +98,9 @@ namespace model {
return meshes[meshes.size() - 1];
}
void calcBounds();
const AABB& getBounds() const;
/// @brief Remove all empty meshes
void clean();

View file

@ -19,6 +19,14 @@ static void set_blend_mode(BlendMode mode) {
case BlendMode::inversion:
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA);
break;
case BlendMode::coverage:
glBlendFuncSeparate(
GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA
);
break;
case BlendMode::premultiplied:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
break;
}
}

View file

@ -8,7 +8,11 @@ using namespace advanced_pipeline;
static debug::Logger logger("gl-gbuffer");
void GBuffer::createBuffer(Buffer& buffer) {
uint GBuffer::getSSAODownsample() const {
return 2;
}
void GBuffer::createBuffer(Buffer& buffer, int downsample) {
if (buffer.buffer == 0) {
if (&buffer == &depthBuffer)
glGenRenderbuffers(1, &depthBuffer.buffer);
@ -27,8 +31,8 @@ void GBuffer::createBuffer(Buffer& buffer) {
GL_TEXTURE_2D,
0,
buffer.internalformat,
width,
height,
width / downsample,
height / downsample,
0,
buffer.format,
buffer.type,
@ -48,8 +52,7 @@ void GBuffer::createBuffer(Buffer& buffer) {
}
GBuffer::GBuffer(uint width, uint height)
: width(width), height(height),
: width(width), height(height),
colorBuffer {0, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, GL_COLOR_ATTACHMENT0},
positionsBuffer {0, GL_RGBA16F, GL_RGBA, GL_FLOAT, GL_COLOR_ATTACHMENT1},
normalsBuffer {0, GL_RGBA16F, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT2},
@ -83,7 +86,7 @@ GBuffer::GBuffer(uint width, uint height)
glGenFramebuffers(1, &ssaoFbo);
glBindFramebuffer(GL_FRAMEBUFFER, ssaoFbo);
createBuffer(ssaoBuffer);
createBuffer(ssaoBuffer, getSSAODownsample());
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoBuffer.buffer, 0
);
@ -168,7 +171,7 @@ void GBuffer::resize(uint width, uint height) {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, ssaoFbo);
createBuffer(ssaoBuffer);
createBuffer(ssaoBuffer, getSSAODownsample());
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

View file

@ -24,6 +24,8 @@ public:
uint getHeight() const;
std::unique_ptr<ImageData> toImage() const;
uint getSSAODownsample() const;
private:
struct Buffer {
uint buffer;
@ -45,5 +47,5 @@ private:
uint ssaoFbo;
Buffer ssaoBuffer;
void createBuffer(Buffer& buffer);
void createBuffer(Buffer& buffer, int downsample = 1);
};

View file

@ -0,0 +1,20 @@
#pragma once
#include <cstddef>
#include "MeshData.hpp"
template <typename InstanceStructure>
class InstanceBuffer {
unsigned int vbo;
size_t capacity;
public:
InstanceBuffer();
~InstanceBuffer();
void reload(const InstanceStructure* instances, size_t count);
void bind(int location, size_t first) const;
};
#include "graphics/core/InstanceBuffer.inl"

View file

@ -0,0 +1,55 @@
#pragma once
#include <algorithm>
#include "gl_util.hpp"
template <typename InstanceStructure>
InstanceBuffer<InstanceStructure>::InstanceBuffer() : vbo(0), capacity(0) {
static_assert(
calc_size(InstanceStructure::ATTRIBUTES) == sizeof(InstanceStructure)
);
glGenBuffers(1, &vbo);
}
template <typename InstanceStructure>
InstanceBuffer<InstanceStructure>::~InstanceBuffer() {
glDeleteBuffers(1, &vbo);
}
template <typename InstanceStructure>
void InstanceBuffer<InstanceStructure>::reload(
const InstanceStructure* instances, size_t count
) {
size_t size = count * sizeof(InstanceStructure);
if (size > capacity) {
capacity = std::max(size, capacity * 2);
}
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, capacity, nullptr, GL_STREAM_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, size, instances);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
template <typename InstanceStructure>
void InstanceBuffer<InstanceStructure>::bind(int location, size_t first) const {
const auto& attrs = InstanceStructure::ATTRIBUTES;
glBindBuffer(GL_ARRAY_BUFFER, vbo);
size_t offset = first * sizeof(InstanceStructure);
for (int i = 0; attrs[i].count; i++) {
const VertexAttribute& attr = attrs[i];
glVertexAttribPointer(
location + i,
attr.count,
gl::to_glenum(attr.type),
attr.normalized,
sizeof(InstanceStructure),
(GLvoid*)offset
);
glVertexAttribDivisor(location + i, 1);
glEnableVertexAttribArray(location + i);
offset += attr.size();
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
}

View file

@ -3,6 +3,7 @@
#include <vector>
#include "MeshData.hpp"
#include "InstanceBuffer.hpp"
struct MeshStats {
@ -65,6 +66,13 @@ public:
/// @brief Draw mesh as triangles
void draw() const;
template <typename InstanceStructure>
void drawInstanced(
const InstanceBuffer<InstanceStructure>& instances,
size_t first,
size_t count
) const;
private:
};

View file

@ -3,14 +3,6 @@
#include "MeshData.hpp"
#include "gl_util.hpp"
inline constexpr size_t calc_size(const VertexAttribute attrs[]) {
size_t vertexSize = 0;
for (int i = 0; attrs[i].count; i++) {
vertexSize += attrs[i].size();
}
return vertexSize;
}
template <typename VertexStructure>
inline std::vector<IndexBufferData> convert_to_ibd(const MeshData<VertexStructure>& data) {
std::vector<IndexBufferData> indices;
@ -147,3 +139,22 @@ template <typename VertexStructure>
void Mesh<VertexStructure>::draw() const {
draw(GL_TRIANGLES);
}
template <typename VertexStructure>
template <typename InstanceStructure>
void Mesh<VertexStructure>::drawInstanced(
const InstanceBuffer<InstanceStructure>& instances,
size_t first,
size_t count
) const {
if (vertexCount == 0 || count == 0) {
return;
}
MeshStats::drawCalls++;
glBindVertexArray(vao);
instances.bind(count_attributes(VertexStructure::ATTRIBUTES), first);
glDrawArraysInstanced(GL_TRIANGLES, 0, vertexCount, count);
glBindVertexArray(0);
MeshStats::vertices += vertexCount * count;
}

View file

@ -37,6 +37,22 @@ struct VertexAttribute {
}
};
inline constexpr size_t calc_size(const VertexAttribute attrs[]) {
size_t vertexSize = 0;
for (int i = 0; attrs[i].count; i++) {
vertexSize += attrs[i].size();
}
return vertexSize;
}
inline constexpr int count_attributes(const VertexAttribute attrs[]) {
int count = 0;
while (attrs[count].count) {
count++;
}
return count;
}
/// @brief Raw mesh data structure
template<typename VertexStructure>
struct MeshData {

View file

@ -34,7 +34,8 @@ PostProcessing::PostProcessing(size_t effectSlotsCount)
quadMesh = std::make_unique<Mesh<PostProcessingVertex>>(meshData, 6);
std::vector<glm::vec3> ssaoNoise;
for (unsigned int i = 0; i < 16; i++)
int res = 4;
for (unsigned int i = 0; i < res*res; i++)
{
glm::vec3 noise(
(rand() / static_cast<float>(RAND_MAX)) * 2.0 - 1.0,
@ -44,7 +45,7 @@ PostProcessing::PostProcessing(size_t effectSlotsCount)
}
glGenTextures(1, &noiseTexture);
glBindTexture(GL_TEXTURE_2D, noiseTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 4, 4, 0, GL_RGB, GL_FLOAT, ssaoNoise.data());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, res, res, 0, GL_RGB, GL_FLOAT, ssaoNoise.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@ -94,7 +95,8 @@ void PostProcessing::configureEffect(
PostEffect& effect,
Shader& shader,
float timer,
const Camera& camera
const Camera& camera,
unsigned int downsample
) {
const auto& viewport = context.getViewport();
shader.uniform1i("u_screen", TARGET_COLOR);
@ -106,7 +108,7 @@ void PostProcessing::configureEffect(
}
shader.uniform1i("u_noise", TARGET_SSAO); // used in SSAO pass
shader.uniform1i("u_ssao", TARGET_SSAO);
shader.uniform2i("u_screenSize", viewport);
shader.uniform2i("u_screenSize", viewport / downsample);
shader.uniform3f("u_cameraPos", camera.position);
shader.uniform1f("u_timer", timer);
shader.uniformMatrix("u_projection", camera.getProjection());
@ -134,15 +136,14 @@ void PostProcessing::renderDeferredShading(
auto& ssaoEffect = assets.require<PostEffect>("ssao");
auto& shader = ssaoEffect.use();
configureEffect(
context,
ssaoEffect,
shader,
timer,
camera
);
uint ssaoDownscale = gbuffer->getSSAODownsample();
configureEffect(context, ssaoEffect, shader, timer, camera, ssaoDownscale);
gbuffer->bindSSAO();
quadMesh->draw();
{
auto ssaoContext = context.sub();
ssaoContext.setViewport(context.getViewport() / ssaoDownscale);
quadMesh->draw();
}
gbuffer->unbind();
{

View file

@ -66,7 +66,8 @@ private:
PostEffect& effect,
Shader& shader,
float timer,
const Camera& camera
const Camera& camera,
unsigned downsample = 1U
);
void refreshFbos(uint width, uint height);

View file

@ -0,0 +1,146 @@
#include "TranslucentLayers.hpp"
#include <GL/glew.h>
#include <string>
#include "Mesh.hpp"
#include "PostProcessing.hpp"
#include "Shader.hpp"
#include "debug/Logger.hpp"
static debug::Logger logger("gl-translucent-layers");
inline constexpr int FIRST_TEXTURE_UNIT = advanced_pipeline::TARGETS_COUNT;
static void setup_texture(uint texture) {
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
TranslucentLayers::Layer::Layer() {
glGenFramebuffers(1, &fbo);
glGenTextures(1, &color);
glGenTextures(1, &depth);
}
TranslucentLayers::Layer::~Layer() {
glDeleteFramebuffers(1, &fbo);
glDeleteTextures(1, &color);
glDeleteTextures(1, &depth);
}
void TranslucentLayers::Layer::bind() const {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
}
void TranslucentLayers::Layer::unbind() const {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void TranslucentLayers::Layer::allocate(uint width, uint height) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
setup_texture(color);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr
);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color, 0
);
setup_texture(depth);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr
);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0
);
GLenum attachments[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, attachments);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
logger.error() << "translucent layer framebuffer is not complete!";
}
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
TranslucentLayers::TranslucentLayers(size_t count, uint width, uint height)
: width(width), height(height) {
for (size_t i = 0; i < count; i++) {
auto layer = std::make_unique<Layer>();
layer->allocate(width, height);
layers.push_back(std::move(layer));
}
PostProcessingVertex meshData[] {
{{-1.0f, -1.0f}},
{{-1.0f, 1.0f}},
{{1.0f, 1.0f}},
{{-1.0f, -1.0f}},
{{1.0f, 1.0f}},
{{1.0f, -1.0f}},
};
quadMesh = std::make_unique<Mesh<PostProcessingVertex>>(meshData, 6);
}
TranslucentLayers::~TranslucentLayers() = default;
void TranslucentLayers::resize(uint width, uint height) {
if (this->width == width && this->height == height) {
return;
}
this->width = width;
this->height = height;
for (auto& layer : layers) {
layer->allocate(width, height);
}
}
void TranslucentLayers::prepare(uint sourceFbo) {
const GLfloat transparent[4] {0.0f, 0.0f, 0.0f, 0.0f};
for (const auto& layer : layers) {
glBindFramebuffer(GL_READ_FRAMEBUFFER, sourceFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, layer->fbo);
glBlitFramebuffer(
0, 0, width, height, 0, 0, width, height,
GL_DEPTH_BUFFER_BIT, GL_NEAREST
);
glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo);
glClearBufferfv(GL_COLOR, 0, transparent);
}
glBindFramebuffer(GL_FRAMEBUFFER, sourceFbo);
}
Bindable& TranslucentLayers::getLayer(size_t index) {
return *layers.at(index);
}
void TranslucentLayers::compose(Shader& shader) {
shader.use();
int count = static_cast<int>(layers.size());
for (int i = 0; i < count; i++) {
int colorUnit = FIRST_TEXTURE_UNIT + i;
int depthUnit = FIRST_TEXTURE_UNIT + count + i;
glActiveTexture(GL_TEXTURE0 + colorUnit);
glBindTexture(GL_TEXTURE_2D, layers[i]->color);
shader.uniform1i("u_layerColor" + std::to_string(i), colorUnit);
glActiveTexture(GL_TEXTURE0 + depthUnit);
glBindTexture(GL_TEXTURE_2D, layers[i]->depth);
shader.uniform1i("u_layerDepth" + std::to_string(i), depthUnit);
}
quadMesh->draw();
for (int i = 0; i < count * 2; i++) {
glActiveTexture(GL_TEXTURE0 + FIRST_TEXTURE_UNIT + i);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
}

View file

@ -0,0 +1,46 @@
#pragma once
#include "typedefs.hpp"
#include "commons.hpp"
#include <memory>
#include <vector>
template<typename VertexStructure> class Mesh;
struct PostProcessingVertex;
class Shader;
class TranslucentLayers {
public:
TranslucentLayers(size_t count, uint width, uint height);
~TranslucentLayers();
void resize(uint width, uint height);
void prepare(uint sourceFbo);
Bindable& getLayer(size_t index);
void compose(Shader& shader);
private:
class Layer : public Bindable {
public:
uint fbo = 0;
uint color = 0;
uint depth = 0;
Layer();
~Layer() override;
void bind() const override;
void unbind() const override;
void allocate(uint width, uint height);
};
uint width;
uint height;
std::vector<std::unique_ptr<Layer>> layers;
std::unique_ptr<Mesh<PostProcessingVertex>> quadMesh;
};

View file

@ -17,7 +17,11 @@ enum class BlendMode {
/// @brief Additive blending mode.
addition,
/// @brief Subtractive blending mode.
inversion
inversion,
/// @brief Normal color blending with alpha accumulated as coverage.
coverage,
/// @brief Blending of premultiplied-alpha color.
premultiplied
};
/// @brief Standard GLFW 3.4 cursor shapes (same order and count as in GLFW).

View file

@ -70,9 +70,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) {
);
break;
case BlockModelType::AABB: {
const auto& aabb =
(def.rotatable ? def.rt.hitboxes[vox->state.rotation]
: def.hitboxes).at(0);
const auto& aabb = def.getHitboxes(vox->state).at(0);
const auto& size = aabb.size();
batch->cube(
glm::vec3(wrapper.position) + aabb.center(),
@ -121,9 +119,7 @@ void BlockWrapsRenderer::refreshWrapper(BlockWrapper& wrapper) {
wrapper.modelType = def.getModel(vox->state.userbits).type;
switch (wrapper.modelType) {
case BlockModelType::AABB: {
const auto& aabb =
(def.rotatable ? def.rt.hitboxes[vox->state.rotation]
: def.hitboxes).at(0);
const auto& aabb = def.getHitboxes(vox->state).at(0);
const auto& size = aabb.size();
wrapper.uvRegions[0].scale(size.z, size.y);
wrapper.uvRegions[1].scale(size.z, size.y);
@ -143,8 +139,10 @@ void BlockWrapsRenderer::draw(const DrawContext& pctx) {
auto& shader = assets.require<Shader>("entity");
shader.use();
shader.uniform1i("u_alphaClip", false);
shader.uniform1i("u_dithering", 0);
shader.uniform1f("u_alphaThreshold", 0.15f);
shader.uniform1i("u_opaque", false);
shader.uniform1i("u_forward", false);
shader.uniform1i("u_forwardLight", false);
for (const auto& [_, wrapper] : wrappers) {
if (wrapper->dirtySides) {

View file

@ -46,7 +46,7 @@ std::unique_ptr<ImageData> BlocksPreview::draw(
case BlockModelType::AABB:
{
glm::vec3 hitbox {};
for (const auto& box : def.hitboxes) {
for (const auto& box : def.defaults.hitboxes) {
hitbox = glm::max(hitbox, box.size());
}
offset = glm::vec3(1, 1, 0.0f);

View file

@ -10,7 +10,6 @@
#include "frontend/ContentGfxCache.hpp"
const glm::vec3 BlocksRenderer::SUN_VECTOR(0.528265, 0.833149, -0.163704);
constexpr float DIRECTIONAL_LIGHT_FACTOR = 0.3f;
BlocksRenderer::BlocksRenderer(
size_t capacity,
@ -128,7 +127,7 @@ void BlocksRenderer::faceAO(
float s = 0.5f;
if (lights) {
float d = glm::dot(glm::normalize(Z), SUN_VECTOR);
d = (1.0f - DIRECTIONAL_LIGHT_FACTOR) + d * DIRECTIONAL_LIGHT_FACTOR;
d = (1.0f - directionalLightFactor) + d * directionalLightFactor;
auto axisX = glm::normalize(X);
auto axisY = glm::normalize(Y);
@ -167,7 +166,7 @@ void BlocksRenderer::face(
float s = 0.5f;
if (lights) {
float d = glm::dot(glm::normalize(Z), SUN_VECTOR);
d = (1.0f - DIRECTIONAL_LIGHT_FACTOR) + d * DIRECTIONAL_LIGHT_FACTOR;
d = (1.0f - directionalLightFactor) + d * directionalLightFactor;
tint *= d;
}
vertex(coord + (-X - Y + Z) * s, region.u1, region.v1, tint, Z, lights ? 0 : 1);
@ -225,15 +224,16 @@ void BlocksRenderer::blockAABB(
const glm::ivec3& icoord,
const UVRegion(&texfaces)[6],
const Block* block,
ubyte rotation,
blockstate states,
bool lights,
bool ao
) {
if (block->hitboxes.empty()) {
const auto& hitboxes = block->getVariantByBits(states.userbits).hitboxes;
if (hitboxes.empty()) {
return;
}
AABB hitbox = block->hitboxes[0];
for (const auto& box : block->hitboxes) {
AABB hitbox = hitboxes[0];
for (const auto& box : hitboxes) {
hitbox.a = glm::min(hitbox.a, box.a);
hitbox.b = glm::max(hitbox.b, box.b);
}
@ -244,7 +244,7 @@ void BlocksRenderer::blockAABB(
glm::vec3 coord(icoord);
if (block->rotatable) {
auto& rotations = block->rotations;
auto& orient = rotations.variants[rotation];
auto& orient = rotations.variants[states.rotation];
X = orient.axes[0];
Y = orient.axes[1];
Z = orient.axes[2];
@ -317,7 +317,11 @@ void BlocksRenderer::blockCustomModel(
);
}
const auto& model = cache.getModel(block.rt.id, block.getVariantIndex(states.userbits));
const auto& model = cache.getModel(
block.rt.id,
block.getVariantIndex(states.userbits),
block.uvLock && block.rotatable ? states.rotation : 0
);
for (const auto& mesh : model.meshes) {
if (vertexCount + mesh.vertices.size() >= capacity
|| indexCount + mesh.vertices.size() >= capacity) {
@ -349,7 +353,7 @@ void BlocksRenderer::blockCustomModel(
}
float d = glm::dot(n, SUN_VECTOR);
d = (1.0f - DIRECTIONAL_LIGHT_FACTOR) + d * DIRECTIONAL_LIGHT_FACTOR;
d = (1.0f - directionalLightFactor) + d * directionalLightFactor;
glm::vec3 t = glm::cross(r, n);
for (int i = 0; i < 3; i++) {
@ -538,7 +542,7 @@ void BlocksRenderer::render(
}
case BlockModelType::AABB: {
if (!denseRender)
blockAABB({x, y, z}, texfaces, &def, vox.state.rotation,
blockAABB({x, y, z}, texfaces, &def, vox.state,
!def.shadeless, def.ambientOcclusion && enableAO);
break;
}
@ -610,7 +614,7 @@ SortingMeshData BlocksRenderer::renderTranslucent(
{x, y, z},
texfaces,
&def,
vox.state.rotation,
vox.state,
!def.shadeless,
def.ambientOcclusion && enableAO
);
@ -692,6 +696,11 @@ SortingMeshData BlocksRenderer::renderTranslucent(
void BlocksRenderer::build(
const Chunk* chunk, const VoxelsRenderVolume& volume
) {
directionalLightFactor = settings.graphics.shadowsQuality.get() > 0 &&
settings.graphics.advancedRender.get()
? 0.0f
: DEFAULT_DIRECTIONAL_LIGHT_FACTOR;
meshAABB = AABB(glm::vec3(CHUNK_W, CHUNK_H, CHUNK_D));
this->chunk = chunk;
this->voxelsBuffer = &volume;

View file

@ -23,6 +23,8 @@ struct UVRegion;
class BlocksRenderer final {
public:
static constexpr float DEFAULT_DIRECTIONAL_LIGHT_FACTOR = 0.3f;
BlocksRenderer(
size_t capacity,
const Block* const* blockDefs,
@ -56,6 +58,8 @@ private:
bool cancelled = false;
bool densePass = false;
bool denseRender = false;
float directionalLightFactor = 0.0f;
AABB meshAABB {};
const Chunk* chunk = nullptr;
const VoxelsRenderVolume* voxelsBuffer = nullptr;
@ -124,7 +128,7 @@ private:
const glm::ivec3& coord,
const UVRegion(&faces)[6],
const Block* block,
ubyte rotation,
blockstate states,
bool lights,
bool ambientOcclusion
);

View file

@ -159,7 +159,7 @@ void Decorator::updateAcoustics(const Camera& camera) {
acoustics.reverbReflectionsDelay = minDistance / speedOfSound;
acoustics.reverbLateReflectionsDelay = averageDistance / speedOfSound;
acoustics.reverbDecayTime = decayTime;
acoustics.reverbRoomRolloff = escapeRatio * 1.5f;
acoustics.reverbRoomRolloff = 0.1f + escapeRatio * 1.5f;
acoustics.reverbAbsorption = averageAbsorption;
audio::set_acoustics(std::move(acoustics));

View file

@ -0,0 +1,177 @@
#include "EntitiesRenderer.hpp"
#include "animation/rigging.hpp"
#include "assets/Assets.hpp"
#include "graphics/core/DrawContext.hpp"
#include "graphics/core/LineBatch.hpp"
#include "maths/FrustumCulling.hpp"
#include "objects/Entities.hpp"
#include "objects/Entity.hpp"
#include "objects/EntityDef.hpp"
#include "ModelBatch.hpp"
static void debug_render_skeleton(
LineBatch& batch,
const rigging::Bone* bone,
const rigging::Skeleton& skeleton
) {
size_t pindex = bone->getIndex();
for (auto& sub : bone->getBones()) {
size_t sindex = sub->getIndex();
const auto& matrices = skeleton.calculated.matrices;
batch.line(
glm::vec3(matrices[pindex] * glm::vec4(0, 0, 0, 1)),
glm::vec3(matrices[sindex] * glm::vec4(0, 0, 0, 1)),
glm::vec4(0, 0.5f, 0, 1)
);
debug_render_skeleton(batch, sub.get(), skeleton);
}
}
static glm::vec3 calc_extent(
const Transform& transform,
const Rigidbody& rigidbody,
const rigging::Skeleton& skeleton
) {
const auto& size = transform.size;
float scale = glm::max(
glm::abs(size.x), glm::max(glm::abs(size.y), glm::abs(size.z))
);
return glm::max(
rigidbody.hitbox.getHalfSize(), glm::vec3(skeleton.boundsRadius * scale)
);
}
static bool check_frustum(
const Frustum& frustum,
const Transform& transform,
const Rigidbody& rigidbody,
const rigging::Skeleton& skeleton
) {
glm::vec3 ext = calc_extent(transform, rigidbody, skeleton);
return frustum.isBoxVisible(transform.pos - ext, transform.pos + ext);
}
EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities)
: assets(assets), entities(entities) {
}
void EntitiesRenderer::render(
ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity
) {
for (const auto& [uid, entity] : entities.getEntities()) {
if (!entity->getSkeleton() || uid == fpsEntity) {
continue;
}
const auto& transform = entity->getTransform();
const auto& rigidbody = entity->getRigidbody();
auto& skeleton = *entity->getSkeleton();
const auto& def = entity->getID().def;
const auto& pos = transform.pos;
const auto& size = transform.size;
const auto& rigConfig = skeleton.config;
if (rigConfig == nullptr) {
continue;
}
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) {
if (!skeleton.boundsDirty || !skeleton.visible) {
continue;
}
rigConfig->updateBounds(assets, skeleton, transform.rot, pos, size);
if (!check_frustum(*frustum, transform, rigidbody, skeleton)) {
continue;
}
}
rigConfig->render(
assets,
batch,
skeleton,
def.lightingMode,
transform.rot,
pos,
size,
def.translucent
);
}
}
void EntitiesRenderer::renderDebug(
LineBatch& batch,
const Frustum* frustum,
const DrawContext& pctx,
entityid_t fpsEntity
) {
const auto& all = entities.getEntities();
{
auto ctx = pctx.sub(&batch);
ctx.setLineWidth(1);
for (const auto& [uid, entity] : all) {
if (!entity->getSkeleton()) {
continue;
}
const auto& transform = entity->getTransform();
const auto& rigidbody = entity->getRigidbody();
const auto& skeleton = *entity->getSkeleton();
const auto& hitbox = rigidbody.hitbox;
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) {
continue;
}
batch.box(
hitbox.position, hitbox.getHalfSize() * 2.0f, glm::vec4(1.0f)
);
glm::vec3 ext = calc_extent(transform, rigidbody, skeleton);
batch.box(
transform.pos, ext * 2.0f, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)
);
for (auto& sensor : rigidbody.sensors) {
if (sensor.type != SensorType::AABB) continue;
batch.box(
sensor.calculated.aabb.center(),
sensor.calculated.aabb.size(),
glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)
);
}
}
}
{
auto ctx = pctx.sub(&batch);
ctx.setDepthTest(false);
ctx.setDepthMask(false);
ctx.setLineWidth(2);
for (const auto& [uid, entity] : all) {
if (!entity->getSkeleton() || uid == fpsEntity) {
continue;
}
const auto& transform = entity->getTransform();
const auto& rigidbody = entity->getRigidbody();
const auto& skeleton = *entity->getSkeleton();
auto config = skeleton.config;
if (config == nullptr) {
continue;
}
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) {
continue;
}
auto bone = config->getRoot();
debug_render_skeleton(batch, bone, skeleton);
}
}
}
void EntitiesRenderer::updateCulling(
const Frustum* frustum, entityid_t fpsEntity
) {
for (const auto& [uid, entity] : entities.getEntities()) {
if (!entity->getSkeleton()) {
continue;
}
auto& skeleton = *entity->getSkeleton();
if (frustum == nullptr || uid == fpsEntity) {
skeleton.culled = false;
continue;
}
skeleton.culled = !check_frustum(
*frustum, entity->getTransform(), entity->getRigidbody(), skeleton
);
}
}

View file

@ -0,0 +1,30 @@
#pragma once
#include "typedefs.hpp"
class Assets;
class DrawContext;
class Entities;
class Frustum;
class LineBatch;
class ModelBatch;
class EntitiesRenderer {
const Assets& assets;
Entities& entities;
public:
EntitiesRenderer(const Assets& assets, Entities& entities);
void render(
ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity
);
void renderDebug(
LineBatch& batch,
const Frustum* frustum,
const DrawContext& ctx,
entityid_t fpsEntity
);
void updateCulling(const Frustum* frustum, entityid_t fpsEntity);
};

View file

@ -2,47 +2,18 @@
#include "assets/assets_util.hpp"
#include "graphics/commons/Model.hpp"
#include "graphics/core/Mesh.hpp"
#include "graphics/core/Atlas.hpp"
#include "graphics/core/Texture.hpp"
#include "graphics/core/ImageData.hpp"
#include "graphics/core/Mesh.hpp"
#include "assets/Assets.hpp"
#include "voxels/Chunks.hpp"
#include "lighting/Lightmap.hpp"
#include "settings.hpp"
#include "MainBatch.hpp"
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/ext/matrix_transform.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/gtx/quaternion.hpp>
#include <algorithm>
inline constexpr glm::vec3 X(1, 0, 0);
inline constexpr glm::vec3 Y(0, 1, 0);
inline constexpr glm::vec3 Z(0, 0, 1);
struct DecomposedMat4 {
glm::vec3 scale;
glm::mat3 rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
};
static glm::mat4 extract_rotation(glm::mat4 matrix) {
DecomposedMat4 decomposed = {};
glm::quat rotation;
glm::decompose(
matrix,
decomposed.scale,
rotation,
decomposed.translation,
decomposed.skew,
decomposed.perspective
);
return glm::toMat3(rotation);
}
inline constexpr uint64_t COLLECT_EVERY = 600;
inline constexpr uint64_t UNUSED_FRAMES = 1200;
ModelBatch::ModelBatch(
size_t capacity,
@ -50,108 +21,204 @@ ModelBatch::ModelBatch(
const Chunks& chunks,
const EngineSettings& settings
)
: assets(assets),
chunks(chunks),
settings(settings),
batch(std::make_unique<MainBatch>(capacity)) {}
: assets(assets), chunks(chunks), settings(settings) {
entries.reserve(capacity / 36);
const ubyte pixels[] = {255, 255, 255, 255};
ImageData image(ImageFormat::RGBA8888, 1, 1, pixels);
blank = Texture::from(&image);
instanceBuffer = std::make_unique<InstanceBuffer<Instance>>();
}
ModelBatch::~ModelBatch() = default;
void ModelBatch::draw(
const model::Mesh& mesh,
const glm::mat4& matrix,
const glm::mat3& rotation,
const glm::vec4& tint,
const TextureNamesMap* varTextures,
bool backlight
ModelBatch::GpuModel& ModelBatch::upload(
const std::shared_ptr<model::Model>& model
) {
setTexture(mesh.texture, varTextures);
size_t vcount = mesh.vertices.size();
const auto& vertexData = mesh.vertices.data();
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 + localLightsOffset;
lights = MainBatch::sampleLight(gpos, chunks, backlight);
auto& gpuModel = models[model.get()];
bool valid = gpuModel.model.lock() == model &&
gpuModel.meshes.size() == model->meshes.size();
for (size_t i = 0; valid && i < gpuModel.meshes.size(); i++) {
valid = gpuModel.meshes[i].vertexCount ==
model->meshes[i].vertices.size();
}
for (size_t i = 0; i < vcount / 3; i++) {
batch->prepare(3);
for (size_t j = 0; j < 3; j++) {
const auto vert = vertexData[i * 3 + j];
float d = 1.0f;
auto norm = rotation * vert.normal;
if (mesh.shading) {
d = glm::dot(norm, SUN_VECTOR);
d = 0.8f + d * 0.2f;
}
batch->vertex(
matrix * glm::vec4(vert.coord, 1.0f),
vert.uv,
lights * d,
tint,
norm,
mesh.shading ? 0.0f : 1.0f
);
static_assert(sizeof(Vertex) == sizeof(model::Vertex));
if (!valid) {
gpuModel.meshes.clear();
gpuModel.model = model;
for (const auto& mesh : model->meshes) {
gpuModel.meshes.push_back(GpuMesh {
std::make_unique<Mesh<Vertex>>(
reinterpret_cast<const Vertex*>(mesh.vertices.data()),
mesh.vertices.size()
),
mesh.vertices.size()});
}
}
gpuModel.lastUsed = frame;
return gpuModel;
}
void ModelBatch::collectUnused() {
for (auto it = models.begin(); it != models.end();) {
if (frame - it->second.lastUsed > UNUSED_FRAMES ||
it->second.model.expired()) {
it = models.erase(it);
} else {
++it;
}
}
}
const util::TextureRegion& ModelBatch::getTexture(
const std::string& name, const TextureNamesMap* varTextures
) {
static const util::TextureRegion NONE {nullptr, UVRegion(0, 0, 1, 1)};
if (varTextures && !name.empty() && name.at(0) == '$') {
const auto& found = varTextures->find(name);
if (found == varTextures->end()) {
return NONE;
}
return getTexture(found->second, varTextures);
}
const auto& found = textures.find(&name);
if (found != textures.end()) {
return found->second;
}
auto byName = texturesByName.find(name);
if (byName == texturesByName.end()) {
byName = texturesByName.emplace(
name, util::get_texture_region(assets, name, "blocks:notfound")
).first;
}
return textures[&name] = byName->second;
}
void ModelBatch::draw(
const glm::mat4& matrix,
const glm::vec4& tint,
const glm::vec3& lightSampleOffset,
const model::Model* model,
const TextureNamesMap* varTextures
const std::shared_ptr<model::Model>& model,
const TextureNamesMap* varTextures,
bool translucent
) {
for (const auto& mesh : model->meshes) {
entries.push_back(DrawEntry {
matrix,
extract_rotation(matrix),
tint,
lightSampleOffset,
&mesh,
varTextures});
auto& queue =
translucent || tint.a < 1.0f ? translucentEntries : entries;
const auto& gpuModel = upload(model);
glm::vec3 lightSamplePos =
glm::vec3(matrix[3]) + lightsOffset + lightSampleOffset;
for (size_t i = 0; i < model->meshes.size(); i++) {
const auto& mesh = model->meshes[i];
if (mesh.vertices.empty()) {
continue;
}
const auto& region = getTexture(mesh.texture, varTextures);
const auto& uv = region.region;
queue.push_back(DrawEntry {
region.texture ? region.texture : blank.get(),
gpuModel.meshes[i].mesh.get(),
lightSamplePos,
mesh.shading,
Instance {
matrix,
tint,
glm::vec4(1, 1, 1, 0),
glm::vec4(uv.u1, uv.v1, uv.getWidth(), uv.getHeight()),
glm::vec4(mesh.shading ? 1.0f : 0.0f, 0, 0, 0)}});
}
}
void ModelBatch::resetOrder(size_t count) {
order.resize(count);
for (size_t i = 0; i < count; i++) {
order[i] = i;
}
}
void ModelBatch::render(std::vector<DrawEntry>& queue) {
if (queue.empty()) {
return;
}
bool backlight = settings.graphics.backlight.get();
instances.resize(queue.size());
for (size_t i = 0; i < order.size(); i++) {
auto& entry = queue[order[i]];
if (entry.shading) {
entry.instance.light =
MainBatch::sampleLight(entry.lightSamplePos, chunks, backlight);
}
instances[i] = entry.instance;
}
instanceBuffer->reload(instances.data(), instances.size());
const Texture* boundTexture = nullptr;
size_t start = 0;
for (size_t i = 1; i <= order.size(); i++) {
if (i < order.size()) {
const auto& prev = queue[order[i - 1]];
const auto& next = queue[order[i]];
if (prev.texture == next.texture && prev.mesh == next.mesh) {
continue;
}
}
const auto& entry = queue[order[start]];
if (entry.texture != boundTexture) {
boundTexture = entry.texture;
boundTexture->bind();
}
entry.mesh->drawInstanced(*instanceBuffer, start, i - start);
start = i;
}
queue.clear();
}
void ModelBatch::finishFrame() {
frame++;
textures.clear();
texturesByName.clear();
if (frame % COLLECT_EVERY == 0) {
collectUnused();
}
}
void ModelBatch::render() {
std::sort(entries.begin(), entries.end(),
[](const DrawEntry& a, const DrawEntry& b) {
return a.mesh->texture < b.mesh->texture;
renderOpaque();
resetOrder(translucentEntries.size());
render(translucentEntries);
finishFrame();
}
void ModelBatch::renderOpaque() {
resetOrder(entries.size());
std::sort(order.begin(), order.end(), [this](size_t a, size_t b) {
const auto& ea = entries[a];
const auto& eb = entries[b];
if (ea.texture != eb.texture) {
return ea.texture < eb.texture;
}
);
bool backlight = settings.graphics.backlight.get();
for (auto& entry : entries) {
localLightsOffset = entry.lightSampleOffset;
draw(
*entry.mesh,
entry.matrix,
entry.rotation,
entry.tint,
entry.varTextures,
backlight
);
localLightsOffset = {};
return ea.mesh < eb.mesh;
});
render(entries);
}
void ModelBatch::renderTranslucent(const glm::vec3& cameraPosition) {
distances.resize(translucentEntries.size());
for (size_t i = 0; i < translucentEntries.size(); i++) {
glm::vec3 delta =
glm::vec3(translucentEntries[i].instance.matrix[3]) - cameraPosition;
distances[i] = glm::dot(delta, delta);
}
batch->flush();
entries.clear();
resetOrder(translucentEntries.size());
std::stable_sort(order.begin(), order.end(), [this](size_t a, size_t b) {
return distances[a] > distances[b];
});
render(translucentEntries);
finishFrame();
}
void ModelBatch::setLightsOffset(const glm::vec3& offset) {
lightsOffset = offset;
}
void ModelBatch::setTexture(const std::string& name,
const TextureNamesMap* varTextures) {
if (varTextures && !name.empty() && name.at(0) == '$') {
const auto& found = varTextures->find(name);
if (found == varTextures->end()) {
return batch->setTexture(nullptr);
} else {
return setTexture(found->second, varTextures);
}
}
auto region = util::get_texture_region(assets, name, "blocks:notfound");
batch->setTexture(region.texture, region.region);
}

View file

@ -6,12 +6,17 @@
#include <glm/glm.hpp>
#include <unordered_map>
template<typename VertexStructure> class Mesh;
#include "assets/assets_util.hpp"
#include "graphics/core/MeshData.hpp"
template<typename VertexStructure>
class Mesh;
template<typename InstanceStructure>
class InstanceBuffer;
class Texture;
class Chunks;
class Assets;
struct EngineSettings;
class MainBatch;
namespace model {
struct Mesh;
@ -34,11 +39,17 @@ public:
const glm::mat4& matrix,
const glm::vec4& tint,
const glm::vec3& lightSampleOffset,
const model::Model* model,
const TextureNamesMap* varTextures
const std::shared_ptr<model::Model>& model,
const TextureNamesMap* varTextures,
bool translucent = false
);
void render();
void renderOpaque();
void renderTranslucent(const glm::vec3& cameraPosition);
void setLightsOffset(const glm::vec3& offset);
private:
const Assets& assets;
@ -46,31 +57,77 @@ private:
const EngineSettings& settings;
glm::vec3 lightsOffset {};
glm::vec3 localLightsOffset {};
static inline glm::vec3 SUN_VECTOR {0.411934f, 0.863868f, -0.279161f};
struct Vertex {
glm::vec3 coord;
glm::vec2 uv;
glm::vec3 normal;
std::unique_ptr<MainBatch> batch;
static constexpr VertexAttribute ATTRIBUTES[] = {
{VertexAttribute::Type::FLOAT, false, 3},
{VertexAttribute::Type::FLOAT, false, 2},
{VertexAttribute::Type::FLOAT, false, 3},
{{}, 0}};
};
void draw(
const model::Mesh& mesh,
const glm::mat4& matrix,
const glm::mat3& rotation,
const glm::vec4& tint,
const TextureNamesMap* varTextures,
bool backlight
);
struct Instance {
glm::mat4 matrix;
glm::vec4 tint;
glm::vec4 light;
glm::vec4 uvRegion;
glm::vec4 params;
void setTexture(const std::string& name,
const TextureNamesMap* varTextures);
static constexpr VertexAttribute ATTRIBUTES[] = {
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::FLOAT, false, 4},
{VertexAttribute::Type::FLOAT, false, 4},
{{}, 0}};
};
struct GpuMesh {
std::unique_ptr<Mesh<Vertex>> mesh;
size_t vertexCount = 0;
};
struct GpuModel {
std::weak_ptr<model::Model> model;
std::vector<GpuMesh> meshes;
uint64_t lastUsed = 0;
};
struct DrawEntry {
glm::mat4 matrix;
glm::mat3 rotation;
glm::vec4 tint;
glm::vec3 lightSampleOffset;
const model::Mesh* mesh;
const TextureNamesMap* varTextures;
const Texture* texture;
const Mesh<Vertex>* mesh;
glm::vec3 lightSamplePos;
bool shading;
Instance instance;
};
std::unordered_map<const model::Model*, GpuModel> models;
std::unordered_map<const std::string*, util::TextureRegion> textures;
std::unordered_map<std::string, util::TextureRegion> texturesByName;
std::vector<DrawEntry> entries;
std::vector<DrawEntry> translucentEntries;
std::vector<size_t> order;
std::vector<float> distances;
std::vector<Instance> instances;
std::unique_ptr<InstanceBuffer<Instance>> instanceBuffer;
std::unique_ptr<Texture> blank;
uint64_t frame = 0;
GpuModel& upload(const std::shared_ptr<model::Model>& model);
void collectUnused();
void resetOrder(size_t count);
void render(std::vector<DrawEntry>& queue);
void finishFrame();
const util::TextureRegion& getTexture(
const std::string& name, const TextureNamesMap* varTextures
);
};

View file

@ -187,6 +187,7 @@ model::Model ModelsGenerator::fromCustom(
mesh.vertices.push_back({v2, glm::vec2(reg.u2, reg.v2), norm});
mesh.vertices.push_back({v3, glm::vec2(reg.u1, reg.v2), norm});
}
model.calcBounds();
return model;
}
@ -213,7 +214,7 @@ model::Model ModelsGenerator::generate(
mesh.shading = !blockDef.shadeless;
switch (blockModel.type) {
case BlockModelType::AABB: {
glm::vec3 size = blockDef.hitboxes.at(0).size();
glm::vec3 size = variant.hitboxes.at(0).size();
float m = glm::max(size.x, glm::max(size.y, size.z));
m = glm::min(1.0f, m);
mesh.scale(size / m);

View file

@ -6,6 +6,7 @@
#include "CloudsRenderer.hpp"
#include "DebugLinesRenderer.hpp"
#include "Emitter.hpp"
#include "EntitiesRenderer.hpp"
#include "HandsRenderer.hpp"
#include "ModelBatch.hpp"
#include "NamedSkeletons.hpp"
@ -35,6 +36,7 @@
#include "graphics/core/Shadows.hpp"
#include "graphics/core/Cubemap.hpp"
#include "graphics/core/Texture.hpp"
#include "graphics/core/TranslucentLayers.hpp"
#include "items/Inventory.hpp"
#include "items/ItemDef.hpp"
#include "items/ItemStack.hpp"
@ -47,6 +49,7 @@
#include "voxels/Block.hpp"
#include "voxels/Chunk.hpp"
#include "voxels/Chunks.hpp"
#include "voxels/blocks_agent.hpp"
#include "voxels/Pathfinding.hpp"
#include "window/Window.hpp"
#include "world/Level.hpp"
@ -66,6 +69,31 @@ inline constexpr size_t MODEL_BATCH_CAPACITY = 20'000;
static debug::Logger logger("world-renderer");
namespace translucent {
enum Layer : size_t {
BLOCKS,
ENTITIES,
WEATHER,
COUNT
};
}
struct EntityShaderPass {
float alphaThreshold;
bool opaque;
bool forward;
bool forwardLight;
float opacity;
};
static void setup_entity_pass(Shader& shader, const EntityShaderPass& pass) {
shader.uniform1f("u_alphaThreshold", pass.alphaThreshold);
shader.uniform1i("u_opaque", pass.opaque);
shader.uniform1i("u_forward", pass.forward);
shader.uniform1i("u_forwardLight", pass.forwardLight);
shader.uniform1f("u_opacity", pass.opacity);
}
bool WorldRenderer::showChunkBorders = false;
bool WorldRenderer::showEntitiesDebug = false;
@ -134,6 +162,7 @@ WorldRenderer::WorldRenderer(
shadowMapping = std::make_unique<Shadows>(level);
debugLines = std::make_unique<DebugLinesRenderer>(level);
cloudsRenderer = std::make_unique<CloudsRenderer>();
entitiesRenderer = std::make_unique<EntitiesRenderer>(assets, *level.entities);
keepAlive(observe_setting(settings.graphics.enableFog, dirtySettings));
keepAlive(observe_setting(settings.graphics.advancedRender, dirtySettings));
@ -147,6 +176,7 @@ void WorldRenderer::refreshSettings() {
Shader* affectedShaders[] {
&assets.require<Shader>("main"),
&assets.require<Shader>("entity"),
&assets.require<Shader>("model"),
&assets.require<Shader>("clouds"),
&assets.require<Shader>("translucent"),
&assets.require<PostEffect>("deferred_lighting").getShader(),
@ -246,17 +276,19 @@ void WorldRenderer::renderOpaque(
frustumCulling->update(camera.getProjView());
}
entityShader.uniform1i("u_alphaClip", true);
entityShader.uniform1i("u_dithering", 1);
entityShader.uniform1f("u_opacity", 1.0f);
level.entities->render(
assets,
setup_entity_pass(entityShader, {0.5f, true, false, false, 1.0f});
auto& modelShader = assets.require<Shader>("model");
setupWorldShader(modelShader, camera, settings, fogFactor);
setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f});
entitiesRenderer->render(
*modelBatch,
culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0
);
modelBatch->render();
modelBatch->renderOpaque();
entityShader.use();
particles->render(camera);
auto& mainShader = assets.require<Shader>("main");
@ -292,9 +324,9 @@ void WorldRenderer::renderBlockSelection() {
const glm::vec3 point = selection.hitPosition;
const glm::vec3 norm = selection.normal;
const std::vector<AABB>& hitboxes =
block.rotatable ? block.rt.hitboxes[selection.vox.state.rotation]
: block.hitboxes;
const auto& hitboxes = block.getHitboxes(
blocks_agent::hitbox_state(*player.chunks, pos, selection.vox.state)
);
lineBatch->lineWidth(2.0f);
for (auto& hitbox : hitboxes) {
@ -323,7 +355,7 @@ void WorldRenderer::renderInWorldLines(
if (debug && showEntitiesDebug) {
auto ctx = pctx.sub(lineBatch.get());
bool culling = engine.getSettings().graphics.frustumCulling.get();
level.entities->renderDebug(
entitiesRenderer->renderDebug(
*lineBatch, culling ? frustumCulling.get() : nullptr, ctx,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0
);
@ -335,7 +367,7 @@ void WorldRenderer::updateEntitiesCulling(const Camera& camera) {
if (culling) {
frustumCulling->update(camera.getProjView());
}
level.entities->updateCulling(
entitiesRenderer->updateCulling(
culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0
@ -373,21 +405,7 @@ void WorldRenderer::renderFrameClassic(
renderDebugLines(ctx, camera);
}
DrawContext wctx = ctx.sub();
wctx.useTexture(advanced_pipeline::TARGET_SKYBOX, skybox->getCubemap());
wctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr);
// Translucent blocks
{
const auto& settings = engine.getSettings();
auto& translucentShader = assets.require<Shader>("translucent");
auto sctx = wctx.sub();
sctx.setCullFace(true);
translucentShader.use();
setupWorldShader(translucentShader, camera, settings, calcFogFactor());
chunksRenderer->drawSortedMeshes(camera, translucentShader);
}
renderWeatherEffects(camera);
renderTranslucency(ctx, camera, postProcessing);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
@ -418,6 +436,7 @@ void WorldRenderer::renderFrameAdvanced(
ctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr);
postProcessing.bindDepthBuffer();
ctx.setFramebuffer(postProcessing.getFramebuffer());
skybox->draw(
level.environment, ctx, camera, worldInfo.daytime, weather.clouds()
);
@ -426,21 +445,7 @@ void WorldRenderer::renderFrameAdvanced(
renderDebugLines(ctx, camera);
}
DrawContext wctx = ctx.sub();
wctx.useTexture(advanced_pipeline::TARGET_SKYBOX, skybox->getCubemap());
wctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr);
// Translucent blocks
{
const auto& settings = engine.getSettings();
auto& translucentShader = assets.require<Shader>("translucent");
auto sctx = wctx.sub();
sctx.setCullFace(true);
translucentShader.use();
setupWorldShader(translucentShader, camera, settings, fogFactor);
chunksRenderer->drawSortedMeshes(camera, translucentShader);
}
renderWeatherEffects(camera);
renderTranslucency(ctx, camera, postProcessing);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
@ -528,10 +533,10 @@ void WorldRenderer::renderWeatherEffects(Camera& camera) {
float zero = weather->fall.minOpacity;
float one = weather->fall.maxOpacity;
float t = (weather->intensity * (one - zero)) * maxIntensity + zero;
entityShader.uniform1i("u_alphaClip", weather->fall.opaque);
entityShader.uniform1i("u_dithering", 0);
entityShader.uniform1f(
"u_opacity", weather->fall.opaque ? t * t : t
bool opaque = weather->fall.opaque;
setup_entity_pass(
entityShader,
{opaque ? 0.5f : 0.15f, false, true, false, opaque ? t * t : t}
);
if (weather->intensity > 1.e-3f && !weather->fall.texture.empty()) {
precipitation->render(camera, *weather);
@ -539,6 +544,67 @@ void WorldRenderer::renderWeatherEffects(Camera& camera) {
}
}
void WorldRenderer::renderTranslucency(
const DrawContext& pctx,
Camera& camera,
PostProcessing& postProcessing
) {
const auto& settings = engine.getSettings();
float fogFactor = calcFogFactor();
auto& frame = *postProcessing.getFramebuffer();
const auto& vp = pctx.getViewport();
if (translucentLayers == nullptr) {
translucentLayers = std::make_unique<TranslucentLayers>(
translucent::COUNT, vp.x, vp.y
);
} else {
translucentLayers->resize(vp.x, vp.y);
}
translucentLayers->prepare(frame.getFBO());
DrawContext ctx = pctx.sub();
ctx.setFramebuffer(&frame);
ctx.setDepthTest(true);
ctx.setDepthMask(true);
ctx.setBlendMode(BlendMode::coverage);
ctx.useTexture(advanced_pipeline::TARGET_SKYBOX, skybox->getCubemap());
ctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr);
{
auto lctx = ctx.sub();
lctx.setFramebuffer(&translucentLayers->getLayer(translucent::BLOCKS));
lctx.setCullFace(true);
auto& shader = assets.require<Shader>("translucent");
shader.use();
setupWorldShader(shader, camera, settings, fogFactor);
chunksRenderer->drawSortedMeshes(camera, shader);
}
{
auto lctx = ctx.sub();
lctx.setFramebuffer(&translucentLayers->getLayer(translucent::ENTITIES));
lctx.setCullFace(true);
auto& shader = assets.require<Shader>("model");
setupWorldShader(shader, camera, settings, fogFactor);
setup_entity_pass(shader, {0.002f, false, true, true, 1.0f});
modelBatch->renderTranslucent(camera.position);
}
{
auto lctx = ctx.sub();
lctx.setFramebuffer(&translucentLayers->getLayer(translucent::WEATHER));
renderWeatherEffects(camera);
}
{
auto cctx = ctx.sub();
cctx.setDepthTest(false);
cctx.setDepthMask(false);
cctx.setBlendMode(BlendMode::premultiplied);
translucentLayers->compose(
assets.require<Shader>("translucent_composite")
);
}
}
void WorldRenderer::renderDebugLines(const DrawContext& ctx, Camera& camera) {
auto& linesShader = assets.require<Shader>("lines");
linesShader.use();
@ -550,7 +616,7 @@ void WorldRenderer::renderDebugLines(const DrawContext& ctx, Camera& camera) {
}
void WorldRenderer::renderHandsPass(const DrawContext& pctx, Camera& camera) {
auto& entityShader = assets.require<Shader>("entity");
auto& modelShader = assets.require<Shader>("model");
DrawContext ctx = pctx.sub();
ctx.setDepthTest(true);
@ -565,7 +631,8 @@ void WorldRenderer::renderHandsPass(const DrawContext& pctx, Camera& camera) {
hudcam.setFov(0.9f);
hudcam.position = {};
setupWorldShader(entityShader, hudcam, engine.getSettings(), 0.0f);
setupWorldShader(modelShader, hudcam, engine.getSettings(), 0.0f);
setup_entity_pass(modelShader, {0.15f, false, false, false, 1.0f});
hands->render(camera);
}

View file

@ -18,6 +18,7 @@ class ChunksRenderer;
class DebugLinesRenderer;
class DrawContext;
class Engine;
class EntitiesRenderer;
class Frustum;
class HandsRenderer;
class Level;
@ -33,6 +34,7 @@ class Shader;
class Shadows;
class Skybox;
class TextsRenderer;
class TranslucentLayers;
class CloudsRenderer;
struct EngineSettings;
struct Weather;
@ -79,6 +81,8 @@ private:
std::unique_ptr<DebugLinesRenderer> debugLines;
std::unique_ptr<PrecipitationRenderer> precipitation;
std::unique_ptr<CloudsRenderer> cloudsRenderer;
std::unique_ptr<EntitiesRenderer> entitiesRenderer;
std::unique_ptr<TranslucentLayers> translucentLayers;
float timer = 0.0f;
bool debug = false;
@ -125,6 +129,12 @@ private:
void renderWeatherEffects(Camera& camera);
void renderTranslucency(
const DrawContext& context,
Camera& camera,
PostProcessing& postProcessing
);
void renderHandsPass(const DrawContext& pctx, Camera& camera);
void renderDebugLines(const DrawContext& context, Camera& camera);

View file

@ -92,10 +92,18 @@ void Container::act(float delta) {
// TODO: make it interval-based
gui.getWindow().setShouldRefresh();
}
for (IntervalEvent& event : intervalEvents) {
event.timer += delta;
if (event.timer > event.interval) {
event.callback();
for (size_t i = 0; i < intervalEvents.size(); i++) {
if (intervalEvents[i].repeat == 0) {
continue;
}
intervalEvents[i].timer += delta;
if (intervalEvents[i].timer > intervalEvents[i].interval) {
auto callback = intervalEvents[i].callback;
callback();
IntervalEvent& event = intervalEvents[i];
if (event.repeat == 0) {
continue;
}
event.timer = fmod(event.timer, event.interval);
if (event.repeat > 0) {
event.repeat--;
@ -232,8 +240,19 @@ void Container::clear() {
refresh();
}
void Container::listenInterval(float interval, OnTimeOut callback, int repeat) {
intervalEvents.push_back({std::move(callback), interval, 0.0f, repeat});
int Container::listenInterval(float interval, OnTimeOut callback, int repeat) {
int id = nextIntervalId++;
intervalEvents.push_back({id, std::move(callback), interval, 0.0f, repeat});
return id;
}
void Container::cancelInterval(int id) {
for (auto& event : intervalEvents) {
if (event.id == id) {
event.repeat = 0;
return;
}
}
}
void Container::setSize(const glm::vec2& size) {

View file

@ -13,6 +13,7 @@ namespace gui {
protected:
std::vector<std::shared_ptr<UINode>> nodes;
std::vector<IntervalEvent> intervalEvents;
int nextIntervalId = 1;
int scrollY = 0;
int scrollX = 0;
int scrollStep = 40;
@ -41,7 +42,8 @@ namespace gui {
virtual void remove(const std::string& id);
virtual void scrolled(int value) override;
virtual void setScrollable(bool flag);
void listenInterval(float interval, OnTimeOut callback, int repeat=-1);
int listenInterval(float interval, OnTimeOut callback, int repeat=-1);
void cancelInterval(int id);
virtual glm::vec2 getContentOffset() const override {
return glm::vec2(scrollX, scrollY);
};

View file

@ -8,6 +8,7 @@ namespace gui {
using OnTimeOut = std::function<void()>;
struct IntervalEvent {
int id;
OnTimeOut callback;
float interval;
float timer;

View file

@ -125,6 +125,7 @@ void guiutil::confirm(
label->setSize(glm::vec2(600, 50));
label->setMultiline(true);
label->setTextWrapping(true);
label->setMarkup("md");
panel->add(label);
auto subpanel = std::make_shared<Panel>(gui, glm::vec2(600, 53));

View file

@ -0,0 +1,11 @@
#pragma once
#include "interfaces/Process.hpp"
class SystemProcess : public Process {
public:
virtual ~SystemProcess() override = default;
virtual int getStdinDescriptor() const = 0;
virtual int getStdoutDescriptor() const = 0;
};

View file

@ -14,8 +14,13 @@ std::filesystem::path io::MemoryDevice::resolve(std::string_view path) {
std::unique_ptr<std::ostream> io::MemoryDevice::write(std::string_view path) {
std::string filePath = std::string(path);
auto memoryStream = std::make_unique<memory_ostream>();
memoryStream->set_sync_callback([this, filePath](std::string_view data) {
createFile(std::move(filePath), util::Buffer<char>(data.data(), data.size()));
});
return std::make_unique<finalizing_ostream>(
std::make_unique<memory_ostream>(),
std::move(memoryStream),
[this, filePath](auto ostream) {
auto& memoryStream = dynamic_cast<memory_ostream&>(*ostream);
createFile(std::move(filePath), memoryStream.release());

132
src/io/fd_istream.hpp Normal file
View file

@ -0,0 +1,132 @@
#pragma once
#include <array>
#include <istream>
#include <streambuf>
#include <vector>
#ifdef _WIN32
#include <Windows.h>
#endif
#ifndef _WIN32
#include <unistd.h>
#endif
class fd_istreambuf final : public std::streambuf {
static constexpr size_t BUFFER_SIZE = 4096;
public:
#ifdef _WIN32
explicit fd_istreambuf(HANDLE handle)
: handle(handle) {
setg(buffer.data(), buffer.data(), buffer.data());
}
~fd_istreambuf() override {
if (handle != nullptr && handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
handle = INVALID_HANDLE_VALUE;
}
}
protected:
int_type underflow() override {
if (handle == nullptr || handle == INVALID_HANDLE_VALUE) {
return traits_type::eof();
}
if (gptr() != egptr()) {
return traits_type::to_int_type(*gptr());
}
std::array<char, BUFFER_SIZE> chunk {};
DWORD readCount = 0;
if (!ReadFile(
handle,
chunk.data(),
static_cast<DWORD>(chunk.size()),
&readCount,
nullptr
) ||
readCount == 0) {
return traits_type::eof();
}
buffer.assign(chunk.begin(), chunk.begin() + readCount);
setg(buffer.data(), buffer.data(), buffer.data() + buffer.size());
return traits_type::to_int_type(*gptr());
}
pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode)
override {
return pos_type(off_type(-1));
}
pos_type seekpos(pos_type, std::ios_base::openmode) override {
return pos_type(off_type(-1));
}
private:
HANDLE handle;
std::vector<char> buffer;
#else
explicit fd_istreambuf(int fd)
: fd(fd) {
setg(buffer.data(), buffer.data(), buffer.data());
}
~fd_istreambuf() override {
if (fd >= 0) {
::close(fd);
fd = -1;
}
}
protected:
int_type underflow() override {
if (fd < 0) {
return traits_type::eof();
}
if (gptr() != egptr()) {
return traits_type::to_int_type(*gptr());
}
buffer.resize(BUFFER_SIZE);
const auto count = ::read(fd, buffer.data(), buffer.size());
if (count <= 0) {
return traits_type::eof();
}
buffer.resize(static_cast<size_t>(count));
setg(buffer.data(), buffer.data(), buffer.data() + buffer.size());
return traits_type::to_int_type(*gptr());
}
pos_type seekoff(
off_type,
std::ios_base::seekdir,
std::ios_base::openmode
) override {
return pos_type(off_type(-1));
}
pos_type seekpos(pos_type, std::ios_base::openmode) override {
return pos_type(off_type(-1));
}
private:
int fd;
std::vector<char> buffer;
#endif
};
class fd_istream final : public std::istream {
public:
#ifdef _WIN32
explicit fd_istream(HANDLE handle)
: std::istream(&buf), buf(handle) {}
#else
explicit fd_istream(int fd)
: std::istream(&buf), buf(fd) {}
#endif
private:
fd_istreambuf buf;
};

158
src/io/fd_ostream.hpp Normal file
View file

@ -0,0 +1,158 @@
#pragma once
#include <array>
#include <iostream>
#include <streambuf>
#ifdef _WIN32
#include <Windows.h>
#endif
#ifndef _WIN32
#include <unistd.h>
#endif
class fd_ostreambuf final : public std::streambuf {
static constexpr size_t BUFFER_SIZE = 4096;
public:
#ifdef _WIN32
explicit fd_ostreambuf(HANDLE handle) : handle(handle) {
setp(buffer.data(), buffer.data() + buffer.size());
}
~fd_ostreambuf() override {
fd_ostreambuf::sync();
if (handle != nullptr && handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
handle = INVALID_HANDLE_VALUE;
}
}
protected:
int_type overflow(int_type ch) override {
if (ch == traits_type::eof()) {
return traits_type::not_eof(ch);
}
if (pptr() == epptr()) {
if (sync() != 0) {
return traits_type::eof();
}
}
*pptr() = traits_type::to_char_type(ch);
pbump(1);
return ch;
}
int sync() override {
if (handle == nullptr || handle == INVALID_HANDLE_VALUE) {
return -1;
}
const auto size = static_cast<size_t>(pptr() - pbase());
if (size == 0) {
return 0;
}
DWORD written = 0;
if (!WriteFile(
handle, pbase(), static_cast<DWORD>(size), &written, nullptr
)) {
return -1;
}
setp(buffer.data(), buffer.data() + buffer.size());
return 0;
}
pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode)
override {
return pos_type(off_type(-1));
}
pos_type seekpos(pos_type, std::ios_base::openmode) override {
return pos_type(off_type(-1));
}
private:
HANDLE handle;
std::array<char, BUFFER_SIZE> buffer {};
#else
explicit fd_ostreambuf(int fd) : fd(fd) {
setp(buffer.data(), buffer.data() + buffer.size());
}
~fd_ostreambuf() override {
fd_ostreambuf::sync();
if (fd >= 0) {
::close(fd);
fd = -1;
}
}
protected:
int_type overflow(int_type ch) override {
if (ch == traits_type::eof()) {
return traits_type::not_eof(ch);
}
if (pptr() == epptr()) {
if (sync() != 0) {
return traits_type::eof();
}
}
*pptr() = traits_type::to_char_type(ch);
pbump(1);
return ch;
}
int sync() override {
if (fd < 0) {
return -1;
}
const auto size = static_cast<size_t>(pptr() - pbase());
if (size == 0) {
return 0;
}
char* ptr = pbase();
size_t remaining = size;
while (remaining > 0) {
const auto written = ::write(fd, ptr, remaining);
if (written < 0) {
if (errno == EINTR) {
continue;
}
return -1;
}
ptr += written;
remaining -= static_cast<size_t>(written);
}
setp(buffer.data(), buffer.data() + buffer.size());
return 0;
}
pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode)
override {
return pos_type(off_type(-1));
}
pos_type seekpos(pos_type, std::ios_base::openmode) override {
return pos_type(off_type(-1));
}
private:
int fd;
std::array<char, BUFFER_SIZE> buffer {};
#endif
};
class fd_ostream final : public std::ostream {
public:
#ifdef _WIN32
explicit fd_ostream(HANDLE handle) : std::ostream(&buf), buf(handle) {
}
#else
explicit fd_ostream(int fd) : std::ostream(&buf), buf(fd) {
}
#endif
private:
fd_ostreambuf buf;
};

View file

@ -3,6 +3,9 @@
#include <iostream>
#include <streambuf>
#include <cstring>
#include <climits>
#include <memory>
#include <functional>
#include <algorithm>
#include <string_view>
@ -13,94 +16,111 @@ public:
explicit memory_buffer(size_t initial_size = 64)
: buffer(std::make_unique<char[]>(initial_size)),
capacity(initial_size) {
setp(buffer.get(), buffer.get() + initial_size);
setp(buffer.get(), buffer.get() + capacity);
}
std::string_view view() const {
return std::string_view(pbase(), pptr() - pbase());
return std::string_view(pbase(), size());
}
util::Buffer<char> release() {
return {std::move(buffer), size()};
size_t n = size();
return {std::move(buffer), n};
}
size_t size() const {
return pptr() - pbase();
return std::max(length, position());
}
void set_sync_callback(std::function<void(std::string_view)> callback) {
on_sync = std::move(callback);
}
protected:
int_type overflow(int_type c) override {
if (c == traits_type::eof())
return traits_type::eof();
const size_t data_size = pptr() - pbase();
const size_t new_capacity = std::max(capacity * 2, data_size + 1);
auto new_buffer = std::make_unique<char[]>(new_capacity);
std::memcpy(new_buffer.get(), pbase(), data_size);
buffer = std::move(new_buffer);
capacity = new_capacity;
setp(buffer.get(), buffer.get() + new_capacity);
pbump(data_size);
reserve(position() + 1);
*pptr() = traits_type::to_char_type(c);
pbump(1);
return c;
}
pos_type seekoff(
off_type off,
std::ios_base::seekdir way,
std::ios_base::openmode mode = std::ios_base::out
std::ios_base::seekdir dir,
std::ios_base::openmode which
) override {
// only position query (tellp) is supported
if (off == 0 && way == std::ios_base::cur &&
(mode & std::ios_base::out)) {
return pos_type(off_type(size()));
if (!(which & std::ios_base::out)) {
return pos_type(off_type(-1));
}
return pos_type(off_type(-1));
length = size();
off_type base;
switch (dir) {
case std::ios_base::beg: base = 0; break;
case std::ios_base::cur: base = position(); break;
case std::ios_base::end: base = length; break;
default: return pos_type(off_type(-1));
}
off_type target = base + off;
if (target < 0 || target > static_cast<off_type>(length)) {
return pos_type(off_type(-1));
}
set_position(target);
return pos_type(target);
}
std::streamsize xsputn(const char* s, std::streamsize count) override {
const std::streamsize avail = epptr() - pptr();
if (avail >= count) {
std::memcpy(pptr(), s, count);
pbump(count);
return count;
}
std::streamsize written = 0;
if (avail > 0) {
std::memcpy(pptr(), s, avail);
written += avail;
s += avail;
count -= avail;
pbump(avail);
}
const size_t data_size = pptr() - pbase();
const size_t required_capacity = data_size + count;
const size_t new_capacity = std::max(capacity * 2, required_capacity);
auto new_buffer = std::make_unique<char[]>(new_capacity);
std::memcpy(new_buffer.get(), pbase(), data_size);
std::memcpy(new_buffer.get() + data_size, s, count);
buffer = std::move(new_buffer);
capacity = new_capacity;
setp(buffer.get(), buffer.get() + new_capacity);
pbump(data_size + count);
written += count;
return written;
pos_type seekpos(pos_type pos, std::ios_base::openmode which) override {
return seekoff(off_type(pos), std::ios_base::beg, which);
}
private:
std::unique_ptr<char[]> buffer;
size_t capacity;
size_t length = 0;
size_t position() const {
return pptr() - pbase();
}
void advance(size_t n) {
while (n > 0) {
int step = static_cast<int>(std::min<size_t>(n, INT_MAX));
pbump(step);
n -= step;
}
}
void set_position(size_t pos) {
setp(buffer.get(), buffer.get() + capacity);
advance(pos);
}
void reserve(size_t required) {
if (required <= capacity) {
return;
}
size_t pos = position();
length = size();
size_t new_capacity = std::max(capacity * 2, required);
auto new_buffer = std::make_unique<char[]>(new_capacity);
std::memcpy(new_buffer.get(), buffer.get(), length);
buffer = std::move(new_buffer);
capacity = new_capacity;
set_position(pos);
}
int sync() override {
if (on_sync) {
on_sync(view());
}
return 0;
}
std::function<void(std::string_view)> on_sync;
};
class memory_ostream : public std::ostream {
@ -115,6 +135,10 @@ public:
util::Buffer<char> release() {
return buffer.release();
}
void set_sync_callback(std::function<void(std::string_view)> callback) {
buffer.set_sync_callback(std::move(callback));
}
private:
memory_buffer buffer;
};

View file

@ -3,8 +3,7 @@
#include "util/stringutil.hpp"
ItemDef::ItemDef(const std::string& name)
: name(name),
caption(util::id_to_caption(name)),
: name(name),
scriptName(name.substr(name.find(':') + 1)) {
}
void ItemDef::cloneTo(ItemDef& dst) {

View file

@ -69,11 +69,11 @@ void BlocksController::breakBlock(
onBlockInteraction(
player, glm::ivec3(x, y, z), def, BlockInteraction::destruction
);
scripting::on_block_broken(player, def, glm::ivec3(x, y, z));
blocks_agent::set(chunks, x, y, z, 0, {});
if (lighting) {
lighting->onBlockSet(x, y, z, 0);
}
scripting::on_block_broken(player, def, glm::ivec3(x, y, z));
if (def.rt.extended) {
updateSides(x, y, z , def.size.x, def.size.y, def.size.z);
} else {
@ -130,14 +130,26 @@ void BlocksController::updateBlock(int x, int y, int z) {
}
void BlocksController::update(float delta, uint padding) {
if (int parts = randTickClock.update(delta)) {
for (int i = 0; i < parts; i++) {
randomTick(randTickClock.convertPart(i), randTickClock.getParts(), padding);
auto& worldInfo = level.getWorld().getInfo();
if (worldInfo.getLogicFlag("random_ticks", true)) {
if (int parts = randTickClock.update(delta)) {
for (int i = 0; i < parts; i++) {
randomTick(
randTickClock.convertPart(i),
randTickClock.getParts(),
padding
);
}
}
}
if (int parts = blocksTickClock.update(delta)) {
for (int i = 0; i < parts; i++) {
onBlocksTick(blocksTickClock.convertPart(i), blocksTickClock.getParts());
if (worldInfo.getLogicFlag("block_ticks", true)) {
if (int parts = blocksTickClock.update(delta)) {
for (int i = 0; i < parts; i++) {
onBlocksTick(
blocksTickClock.convertPart(i), blocksTickClock.getParts()
);
}
}
}
if (worldTickClock.update(delta)) {

View file

@ -55,6 +55,32 @@ void EngineController::deleteWorld(const std::string& name) {
);
}
void EngineController::deleteWorldContent(
const std::string& name, ContentRemovalRequest request, bool loadWorld
) {
io::path folder = engine.getPaths().getWorldFolderByName(name);
auto deletion = [this, folder, loadWorld, request=std::move(request)]() {
logger.info() << "deleting content from the world";
WorldFiles worldFiles(folder);
worldFiles.deleteContent(std::move(request));
if (loadWorld) {
openWorld(folder.name(), true);
}
};
if (engine.isHeadless()) {
deletion();
return;
}
guiutil::confirm(
engine,
langs::get(L"delete-content-confirm", L"world") + L" (" +
util::str2wstr_utf8(folder.string()) + L")",
deletion
);
}
std::shared_ptr<Task> create_converter(
Engine& engine,
const std::shared_ptr<WorldFiles>& worldFiles,
@ -174,20 +200,20 @@ static dv::value create_missing_content_report(
}
void EngineController::onMissingContent(
const std::string& worldName,
const std::shared_ptr<ContentReport>& report
) {
auto fullReport = create_missing_content_report(report);
fullReport["world"] = worldName;
if (engine.isHeadless()) {
throw std::runtime_error(
"missing content: " +
util::quote(json::stringify(create_missing_content_report(report), true, " "))
util::quote(json::stringify(std::move(fullReport), true, " "))
);
} else {
engine.setScreen(std::make_shared<MenuScreen>(engine));
menus::show(
engine,
"reports/missing_content",
{create_missing_content_report(report)}
);
menus::show(engine, "reports/missing_content", {std::move(fullReport)});
}
}
@ -234,7 +260,7 @@ void EngineController::openWorld(const std::string& name, bool confirmConvert) {
return;
}
if (report->hasMissingContent()) {
onMissingContent(report);
onMissingContent(name, report);
return;
}

View file

@ -9,12 +9,16 @@ class Engine;
class World;
class ContentReport;
class LevelController;
struct ContentRemovalRequest;
class EngineController {
Engine& engine;
int64_t localPlayer = -1;
void onMissingContent(const std::shared_ptr<ContentReport>& report);
void onMissingContent(
const std::string& worldName,
const std::shared_ptr<ContentReport>& report
);
public:
EngineController(Engine& engine);
@ -27,6 +31,10 @@ public:
/// @param name world name
void deleteWorld(const std::string& name);
void deleteWorldContent(
const std::string& name, ContentRemovalRequest request, bool loadWorld
);
void reconfigPacks(
LevelController* controller,
const std::vector<std::string>& packsToAdd,

View file

@ -459,7 +459,7 @@ void PlayerController::processRightClick(
blockid_t chosenBlock = def.rt.id;
if (def.obstacle) {
const auto& hitboxes = def.rt.hitboxes[state.rotation];
const auto& hitboxes = def.getHitboxes(state);
for (const AABB& blockAABB : hitboxes) {
if (level.entities->hasBlockingInside(blockAABB.translated(coord)
)) {
@ -480,6 +480,11 @@ void PlayerController::processRightClick(
}
}
if (chosenBlock != vox->id && chosenBlock) {
if (!scripting::can_block_be_placed(
&player, def, coord, state.rotation
)) {
return;
}
if (!player.isInfiniteItems()) {
auto& slot = player.getInventory()->getSlot(player.getChosenSlot());
slot.setCount(slot.getCount() - 1);
@ -493,11 +498,11 @@ void PlayerController::processRightClick(
void PlayerController::updateEntityInteraction(
entityid_t eid, bool lclick, bool rclick
) {
auto entityOpt = level.entities->get(eid);
if (!entityOpt.has_value()) {
auto entityPtr = level.entities->get(eid);
if (entityPtr == nullptr) {
return;
}
auto entity = *entityOpt;
const auto& entity = *entityPtr;
if (lclick) {
scripting::on_attacked(entity, &player, player.getEntity());
}

View file

@ -19,6 +19,18 @@ namespace {
std::unique_ptr<std::ostream> out;
};
std::vector<std::optional<StreamDescriptor>> descriptors;
int add_descriptor(StreamDescriptor descriptor) {
for (int i = 0; i < static_cast<int>(descriptors.size()); ++i) {
if (!descriptors[i].has_value()) {
descriptors[i] = std::move(descriptor);
return i;
}
}
descriptors.emplace_back(std::move(descriptor));
return static_cast<int>(descriptors.size() - 1);
}
}
std::istream* io_descriptors::get_input(int id) {
@ -121,6 +133,18 @@ void io_descriptors::close(int id) {
::descriptors[id] = std::nullopt;
}
int io_descriptors::add_descriptor(std::unique_ptr<std::istream> stream) {
return add_descriptor(StreamDescriptor {
std::move(stream), nullptr
});
}
int io_descriptors::add_descriptor(std::unique_ptr<std::ostream> stream) {
return add_descriptor(StreamDescriptor {
nullptr, std::move(stream)
});
}
int io_descriptors::open_descriptor(const io::path& path, bool write, bool read) {
std::unique_ptr<std::istream> in;
std::unique_ptr<std::ostream> out;
@ -138,15 +162,9 @@ int io_descriptors::open_descriptor(const io::path& path, bool write, bool read)
return -1;
}
for (int i = 0; i < static_cast<int>(descriptors.size()); ++i) {
if (!descriptors[i].has_value()) {
descriptors[i] = StreamDescriptor{ std::move(in), std::move(out) };
return i;
}
}
::descriptors.emplace_back(StreamDescriptor{ std::move(in), std::move(out) });
return static_cast<int>(::descriptors.size() - 1);
return add_descriptor(StreamDescriptor{
std::move(in), std::move(out)
});
}

View file

@ -1,6 +1,7 @@
#pragma once
#include <istream>
#include <memory>
#include <ostream>
#include "io/fwd.hpp"
@ -22,6 +23,8 @@ namespace scripting::io_descriptors {
void close(int id);
int open_descriptor(const io::path& path, bool write, bool read);
int add_descriptor(std::unique_ptr<std::istream> stream);
int add_descriptor(std::unique_ptr<std::ostream> stream);
void close_all_descriptors();
}

View file

@ -62,6 +62,7 @@ static int l_set_model(lua::State* L) {
} else {
modelOverride = {lua::require_string(L, 3), {}, true};
}
skeleton->boundsDirty = true;
}
return 0;
}
@ -85,6 +86,18 @@ static int l_set_matrix(lua::State* L) {
}
auto index = index_range_check(*skeleton, lua::tointeger(L, 2));
skeleton->pose.matrices[index] = lua::tomat4(L, 3);
skeleton->boundsDirty = true;
}
return 0;
}
static int l_get_bone_offset(lua::State* L) {
if (auto skeleton = get_skeleton(L)) {
if (skeleton->config == nullptr) {
return 0;
}
auto index = index_range_check(*skeleton, lua::tointeger(L, 2));
return lua::pushvec(L, skeleton->config->getBones()[index]->getOffset());
}
return 0;
}
@ -93,6 +106,7 @@ static int l_reset_pose(lua::State* L) {
if (auto skeleton = get_skeleton(L)) {
auto& pose = skeleton->pose;
std::fill(pose.matrices.begin(), pose.matrices.end(), glm::mat4(1.0f));
skeleton->boundsDirty = true;
}
return 0;
}
@ -146,6 +160,7 @@ static int l_set_visible(lua::State* L) {
} else {
skeleton->visible = lua::toboolean(L, 2);
}
skeleton->boundsDirty = true;
}
return 0;
}
@ -190,7 +205,9 @@ static int l_is_interpolated(lua::State* L) {
static int l_set_interpolated(lua::State* L) {
if (auto skeleton = get_skeleton(L)) {
skeleton->interpolation.setEnabled(lua::toboolean(L, 2));
bool enabled = lua::toboolean(L, 2);
skeleton->interpolation.setEnabled(enabled);
skeleton->rotationInterpolation.setEnabled(enabled);
}
return 0;
}
@ -332,6 +349,7 @@ static int l_apply_track(lua::State* L) {
return index > 0 && index <= MAX_TRACK_VALUES ? values[index] : fallback;
};
auto& matrices = skeleton->pose.matrices;
skeleton->boundsDirty = true;
for (size_t i = 0; i < track.bones.size(); i++) {
int index = track.indices[i];
if (index < 0 || static_cast<size_t>(index) >= matrices.size()) {
@ -372,6 +390,7 @@ const luaL_Reg skeletonlib[] = {
{"set_model", lua::wrap<l_set_model>},
{"get_matrix", lua::wrap<l_get_matrix>},
{"set_matrix", lua::wrap<l_set_matrix>},
{"get_bone_offset", lua::wrap<l_get_bone_offset>},
{"reset_pose", lua::wrap<l_reset_pose>},
{"get_texture", lua::wrap<l_get_texture>},
{"set_texture", lua::wrap<l_set_texture>},

View file

@ -61,9 +61,11 @@ static int l_get_rot(lua::State* L) {
static int l_set_rot(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
auto matrix = lua::tomat4(L, 2);
glm::mat3 matrix(lua::tomat4(L, 2));
check_valid(matrix);
entity->getTransform().setRot(matrix);
auto rotation = glm::normalize(glm::quat_cast(matrix));
entity->getTransform().setRot(glm::mat3_cast(rotation));
entity->setInterpolatedRotation(rotation);
}
return 0;
}

View file

@ -19,13 +19,16 @@
#include "util/stringutil.hpp"
#include "window/Window.hpp"
#include "world/Level.hpp"
#include "world/files/WorldFiles.hpp"
#include <array>
#include <unordered_map>
using namespace scripting;
namespace {
static std::array<std::unique_ptr<Process>, MAX_SUBPROCESSES> processes;
static std::unordered_map<int, std::unique_ptr<SystemProcess>> processes;
static int next_process_id = 1;
}
/// @brief Check if content is loaded
@ -325,11 +328,45 @@ static int l_delete_world(lua::State* L) {
return 0;
}
static ContentRemovalRequest parse_content_removal_request(lua::State* L, int idx) {
ContentRemovalRequest request;
if (!lua::istable(L, idx)) {
throw std::runtime_error("table expected as argument");
}
if (!lua::getfield(L, "units", idx)) {
throw std::runtime_error("table with 'units' field expected");
}
if (!lua::istable(L, -1)) {
throw std::runtime_error("'units' field must be a table");
}
int len = lua::objlen(L, -1);
for (int i = 0; i < len; i++) {
lua::rawgeti(L, i + 1);
request.units.emplace_back(lua::require_lstring(L, -1));
lua::pop(L);
}
return request;
}
static int l_delete_world_content(lua::State* L) {
auto name = lua::require_string(L, 1);
auto controller = engine->getController();
auto request = parse_content_removal_request(L, 2);
bool loadWorld = lua::toboolean(L, 3);
controller->deleteWorldContent(name, request, loadWorld);
return 0;
}
/// @brief Get engine version
/// @return major, minor
/// @return major, minor, [patch]
static int l_get_version(lua::State* L) {
return lua::pushvec_stack(
L, glm::vec2(ENGINE_VERSION_MAJOR, ENGINE_VERSION_MINOR)
L,
#ifdef VC_VERSION_PATCH
glm::vec3(ENGINE_VERSION_MAJOR, ENGINE_VERSION_MINOR, ENGINE_VERSION_PATCH)
#else
glm::vec2(ENGINE_VERSION_MAJOR, ENGINE_VERSION_MINOR)
#endif
);
}
@ -429,6 +466,7 @@ static int l_start_background_instance(lua::State* L) {
"--sub-depth", std::to_string(engine->getCoreParameters()
.subProcessDepth + 1),
"--log", io::resolve(outputPath).u8string(),
"--stdin-cmd",
};
args.emplace_back("--project");
args.emplace_back(io::resolve(engine->getProject().path).u8string());
@ -444,25 +482,17 @@ static int l_start_background_instance(lua::State* L) {
}
}
int handle = -1;
for (int i = 0; i < ::processes.size(); i++) {
if (!::processes[i] || !::processes[i]->isActive()) {
handle = i;
break;
}
}
if (handle == -1) {
if (::processes.size() >= MAX_SUBPROCESSES) {
throw std::runtime_error("sub-processes limit exceeded");
}
::processes[handle] =
platform::new_engine_instance(std::move(args), "", true);
return lua::pushinteger(L, handle);
int id = ::next_process_id++;
::processes[id] = platform::new_engine_instance(std::move(args), "", true);
return lua::pushinteger(L, id);
}
static int l_is_instance_alive(lua::State* L) {
int handle = lua::tointeger(L, 1);
if (handle < 0 || handle >= ::processes.size()) {
if (handle < 0 || ::processes.find(handle) == ::processes.end()) {
throw std::runtime_error("invalid process handle");
}
auto& process = ::processes[handle];
@ -471,16 +501,42 @@ static int l_is_instance_alive(lua::State* L) {
static int l_terminate_instance(lua::State* L) {
int handle = lua::tointeger(L, 1);
if (handle < 0 || handle >= ::processes.size()) {
if (handle < 0 || ::processes.find(handle) == ::processes.end()) {
throw std::runtime_error("invalid process handle");
}
auto it = ::processes.find(handle);
if (it->second == nullptr) {
::processes.erase(it);
return lua::pushboolean(L, false);
}
bool active = it->second->isActive();
it->second.reset();
::processes.erase(it);
return lua::pushboolean(L, active);
}
static int l_get_stdin_stream(lua::State* L) {
int handle = lua::tointeger(L, 1);
if (handle < 0 || ::processes.find(handle) == ::processes.end()) {
throw std::runtime_error("invalid process handle");
}
auto& process = ::processes[handle];
if (process == nullptr) {
return lua::pushboolean(L, false);
return 0;
}
bool active = process->isActive();
process.reset();
return lua::pushboolean(L, active);
return lua::pushinteger(L, process->getStdinDescriptor());
}
static int l_get_stdout_stream(lua::State* L) {
int handle = lua::tointeger(L, 1);
if (handle < 0 || ::processes.find(handle) == ::processes.end()) {
throw std::runtime_error("invalid process handle");
}
auto& process = ::processes[handle];
if (process == nullptr) {
return 0;
}
return lua::pushinteger(L, process->getStdoutDescriptor());
}
const luaL_Reg applib[] = {
@ -512,12 +568,16 @@ const luaL_Reg applib[] = {
{"save_world", lua::wrap<l_save_world>},
{"close_world", lua::wrap<l_close_world>},
{"delete_world", lua::wrap<l_delete_world>},
{"delete_world_content", lua::wrap<l_delete_world_content>},
/// other
{"get_version", lua::wrap<l_get_version>},
{"create_memory_device", lua::wrap<l_create_memory_device>},
// sub-instances
{"start_debug_instance", lua::wrap<l_start_debug_instance>},
{"start_background_instance", lua::wrap<l_start_background_instance>},
{"is_instance_alive", lua::wrap<l_is_instance_alive>},
{"terminate_instance", lua::wrap<l_terminate_instance>},
{"get_stdin_stream", lua::wrap<l_get_stdin_stream>},
{"get_stdout_stream", lua::wrap<l_get_stdout_stream>},
{nullptr, nullptr}
};

View file

@ -6,6 +6,7 @@
#include "coders/obj.hpp"
#include "coders/png.hpp"
#include "coders/vcm.hpp"
#include "coders/vec3.hpp"
#include "debug/Logger.hpp"
#include "engine/Engine.hpp"
#include "graphics/commons/Model.hpp"
@ -27,6 +28,35 @@ static void load_texture(
}
}
static void store_vcm(
Assets& assets,
const std::string& modelName,
const std::string& skeletonName,
vcm::VcmModel& vcmModel
) {
auto skeleton = std::make_unique<rigging::SkeletonConfig>(
std::move(*vcmModel.skeleton)
);
if (vcmModel.parts.size() > 1) {
for (auto& [partName, model] : vcmModel.parts) {
assets.store(
std::make_unique<model::Model>(std::move(model)),
modelName + "." + partName
);
}
for (auto& bone : skeleton->getBones()) {
bone->setModel(modelName + "." + bone->model.name);
}
} else {
assets.store(
std::make_unique<model::Model>(std::move(vcmModel.parts["root"])),
modelName
);
skeleton->getRoot()->setModel(modelName);
}
assets.store(std::move(skeleton), skeletonName);
}
static int l_request_texture(lua::State* L) {
std::string filename = lua::require_string(L, 1);
std::string alias = lua::require_string(L, 2);
@ -85,7 +115,6 @@ static int l_parse_model(lua::State* L) {
auto& assets = engine->requireAssets();
auto format = lua::require_lstring(L, 1);
auto string = lua::require_lstring(L, 2);
std::string name = lua::require_string(L, 3);
std::string skeletonName;
if (lua::isstring(L, 4)) {
@ -93,10 +122,71 @@ static int l_parse_model(lua::State* L) {
}
if (format == "obj") {
auto string = lua::require_lstring(L, 2);
assets.store(obj::parse(name, string), name);
return 0;
}
if (format == "vec3") {
auto content = lua::bytearray_as_string(L, 2);
util::Buffer<ubyte> buffer(content.size());
for (size_t i = 0; i < content.size(); i++) {
buffer[i] = static_cast<ubyte>(content[i]);
}
auto vec3File = vec3::load(name, buffer);
for (auto& [modelName, model] : vec3File.models) {
auto fullName = name;
if (name != modelName) {
fullName += "." + modelName;
}
model.model.translate(model.origin);
assets.store(
std::make_unique<model::Model>(std::move(model.model)),
fullName
);
}
return 0;
}
if (format != "xml" && format != "vcm") {
throw std::runtime_error(
"unknown format " + util::quote(std::string(format))
);
}
auto string = lua::require_lstring(L, 2);
auto vcmModel = vcm::parse(name, string, format == "xml");
if (skeletonName.empty()) {
assets.store(
std::make_unique<model::Model>(std::move(vcmModel.squash())), name
);
return 0;
}
if (!vcmModel.skeleton) {
throw std::runtime_error(
"model format " + util::quote(std::string(format)) +
" does not define a skeleton"
);
}
store_vcm(assets, name, skeletonName, vcmModel);
return 0;
}
static int l_parse_skeleton(lua::State* L) {
auto& assets = engine->requireAssets();
auto format = lua::require_lstring(L, 1);
auto string = lua::require_lstring(L, 2);
std::string name = lua::require_string(L, 3);
if (format == "json") {
auto skeleton = rigging::SkeletonConfig::parse(string, name, name);
assets.store(std::move(skeleton), name);
return 0;
}
if (format != "xml" && format != "vcm") {
throw std::runtime_error(
"unknown format " + util::quote(std::string(format))
@ -104,34 +194,17 @@ static int l_parse_model(lua::State* L) {
}
auto vcmModel = vcm::parse(name, string, format == "xml");
if (skeletonName.empty()) {
assets.store(
std::make_unique<model::Model>(std::move(vcmModel.squash())), name
if (!vcmModel.skeleton) {
throw std::runtime_error(
"model format " + util::quote(std::string(format)) +
" does not define a skeleton"
);
} else {
auto skeleton = std::make_unique<rigging::SkeletonConfig>(
std::move(*vcmModel.skeleton)
);
if (vcmModel.parts.size() > 1) {
for (auto& [partName, model] : vcmModel.parts) {
assets.store(
std::make_unique<model::Model>(std::move(model)),
name + "." + partName
);
}
for (auto& bone : skeleton->getBones()) {
bone->setModel(name + "." + bone->model.name);
}
} else {
assets.store(
std::make_unique<model::Model>(
std::move(vcmModel.parts["root"])), name
);
skeleton->getRoot()->setModel(name);
}
assets.store(std::move(skeleton), skeletonName);
}
assets.store(
std::make_unique<rigging::SkeletonConfig>(std::move(*vcmModel.skeleton)),
name
);
return 0;
}
@ -151,7 +224,7 @@ static int l_to_canvas(lua::State* L) {
return 0;
}
auto atlasName = alias.substr(0, sep);
if (auto atlas = assets.get<Atlas>(std::string(atlasName))) {
auto textureName = std::string(alias.substr(sep + 1));
auto image = atlas->shareImageData();
@ -178,6 +251,7 @@ const luaL_Reg assetslib[] = {
{"load_texture", lua::wrap<l_load_texture>},
{"parse_animation", lua::wrap<l_parse_animation>},
{"parse_model", lua::wrap<l_parse_model>},
{"parse_skeleton", lua::wrap<l_parse_skeleton>},
{"to_canvas", lua::wrap<l_to_canvas>},
{nullptr, nullptr}
};

View file

@ -4,9 +4,9 @@
#include "engine/EnginePaths.hpp"
#include "api_lua.hpp"
inline const char* DEFAULT_CHANNEL = "regular";
static inline const char* DEFAULT_CHANNEL = "regular";
inline int extract_channel_index(lua::State* L, int idx) {
static int extract_channel_index(lua::State* L, int idx) {
const char* channel = DEFAULT_CHANNEL;
if (lua::isstring(L, idx)) {
channel = lua::tostring(L, idx);
@ -18,7 +18,7 @@ inline int extract_channel_index(lua::State* L, int idx) {
return index;
}
inline audio::speakerid_t play_sound(
static audio::speakerid_t play_sound(
const char* name,
bool relative,
lua::Number x,
@ -54,7 +54,7 @@ inline audio::speakerid_t play_sound(
);
}
inline audio::speakerid_t play_stream(
static audio::speakerid_t play_stream(
const char* filename,
bool relative,
lua::Number x,

View file

@ -468,7 +468,10 @@ static int l_get_hitbox(lua::State* L) {
} else {
rotation = 0;
}
auto& hitbox = def->rt.hitboxes[rotation].at(hitboxIndex);
const auto& variant =
def->variants ? def->variants->variants[get_variant_index(L, *def, 4)]
: def->defaults;
auto& hitbox = variant.rt.hitboxes[rotation].at(hitboxIndex);
lua::createtable(L, 2, 0);
lua::pushvec3(L, hitbox.min());

View file

@ -28,7 +28,7 @@ static const EntityDef* require_entity_def(lua::State* L) {
}
static int l_exists(lua::State* L) {
return lua::pushboolean(L, get_entity(L, 1).has_value());
return lua::pushboolean(L, get_entity(L, 1) != nullptr);
}
static int l_def_index(lua::State* L) {
@ -138,8 +138,7 @@ static int l_get_all_in_box(lua::State* L) {
auto found = level->entities->getAllInside(AABB(pos, pos + size));
lua::createtable(L, found.size(), 0);
for (size_t i = 0; i < found.size(); i++) {
const auto& entity = found[i];
lua::pushinteger(L, entity.getUID());
lua::pushinteger(L, found[i]->getUID());
lua::rawseti(L, i + 1);
}
return 1;
@ -151,8 +150,7 @@ static int l_get_all_in_radius(lua::State* L) {
auto found = level->entities->getAllInRadius(pos, radius);
lua::createtable(L, found.size(), 0);
for (size_t i = 0; i < found.size(); i++) {
const auto& entity = found[i];
lua::pushinteger(L, entity.getUID());
lua::pushinteger(L, found[i]->getUID());
lua::rawseti(L, i + 1);
}
return 1;

View file

@ -1,7 +1,5 @@
#pragma once
#include <optional>
#include "frontend/hud.hpp"
#include "objects/Entities.hpp"
#include "objects/Entity.hpp"
@ -13,7 +11,7 @@ namespace scripting {
extern Hud* hud;
}
inline std::optional<Entity> get_entity(lua::State* L, int idx) {
inline Entity* get_entity(lua::State* L, int idx) {
auto id = lua::tointeger(L, idx);
auto level = scripting::controller->getLevel();
return level->entities->get(id);

View file

@ -305,13 +305,14 @@ static int l_read_descriptor(lua::State* L) {
int maxlen = lua::tointeger(L, 2);
auto& stream = io_descriptors::require_input(descriptor);
if (stream.eof()) {
stream.clear();
}
util::Buffer<char> buffer(maxlen);
stream.read(buffer.data(), maxlen);
std::streamsize read_len = stream.gcount();
std::streamsize read_len = stream.gcount();
if (stream.eof()) {
stream.clear(stream.rdstate() & std::ios::badbit);
}
return lua::create_bytearray(L, buffer.data(), read_len);
}

View file

@ -157,7 +157,18 @@ static int l_container_set_interval(lua::State* L) {
if (auto container = std::dynamic_pointer_cast<Container>(node.node)) {
lua::pushvalue(L, 3);
auto runnable = lua::create_runnable(L);
container->listenInterval(interval, runnable);
return lua::pushinteger(
L, container->listenInterval(interval, runnable)
);
}
return 0;
}
static int l_container_clear_interval(lua::State* L) {
auto node = get_document_node(L, 1);
auto id = lua::tointeger(L, 2);
if (auto container = std::dynamic_pointer_cast<Container>(node.node)) {
container->cancelInterval(id);
}
return 0;
}
@ -502,6 +513,13 @@ static int p_set_interval(UINode* node, lua::State* L) {
return 0;
}
static int p_clear_interval(UINode* node, lua::State* L) {
if (dynamic_cast<Container*>(node)) {
return lua::pushcfunction(L, lua::wrap<l_container_clear_interval>);
}
return 0;
}
static int p_get_content_offset(UINode* node, lua::State* L) {
return lua::pushvec(L, node->getContentOffset());
}
@ -667,6 +685,7 @@ static int l_gui_getattr(lua::State* L) {
{"reposition", p_get_reposition},
{"clear", p_get_clear},
{"setInterval", p_set_interval},
{"clearInterval", p_clear_interval},
{"placeholder", p_get_placeholder},
{"hint", p_get_hint},
{"valid", p_is_valid},

View file

@ -194,6 +194,15 @@ static int l_set_allow_pause(lua::State* L) {
return 0;
}
static int l_is_hotbar_visible(lua::State* L) {
return lua::pushboolean(L, hud->isHotbarVisible());
}
static int l_set_hotbar_visible(lua::State* L) {
hud->setHotbarVisible(lua::toboolean(L, 1));
return 0;
}
static int l_reload_script(lua::State* L) {
auto packid = lua::require_string(L, 1);
if (content == nullptr) {
@ -237,6 +246,8 @@ const luaL_Reg hudlib[] = {
{"_set_content_access", wrap_hud<l_set_content_access>},
{"_set_debug_cheats", wrap_hud<l_set_debug_cheats>},
{"set_allow_pause", wrap_hud<l_set_allow_pause>},
{"is_hotbar_visible", wrap_hud<l_is_hotbar_visible>},
{"set_hotbar_visible", wrap_hud<l_set_hotbar_visible>},
{"reload_script", wrap_hud<l_reload_script>},
{"is_open", wrap_hud<l_is_open>},
{nullptr, nullptr}

View file

@ -100,6 +100,20 @@ static int l_set_jump_height(lua::State* L) {
return 0;
}
static int l_set_width(lua::State* L) {
if (auto agent = get_agent(L)) {
agent->width = lua::tonumber(L, 2);
}
return 0;
}
static int l_set_height(lua::State* L) {
if (auto agent = get_agent(L)) {
agent->height = lua::touinteger(L, 2);
}
return 0;
}
static int l_avoid_tag(lua::State* L) {
if (auto agent = get_agent(L)) {
int index =
@ -125,6 +139,8 @@ const luaL_Reg pathfindinglib[] = {
{"pull_route", lua::wrap<l_pull_route>},
{"set_max_visited", lua::wrap<l_set_max_visited_blocks>},
{"set_jump_height", lua::wrap<l_set_jump_height>},
{"set_width", lua::wrap<l_set_width>},
{"set_height", lua::wrap<l_set_height>},
{"avoid_tag", lua::wrap<l_avoid_tag>},
{nullptr, nullptr}
};

View file

@ -121,7 +121,21 @@ static int l_get_inv(lua::State* L) {
static int l_set_selected_slot(lua::State* L) {
if (auto player = get_player(L, 1)) {
player->setChosenSlot(lua::tointeger(L, 2) % 10);
player->setChosenSlot(lua::tointeger(L, 2) % player->getHotbarSize());
}
return 0;
}
static int l_get_hotbar_size(lua::State* L) {
if (auto player = get_player(L, 1)) {
return lua::pushinteger(L, player->getHotbarSize());
}
return 0;
}
static int l_set_hotbar_size(lua::State* L) {
if (auto player = get_player(L, 1)) {
player->setHotbarSize(lua::tointeger(L, 2));
}
return 0;
}
@ -401,6 +415,8 @@ const luaL_Reg playerlib[] = {
{"get_interaction_distance", lua::wrap<l_get_interaction_distance>},
{"set_interaction_distance", lua::wrap<l_set_interaction_distance>},
{"set_selected_slot", lua::wrap<l_set_selected_slot>},
{"get_hotbar_size", lua::wrap<l_get_hotbar_size>},
{"set_hotbar_size", lua::wrap<l_set_hotbar_size>},
{"get_selected_block", lua::wrap<l_get_selected_block>},
{"get_selected_entity", lua::wrap<l_get_selected_entity>},
{"set_spawnpoint", lua::wrap<l_set_spawnpoint>},

View file

@ -108,6 +108,17 @@ static int l_get_seed(lua::State* L) {
return lua::pushinteger(L, require_world_info().seed);
}
static int l_get_logic(lua::State* L) {
auto name = lua::require_string(L, 1);
return lua::pushvalue(L, require_world_info().getLogicValue(name));
}
static int l_set_logic(lua::State* L) {
auto name = lua::require_string(L, 1);
require_world_info().setLogicValue(name, lua::tovalue(L, 2));
return 0;
}
static int l_exists(lua::State* L) {
auto name = lua::require_string(L, 1);
auto worldsDir = engine->getPaths().getWorldFolderByName(name);
@ -250,6 +261,8 @@ const luaL_Reg worldlib[] = {
{"set_day_time_speed", lua::wrap<l_set_day_time_speed>},
{"get_day_time_speed", lua::wrap<l_get_day_time_speed>},
{"get_seed", lua::wrap<l_get_seed>},
{"get_logic", lua::wrap<l_get_logic>},
{"set_logic", lua::wrap<l_set_logic>},
{"get_generator", lua::wrap<l_get_generator>},
{"is_day", lua::wrap<l_is_day>},
{"is_night", lua::wrap<l_is_night>},

View file

@ -24,6 +24,7 @@
#include "world/Level.hpp"
#include "world/World.hpp"
#include "interfaces/Process.hpp"
#include "objects/EntityDef.hpp"
#include <iostream>
#include <stdexcept>
@ -215,7 +216,7 @@ std::unique_ptr<Process> scripting::start_app_script(const io::path& script) {
}
[[nodiscard]] scriptenv scripting::create_doc_environment(
const scriptenv& parent, const std::string& name
const scriptenv& parent, const std::string& name, bool app
) {
auto L = lua::get_main_state();
int id = lua::create_environment(L, *parent);
@ -225,6 +226,12 @@ std::unique_ptr<Process> scripting::start_app_script(const io::path& script) {
lua::pushstring(L, name);
lua::setfield(L, "DOC_NAME");
if (app) {
if (lua::getregistry(L, "app")) {
lua::setfield(L, "app");
}
}
if (lua::getglobal(L, "Document")) {
if (lua::getfield(L, "new")) {
lua::pushstring(L, name);
@ -261,7 +268,12 @@ static int push_properties_tables(
}
void scripting::on_assets_loading() {
lua::call_internal(lua::get_main_state(), "backup_and_clear_animation");
auto L = lua::get_main_state();
lua::call_internal(L, "backup_and_clear_animation");
for (auto& pack : content_control->getAllContentPacks()) {
lua::emit_event(L, pack.id + ":.onassetsloading");
}
}
void scripting::revert_assets_loading() {
@ -293,6 +305,11 @@ void scripting::on_content_load(Content* content) {
lua::setfield(L, "properties");
lua::pop(L);
}
if (lua::getglobal(L, "entities")) {
push_properties_tables(L, indices.entities);
lua::setfield(L, "properties");
lua::pop(L);
}
lua::getregistry(L, "app");
lua::setglobal(L, "__vc_app");
@ -345,7 +362,9 @@ void scripting::on_world_tick(int tps) {
lua::pop(L);
}
for (auto& pack : content_control->getAllContentPacks()) {
lua::emit_event(L, pack.id + ":.worldtick");
lua::emit_event(L, pack.id + ":.worldtick", [tps](lua::State* L) {
return lua::pushinteger(L, tps);
});
}
}
@ -451,6 +470,23 @@ static bool on_block_common(
return result;
}
bool scripting::can_block_be_placed(
Player* player, const Block& block, const glm::ivec3& pos, int rotation
) {
if (!block.rt.funcsset.canbeplaced) {
return true;
}
std::string name = block.name + ".canbeplaced";
return lua::emit_event(
lua::get_main_state(), name, [pos, player, rotation](auto L) {
lua::pushivec_stack(L, pos);
lua::pushinteger(L, player ? player->getId() : -1);
lua::pushinteger(L, rotation);
return 5;
}
);
}
void scripting::on_block_placed(
Player* player, const Block& block, const glm::ivec3& pos
) {
@ -717,6 +753,8 @@ void scripting::load_content_script(
register_event(env, "on_breaking", prefix + ".breaking");
funcsset.onbroken = register_event(env, "on_broken", prefix + ".broken");
funcsset.onplaced = register_event(env, "on_placed", prefix + ".placed");
funcsset.canbeplaced =
register_event(env, "can_be_placed", prefix + ".canbeplaced");
funcsset.onreplaced =
register_event(env, "on_replaced", prefix + ".replaced");
funcsset.oninteract =
@ -821,6 +859,7 @@ void scripting::load_content_script(
register_event(env, "on_scripts_loading", prefix + ":.onscriptsloading");
register_event(env, "on_content_loaded", prefix + ":.oncontentloaded");
register_event(env, "on_assets_loading", prefix + ":.onassetsloading");
}
void scripting::load_layout_script(

View file

@ -65,7 +65,7 @@ namespace scripting {
scriptenv create_pack_environment(const ContentPack& pack);
scriptenv create_environment(const scriptenv& parent);
scriptenv create_doc_environment(
const scriptenv& parent, const std::string& name
const scriptenv& parent, const std::string& name, bool app = false
);
void process_post_runnables();
@ -92,6 +92,9 @@ namespace scripting {
void on_blocks_tick(const Block& block, int tps);
void update_block(const Block& block, const glm::ivec3& pos);
void random_update_block(const Block& block, const glm::ivec3& pos);
bool can_block_be_placed(
Player* player, const Block& block, const glm::ivec3& pos, int rotation
);
void on_block_placed(
Player* player, const Block& block, const glm::ivec3& pos
);

View file

@ -33,6 +33,9 @@ int main(int argc, char** argv) {
std::cerr << err.what() << std::endl;
return EXIT_FAILURE;
}
#ifndef _WIN32
std::signal(SIGPIPE, SIG_IGN);
#endif
std::signal(SIGTERM, sigterm_handler);
#ifdef NDEBUG
std::signal(SIGINT, sigterm_handler);

View file

@ -35,7 +35,7 @@ struct UVRegion {
v2 = v1 + uvh * h;
}
inline glm::vec2 apply(const glm::vec2& uv) {
glm::vec2 apply(const glm::vec2& uv) const {
float w = getWidth();
float h = getHeight();
return glm::vec2(u1 + uv.x * w, v1 + uv.y * h);

View file

@ -183,4 +183,19 @@ namespace util {
}
return false;
}
inline void uv_by_normal(
const glm::vec3& n, glm::vec3& u, glm::vec3& v
) {
if (std::abs(n.y) > 0.5f) {
u = {n.y > 0 ? 1 : -1, 0, 0};
v = {0, 0, -1};
} else if (std::abs(n.z) > 0.5f) {
u = {n.z > 0 ? 1 : -1, 0, 0};
v = {0, 1, 0};
} else {
u = {0, 0, n.x > 0 ? -1 : 1};
v = {0, 1, 0};
}
}
}

View file

@ -9,18 +9,12 @@
#include "engine/Engine.hpp"
#include "Entity.hpp"
#include "EntityDef.hpp"
#include "graphics/commons/Model.hpp"
#include "graphics/core/DrawContext.hpp"
#include "graphics/core/LineBatch.hpp"
#include "graphics/render/ModelBatch.hpp"
#include "logic/scripting/scripting.hpp"
#include "maths/FrustumCulling.hpp"
#include "maths/rays.hpp"
#include "maths/util.hpp"
#include "physics/PhysicsSolver.hpp"
#include "world/Level.hpp"
#include <entt/entity/registry.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <limits>
#include <sstream>
@ -28,8 +22,7 @@
static debug::Logger logger("entities");
Entities::Entities(Level& level)
: registry(std::make_unique<entt::registry>()),
level(level),
: level(level),
sensorsTickClock(20, 3),
updateTickClock(20, 3) {
}
@ -40,12 +33,12 @@ void Entities::setAssets(Assets& assets) {
this->assets = &assets;
}
std::optional<Entity> Entities::get(entityid_t id) {
Entity* Entities::get(entityid_t id) {
const auto& found = entities.find(id);
if (found != entities.end() && registry->valid(found->second)) {
return Entity(*this, id, *registry, found->second);
if (found != entities.end()) {
return found->second.get();
}
return std::nullopt;
return nullptr;
}
entityid_t Entities::spawn(
@ -81,33 +74,30 @@ entityid_t Entities::spawn(
throw std::runtime_error(ss.str());
}
}
auto entity = registry->create();
entities[id] = entity;
uids[entity] = id;
registry->emplace<EntityId>(entity, id, def);
const auto& tsf = registry->emplace<Transform>(
entity,
position,
glm::vec3(1.0f),
glm::mat3(1.0f),
glm::mat4(1.0f),
true
);
auto& body = registry->emplace<Rigidbody>(
entity,
true,
Hitbox {id, def.bodyType, position, def.hitbox * 0.5f},
std::vector<Sensor> {}
);
body.initialize(def, id, *this);
auto& scripting = registry->emplace<ScriptComponents>(entity);
std::unique_ptr<rigging::Skeleton> skeletonInstance;
if (assets) {
registry->emplace<rigging::Skeleton>(
entity, skeleton ? skeleton->instance() : rigging::Skeleton(nullptr)
skeletonInstance = std::make_unique<rigging::Skeleton>(
skeleton ? skeleton->instance() : rigging::Skeleton(nullptr)
);
}
auto& entity = *(entities[id] = std::make_unique<Entity>(
*this,
EntityId {id, def},
Transform {
position, glm::vec3(1.0f), glm::mat3(1.0f), glm::mat4(1.0f), true
},
Rigidbody {
true,
Hitbox {id, def.bodyType, position, def.hitbox * 0.5f},
std::vector<Sensor> {}
},
std::move(skeletonInstance)
));
const auto& tsf = entity.getTransform();
auto& body = entity.getRigidbody();
body.initialize(def, id, *this);
auto& scripting = entity.getScripting();
for (auto& instance : def.components) {
auto component = std::make_unique<UserComponent>(
@ -118,7 +108,7 @@ entityid_t Entities::spawn(
dv::value componentsMap = nullptr;
if (saved != nullptr) {
componentsMap = saved["comps"];
loadEntity(saved, get(id).value());
loadEntity(saved, entity);
}
body.hitbox.position = tsf.pos;
scripting::on_entity_spawn(
@ -144,7 +134,7 @@ void Entities::loadEntity(const dv::value& map) {
spawn(def, {}, nullptr, map, uid);
}
void Entities::loadEntity(const dv::value& map, Entity entity) {
void Entities::loadEntity(const dv::value& map, Entity& entity) {
auto& transform = entity.getTransform();
auto& body = entity.getRigidbody();
auto skeleton = entity.getSkeleton();
@ -175,12 +165,12 @@ std::optional<Entities::RaycastResult> Entities::rayCast(
const RaycastSettings& settings
) {
Ray ray(start, dir);
auto view = registry->view<EntityId, Transform, Rigidbody>();
entityid_t foundUID = 0;
glm::ivec3 foundNormal;
for (auto [entity, eid, transform, body] : view.each()) {
for (const auto& [uid, entity] : entities) {
const auto& eid = entity->getID();
const auto& body = entity->getRigidbody();
const auto& hitbox = body.hitbox;
if (eid.uid == settings.ignoredUid || !body.enabled ||
(settings.solidEntitiesOnly && !eid.def.solid) ||
@ -227,40 +217,38 @@ void Entities::onSave(const Entity& entity) {
scripting::on_entity_save(entity);
}
dv::value Entities::serialize(const std::vector<Entity>& entities) {
dv::value Entities::serialize(const std::vector<Entity*>& entities) {
auto list = dv::list();
for (auto& entity : entities) {
const EntityId& eid = entity.getID();
if (!entity.getDef().save.enabled || eid.destroyFlag) {
for (auto entity : entities) {
const EntityId& eid = entity->getID();
if (!entity->getDef().save.enabled || eid.destroyFlag) {
continue;
}
level.entities->onSave(entity);
level.entities->onSave(*entity);
if (!eid.destroyFlag) {
list.add(entity.serialize());
list.add(entity->serialize());
}
}
return list;
}
void Entities::despawn(std::vector<Entity> entities) {
for (auto& entity : entities) {
entity.destroy();
void Entities::despawn(const std::vector<Entity*>& entities) {
for (auto entity : entities) {
entity->destroy();
}
}
void Entities::clean() {
for (auto it = entities.begin(); it != entities.end();) {
if (!registry->get<EntityId>(it->second).destroyFlag) {
if (!it->second->getID().destroyFlag) {
++it;
} else {
auto& rigidbody = registry->get<Rigidbody>(it->second);
auto& rigidbody = it->second->getRigidbody();
// todo: refactor
auto physics = level.physics.get();
for (auto& sensor : rigidbody.sensors) {
physics->removeSensor(&sensor);
}
uids.erase(it->second);
registry->destroy(it->second);
it = entities.erase(it);
}
}
@ -309,15 +297,16 @@ void Entities::preparePhysics(float delta) {
auto part = sensorsTickClock.convertPart(i);
auto allParts = sensorsTickClock.getParts();
auto view = registry->view<EntityId, Transform, Rigidbody>();
for (auto [entity, eid, transform, rigidbody] : view.each()) {
for (const auto& [uid, entity] : entities) {
const auto& eid = entity->getID();
auto& rigidbody = entity->getRigidbody();
if (!rigidbody.enabled) {
continue;
}
if ((eid.uid + part) % allParts != 0) {
continue;
}
updateSensors(rigidbody, transform, sensors);
updateSensors(rigidbody, entity->getTransform(), sensors);
}
}
}
@ -325,8 +314,9 @@ void Entities::preparePhysics(float delta) {
hitboxes.clear();
solidHitboxes.clear();
auto view = registry->view<EntityId, Rigidbody>();
for (auto [entity, eid, rigidbody] : view.each()) {
for (const auto& [uid, entity] : entities) {
const auto& eid = entity->getID();
auto& rigidbody = entity->getRigidbody();
auto bodyType = rigidbody.hitbox.type;
if (eid.destroyFlag || !rigidbody.enabled) {
continue;
@ -350,13 +340,15 @@ void Entities::preparePhysics(float delta) {
void Entities::updatePhysics(float delta) {
preparePhysics(delta);
auto view = registry->view<EntityId, Transform, Rigidbody>();
auto physics = level.physics.get();
int substeps = std::max<int>(std::min<int>(delta * 1000, 200), 8);
physics->step(*level.chunks, delta, substeps);
for (auto [entity, eid, transform, rigidbody] : view.each()) {
for (const auto& [uid, entity] : entities) {
const auto& eid = entity->getID();
auto& transform = entity->getTransform();
auto& rigidbody = entity->getRigidbody();
if (!rigidbody.enabled ||
rigidbody.hitbox.type == BodyType::STATIC) {
continue;
@ -373,11 +365,11 @@ void Entities::updatePhysics(float delta) {
}
if (hitbox.grounded && !hitbox.prevGrounded) {
scripting::on_entity_grounded(
*get(eid.uid), glm::length(hitbox.prevVelocity - hitbox.velocity)
*entity, glm::length(hitbox.prevVelocity - hitbox.velocity)
);
}
if (!hitbox.grounded && hitbox.prevGrounded) {
scripting::on_entity_fall(*get(eid.uid));
scripting::on_entity_fall(*entity);
}
}
}
@ -395,178 +387,51 @@ void Entities::update(float delta) {
updatePhysics(delta);
scripting::on_entities_physics_update(delta);
auto view = registry->view<Transform, rigging::Skeleton>();
for (auto [entity, transform, skeleton] : view.each()) {
for (const auto& [uid, entity] : entities) {
if (!entity->getSkeleton()) {
continue;
}
auto& transform = entity->getTransform();
auto& skeleton = *entity->getSkeleton();
if (transform.dirty) {
transform.refresh();
}
if (skeleton.interpolation.isEnabled()) {
skeleton.interpolation.updateTimer(delta);
}
}
}
static void debug_render_skeleton(
LineBatch& batch,
const rigging::Bone* bone,
const rigging::Skeleton& skeleton
) {
size_t pindex = bone->getIndex();
for (auto& sub : bone->getBones()) {
size_t sindex = sub->getIndex();
const auto& matrices = skeleton.calculated.matrices;
batch.line(
glm::vec3(matrices[pindex] * glm::vec4(0, 0, 0, 1)),
glm::vec3(matrices[sindex] * glm::vec4(0, 0, 0, 1)),
glm::vec4(0, 0.5f, 0, 1)
);
debug_render_skeleton(batch, sub.get(), skeleton);
}
}
void Entities::renderDebug(
LineBatch& batch, const Frustum* frustum, const DrawContext& pctx, entityid_t fpsEntity
) {
{
auto ctx = pctx.sub(&batch);
ctx.setLineWidth(1);
auto view = registry->view<Transform, Rigidbody>();
for (auto [entity, transform, rigidbody] : view.each()) {
const auto& hitbox = rigidbody.hitbox;
const auto& pos = transform.pos;
const auto& size = transform.size;
if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) {
continue;
}
batch.box(
hitbox.position, hitbox.getHalfSize() * 2.0f, glm::vec4(1.0f)
);
for (auto& sensor : rigidbody.sensors) {
if (sensor.type != SensorType::AABB) continue;
batch.box(
sensor.calculated.aabb.center(),
sensor.calculated.aabb.size(),
glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)
);
}
if (skeleton.rotationInterpolation.isEnabled()) {
skeleton.rotationInterpolation.updateTimer(delta);
}
}
{
auto view = registry->view<EntityId, Transform, rigging::Skeleton>();
auto ctx = pctx.sub(&batch);
ctx.setDepthTest(false);
ctx.setDepthMask(false);
ctx.setLineWidth(2);
for (auto [entity, eid, transform, skeleton] : view.each()) {
if (eid.uid == fpsEntity) {
continue;
}
auto config = skeleton.config;
if (config == nullptr) {
continue;
}
const auto& pos = transform.pos;
const auto& size = transform.size;
if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) {
continue;
}
auto bone = config->getRoot();
debug_render_skeleton(batch, bone, skeleton);
}
}
}
void Entities::render(
const Assets& assets,
ModelBatch& batch,
const Frustum* frustum,
entityid_t fpsEntity
) {
auto view = registry->view<EntityId, Transform, rigging::Skeleton, Rigidbody>();
for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) {
if (eid.uid == fpsEntity) {
continue;
}
const auto& def = eid.def;
const auto& pos = transform.pos;
const auto& size = transform.size;
const auto& halfSize = rigidbody.hitbox.getHalfSize();
// todo: more correct frustum culling
if (frustum && !frustum->isBoxVisible(pos - halfSize, pos + halfSize)) {
continue;
}
const auto& rigConfig = skeleton.config;
if (rigConfig) {
rigConfig->render(
assets,
batch,
skeleton,
def.lightingMode,
transform.rot,
pos,
size
);
}
}
}
void Entities::updateCulling(const Frustum* frustum, entityid_t fpsEntity) {
auto view = registry->view<EntityId, Transform, rigging::Skeleton, Rigidbody>();
for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) {
if (frustum == nullptr || eid.uid == fpsEntity) {
skeleton.culled = false;
continue;
}
const auto& pos = transform.pos;
const auto& halfSize = rigidbody.hitbox.getHalfSize();
skeleton.culled = !frustum->isBoxVisible(pos - halfSize, pos + halfSize);
}
}
bool Entities::hasBlockingInside(AABB aabb) {
constexpr float eps = 0.05f;
auto view = registry->view<EntityId, Rigidbody>();
for (auto [entity, eid, body] : view.each()) {
AABB bodyAABB(body.hitbox.getAABB());
for (const auto& [uid, entity] : entities) {
AABB bodyAABB(entity->getRigidbody().hitbox.getAABB());
bodyAABB.scale(glm::vec3(1.0f - eps));
if (eid.def.blocking && aabb.intersects(bodyAABB)) {
if (entity->getID().def.blocking && aabb.intersects(bodyAABB)) {
return true;
}
}
return false;
}
std::vector<Entity> Entities::getAllInside(AABB aabb) {
std::vector<Entity> collected;
auto view = registry->view<EntityId, Transform>();
for (auto [entity, eid, transform] : view.each()) {
if (!eid.destroyFlag && aabb.contains(transform.pos)) {
const auto& found = uids.find(entity);
if (found == uids.end()) {
continue;
}
if (auto wrapper = get(found->second)) {
collected.push_back(*wrapper);
}
std::vector<Entity*> Entities::getAllInside(AABB aabb) {
std::vector<Entity*> collected;
for (const auto& [uid, entity] : entities) {
if (!entity->getID().destroyFlag && aabb.contains(entity->getTransform().pos)) {
collected.push_back(entity.get());
}
}
return collected;
}
std::vector<Entity> Entities::getAllInRadius(glm::vec3 center, float radius) {
std::vector<Entity> collected;
auto view = registry->view<Transform>();
for (auto [entity, transform] : view.each()) {
if (glm::distance2(transform.pos, center) <= radius * radius) {
const auto& found = uids.find(entity);
if (found == uids.end()) {
continue;
}
if (auto wrapper = get(found->second)) {
collected.push_back(*wrapper);
}
std::vector<Entity*> Entities::getAllInRadius(glm::vec3 center, float radius) {
std::vector<Entity*> collected;
for (const auto& [uid, entity] : entities) {
if (glm::distance2(entity->getTransform().pos, center) <= radius * radius) {
collected.push_back(entity.get());
}
}
return collected;

View file

@ -6,6 +6,7 @@
#include <vector>
#include "constants.hpp"
#include "Entity.hpp"
#include "physics/Hitbox.hpp"
#include "Transform.hpp"
#include "Rigidbody.hpp"
@ -13,19 +14,13 @@
#include "typedefs.hpp"
#include "util/Clock.hpp"
#include <entt/entity/fwd.hpp>
#include <unordered_map>
#include <map>
struct EntityDef;
class Level;
class Assets;
class Entity;
class LineBatch;
class ModelBatch;
class Frustum;
class Entities;
class DrawContext;
namespace rigging {
struct Skeleton;
@ -33,10 +28,8 @@ namespace rigging {
}
class Entities final {
std::unique_ptr<entt::registry> registry;
Level& level;
std::unordered_map<entityid_t, entt::entity> entities;
std::unordered_map<entt::entity, entityid_t> uids;
std::map<entityid_t, std::unique_ptr<Entity>> entities;
entityid_t nextID = 1;
util::Clock sensorsTickClock;
util::Clock updateTickClock;
@ -57,18 +50,6 @@ public:
void updatePhysics(float delta);
void update(float delta);
void renderDebug(
LineBatch& batch, const Frustum* frustum, const DrawContext& ctx, entityid_t fpsEntity
);
void render(
const Assets& assets,
ModelBatch& batch,
const Frustum* frustum,
entityid_t fpsEntity
);
void updateCulling(const Frustum* frustum, entityid_t fpsEntity);
entityid_t spawn(
const EntityDef& def,
glm::vec3 position,
@ -77,7 +58,7 @@ public:
entityid_t uid = 0
);
std::optional<Entity> get(entityid_t id);
Entity* get(entityid_t id);
struct RaycastSettings {
/// @param ignore Ignored entity uid
@ -111,19 +92,24 @@ public:
void loadEntities(dv::value map);
void loadEntity(const dv::value& map);
void loadEntity(const dv::value& map, Entity entity);
void loadEntity(const dv::value& map, Entity& entity);
void onSave(const Entity& entity);
bool hasBlockingInside(AABB aabb);
std::vector<Entity> getAllInside(AABB aabb);
std::vector<Entity> getAllInRadius(glm::vec3 center, float radius);
std::vector<Entity*> getAllInside(AABB aabb);
std::vector<Entity*> getAllInRadius(glm::vec3 center, float radius);
void despawn(entityid_t id);
void despawn(std::vector<Entity> entities);
dv::value serialize(const std::vector<Entity>& entities);
void despawn(const std::vector<Entity*>& entities);
dv::value serialize(const std::vector<Entity*>& entities);
void setNextID(entityid_t id) {
nextID = id;
}
inline const std::map<entityid_t, std::unique_ptr<Entity>>& getEntities(
) const {
return entities;
}
inline size_t size() const {
return entities.size();
}

View file

@ -8,51 +8,62 @@
#include "ScriptComponents.hpp"
#include "Transform.hpp"
#include <entt/entt.hpp>
static inline std::string SAVED_DATA_VARNAME = "SAVED_DATA";
Entity::Entity(
Entities& entities,
EntityId id,
Transform transform,
Rigidbody rigidbody,
std::unique_ptr<rigging::Skeleton> skeleton
)
: entities(entities),
id(std::move(id)),
transform(std::move(transform)),
rigidbody(std::move(rigidbody)),
skeleton(std::move(skeleton)) {
}
Entity::~Entity() = default;
void Entity::setInterpolatedPosition(const glm::vec3& position) {
if (auto skeleton = getSkeleton()) {
if (skeleton) {
skeleton->interpolation.refresh(position);
}
}
glm::vec3 Entity::getInterpolatedPosition() const {
if (auto skeleton = getSkeleton()) {
if (skeleton->interpolation.isEnabled()) {
return skeleton->interpolation.getCurrent();
if (skeleton) {
const auto& interpolation = skeleton->interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) {
return interpolation.getCurrent();
}
}
return getTransform().pos;
return transform.pos;
}
void Entity::setInterpolatedRotation(const glm::quat& rotation) {
if (skeleton) {
skeleton->rotationInterpolation.refresh(rotation);
}
}
void Entity::destroy() {
if (isValid()) {
entities.despawn(id);
}
}
rigging::Skeleton* Entity::getSkeleton() const {
return registry.try_get<rigging::Skeleton>(entity);
entities.despawn(id.uid);
}
void Entity::setRig(std::shared_ptr<const rigging::SkeletonConfig> rigConfig) {
auto& skeleton = registry.get<rigging::Skeleton>(entity);
skeleton.setConfig(std::move(rigConfig));
if (skeleton) {
skeleton->setConfig(std::move(rigConfig));
}
}
dv::value Entity::serialize() const {
const auto& eid = getID();
const auto& def = eid.def;
const auto& transform = getTransform();
const auto& rigidbody = getRigidbody();
const auto& scripts = getScripting();
auto skeleton = getSkeleton();
const auto& def = id.def;
auto root = dv::object();
root["def"] = def.name;
root["uid"] = eid.uid;
root["uid"] = id.uid;
root[COMP_TRANSFORM] = transform.serialize();
root[COMP_RIGIDBODY] =
@ -68,9 +79,9 @@ dv::value Entity::serialize() const {
);
}
}
if (!scripts.components.empty()) {
if (!scripting.components.empty()) {
auto& compsMap = root.object("comps");
for (auto& comp : scripts.components) {
for (auto& comp : scripting.components) {
if (comp->env == nullptr) {
continue;
}
@ -82,45 +93,11 @@ dv::value Entity::serialize() const {
return root;
}
EntityId& Entity::getID() const {
return registry.get<EntityId>(entity);
}
bool Entity::isValid() const {
return registry.valid(entity);
}
Transform& Entity::getTransform() const {
return registry.get<Transform>(entity);
}
ScriptComponents& Entity::getScripting() const {
return registry.get<ScriptComponents>(entity);
}
const EntityDef& Entity::getDef() const {
return registry.get<EntityId>(entity).def;
}
Rigidbody& Entity::getRigidbody() const {
return registry.get<Rigidbody>(entity);
}
entityid_t Entity::getUID() const {
return registry.get<EntityId>(entity).uid;
}
int64_t Entity::getPlayer() const {
return registry.get<EntityId>(entity).player;
}
void Entity::setPlayer(int64_t id) {
auto& eid = registry.get<EntityId>(entity);
if (eid.player == id) {
void Entity::setPlayer(int64_t player) {
if (id.player == player) {
return;
}
eid.player = id;
scripting::on_entity_player_set(*this, id);
id.player = player;
scripting::on_entity_player_set(*this, player);
}

View file

@ -2,16 +2,17 @@
#include "typedefs.hpp"
#include "data/dv_fwd.hpp"
#include "Transform.hpp"
#include "Rigidbody.hpp"
#include "ScriptComponents.hpp"
#include <memory>
#include <string>
#include <entt/fwd.hpp>
#include <glm/vec3.hpp>
#include <glm/gtc/quaternion.hpp>
class Entities;
struct EntityDef;
struct Transform;
struct Rigidbody;
struct ScriptComponents;
inline std::string COMP_TRANSFORM = "transform";
inline std::string COMP_RIGIDBODY = "rigidbody";
@ -31,50 +32,83 @@ struct EntityId {
class Entity {
Entities& entities;
entityid_t id;
entt::registry& registry;
const entt::entity entity;
EntityId id;
Transform transform;
Rigidbody rigidbody;
ScriptComponents scripting;
std::unique_ptr<rigging::Skeleton> skeleton;
public:
Entity(
Entities& entities,
entityid_t id,
entt::registry& registry,
const entt::entity entity
)
: entities(entities), id(id), registry(registry), entity(entity) {
}
EntityId id,
Transform transform,
Rigidbody rigidbody,
std::unique_ptr<rigging::Skeleton> skeleton
);
Entity(const Entity&) = delete;
Entity& operator=(const Entity&) = delete;
~Entity();
dv::value serialize() const;
EntityId& getID() const;
EntityId& getID() {
return id;
}
const EntityId& getID() const {
return id;
}
bool isValid() const;
const EntityDef& getDef() const {
return id.def;
}
const EntityDef& getDef() const;
Transform& getTransform() {
return transform;
}
const Transform& getTransform() const {
return transform;
}
Transform& getTransform() const;
Rigidbody& getRigidbody() {
return rigidbody;
}
const Rigidbody& getRigidbody() const {
return rigidbody;
}
Rigidbody& getRigidbody() const;
ScriptComponents& getScripting() {
return scripting;
}
const ScriptComponents& getScripting() const {
return scripting;
}
ScriptComponents& getScripting() const;
rigging::Skeleton* getSkeleton() const;
rigging::Skeleton* getSkeleton() {
return skeleton.get();
}
const rigging::Skeleton* getSkeleton() const {
return skeleton.get();
}
void setRig(std::shared_ptr<const rigging::SkeletonConfig> rigConfig);
entityid_t getUID() const;
entityid_t getUID() const {
return id.uid;
}
int64_t getPlayer() const;
int64_t getPlayer() const {
return id.player;
}
void setPlayer(int64_t id);
void setPlayer(int64_t player);
void setInterpolatedPosition(const glm::vec3& position);
glm::vec3 getInterpolatedPosition() const;
entt::entity getHandler() const {
return entity;
}
void setInterpolatedRotation(const glm::quat& rotation);
void destroy();
};

View file

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

View file

@ -19,6 +19,8 @@ struct EntityDef {
/// @brief Entity string id (with prefix included)
std::string const name;
dv::value properties = nullptr;
/// @brief Component instances
std::vector<ComponentInstance> components;
@ -42,6 +44,9 @@ struct EntityDef {
/// @brief Model lighting mode
ModelLightingMode lightingMode = ModelLightingMode::SOLID;
/// @brief Render the entity in the translucent pass
bool translucent = false;
/// @brief Can the entity be interacted with cursor (on_attack, on_use)
bool selectable = true;

View file

@ -41,6 +41,12 @@ Player::Player(
name(name),
speed(speed),
chosenSlot(0),
hotbarSize(glm::max(
1,
static_cast<int>(
level.content.getDefaults()["hotbar-size"].asInteger(10)
)
)),
position(position),
inventory(std::move(inv)),
eid(eid),
@ -101,7 +107,7 @@ void Player::updateSelectedEntity() {
void Player::postUpdate() {
auto entity = level.entities->get(eid);
if (!entity.has_value()) {
if (entity == nullptr) {
return;
}
auto& hitbox = entity->getRigidbody().hitbox;
@ -153,13 +159,22 @@ void Player::attemptToChooseSpawnpoint() {
}
void Player::setChosenSlot(int index) {
chosenSlot = index;
chosenSlot = glm::clamp(index, 0, hotbarSize - 1);
}
int Player::getChosenSlot() const {
return chosenSlot;
}
void Player::setHotbarSize(int size) {
hotbarSize = glm::max(1, size);
setChosenSlot(chosenSlot);
}
int Player::getHotbarSize() const {
return hotbarSize;
}
float Player::getSpeed() const {
return speed;
}

View file

@ -49,6 +49,7 @@ class Player : public Serializable {
float speed;
int chosenSlot;
int hotbarSize;
glm::vec3 position;
glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")};
std::shared_ptr<Inventory> inventory;
@ -96,6 +97,10 @@ public:
int getChosenSlot() const;
void setHotbarSize(int size);
int getHotbarSize() const;
float getSpeed() const;
bool isSuspended() const;

View file

@ -45,9 +45,7 @@ template <void (*callback)(const Entity&, size_t, entityid_t)>
static sensorcallback create_sensor_callback(Entities& entities) {
return [&entities](auto entityid, auto index, auto otherid) {
if (auto entity = entities.get(entityid)) {
if (entity->isValid()) {
callback(*entity, index, otherid);
}
callback(*entity, index, otherid);
}
};
}

View file

@ -4,7 +4,6 @@
#include "physics/Hitbox.hpp"
#include <vector>
#include <entt/fwd.hpp>
class Entities;
struct EntityDef;
@ -13,9 +12,9 @@ struct Rigidbody {
bool enabled = true;
Hitbox hitbox;
std::vector<Sensor> sensors;
float mass;
float elasticity;
bool selectable;
float mass = 1.0f;
float elasticity = 0.0f;
bool selectable = false;
dv::value serialize(bool saveVelocity, bool saveBodySettings) const;
void deserialize(const dv::value& root);

View file

@ -5,6 +5,7 @@
#include "maths/util.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
static debug::Logger logger("entity-transform");

View file

@ -16,8 +16,8 @@ struct Transform {
glm::mat4 combined;
bool dirty = true;
glm::vec3 displayPos;
glm::vec3 displaySize;
glm::vec3 displayPos {};
glm::vec3 displaySize {};
dv::value serialize() const;
void deserialize(const dv::value& root);

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