From aa60ae3fadf7fd0185fe2e31aa489d91567c19e6 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 28 Nov 2024 16:33:38 +0300 Subject: [PATCH 1/6] improve properties filter --- res/scripts/post_content.lua | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/res/scripts/post_content.lua b/res/scripts/post_content.lua index 56d66a5c..ae67c678 100644 --- a/res/scripts/post_content.lua +++ b/res/scripts/post_content.lua @@ -1,17 +1,32 @@ local user_props = file.read_combined_object("config/user-props.toml") -local names = {} +local names = { + "parent", "caption", "texture", "texture-faces", "model", "model-name", + "model-primitives", "material", "rotation", "hitboxes", "hitbox", "emission", + "size", "obstacle", "replaceable", "light-passing", "sky-light-passing", + "shadeless", "ambient-occlusion", "breakable", "selectable", "grounded", + "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" +} for name, _ in pairs(user_props) do table.insert(names, name) end -- remove undefined properties for id, blockprops in pairs(block.properties) do for propname, value in pairs(blockprops) do - if propname:find(':') and not table.has(names, propname) then - print("erase property", propname) + if not table.has(names, propname) then blockprops[propname] = nil end end end +for id, itemprops in pairs(item.properties) do + for propname, value in pairs(itemprops) do + if not table.has(names, propname) then + itemprops[propname] = nil + end + end +end local function make_read_only(t) setmetatable(t, { From ba1a82539fa5ec1982d0526485c2e1a5fcb1992c Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 28 Nov 2024 16:42:46 +0300 Subject: [PATCH 2/6] update doc/*/block-properties.md --- doc/en/block-properties.md | 9 +++++++++ doc/ru/block-properties.md | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/doc/en/block-properties.md b/doc/en/block-properties.md index 18c068ca..fb874e0c 100644 --- a/doc/en/block-properties.md +++ b/doc/en/block-properties.md @@ -187,3 +187,12 @@ Available data types: - Currently, the total sum of the field sizes cannot exceed 240 bytes. - A field without an array length specification is equivalent to an array of 1 element. - A character array can be used to store UTF-8 strings. + +## User properties + +User properties must be declared in `pack:config/user-props.toml` file: +```toml +"pack:property_name" = {} +``` + +Example: [user properties of pack **base**](../../res/content/base/config/user-props.toml). diff --git a/doc/ru/block-properties.md b/doc/ru/block-properties.md index 79b08da2..1862e659 100644 --- a/doc/ru/block-properties.md +++ b/doc/ru/block-properties.md @@ -199,3 +199,12 @@ - На данный момент общая сумма размеров полей не может превышать 240 байт. - Поле без указания длины массива эквивалентно массиву из 1 элемента. - Массив символьного типа может использоваться для хранения UTF-8 строк. + +## Пользовательские свойства + +Пользовательские свойства должны быть объявляены в файле `пак:config/user-props.toml`: +```toml +"пак:имя_свойства" = {} +``` + +Пример: [пользовательские свойства пака **base**](../../res/content/base/config/user-props.toml). From ca83dcf9a7a820b5d602865141701d87b9a2baaf Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 28 Nov 2024 17:48:06 +0300 Subject: [PATCH 3/6] update doc/*/xml-ui-layouts.md --- doc/en/xml-ui-layouts.md | 1 + doc/ru/xml-ui-layouts.md | 1 + 2 files changed, 2 insertions(+) diff --git a/doc/en/xml-ui-layouts.md b/doc/en/xml-ui-layouts.md index d598faa2..d77a93ed 100644 --- a/doc/en/xml-ui-layouts.md +++ b/doc/en/xml-ui-layouts.md @@ -98,6 +98,7 @@ Inner text is a button text. Inner text - initially entered text - `placeholder` - placeholder text (used if the text field is empty) +- `hint` - text displayed if the text field is empty (not sent to consumer, sub-consumer and validator). - `supplier` - text supplier (called every frame) - `consumer` - lua function that receives the entered text. Called only when input is complete - `sub-consumer` - lua function-receiver of the input text. Called during text input or deletion. diff --git a/doc/ru/xml-ui-layouts.md b/doc/ru/xml-ui-layouts.md index f4502a94..5c71690f 100644 --- a/doc/ru/xml-ui-layouts.md +++ b/doc/ru/xml-ui-layouts.md @@ -99,6 +99,7 @@ Внутренний текст - изначально введенный текст - `placeholder` - текст подстановки (используется если текстовое поле пусто) +- `hint` - текст, отображаемый, если текстовое поле пусто (не отправляется в consumer, sub-consumer и validator). - `supplier` - поставщик текста (вызывается каждый кадр) - `consumer` - lua функция-приемник введенного текста. Вызывается только при завершении ввода - `sub-consumer` - lua функция-приемник вводимого текста. Вызывается во время ввода или удаления текста. From 95689b111510bcf480c965d4827cc6371692d0a9 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 28 Nov 2024 18:09:12 +0300 Subject: [PATCH 4/6] add doc/*/scripting/builtins/libnetwork.md --- doc/en/scripting.md | 1 + doc/en/scripting/builtins/libnetwork.md | 94 +++++++++++++++++++++++++ doc/ru/scripting.md | 1 + doc/ru/scripting/builtins/libnetwork.md | 94 +++++++++++++++++++++++++ src/network/Network.cpp | 1 + 5 files changed, 191 insertions(+) create mode 100644 doc/en/scripting/builtins/libnetwork.md create mode 100644 doc/ru/scripting/builtins/libnetwork.md diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 6b33f7d9..7b113e44 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -22,6 +22,7 @@ Subsections: - [inventory](scripting/builtins/libinventory.md) - [item](scripting/builtins/libitem.md) - [mat4](scripting/builtins/libmat4.md) + - [network](scripting/builtins/libnetwork.md) - [pack](scripting/builtins/libpack.md) - [player](scripting/builtins/libplayer.md) - [quat](scripting/builtins/libquat.md) diff --git a/doc/en/scripting/builtins/libnetwork.md b/doc/en/scripting/builtins/libnetwork.md new file mode 100644 index 00000000..1e519d9d --- /dev/null +++ b/doc/en/scripting/builtins/libnetwork.md @@ -0,0 +1,94 @@ +# *network* library + +A library for working with the network. + +## HTTP requests + +```lua +-- Performs a GET request to the specified URL. +-- After receiving the response, passes the text to the callback function. +network.get(url: str, callback: function(str)) + +-- Example: +network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s) + print(json.parse(s).name) -- will output the name of the latest engine release +end) + +-- A variant for binary files, with a byte array instead of a string in the response. +network.get_binary(url: str, callback: function(table|ByteArray)) +``` + +## TCP Connections + +```lua +network.tcp_connect( + -- Address + address: str, + -- Port + port: int, + -- Function called upon successful connection + -- Sending will not work before connection + -- Socket is passed as the only argument + callback: function(Socket) +) --> Socket +``` + +Initiates TCP connection. + +The Socket class has the following methods: + +```lua +-- Sends a byte array +socket:send(table|ByteArray) + +-- Reads the received data +socket:recv( + -- Maximum size of the byte array to read + length: int, + -- Use table instead of Bytearray + [optional] usetable: bool=false +) -> nil|table|Bytearray +-- Returns nil on error (socket is closed or does not exist). +-- If there is no data yet, returns an empty byte array. + +-- Closes the connection +socket:close() + +-- Checks that the socket exists and is not closed. +socket:is_alive() --> bool + +-- Checks if the connection is present (using socket:send(...) is available). +socket:is_connected() --> bool +``` + +```lua +-- Opens a TCP server. +network.tcp_open( + -- Port + port: int, + -- Function called when connecting + -- The socket of the connected client is passed as the only argument + callback: function(Socket) +) --> ServerSocket +``` + +The SocketServer class has the following methods: + +```lua +-- Closes the server, breaking connections with clients. +server:close() + +-- Checks if the TCP server exists and is open. +server:is_open() --> bool +``` + +## Analytics + +```lua +-- Returns the approximate amount of data sent (including connections to localhost) +-- in bytes. +network.get_total_upload() --> int +-- Returns the approximate amount of data received (including connections to localhost) +-- in bytes. +network.get_total_download() --> int +``` diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index 19f4570a..8e0c9df3 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -22,6 +22,7 @@ - [inventory](scripting/builtins/libinventory.md) - [item](scripting/builtins/libitem.md) - [mat4](scripting/builtins/libmat4.md) + - [network](scripting/builtins/libnetwork.md) - [pack](scripting/builtins/libpack.md) - [player](scripting/builtins/libplayer.md) - [quat](scripting/builtins/libquat.md) diff --git a/doc/ru/scripting/builtins/libnetwork.md b/doc/ru/scripting/builtins/libnetwork.md new file mode 100644 index 00000000..8a937330 --- /dev/null +++ b/doc/ru/scripting/builtins/libnetwork.md @@ -0,0 +1,94 @@ +# Библиотека *network* + +Библиотека для работы с сетью. + +## HTTP-запросы + +```lua +-- Выполняет GET запрос к указанному URL. +-- После получения ответа, передаёт текст в функцию callback. +network.get(url: str, callback: function(str)) + +-- Пример: +network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s) + print(json.parse(s).name) -- выведет имя последнего релиза движка +end) + +-- Вариант для двоичных файлов, с массивом байт вместо строки в ответе. +network.get_binary(url: str, callback: function(table|ByteArray)) +``` + +## TCP-Соединения + +```lua +network.tcp_connect( + -- Адрес + address: str, + -- Порт + port: int, + -- Функция, вызываемая при успешном подключении + -- До подключения отправка работать не будет + -- Как единственный аргумент передаётся сокет + callback: function(Socket) +) --> Socket +``` + +Инициирует TCP подключение. + +Класс Socket имеет следующие методы: + +```lua +-- Отправляет массив байт +socket:send(table|ByteArray) + +-- Читает полученные данные +socket:recv( + -- Максимальный размер читаемого массива байт + length: int, + -- Использовать таблицу вместо Bytearray + [опционально] usetable: bool=false +) -> nil|table|Bytearray +-- В случае ошибки возвращает nil (сокет закрыт или несуществует). +-- Если данных пока нет, возвращает пустой массив байт. + +-- Закрывает соединение +socket:close() + +-- Проверяет, что сокет существует и не закрыт. +socket:is_alive() --> bool + +-- Проверяет наличие соединения (доступно использование socket:send(...)). +socket:is_connected() --> bool +``` + +```lua +-- Открывает TCP-сервер. +network.tcp_open( + -- Порт + port: int, + -- Функция, вызываемая при поключениях + -- Как единственный аргумент передаётся сокет подключенного клиента + callback: function(Socket) +) --> ServerSocket +``` + +Класс SocketServer имеет следующие методы: + +```lua +-- Закрывает сервер, разрывая соединения с клиентами. +server:close() + +-- Проверяет, существует и открыт ли TCP сервер. +server:is_open() --> bool +``` + +## Аналитика + +```lua +-- Возвращает приблизительный объем отправленных данных (включая соединения с localhost) +-- в байтах. +network.get_total_upload() --> int +-- Возвращает приблизительный объем полученных данных (включая соединения с localhost) +-- в байтах. +network.get_total_download() --> int +``` diff --git a/src/network/Network.cpp b/src/network/Network.cpp index f0ebd3ca..bc4643bf 100644 --- a/src/network/Network.cpp +++ b/src/network/Network.cpp @@ -99,6 +99,7 @@ public: curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, request.followLocation); + curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl"); if (request.maxSize == 0) { curl_easy_setopt( curl, CURLOPT_MAXFILESIZE, std::numeric_limits::max() From 14650562c2e53a809a75d88c631573d856697042 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 28 Nov 2024 18:13:21 +0300 Subject: [PATCH 5/6] update CURLOPT_USERAGENT value --- src/network/Network.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/network/Network.cpp b/src/network/Network.cpp index bc4643bf..5a1931ac 100644 --- a/src/network/Network.cpp +++ b/src/network/Network.cpp @@ -99,7 +99,7 @@ public: curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, request.followLocation); - curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl"); + curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/7.81.0"); if (request.maxSize == 0) { curl_easy_setopt( curl, CURLOPT_MAXFILESIZE, std::numeric_limits::max() From a5609f3e0c736f12b6b5e9ef2138a6ba4fdd8ac5 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 28 Nov 2024 18:28:42 +0300 Subject: [PATCH 6/6] add doc/*/scripting/builtins/libgfx-blockwraps.md --- doc/en/scripting.md | 1 + .../scripting/builtins/libgfx-blockwraps.md | 22 ++++++++++++++++++ doc/ru/scripting.md | 1 + .../scripting/builtins/libgfx-blockwraps.md | 23 +++++++++++++++++++ 4 files changed, 47 insertions(+) create mode 100644 doc/en/scripting/builtins/libgfx-blockwraps.md create mode 100644 doc/ru/scripting/builtins/libgfx-blockwraps.md diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 7b113e44..b00930f1 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -15,6 +15,7 @@ Subsections: - [cameras](scripting/builtins/libcameras.md) - [entities](scripting/builtins/libentities.md) - [file](scripting/builtins/libfile.md) + - [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md) - [gfx.particles](particles.md#gfxparticles-library) - [gfx.text3d](3d-text.md#gfxtext3d-library) - [gui](scripting/builtins/libgui.md) diff --git a/doc/en/scripting/builtins/libgfx-blockwraps.md b/doc/en/scripting/builtins/libgfx-blockwraps.md new file mode 100644 index 00000000..e03374dd --- /dev/null +++ b/doc/en/scripting/builtins/libgfx-blockwraps.md @@ -0,0 +1,22 @@ +# Library *gfx.blockwraps* + +Library for working with *block wrappers*. + +Block wrappers are introduced to implement block destruction animation and can be used for other purposes. + +```lua +-- Creates a wrapper at the specified position, with the specified texture. +-- Returns the wrapper id. +gfx.blockwraps.wrap(position: vec3, texture: str) --> int + +-- Removes the wrapper, if it exists. +gfx.blockwraps.unwrap(id: int) + +-- Changes the position of the wrapper, if it exists. +gfx.blockwraps.set_pos(id: int, position: vec3) + +-- Changes the texture of the wrapper, if it exists. +gfx.blockwraps.set_texture(id: int, texture: str) +``` + +Wrappers are not automatically removed without calling `unwrap`. diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index 8e0c9df3..63191ea8 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -15,6 +15,7 @@ - [cameras](scripting/builtins/libcameras.md) - [entities](scripting/builtins/libentities.md) - [file](scripting/builtins/libfile.md) + - [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md) - [gfx.particles](particles.md#библиотека-gfxparticles) - [gfx.text3d](3d-text.md#библиотека-gfxtext3d) - [gui](scripting/builtins/libgui.md) diff --git a/doc/ru/scripting/builtins/libgfx-blockwraps.md b/doc/ru/scripting/builtins/libgfx-blockwraps.md new file mode 100644 index 00000000..ea794d2b --- /dev/null +++ b/doc/ru/scripting/builtins/libgfx-blockwraps.md @@ -0,0 +1,23 @@ +# Библиотека *gfx.blockwraps* + +Библиотека для работы с *обертками блоков*. + +Обёртки блоков введены для реализации анимации разрушения блоков и могут +использоваться для иных задач. + +```lua +-- Создаёт обертку на указанной позиции, с указанной текстурой. +-- Возвращает id обёртки. +gfx.blockwraps.wrap(position: vec3, texture: str) --> int + +-- Удаляет обертку, если она существует. +gfx.blockwraps.unwrap(id: int) + +-- Меняет позицию обёртки, если она существует. +gfx.blockwraps.set_pos(id: int, position: vec3) + +-- Меняет текстуру обёртки, если она существует. +gfx.blockwraps.set_texture(id: int, texture: str) +``` + +Обертки не удаляются автоматически без вызова `unwrap`.