diff --git a/doc/en/entity-properties.md b/doc/en/entity-properties.md index 41510ff12..6728b4a66 100644 --- a/doc/en/entity-properties.md +++ b/doc/en/entity-properties.md @@ -1,5 +1,17 @@ # Entity properties +## User properties + +Access to custom entity properties is provided through the table `entities.properties[id]["property"]`, where `id` is the entity definition index. + +Custom properties follow the same pack inheritance and override rules as block and item properties, and must be declared in `pack:config/user-props.toml`: + +```toml +"pack:property_name" = {} +``` + +This makes the property available in Lua scripts as `entities.properties[entities.def_index("pack:entity")]["property"]`. + ## Logic ### *components* diff --git a/doc/en/item-properties.md b/doc/en/item-properties.md index 44e8911cc..7913aff3f 100644 --- a/doc/en/item-properties.md +++ b/doc/en/item-properties.md @@ -72,6 +72,45 @@ Property status is displayed in the inventory interface. Display method is defin Defines the name of the script containing the item's event handlers. By default, equals to the item's string id (name). Allows you to reuse a single script for multiple items. +## User properties + +Access to custom item properties is provided through the table `item.properties[id]["property"]`, where `id` is the numeric item index. + +User properties must be declared in `pack:config/user-props.toml`: + +```toml +"pack:property_name" = {} +``` + +### Example usage in Lua - `base_survival:tool` + +```lua +local tool = item.properties[itemid]["base_survival:tool"] +if tool then + local stone_material = tool.materials['base:stone'] + if stone_material then + print(tool.type, stone_material.speed) + end +end +``` + +Definition in item JSON: + +```json +{ + "base_survival:tool": { + "type": "breaker", + "materials": { + "base:stone": { + "speed": 15.0 + } + } + } +} +``` + +Custom property tables follow the same inheritance and override rules as block properties. + ## Tags Tags allow you to designate general properties of items. Names should be formatted as `prefix:tag_name`. diff --git a/doc/en/scripting/builtins/libentities.md b/doc/en/scripting/builtins/libentities.md index 9e653ba78..78b8b8c76 100644 --- a/doc/en/scripting/builtins/libentities.md +++ b/doc/en/scripting/builtins/libentities.md @@ -41,6 +41,11 @@ entities.defs_count() -> int ``` +```lua +-- Table of custom entity properties (see ../../entity-properties.md) +entities.properties: table> +``` + > [!NOTE] > The following functions for retrieving multiple entities return tables with integer keys (uid). > For iteration, use `pairs`, and for calculating the table size, use `table.count_pairs`. diff --git a/doc/ru/entity-properties.md b/doc/ru/entity-properties.md index 5cc922194..5b1ba2d07 100644 --- a/doc/ru/entity-properties.md +++ b/doc/ru/entity-properties.md @@ -1,5 +1,17 @@ # Свойства сущностей +## Пользовательские свойства + +Доступ к пользовательским свойствам сущностей осуществляется через таблицу `entities.properties[id]["свойство"]`, где `id` - индекс определения сущности. + +Пользовательские свойства следуют тем же правилам наследования и переопределения пакетов, что и свойства блоков и предметов, и должны быть объявлены в `pack:config/user-props.toml`: + +```toml +"pack:property_name" = {} +``` + +Это делает свойство доступным в Lua-скриптах как `entities.properties[entities.def_index("pack:entity")]["свойство"]`. + ## Логика ### Список компонентов - *components* diff --git a/doc/ru/item-properties.md b/doc/ru/item-properties.md index 1f4be05be..6c170e527 100644 --- a/doc/ru/item-properties.md +++ b/doc/ru/item-properties.md @@ -71,6 +71,45 @@ Определяет имя скрипта, содержащего обработчики событий предмета. По умолчанию соответствует строковому id (имени) предмета. Свойство обеспечивает возможность использования одного скрипта для нескольких предметов. +## Пользовательские свойства + +Доступ к пользовательским свойствам предметов осуществляется через таблицу `item.properties[id]["свойство"]`, где `id` — числовой индекс предмета. + +Пользовательские свойства должны быть объявлены в файле `пак:config/user-props.toml`: + +```toml +"пак:имя_свойства" = {} +``` + +### Пример использования в Lua - `base_survival:tool` + +```lua +local tool = item.properties[itemid]["base_survival:tool"] +if tool then + local stone_material = tool.materials['base:stone'] + if stone_material then + print(tool.type, stone_material.speed) + end +end +``` + +Описание в JSON предмета: + +```json +{ + "base_survival:tool": { + "type": "breaker", + "materials": { + "base:stone": { + "speed": 15.0 + } + } + } +} +``` + +Пользовательские свойства следуют тем же правилам наследования и переопределения, что и свойства блоков. + ## Теги - *tags* Теги позволяют обозначать обобщённые свойства предметов. Названия следует формировать как `префикс:имя_тега`. diff --git a/doc/ru/scripting/builtins/libentities.md b/doc/ru/scripting/builtins/libentities.md index 045dbe2fd..3c2bcf9c4 100644 --- a/doc/ru/scripting/builtins/libentities.md +++ b/doc/ru/scripting/builtins/libentities.md @@ -40,6 +40,11 @@ entities.def_index(name: string) -> int entities.defs_count() -> int ``` +```lua +-- Таблица пользовательских свойств сущностей (см. ../../entity-properties.md) +entities.properties: table> +``` + > [!NOTE] > Следующие функции для получения нескольких сущностей возвращают таблицы с целочисленными ключами (uid). > Для итерации нужно использовать pairs, для подсчёта размера таблицы - table.count_pairs. diff --git a/res/scripts/post_content.lua b/res/scripts/post_content.lua index 97b2e93b6..cc056f5d4 100644 --- a/res/scripts/post_content.lua +++ b/res/scripts/post_content.lua @@ -2,7 +2,7 @@ local app = __vc_app local internals = __vc_internals local user_props = file.read_combined_object("config/user-props.toml") -local names = { +local core_names = { "parent", "caption", "texture", "texture-faces", "model", "model-name", "model-primitives", "material", "rotation", "hitboxes", "hitbox", "emission", "size", "obstacle", "replaceable", "light-passing", "sky-light-passing", @@ -10,35 +10,61 @@ local names = { "hidden", "draw-group", "picking-item", "surface-replacement", "script-name", "ui-layout", "inventory-size", "tick-interval", "overlay-texture", "translucent", "fields", "particles", "icon-type", "icon", "placing-block", - "stack-size", "name", "script-file", "culling", "solid" + "stack-size", "name", "script-file", "culling", "solid", + "components", "sensors", "body-type", "save", "save-skeleton-pose", + "save-skeleton-textures", "save-body-velocity", "save-body-settings", + "skeleton-name", "lighting-mode", "mass", "elasticity", "step-height", + "blocking", "material", "translucent" } for name, _ in pairs(user_props) do - table.insert(names, name) + table.insert(core_names, name) +end + +local function get_parent_props(lib, props) + if not props.parent then + return {} + end + if lib == entities then + local parent_id = entities.def_index(props.parent) + if parent_id == nil then + return {} + end + return entities.properties[parent_id] or {} + end + if lib.index == nil then + return {} + end + local parent_id = lib.index(props.parent) + if parent_id == nil then + return {} + end + return lib.properties[parent_id] or {} end -- remove undefined properties and build tags set local function process_properties(lib) for id, props in pairs(lib.properties) do - if props.parent then - local parent_props = lib.properties[block.index(props.parent)] or {} - for propname, value in pairs(parent_props) do - if not props[propname] then - props[propname] = value - end + local parent_props = get_parent_props(lib, props) + for propname, value in pairs(parent_props) do + if not props[propname] then + props[propname] = value end end for propname, _ in pairs(props) do - if not table.has(names, propname) then + if not table.has(core_names, propname) then props[propname] = nil end end - props.tags_set = lib.__get_tags(id) + if lib.__get_tags then + props.tags_set = lib.__get_tags(id) + end end end process_properties(block) process_properties(item) +process_properties(entities) local function make_read_only(t) setmetatable(t, { @@ -53,6 +79,16 @@ for k,v in pairs(block.properties) do make_read_only(v) end +make_read_only(item.properties) +for k,v in pairs(item.properties) do + make_read_only(v) +end + +make_read_only(entities.properties) +for k,v in pairs(entities.properties) do + make_read_only(v) +end + local function cache_names(library) local indices = {} local names = {} @@ -87,6 +123,26 @@ end cache_names(block) cache_names(item) +local function cache_entity_names() + local indices = {} + local names = {} + for id=0, entities.defs_count() - 1 do + local name = entities.properties[id].name + indices[name] = id + names[id] = name + end + + function entities.name(id) + return names[id] + end + + function entities.index(name) + return indices[name] + end +end + +cache_entity_names() + __vc_scripts_registry.build_registry() local packs = app.get_content() diff --git a/src/content/ContentBuilder.cpp b/src/content/ContentBuilder.cpp index 83836dfe3..e0caac381 100644 --- a/src/content/ContentBuilder.cpp +++ b/src/content/ContentBuilder.cpp @@ -123,6 +123,13 @@ std::unique_ptr 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()); } diff --git a/src/content/loading/EntityLoader.cpp b/src/content/loading/EntityLoader.cpp index fbc29bddf..91f571c95 100644 --- a/src/content/loading/EntityLoader.cpp +++ b/src/content/loading/EntityLoader.cpp @@ -1,5 +1,6 @@ #define VC_ENABLE_REFLECTION #include "ContentUnitLoader.hpp" +#include "ContentLoadingCommons.hpp" #include "../ContentBuilder.hpp" #include "coders/json.hpp" @@ -16,6 +17,7 @@ template<> void ContentUnitLoader::loadUnit( EntityDef& def, const std::string& name, const io::path& file ) { auto root = io::read_json(file); + process_properties(def, name, root); if (root.has("parent")) { const auto& parentName = root["parent"].asString(); diff --git a/src/logic/scripting/scripting.cpp b/src/logic/scripting/scripting.cpp index 4ccdd7b31..6bca06cfa 100644 --- a/src/logic/scripting/scripting.cpp +++ b/src/logic/scripting/scripting.cpp @@ -24,6 +24,7 @@ #include "world/Level.hpp" #include "world/World.hpp" #include "interfaces/Process.hpp" +#include "objects/EntityDef.hpp" #include #include @@ -298,6 +299,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"); diff --git a/src/objects/EntityDef.hpp b/src/objects/EntityDef.hpp index c50834671..57b88f113 100644 --- a/src/objects/EntityDef.hpp +++ b/src/objects/EntityDef.hpp @@ -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 components;