Merge pull request #1040 from MihailRis/world-logic-configuration

world logic configuration
This commit is contained in:
MihailRis 2026-10-15 12:12:33 +03:00 • committed by GitHub
commit 4354896008
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 140 additions and 12 deletions

View file

@ -1,5 +1,12 @@
# *world* library
Existing world logic parameters:
| Parameter | Type | Default | Description |
| -------------- | ---- | ------- | ----------------------------- |
| `random_ticks` | bool | `true` | Enables random block ticking. |
| `block_ticks` | bool | `true` | Enables block ticking. |
```lua
-- Checks if world is open
world.is_open() -> bool
@ -33,6 +40,14 @@ world.get_total_time() -> number
-- Returns world seed.
world.get_seed() -> int
-- Returns a world logic parameter value by name.
-- Only predefined parameters are supported.
world.get_logic(name: str) -> any
-- Sets a world logic parameter by name.
-- Only predefined parameters are supported.
world.set_logic(name: str, value: any)
-- Returns generator name.
world.get_generator() -> str
@ -112,5 +127,3 @@ world.raycast(
length: number, -- ray length
normal: vec3, -- normal vector of the surface touched by the ray
} or nil if the ray did not touch a block or entity
```
```

View file

@ -1,5 +1,12 @@
# Библиотека *world*
Существующие параметры логики мира:
| Параметр | Тип | По умолчанию | Описание |
| -------------- | ---- | ------------ | -------------------------------- |
| `random_ticks` | bool | `true` | Включает случайные такты блоков. |
| `block_ticks` | bool | `true` | Включает такты блоков. |
```lua
-- Проверяет, открыт ли мир
world.is_open() -> boolean
@ -32,6 +39,14 @@ world.get_total_time() -> number
-- Возвращает зерно мира.
world.get_seed() -> int
-- Возвращает значение параметра логики мира по имени.
-- Поддерживаются только предопределённые параметры.
world.get_logic(name: string) -> any
-- Устанавливает параметр логики мира по имени.
-- Поддерживаются только предопределённые параметры.
world.set_logic(name: string, value: any)
-- Возвращает имя генератора.
world.get_generator() -> string
@ -111,4 +126,3 @@ world.raycast(
length: number, -- длина луча
normal: vec3, -- вектор нормали поверхности, которой касается луч
} или nil если луч не коснулся блока или сущности
```

View file

@ -197,7 +197,9 @@ local function __process_post_runnables()
network.__process_events()
if not hud or not hud.is_paused() then
internals.process_block_register_events()
internals.tick_updating_blocks(time.delta())
if world.is_open() and world.get_logic("block_ticks") then
internals.tick_updating_blocks(time.delta())
end
end
end

View file

@ -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

@ -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

@ -3,6 +3,7 @@
#include <glm/glm.hpp>
#include <memory>
#include <unordered_set>
#include <utility>
#include "content/Content.hpp"
@ -14,6 +15,7 @@
#include "objects/Player.hpp"
#include "objects/Players.hpp"
#include "settings.hpp"
#include "util/stringutil.hpp"
#include "voxels/Chunk.hpp"
#include "voxels/Chunks.hpp"
#include "voxels/GlobalChunks.hpp"
@ -24,6 +26,7 @@
static debug::Logger logger("world");
const float DAYIME_SPECIFIC_SPEED = 1.0f / 1440.0f; // 1.0f/60.0f/24.0f;
world_load_error::world_load_error(const std::string& message)
: std::runtime_error(message) {
}
@ -38,8 +41,7 @@ World::World(
packs(packs),
wfile(std::move(worldFiles)) {}
World::~World() {
}
World::~World() = default;
void World::updateTimers(float delta) {
info.daytime += delta * info.daytimeSpeed * DAYIME_SPECIFIC_SPEED;
@ -76,6 +78,49 @@ void World::write(Level& level) {
writeResources(content);
}
dv::value WorldInfo::getLogicValue(const std::string& name,
const dv::value& def) const {
if (logic.isObject()) {
if (auto field = logic.at(name)) {
return *field;
}
}
const auto& defaults = defaultLogic();
if (defaults.isObject()) {
if (auto field = defaults.at(name)) {
return *field;
}
}
return def;
}
void WorldInfo::setLogicValue(const std::string& name, dv::value value) {
if (!WorldInfo::isLogicKey(name)) {
throw std::runtime_error("unknown logic parameter " + util::quote(name));
}
if (!logic.isObject()) {
logic = dv::object();
}
logic[name] = std::move(value);
}
bool WorldInfo::getLogicFlag(const std::string& name, bool def) const {
auto value = getLogicValue(name, dv::value(def));
if (value.isBoolean()) {
return value.asBoolean();
}
if (value.isInteger()) {
return value.asInteger() != 0;
}
if (value.isNumber()) {
return value.asNumber() != 0.0;
}
if (value.isString()) {
return !value.asString().empty();
}
return def;
}
std::unique_ptr<Level> World::create(
const std::string& name,
const std::string& environment,
@ -216,6 +261,14 @@ void WorldInfo::deserialize(const dv::value& root) {
daytimeSpeed = timeobj["day-time-speed"].asNumber();
totalTime = timeobj["total-time"].asNumber();
}
if (root.has("logic")) {
logic = root["logic"];
} else {
logic = dv::object({
{"random_ticks", true},
{"block_ticks", true}
});
}
nextInventoryId = root["next-inventory-id"].asInteger(2);
nextEntityId = root["next-entity-id"].asInteger(1);
root.at("next-player-id").get(nextPlayerId);
@ -244,5 +297,6 @@ dv::value WorldInfo::serialize() const {
root["next-inventory-id"] = nextInventoryId;
root["next-entity-id"] = nextEntityId;
root["next-player-id"] = nextPlayerId;
root["logic"] = logic;
return root;
}

View file

@ -22,6 +22,18 @@ public:
};
struct WorldInfo : public Serializable {
static const dv::value& defaultLogic() {
static const dv::value logic = dv::object({
{"random_ticks", true},
{"block_ticks", true}
});
return logic;
}
static bool isLogicKey(const std::string& name) {
return defaultLogic().has(name);
}
std::string name;
std::string environment;
std::string explicitGenerator;
@ -29,6 +41,8 @@ struct WorldInfo : public Serializable {
int64_t nextInventoryId = 1;
int64_t nextPlayerId = 0;
dv::value logic = defaultLogic();
/// @brief Day/night loop timer in range 0..1 where
/// 0.0 - is midnight and
/// 0.5 - is noon
@ -45,6 +59,12 @@ struct WorldInfo : public Serializable {
bool isLoaded = false;
dv::value getLogicValue(
const std::string& name, const dv::value& def = nullptr
) const;
void setLogicValue(const std::string& name, dv::value value);
bool getLogicFlag(const std::string& name, bool def = true) const;
dv::value serialize() const override;
void deserialize(const dv::value& src) override;
};