From a6c8da521cf795702080f31cfa911409e4efba2e Mon Sep 17 00:00:00 2001 From: Rost Alexeev <148265518+R0STUS@users.noreply.github.com> Date: Mon, 10 Jun 2024 16:43:47 +0200 Subject: [PATCH 01/14] Vignette effect to screen --- res/shaders/screen.glslf | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/res/shaders/screen.glslf b/res/shaders/screen.glslf index 0117b59f..edeb4270 100644 --- a/res/shaders/screen.glslf +++ b/res/shaders/screen.glslf @@ -2,8 +2,29 @@ in vec2 v_coord; out vec4 f_color; uniform sampler2D u_texture0; +uniform ivec2 u_screenSize; + +float random(vec2 st){ + return fract(sin(dot(st.xy ,vec2(12.9898,78.233))) * 43758.5453); +} + +// Vignette +vec4 apply_vignette(vec4 color) +{ + vec2 position = (gl_FragCoord.xy / u_screenSize) - vec2(0.5); + float dist = length(position); + + float radius = 0.88; + float softness = 0.365; + float vignette = smoothstep(radius, radius - softness, dist); + + color.rgb = color.rgb - (1.0 - vignette); + + return color; +} void main(){ f_color = texture(u_texture0, v_coord); + f_color = apply_vignette(f_color); } From f8d814aab5c41659e4a97ca76cd598f3c58df429 Mon Sep 17 00:00:00 2001 From: Rost Alexeev <148265518+R0STUS@users.noreply.github.com> Date: Tue, 11 Jun 2024 21:50:07 +0200 Subject: [PATCH 02/14] Update screen.glslf --- res/shaders/screen.glslf | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/res/shaders/screen.glslf b/res/shaders/screen.glslf index edeb4270..b06dbe9c 100644 --- a/res/shaders/screen.glslf +++ b/res/shaders/screen.glslf @@ -14,8 +14,8 @@ vec4 apply_vignette(vec4 color) vec2 position = (gl_FragCoord.xy / u_screenSize) - vec2(0.5); float dist = length(position); - float radius = 0.88; - float softness = 0.365; + float radius = 2.0; + float softness = 1.7; float vignette = smoothstep(radius, radius - softness, dist); color.rgb = color.rgb - (1.0 - vignette); From dbe98959d1fa2923ca20957a1358d496752c8d02 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 18:41:38 +0300 Subject: [PATCH 03/14] update doc/ru structure & update docs (ru) --- doc/ru/0.Главная.md | 16 -------- ...едзагрузка-ассетов.md => assets-preload.md} | 0 doc/ru/{7.Аудио.md => audio.md} | 0 .../{9.Модели-блоков.md => block-models.md} | 0 ...Свойства-блоков.md => block-properties.md} | 5 +++ doc/ru/{Консоль.md => console.md} | 0 .../{2.Контент‐паки.md => content-packs.md} | 0 ...спользованию-движка.md => engine-use-recommendations.md} | 0 ...войства-предметов.md => item-properties.md} | 0 doc/ru/main-page.md | 12 ++++++ doc/ru/{8.Скриптинг.md => scripting.md} | 38 +++++++++++++++++++ .../events.md} | 0 .../filesystem.md} | 0 .../modules/core_Vector2&&Vector3.md} | 0 .../modules/core_bit_converter.md} | 0 .../modules/core_data_buffer.md} | 0 .../user-input.md} | 0 ...азметка-интерфейса.md => xml-ui-layouts.md} | 0 18 files changed, 55 insertions(+), 16 deletions(-) delete mode 100644 doc/ru/0.Главная.md rename doc/ru/{6.Предзагрузка-ассетов.md => assets-preload.md} (100%) rename doc/ru/{7.Аудио.md => audio.md} (100%) rename doc/ru/{9.Модели-блоков.md => block-models.md} (100%) rename doc/ru/{3.Свойства-блоков.md => block-properties.md} (97%) rename doc/ru/{Консоль.md => console.md} (100%) rename doc/ru/{2.Контент‐паки.md => content-packs.md} (100%) rename doc/ru/{1.Рекомендации-по-использованию-движка.md => engine-use-recommendations.md} (100%) rename doc/ru/{4.Свойства-предметов.md => item-properties.md} (100%) create mode 100644 doc/ru/main-page.md rename doc/ru/{8.Скриптинг.md => scripting.md} (92%) rename doc/ru/{События-движка.md => scripting/events.md} (100%) rename doc/ru/{Файловая-система-и-сериализация.md => scripting/filesystem.md} (100%) rename doc/ru/{8.3 Модуль-Vector2&&Vector3.md => scripting/modules/core_Vector2&&Vector3.md} (100%) rename doc/ru/{8.1.Модуль-Lua-core_bit_converter.md => scripting/modules/core_bit_converter.md} (100%) rename doc/ru/{8.2.Модуль-Lua-core_data_buffer.md => scripting/modules/core_data_buffer.md} (100%) rename doc/ru/{Пользовательский-ввод.md => scripting/user-input.md} (100%) rename doc/ru/{5.XML-разметка-интерфейса.md => xml-ui-layouts.md} (100%) diff --git a/doc/ru/0.Главная.md b/doc/ru/0.Главная.md deleted file mode 100644 index 3a638d98..00000000 --- a/doc/ru/0.Главная.md +++ /dev/null @@ -1,16 +0,0 @@ -# Разделы - -- [Рекомендации по использованию движка](1.Рекомендации-по-использованию-движка.md) -- [Контент‐паки](2.Контент‐паки.md) -- [Свойства блоков](3.Свойства-блоков.md) -- [Свойства предметов](4.Свойства-предметов.md) -- [XML разметка интерфейса](5.XML-разметка-интерфейса.md) -- [Предзагрузка ассетов](6.Предзагрузка-ассетов.md) -- [Аудио](7.Аудио.md) -- [Скриптинг](8.Скриптинг.md) - - [Модуль core:bit_converter](8.1.Модуль-Lua-core_bit_converter.md) - - [Модуль core:data_buffer](8.2.Модуль-Lua-core_data_buffer.md) - - [Пользовательский ввод](Пользовательский-ввод.md) - - [Файловая система и сериализация](Файловая-система-и-сериализация.md) -- [Консоль](Консоль.md) -- [Модели блоков](9.Модели-блоков.md) diff --git a/doc/ru/6.Предзагрузка-ассетов.md b/doc/ru/assets-preload.md similarity index 100% rename from doc/ru/6.Предзагрузка-ассетов.md rename to doc/ru/assets-preload.md diff --git a/doc/ru/7.Аудио.md b/doc/ru/audio.md similarity index 100% rename from doc/ru/7.Аудио.md rename to doc/ru/audio.md diff --git a/doc/ru/9.Модели-блоков.md b/doc/ru/block-models.md similarity index 100% rename from doc/ru/9.Модели-блоков.md rename to doc/ru/block-models.md diff --git a/doc/ru/3.Свойства-блоков.md b/doc/ru/block-properties.md similarity index 97% rename from doc/ru/3.Свойства-блоков.md rename to doc/ru/block-properties.md index c1cc2bda..982bacc4 100644 --- a/doc/ru/3.Свойства-блоков.md +++ b/doc/ru/block-properties.md @@ -129,3 +129,8 @@ Число слотов инвентаря блока. По-умолчанию - 0 (инвентарь отсутствует) +# Расширенные блоки + +## Размер блока - `size` + +Массив из трех целых чисел. Значение по-умолчанию - `[1, 1, 1]`. diff --git a/doc/ru/Консоль.md b/doc/ru/console.md similarity index 100% rename from doc/ru/Консоль.md rename to doc/ru/console.md diff --git a/doc/ru/2.Контент‐паки.md b/doc/ru/content-packs.md similarity index 100% rename from doc/ru/2.Контент‐паки.md rename to doc/ru/content-packs.md diff --git a/doc/ru/1.Рекомендации-по-использованию-движка.md b/doc/ru/engine-use-recommendations.md similarity index 100% rename from doc/ru/1.Рекомендации-по-использованию-движка.md rename to doc/ru/engine-use-recommendations.md diff --git a/doc/ru/4.Свойства-предметов.md b/doc/ru/item-properties.md similarity index 100% rename from doc/ru/4.Свойства-предметов.md rename to doc/ru/item-properties.md diff --git a/doc/ru/main-page.md b/doc/ru/main-page.md new file mode 100644 index 00000000..b51ee499 --- /dev/null +++ b/doc/ru/main-page.md @@ -0,0 +1,12 @@ +# Разделы + +- [Рекомендации по использованию движка](engine-use-recommendations.md) +- [Контент‐паки](content-packs.md) +- [Свойства блоков](block-properties.md) +- [Свойства предметов](item-properties.md) +- [XML разметка интерфейса](xml-ui-layouts.md) +- [Предзагрузка ассетов](assets-preload.md) +- [Аудио](audio.md) +- [Скриптинг](scripting.md) +- [Консоль](console.md) +- [Модели блоков](block-models.md) diff --git a/doc/ru/8.Скриптинг.md b/doc/ru/scripting.md similarity index 92% rename from doc/ru/8.Скриптинг.md rename to doc/ru/scripting.md index f5ba82c2..05f0f407 100644 --- a/doc/ru/8.Скриптинг.md +++ b/doc/ru/scripting.md @@ -2,6 +2,15 @@ В качестве языка сценариев используется LuaJIT +Подразделы: +- [События движка](scripting/events.md) +- [Пользовательский ввод](scripting/user-input.md) +- [Файловая система и сериализация](scripting/filesystem.md) +- [Модуль core:bit_converter](scripting/modules/core_bit_converter.md) +- [Модуль core:data_buffer](scripting/modules/core_data_buffer.md) +- [Модули core:Vector2, core:Vector3](scripting/modules/core_Vector2&&Vector3.md) + + ```lua require "контентпак:имя_модуля" -- загружает lua модуль из папки modules (расширение не указывается) ``` @@ -373,6 +382,35 @@ block.set_rotation(x: int, y: int, z: int, rotation: int) Устанавливает вращение блока по индексу в его профиле вращения. +### Расширенные блоки + +Расширенные блоки - те, размер которых превышает 1x1x1 + +```python +block.is_extended(id: int) -> bool +``` + +Проверяет, является ли блок расширенным. + +```python +block.get_size(id: int) -> int, int, int +``` + +Возвращает размер блока. + +```python +block.is_segment(x: int, y: int, z: int) -> bool +``` + +Проверяет является ли блок сегментом расширенного блока, не являющимся главным. + +```python +block.seek_origin(x: int, y: int, z: int) -> int, int, int +``` + +Возвращает позицию главного сегмента расширенного блока или исходную позицию, +если блок не являющийся расширенным. + ### Пользовательские биты Выделенная под использования в скриптах часть поля `voxel.states` хранящего доп-информацию о вокселе, такую как вращение блока. На данный момент выделенная часть составляет 8 бит. diff --git a/doc/ru/События-движка.md b/doc/ru/scripting/events.md similarity index 100% rename from doc/ru/События-движка.md rename to doc/ru/scripting/events.md diff --git a/doc/ru/Файловая-система-и-сериализация.md b/doc/ru/scripting/filesystem.md similarity index 100% rename from doc/ru/Файловая-система-и-сериализация.md rename to doc/ru/scripting/filesystem.md diff --git a/doc/ru/8.3 Модуль-Vector2&&Vector3.md b/doc/ru/scripting/modules/core_Vector2&&Vector3.md similarity index 100% rename from doc/ru/8.3 Модуль-Vector2&&Vector3.md rename to doc/ru/scripting/modules/core_Vector2&&Vector3.md diff --git a/doc/ru/8.1.Модуль-Lua-core_bit_converter.md b/doc/ru/scripting/modules/core_bit_converter.md similarity index 100% rename from doc/ru/8.1.Модуль-Lua-core_bit_converter.md rename to doc/ru/scripting/modules/core_bit_converter.md diff --git a/doc/ru/8.2.Модуль-Lua-core_data_buffer.md b/doc/ru/scripting/modules/core_data_buffer.md similarity index 100% rename from doc/ru/8.2.Модуль-Lua-core_data_buffer.md rename to doc/ru/scripting/modules/core_data_buffer.md diff --git a/doc/ru/Пользовательский-ввод.md b/doc/ru/scripting/user-input.md similarity index 100% rename from doc/ru/Пользовательский-ввод.md rename to doc/ru/scripting/user-input.md diff --git a/doc/ru/5.XML-разметка-интерфейса.md b/doc/ru/xml-ui-layouts.md similarity index 100% rename from doc/ru/5.XML-разметка-интерфейса.md rename to doc/ru/xml-ui-layouts.md From 09610a3bb3d2a47cebf35a8fc0f1b6d4cfdfe6a0 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 18:52:47 +0300 Subject: [PATCH 04/14] update doc/en structure --- doc/en/0.Home.md | 11 ----------- .../{6.Assets-preloading.md => assets-preload.md} | 0 doc/en/{7.Audio.md => audio.md} | 0 doc/en/{9.Block-models.md => block-models.md} | 0 .../{3.Block-properties.md => block-properties.md} | 0 doc/en/{2.Content-packs.md => content-packs.md} | 0 ...mendations.md => engine-use-recommendations.md} | 0 .../{4.Item-properties.md => item-properties.md} | 0 doc/en/main-page.md | 14 ++++++++++++++ doc/en/{8.Scripting.md => scripting.md} | 0 doc/en/{5.XML-UI-building.md => xml-ui-layouts.md} | 0 doc/ru/main-page.md | 4 +++- 12 files changed, 17 insertions(+), 12 deletions(-) delete mode 100644 doc/en/0.Home.md rename doc/en/{6.Assets-preloading.md => assets-preload.md} (100%) rename doc/en/{7.Audio.md => audio.md} (100%) rename doc/en/{9.Block-models.md => block-models.md} (100%) rename doc/en/{3.Block-properties.md => block-properties.md} (100%) rename doc/en/{2.Content-packs.md => content-packs.md} (100%) rename doc/en/{1.Engine-usage-recommendations.md => engine-use-recommendations.md} (100%) rename doc/en/{4.Item-properties.md => item-properties.md} (100%) create mode 100644 doc/en/main-page.md rename doc/en/{8.Scripting.md => scripting.md} (100%) rename doc/en/{5.XML-UI-building.md => xml-ui-layouts.md} (100%) diff --git a/doc/en/0.Home.md b/doc/en/0.Home.md deleted file mode 100644 index 70302da8..00000000 --- a/doc/en/0.Home.md +++ /dev/null @@ -1,11 +0,0 @@ -# Sections - -- [Engine usage recommendations](1.Engine-usage-recommendations.md) -- [Content-packs](2.Content-packs.md) -- [Block properties](3.Block-properties.md) -- [Item properties](4.Item-properties.md) -- [XML UI building](5.XML-UI-building.md) -- [Assets preloading](6.Assets-preloading.md) -- [Audio](7.Audio.md) -- [Scripting](8.Scripting.md) -- [Block modoels](9.Block-models.md) diff --git a/doc/en/6.Assets-preloading.md b/doc/en/assets-preload.md similarity index 100% rename from doc/en/6.Assets-preloading.md rename to doc/en/assets-preload.md diff --git a/doc/en/7.Audio.md b/doc/en/audio.md similarity index 100% rename from doc/en/7.Audio.md rename to doc/en/audio.md diff --git a/doc/en/9.Block-models.md b/doc/en/block-models.md similarity index 100% rename from doc/en/9.Block-models.md rename to doc/en/block-models.md diff --git a/doc/en/3.Block-properties.md b/doc/en/block-properties.md similarity index 100% rename from doc/en/3.Block-properties.md rename to doc/en/block-properties.md diff --git a/doc/en/2.Content-packs.md b/doc/en/content-packs.md similarity index 100% rename from doc/en/2.Content-packs.md rename to doc/en/content-packs.md diff --git a/doc/en/1.Engine-usage-recommendations.md b/doc/en/engine-use-recommendations.md similarity index 100% rename from doc/en/1.Engine-usage-recommendations.md rename to doc/en/engine-use-recommendations.md diff --git a/doc/en/4.Item-properties.md b/doc/en/item-properties.md similarity index 100% rename from doc/en/4.Item-properties.md rename to doc/en/item-properties.md diff --git a/doc/en/main-page.md b/doc/en/main-page.md new file mode 100644 index 00000000..919f6a9b --- /dev/null +++ b/doc/en/main-page.md @@ -0,0 +1,14 @@ +# Documentation + +## Sections + +- [Engine usage recommendations](engine-use-recommendations.md) +- [Content-packs](content-packs.md) +- [Block properties](block-properties.md) +- [Item properties](item-properties.md) +- [XML UI building](xml-ui-layouts.md) +- [Assets preloading](assets-preload.md) +- [Audio](audio.md) +- [Scripting](scripting.md) +- [Console](console.md) +- [Block models](block-models.md) diff --git a/doc/en/8.Scripting.md b/doc/en/scripting.md similarity index 100% rename from doc/en/8.Scripting.md rename to doc/en/scripting.md diff --git a/doc/en/5.XML-UI-building.md b/doc/en/xml-ui-layouts.md similarity index 100% rename from doc/en/5.XML-UI-building.md rename to doc/en/xml-ui-layouts.md diff --git a/doc/ru/main-page.md b/doc/ru/main-page.md index b51ee499..e33b25ae 100644 --- a/doc/ru/main-page.md +++ b/doc/ru/main-page.md @@ -1,4 +1,6 @@ -# Разделы +# Документация + +## Разделы - [Рекомендации по использованию движка](engine-use-recommendations.md) - [Контент‐паки](content-packs.md) From a77480276dd7ff596b7c2bf85a0160f9947db0ab Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 18:58:46 +0300 Subject: [PATCH 05/14] update doc/en/block-properties.md --- doc/en/block-properties.md | 6 +++++ doc/ru/block-properties.md | 52 ++++++++++++++++++++------------------ 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/doc/en/block-properties.md b/doc/en/block-properties.md index 6f3cee7e..2c9dffac 100644 --- a/doc/en/block-properties.md +++ b/doc/en/block-properties.md @@ -1,4 +1,5 @@ # Block properties + ## Visual ### *texture* @@ -128,3 +129,8 @@ Examples for block `containermod:container`: Number of block inventory slots. Default - 0 (no inventory). +## Extended blocks + +### *size* + +Array of three integers. Default value is `[1, 1, 1]`. diff --git a/doc/ru/block-properties.md b/doc/ru/block-properties.md index 982bacc4..55b7b4d1 100644 --- a/doc/ru/block-properties.md +++ b/doc/ru/block-properties.md @@ -1,12 +1,14 @@ -# Вид +# Свойства блоков -## Текстура - `texture` +## Вид + +### Текстура - `texture` Название текстуры блока (указывается только имя, без расширения или пути к файлу) Файл текстуры должен находиться в `res/textures/blocks/` и иметь формат **png** -## Текстурирование сторон - `texture-faces` +### Текстурирование сторон - `texture-faces` >[!IMPORTANT] > Не может использоваться одновременно с `texture` @@ -25,7 +27,7 @@ ] ``` -## Модель - `model` +### Модель - `model` Модель блока из списка: - "block" - используется по-умолчанию для всех обычных блоков @@ -33,12 +35,12 @@ - "X" - модель травы (крест из двух спрайтов) - "aabb" - модель, соответствующая хитбоксу блока (составной хитбокс будет объединен в один). Примеры: трубы, лампочки, панели. -## Группа отрисовки - `draw-group` +### Группа отрисовки - `draw-group` Целое число определяющее номер группы отрисовки данного блока. Актуально для полупрозрачных блоков - решает проблемы невидимых сторон блоков за этим блоком. -## Вращение - `rotation` +### Вращение - `rotation` Профиль вращения (набор положений, в которые можно установить блок) из списка: @@ -46,9 +48,9 @@ - "pipe" - профиль "труба". Примеры блоков: бревно, труба, лампочка - "pane" - профиль "панель". Примеры блоков: панель, дверь, табличка -# Освещение +## Освещение -## Излучение - `emission` +### Излучение - `emission` Массив из трех целых чисел - R, G, B освещения от 0 до 15. @@ -59,21 +61,21 @@ - `[0, 0, 0]` - блок не излучает свет (по-умолчанию) -## Светопроводимость - `light-passing` +### Светопроводимость - `light-passing` При значении `true` блок проводит свет от излучающих блоков. -## Солнечная светопроводимость - `sky-light-passing` +### Солнечная светопроводимость - `sky-light-passing` При значении `true` блок не препятствует прохождению вертикального луча солнечного света. -# Физика +## Физика -## Препятствие - `obstacle`: +### Препятствие - `obstacle`: Значение false отключает хитбокс у блока (позволяет игроку проходить сквозь блок) -## Хитбокс - `hitbox`: +### Хитбокс - `hitbox`: Массив из 6 чисел описывающих смещение и размер хитбокса блока. @@ -87,50 +89,50 @@ - смещен на 0.0 м вверх - смещен на 0.5 м на север -## Приземленность - `grounded` +### Приземленность - `grounded` Блок может быть установлен только на полный блок. Разрушается при разрушении блока под ним. -## Выделяемость - `selectable` +### Выделяемость - `selectable` При значении в `false` курсор будет игнорировать блок, выделяя тот, что находится за ним. -## Заменяемость - `replaceable` +### Заменяемость - `replaceable` При значении в `true` на месте блока можно установить любой другой блок. Пример: вода, трава, цветок. -## Разрушаемость - `breakable` +### Разрушаемость - `breakable` При значении в `false` блок нельзя сломать. -# Инвентарь +## Инвентарь -## Скрытый блок - `hidden` +### Скрытый блок - `hidden` При значении в `true` блок не появляется в инвентаре и для него не генерируется предмет, поэтому c 0.17 требуется указать свойство `picking-item` -## Подбираемый предмет - `picking-item` +### Подбираемый предмет - `picking-item` Предмет, который будет выбран при при нажатии средней кнопкой мыши на блок. Пример: блок `door:door_open` скрыт (hidden) поэтому указывается `picking-item: "door:door.item"` -## Имя скрипта - `script-name` +### Имя скрипта - `script-name` Позволяет указать название скрипта блока. Свойство обеспечивает возможность использования одного скрипта для нескольких блоков. Название указывается без `пак:scripts/` и расширения. -## Имя макета UI - `ui-layout` +### Имя макета UI - `ui-layout` Позволяет указать id XML-макета интерфейса блока. По-умолчанию используется строковый id блока. -## Размер инвентаря - `inventory-size` +### Размер инвентаря - `inventory-size` Число слотов инвентаря блока. По-умолчанию - 0 (инвентарь отсутствует) -# Расширенные блоки +## Расширенные блоки -## Размер блока - `size` +### Размер блока - `size` Массив из трех целых чисел. Значение по-умолчанию - `[1, 1, 1]`. From fc64d04333462ee94b5c79700b33f4d29a23462b Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 19:08:46 +0300 Subject: [PATCH 06/14] add doc/en/scripting/events.md --- doc/en/scripting.md | 134 +++---------------------------------- doc/en/scripting/events.md | 126 ++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 125 deletions(-) create mode 100644 doc/en/scripting/events.md diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 5aa1f8cb..b37b7633 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -2,15 +2,20 @@ Project uses LuaJIT as a scripting language. +Subsections: +- [Engine events](scripting/events.md) +- [User input](scripting/user-input.md) +- [Filesystem and serialization](scripting/filesystem.md) +- [Module core:bit_converter](scripting/modules/core_bit_converter.md) +- [Module core:data_buffer](scripting/modules/core_data_buffer.md) +- [Module core:Vector2, core:Vector3](scripting/modules/core_Vector2&&Vector3.md) + + ## Core functions ```lua require "packid:module_name" -- load Lua module from pack-folder/modules/ -- no extension included, just name - --- deprecated functions -load_script("packid:scripts/script_name.lua") -- load Lua script if not loaded yet -load_script("packid:scripts/script_name.lua", true) -- load Lua script anyway ``` ## *pack* library @@ -385,127 +390,6 @@ hud.get_block_inventory() -> int Get open block inventory ID or 0 -## Block events - -```lua -function on_placed(x, y, z, playerid) -``` - -Called on block placed by player - -```lua -function on_broken(x, y, z, playerid) -``` - -Called on block broken by player - -```lua -function on_interact(x, y, z, playerid) -> bool -``` - -Called on block RMB click interaction. Prevents block placing if **true** returned. - -```lua -function on_update(x, y, z) -``` - -Called on block update (near block changed) - -```lua -function on_random_update(x, y, z) -``` - -Called on random block update (grass growth) - -```lua -function on_blocks_tick(tps: int) -``` - -Called tps (20) times per second. - -## Item events - -```lua -function on_use(playerid: int) -``` - -Called on RMB click out of a block. - -```lua -function on_use_on_block(x: int, y: int, z: int, playerid: int) -``` - -Called on block RMB click. Prevents block **placing-block** placing if returns **true** - -```lua -function on_block_break_by(x: int, y: int, z: int, playerid: int) -``` - -Called on block LMB click (unbreakable blocks included). Prevents block destruction if returns **true**. - -## World events - -Script *scripts/world.lua* events. - -```lua -function on_world_open() -``` - -Called on world open. - -```lua -function on_world_save() -``` - -Called before world save. - -```lua -function on_world_tick() -``` - -Called 20 times per second - -```lua -function on_world_quit() -``` - -Called on world close (after saving) - -## Layout events - -Script *layouts/layout_name.xml.lua* events. - -```lua -function on_open(invid: int, x: int, y: int, z: int) -``` - -Called on element added to the screen. -invid=0 if no inventory bound -x,y,z=0 if no block bound - -```lua -function on_close(invid: int) -``` - -Called on element removed from the screen. - -## HUD events - -Script *scripts/hud.lua* events. - - -```lua -function on_hud_open(playerid: int) -``` - -Called after world open. - -```lua -function on_hud_close(playerid: int) -``` - -Called on world close (before saving) - ## Engine libraries ### file diff --git a/doc/en/scripting/events.md b/doc/en/scripting/events.md new file mode 100644 index 00000000..76a69105 --- /dev/null +++ b/doc/en/scripting/events.md @@ -0,0 +1,126 @@ +# Engine events + +## Block events + +Callbacks specified in block script. + +```lua +function on_placed(x, y, z, playerid) +``` + +Called on block placed by player + +```lua +function on_broken(x, y, z, playerid) +``` + +Called on block broken by player + +```lua +function on_interact(x, y, z, playerid) -> bool +``` + +Called on block RMB click interaction. Prevents block placing if **true** returned. + +```lua +function on_update(x, y, z) +``` + +Called on block update (near block changed) + +```lua +function on_random_update(x, y, z) +``` + +Called on random block update (grass growth) + +```lua +function on_blocks_tick(tps: int) +``` + +Called tps (20) times per second. + +## Item events + +Callbacks specified in item script. + +```lua +function on_use(playerid: int) +``` + +Called on RMB click out of a block. + +```lua +function on_use_on_block(x: int, y: int, z: int, playerid: int) +``` + +Called on block RMB click. Prevents block **placing-block** placing if returns **true** + +```lua +function on_block_break_by(x: int, y: int, z: int, playerid: int) +``` + +Called on block LMB click (unbreakable blocks included). Prevents block destruction if returns **true**. + +## World events + +Callbacks specified in *world.lua* script. + +```lua +function on_world_open() +``` + +Called on world open. + +```lua +function on_world_save() +``` + +Called before world save. + +```lua +function on_world_tick() +``` + +Called 20 times per second + +```lua +function on_world_quit() +``` + +Called on world close (after saving) + +## Layout events + +Script *layouts/layout_name.xml.lua* events. + +```lua +function on_open(invid: int, x: int, y: int, z: int) +``` + +Called on element added to the screen. +invid=0 if no inventory bound +x,y,z=0 if no block bound + +```lua +function on_close(invid: int) +``` + +Called on element removed from the screen. + +## HUD events + +Callbacks specified in *hud.lua* script. + + +```lua +function on_hud_open(playerid: int) +``` + +Called after world open. + +```lua +function on_hud_close(playerid: int) +``` + +Called on world close (before saving) From 1081c74afb1cabdf904b82cb3f9ac94da5d02569 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 19:22:11 +0300 Subject: [PATCH 07/14] add doc/en/scripting/user-input.md --- doc/en/scripting/user-input.md | 61 ++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 doc/en/scripting/user-input.md diff --git a/doc/en/scripting/user-input.md b/doc/en/scripting/user-input.md new file mode 100644 index 00000000..b2c6dd6a --- /dev/null +++ b/doc/en/scripting/user-input.md @@ -0,0 +1,61 @@ +# User input + +User input is performed with *bindings* defined with `config/bindings.toml`. + +Example: + +```toml +packid.binding.name="inputtype:codename" +``` + +- packid - optional (recommended) +- inputtype - key or mouse +- codename - key or mouse button code (left/right/middle) + +## Key names + +- space, backspace, tab, enter, caps-lock, escape +- left-ctrl, left-shift, left-alt, left-super +- right-ctrl, right-shift, right-alt, right-super +- delete, home, end, insert, page-up, page-down +- left, right, down, up +- a..z +- 0..9 +- f1..f25 + +## *input* library + +```python +input.keycode(keyname: str) -> int +``` + +Returns key code or -1 if unknown + +```python +input.mousecode(mousename: str) -> int +``` + +Returns mouse button code or -1 if unknown + +```python +input.add_callback(bindname: str, callback: function) +``` + +Add binding activation callback. Example: +```lua +input.add_callback("hud.inventory", function () + print("Inventory open key pressed") +end) +``` + +```python +input.get_mouse_pos() -> {int, int} +``` + +Returns cursor screen position. + +```python +input.get_bindings() -> strings array +``` + +Returns all binding names. From 14b0ec08f79247ad2d36f3ced76ecf416e7223a5 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 20:12:49 +0300 Subject: [PATCH 08/14] add doc/en/scripting/filesystem.md --- doc/en/scripting.md | 103 ++------------------------------- doc/en/scripting/filesystem.md | 89 ++++++++++++++++++++++++++++ doc/ru/scripting/filesystem.md | 9 +-- 3 files changed, 99 insertions(+), 102 deletions(-) create mode 100644 doc/en/scripting/filesystem.md diff --git a/doc/en/scripting.md b/doc/en/scripting.md index b37b7633..6cd8f96b 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -390,84 +390,7 @@ hud.get_block_inventory() -> int Get open block inventory ID or 0 -## Engine libraries - -### file - -Filesystem interaction library. - -```python -file.resolve(path: str) -> str -``` - -Function turns *entry_point:path* (example *user:worlds/house1*) to a regular path. (example *C://Users/user/.voxeng/worlds/house1*) - -> [!NOTE] -> The function should be used for debug only. *entry_point:path* notation is required in all **file** functions. - -Resulting path is not canonical and may be relative. - -```python -file.read(path: str) -> str -``` - -Read whole text file. - -```python -file.read_bytes(path: str) -> array of integers -``` - -Read file into bytes array. - -```python -file.write(path: str, text: str) -> nil -``` - -Overwrite text file. - -```python -file.write_bytes(path: str, data: array of integers) -``` - -Overwrite binary file with bytes array. - -```python -file.length(path: str) -> int -``` - -Get file length (bytes) or 0. - -```python -file.exists(path: str) -> bool -``` - -Check if file or directory exist. - -```python -file.isfile(path: str) -> bool -``` - -Check if the path points to a file. - -```python -file.isdir(path: str) -> bool -``` - -Check if the path points to a directory. - -```python -file.mkdir(path: str) -> bool -``` - -Create directory. Returns true if new directory created - -```python -file.mkdirs(path: str) -> bool -``` - -Create directories chain. Returns true if new directory created - -### time +### *time* library ```python time.uptime() -> float @@ -475,24 +398,8 @@ time.uptime() -> float Returns time elapsed since the engine started. -## Available modules - -### TOML serialization/deserialization - -```lua -local toml = require "core:toml" - -local t = {a=53, b=42, s="test", sub={x=1, y=6}} -local s = toml.serialize(t) -print(s) -local t2 = toml.deserialize(s) -``` -output: -```toml -b = 42 -s = "test" -a = 53 -[sub] -y = 6 -x = 1 +```python +time.delta() -> float ``` + +Returns time elapsed since the last frame. diff --git a/doc/en/scripting/filesystem.md b/doc/en/scripting/filesystem.md new file mode 100644 index 00000000..79e2e7f1 --- /dev/null +++ b/doc/en/scripting/filesystem.md @@ -0,0 +1,89 @@ +# Filesystem and serialization + +### *file* library + +Filesystem interaction library. + +```python +file.resolve(path: str) -> str +``` + +Function turns `entry_point:path` (example `user:worlds/house1`) to a regular path. (example `C://Users/user/.voxeng/worlds/house1`) + +> [!NOTE] +> The function should be used for debug only. *entry_point:path* notation is required in all **file** functions. + +Resulting path is not canonical and may be relative. + +```python +file.read(path: str) -> str +``` + +Read whole text file. + +```python +file.read_bytes(path: str) -> array of integers +``` + +Read file into bytes array. + +```python +file.write(path: str, text: str) -> nil +``` + +Overwrite text file. + +```python +file.write_bytes(path: str, data: array of integers) +``` + +Overwrite binary file with bytes array. + +```python +file.length(path: str) -> int +``` + +Get file length (bytes) or 0. + +```python +file.exists(path: str) -> bool +``` + +Check if file or directory exist. + +```python +file.isfile(path: str) -> bool +``` + +Check if the path points to a file. + +```python +file.isdir(path: str) -> bool +``` + +Check if the path points to a directory. + +```python +file.mkdir(path: str) -> bool +``` + +Create directory. Returns true if new directory created + +```python +file.mkdirs(path: str) -> bool +``` + +Create directories chain. Returns true if new directory created. + +## Storing data in a world + +When saving pack data in the world, you should use the function: + +```python +pack.data_file(packid: str, filename: str) -> str +``` + +Returns data file path like: `world:data/packid/filename` +and creates missing directories. + +If paths other than `data/{packid}/...` are used, data may be lost. diff --git a/doc/ru/scripting/filesystem.md b/doc/ru/scripting/filesystem.md index ed350048..20cd3570 100644 --- a/doc/ru/scripting/filesystem.md +++ b/doc/ru/scripting/filesystem.md @@ -1,10 +1,12 @@ +# Файловая система и сериализация + ## Библиотека *file* Библиотека функций для работы с файлами ```python file.resolve(путь: str) -> str -``` +``` Функция приводит запись `точка_входа:путь` (например `user:worlds/house1`) к обычному пути. (например `C://Users/user/.voxeng/worlds/house1`) @@ -127,11 +129,10 @@ toml.parse(code: str) -> table При сохранении данных пака в мире следует использовать функцию ```python -pack.data_file(packid: str, filename: str) -> str +pack.data_file(id_пака: str, имя_файла: str) -> str ``` -Функция возвращает путь к файлу данных по типу: `world:data/packid/filename` - +Функция возвращает путь к файлу данных по типу: `world:data/id_пака/имя_файла` и создает недостающие директории в пути. При использовании путей не соответствующим `data/{packid}/...` возможна потеря данных при перезаписи мира. From f7310cd5f23698df6a55df120a679010f40fa66b Mon Sep 17 00:00:00 2001 From: Rost Alexeev <148265518+R0STUS@users.noreply.github.com> Date: Thu, 13 Jun 2024 19:25:31 +0200 Subject: [PATCH 09/14] Update screen.glslf --- res/shaders/screen.glslf | 4 ---- 1 file changed, 4 deletions(-) diff --git a/res/shaders/screen.glslf b/res/shaders/screen.glslf index b06dbe9c..d654c5ec 100644 --- a/res/shaders/screen.glslf +++ b/res/shaders/screen.glslf @@ -4,10 +4,6 @@ out vec4 f_color; uniform sampler2D u_texture0; uniform ivec2 u_screenSize; -float random(vec2 st){ - return fract(sin(dot(st.xy ,vec2(12.9898,78.233))) * 43758.5453); -} - // Vignette vec4 apply_vignette(vec4 color) { From 561f6f0ea74ba628d828a5a2c09312a4f4d5ba6e Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 20:27:55 +0300 Subject: [PATCH 10/14] add doc/en/console.md --- doc/en/console.md | 109 ++++++++++++++++++++++++++++++++++++++++++++++ doc/ru/console.md | 4 +- 2 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 doc/en/console.md diff --git a/doc/en/console.md b/doc/en/console.md new file mode 100644 index 00000000..04d3d48d --- /dev/null +++ b/doc/en/console.md @@ -0,0 +1,109 @@ +# Console + +To work with the command interpreter, use the **console** library. + +## Commands creation + +To create a console command, use the following function: + +```python +console.add_command(scheme: str, executor: function) +``` + +Scheme has the following syntax: + +``` +name positional arguments {keyword arguments} +``` + +Name may contain: +- latin letters +- digits (except the first character) +- `.`, `_`, `-` + +Positional arguments are separated by spaces and have the following syntax: + +``` +name:type (option 1) +name:type=default (option 2) +name:type~origin (option 3) +name:type=default~origin (option 4) +``` + +Available types: +- **int** - integer +- **num** - floating-point number +- **str** - string +- **sel** - selector (object id represented by an integer) +- **enum** - enumeration + +Options 3 and 4 show the `~` operator that allows you to use relative values. *Origin* - the value relative to which the user will be specified. For example, the player's position. + +The relative operator only works with numbers (num or int) + +Variables assigned via **console.set** can be specified as origin values. + +Example: + +```python +x:num~pos.x +``` + +Variables may be specified as default values ​​using the `$` prefix: + +```python +t:int=$time +``` + +Enumerations are declared the following way: + +```python +mode:[replace|destruct|none] +``` + +Or with a variable: + +```python +mode:enum $modes +``` + +Selectors are specified with the `@` prefix. At the moment they are unused due to the lack of an object model. Should be made optional and use variables: + +```python +obj:sel=$obj.id # obj.id - player id +``` + +Keyword arguments are specified in a special block, delimited by curly braces `{ }`, following the same pattern as positional arguments. + +Example: + +```python +eval name:str="World" {greeting:str='Hello'} +``` + +## Command scheme examples + +Schemes of standard commands can be found in the file `res/script/stdcmd.lua`. + +Example - command **tp**: + +```python +tp obj:sel=$obj.id x:num~pos.x y:num~pos.y z:num~pos.z +``` + +Full lua code of the command creation: + +```lua +console.add_command( + "tp obj:sel=$obj.id x:num~pos.x y:num~pos.y z:num~pos.z", + "Teleport object", + function (args, kwargs) + player.set_pos(unpack(args)) + end +) +``` + +- Checked values ​​of positional arguments are passed to **args**. +- A table of keyword argument values ​​is passed to **kwargs**. + +The command interpreter performs type checking and casting automatically. diff --git a/doc/ru/console.md b/doc/ru/console.md index a279be61..a142f84f 100644 --- a/doc/ru/console.md +++ b/doc/ru/console.md @@ -1,6 +1,6 @@ # Консоль -Для работы с командным интерпретатором предоставляется библиотека **console** +Для работы с командным интерпретатором предоставляется библиотека **console**. ## Создание команд @@ -83,7 +83,7 @@ eval name:str="World" {greeting:str='Hello'} ## Примеры схем команд -Схемы существующих команд можно найти в файле `res/script/stdcmd.lua`. +Схемы стандартных команд можно найти в файле `res/script/stdcmd.lua`. Пример - команда **tp**: From 899767c430fa172bf281e8991a74b0f4d6dbcc85 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 20:45:20 +0300 Subject: [PATCH 11/14] update doc/en/scripting.md --- doc/en/scripting.md | 142 +++++++++++++++++++++++++++++++++++++++++--- doc/ru/scripting.md | 33 +++++----- 2 files changed, 151 insertions(+), 24 deletions(-) diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 6cd8f96b..9da149c6 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -44,10 +44,10 @@ For pack *containermod* will write text to the file `world:data/containermod/exa ## *player* library - ```python player.get_pos(playerid: int) -> number, number, number ``` + Returns x, y, z coordinates of the player ```python @@ -88,8 +88,25 @@ player.set_noclip(bool) Getter and setter for player noclip mode (collisions disabled) +```python +player.get_selected_block(playerid: int) -> x,y,z +``` + +Returns position of the selected block or nil + ## *world* library +## Библиотека *world* + +```python +world.get_list() -> tables array { + name: str, + icon: str +} +``` + +Retuns worlds information: name and preview/icon (loading automatically). + ```python world.get_day_time() -> number ``` @@ -114,29 +131,67 @@ world.get_seed() -> int Returns world seed. +```python +world.exists() -> bool +``` + +Checks the existence of a world by name. + ## *pack* library ```python pack.get_folder(packid: str) -> str ``` -Returns installed content-pack folder +Returns installed content-pack folder. ```python pack.is_installed(packid: str) -> bool ``` -Check if the world has specified pack installed +Check if the world has specified pack installed. ```python -pack.get_installed() -> array of strings +pack.get_installed() -> strings array ``` -Returns all installed content-pack ids +Returns all installed content-pack ids. + +```python +pack.get_available() -> strings array +``` + +Returns the ids of all content packs available but not installed in the world. + +```python +pack.get_base_packs() -> strings array +``` + +Returns the id of all base packages (non-removeable) + +```python +pack.get_info(packid: str) -> { + id: str, + title: str, + creator: str, + description: str, + version: str, + icon: str, + dependencies: optional strings array +} +``` + +Returns information about the pack (not necessarily installed). +- icon - name of the preview texture (loading automatically) +- dependencies - strings following format `{lvl}{id}`, where lvl: + - `!` - required + - `?` - optional + - `~` - weak + for example `!teal` ## *gui* library -Library contains ui elements access functions. Library should not be directly used, because script *layouts/layout_name.xml.lua* already has a generated variable **document** (instance of **Document**) +The library contains functions for accessing the properties of UI elements. Instead of gui, you should use an object wrapper that provides access to properties through the __index, __newindex meta methods: Example: @@ -145,7 +200,35 @@ print(document.some_button.text) -- where 'some_button' is an element id document.some_button.text = "new text" ``` -## **inventory** library +```python +gui.str(text: str, context: str) -> str +``` + +Returns translated text. + +```python +gui.get_viewport() -> {int, int} +``` + +Returns size of the main container (window). + +```python +gui.get_env(document: str) -> table +``` + +Returns environment (global variables table) of the specified document. + +```python +get_locales_info() -> table of tables where + key - locale id following isolangcode_ISOCOUNTRYCODE format + value - table { + name: str # name of the locale in its language + } +``` + +Returns information about all loaded locales (res/texts/\*). + +## *inventory* library Library for inventories interaction. @@ -213,13 +296,25 @@ If slotB will be chosen automaticly if argument is not specified. block.name(blockid: int) -> str ``` -Returns block string ID (name) by index +Returns block string ID (name) by index. ```python block.index(name: str) -> int ``` -Returns block integer ID (index) by name +Returns block integer ID (index) by name. + +```python +block.material(blockid: int) -> str +``` + +Returns the id of the block material. + +```python +block.caption(blockid: int) -> str +``` + +Returns the block name displayed in the interface. ```python block.get(x: int, y: int, z: int) -> int @@ -296,6 +391,35 @@ block.set_rotation(x: int, y: int, z: int, rotation: int) Set block rotation by index. +### Extended blocks + +Extended blocks are blocks with size greather than 1x1x1 + +```python +block.is_extended(id: int) -> bool +``` + +Checks whether the block is extended. + +```python +block.get_size(id: int) -> int, int, int +``` + +Returns the block size. + +```python +block.is_segment(x: int, y: int, z: int) -> bool +``` + +Checks whether the block is a non-origin segment of an extended block. + +```python +block.seek_origin(x: int, y: int, z: int) -> int, int, int +``` + +Returns the position of the main segment of an extended block or the original position, +if the block is not extended. + ### User bits Part of a voxel data used for scripting. Size: 8 bit. diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index 05f0f407..55f912d7 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -15,7 +15,7 @@ require "контентпак:имя_модуля" -- загружает lua модуль из папки modules (расширение не указывается) ``` -## Библиотека pack +## Библиотека *pack* ```python pack.is_installed(packid: str) -> bool @@ -38,10 +38,12 @@ file.write(pack.data_file(PACK_ID, "example.txt"), text) ``` Для пака *containermod* запишет текст в файл `world:data/containermod/example.txt` -## Библиотека player +## Библиотека *player* + ```python player.get_pos(playerid: int) -> number, number, number ``` + Возвращает x, y, z координаты игрока ```python @@ -88,7 +90,7 @@ player.get_selected_block(playerid: int) -> x,y,z Возвращает координаты выделенного блока, либо nil -## Библиотека world +## Библиотека *world* ```python world.get_list() -> массив таблиц { @@ -129,13 +131,13 @@ world.exists() -> bool Проверяет существование мира по имени. -## Библиотека pack +## Библиотека *pack* ```python pack.get_folder(packid: str) -> str ``` -Возвращает путь к папке установленного контент-пака +Возвращает путь к папке установленного контент-пака. ```python pack.is_installed(packid: str) -> bool @@ -147,13 +149,13 @@ pack.is_installed(packid: str) -> bool pack.get_installed() -> массив строк ``` -Возращает id всех установленных в мире контент-паков +Возращает id всех установленных в мире контент-паков. ```python pack.get_available() -> массив строк ``` -Возвращает id всех доступных, но не установленных в мире контент-паков +Возвращает id всех доступных, но не установленных в мире контент-паков. ```python pack.get_base_packs() -> массив строк @@ -181,13 +183,13 @@ pack.get_info(packid: str) -> { - `~` - weak например `!teal` -## Библиотека gui +## Библиотека *gui* Библиотека содержит функции для доступа к свойствам UI элементов. Вместо gui следует использовать объектную обертку, предоставляющую доступ к свойствам через мета-методы __index, __newindex: + ```lua -local inventory_doc = Document.new("id-макета") -print(inventory_doc.some_button.text) -indentory_doc.some_button.text = "new text" +print(document.some_button.text) -- где 'some_button' - id элемета +document.some_button.text = "новый текст" ``` В скрипте макета `layouts/файл_макета.xml` - `layouts/файл_макета.xml.lua` уже доступна переменная **document** содержащая объект класса Document @@ -219,7 +221,8 @@ get_locales_info() -> таблица таблиц где ``` Возвращает информацию о всех загруженных локалях (res/texts/\*). -## Библиотека inventory + +## Библиотека *inventory* Библиотека функций для работы с инвентарем. @@ -282,19 +285,19 @@ inventory.move(invA: int, slotA: int, invB: int, slotB: int) invA и invB могут указывать на один инвентарь. slotB будет выбран автоматически, если не указывать явно. -## Библиотека block +## Библиотека *block* ```python block.name(blockid: int) -> str ``` -Возвращает строковый id блока по его числовому id +Возвращает строковый id блока по его числовому id. ```python block.index(name: str) -> int ``` -Возвращает числовой id блока, принимая в качестве агрумента строковый +Возвращает числовой id блока, принимая в качестве агрумента строковый. ```python block.material(blockid: int) -> str From 92cc208b0ac37a08563881cf514353c0669d8f97 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 20:48:00 +0300 Subject: [PATCH 12/14] update doc/en/scripting.md --- doc/en/scripting.md | 21 +++++++++++++++++++-- doc/ru/scripting.md | 10 +++++----- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 9da149c6..2c8ddc1a 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -437,7 +437,6 @@ Set specified bits. ## *item* library - ```python item.name(itemid: int) -> str ``` @@ -512,7 +511,25 @@ Remove an element from the screen hud.get_block_inventory() -> int ``` -Get open block inventory ID or 0 +Get open block inventory ID or 0. + +```python +hud.get_player() -> int +``` + +Gives the ID of the player that the UI is bound to. + +```python +hud.pause() +``` + +Opens the pause menu + +```python +hud.resume() +``` + +Closes the pause menu. ### *time* library diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index 55f912d7..e78a95ec 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -496,25 +496,25 @@ hud.open_permanent(layoutid: str) hud.close(layoutid: str) ``` -Удаляет элемент с экрана +Удаляет элемент с экрана. ```python hud.get_block_inventory() -> int ``` -Дает ID инвентаря открытого блока или 0 +Дает ID инвентаря открытого блока или 0. ```python hud.get_player() -> int ``` -Дает ID игрока, к которому привязан пользовательский интерфейс +Дает ID игрока, к которому привязан пользовательский интерфейс. ```python hud.pause() ``` -Открывает меню паузы +Открывает меню паузы. ```python hud.resume() @@ -528,7 +528,7 @@ hud.resume() time.uptime() -> float ``` -Возвращает время с момента запуска движка в секундах +Возвращает время с момента запуска движка в секундах. ```python time.delta() -> float From d057f6843225228b909d4121eea4cff09e7b4cde Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 21:08:06 +0300 Subject: [PATCH 13/14] add doc/en/scripting/modules/* --- doc/en/scripting.md | 2 +- .../scripting/modules/core_bit_converter.md | 93 +++++++++ doc/en/scripting/modules/core_data_buffer.md | 155 ++++++++++++++ .../scripting/modules/core_vector2_vector3.md | 191 ++++++++++++++++++ doc/ru/scripting.md | 2 +- .../scripting/modules/core_bit_converter.md | 22 +- doc/ru/scripting/modules/core_data_buffer.md | 24 ++- ...r2&&Vector3.md => core_vector2_vector3.md} | 8 +- 8 files changed, 471 insertions(+), 26 deletions(-) create mode 100644 doc/en/scripting/modules/core_bit_converter.md create mode 100644 doc/en/scripting/modules/core_data_buffer.md create mode 100644 doc/en/scripting/modules/core_vector2_vector3.md rename doc/ru/scripting/modules/{core_Vector2&&Vector3.md => core_vector2_vector3.md} (97%) diff --git a/doc/en/scripting.md b/doc/en/scripting.md index 2c8ddc1a..f9467336 100644 --- a/doc/en/scripting.md +++ b/doc/en/scripting.md @@ -8,7 +8,7 @@ Subsections: - [Filesystem and serialization](scripting/filesystem.md) - [Module core:bit_converter](scripting/modules/core_bit_converter.md) - [Module core:data_buffer](scripting/modules/core_data_buffer.md) -- [Module core:Vector2, core:Vector3](scripting/modules/core_Vector2&&Vector3.md) +- [Module core:vector2, core:vector3](scripting/modules/core_vector2_vector3.md) ## Core functions diff --git a/doc/en/scripting/modules/core_bit_converter.md b/doc/en/scripting/modules/core_bit_converter.md new file mode 100644 index 00000000..822c1394 --- /dev/null +++ b/doc/en/scripting/modules/core_bit_converter.md @@ -0,0 +1,93 @@ +# Module core:bit_converter + +## Converting values ​​to bytes and back + +```lua +function bit_converter.string_to_bytes(string: str) -> table +``` +Converts a string to bytes + +```lua +function bit_converter.bool_to_byte(boolean: bool) -> integer +``` +Converts a boolean to a byte + +```lua +function bit_converter.single_to_bytes(number: single) -> table +``` +Converts a single precision float value to bytes + +```lua +function bit_converter.double_to_bytes(number: double) -> table +``` +Converts a double precision float value to bytes + +```lua +function bit_converter.uint16_to_bytes(integer: int) -> table +``` +Converts an unsigned 2-bytes integer to bytes + +```lua +function bit_converter.uint32_to_bytes(integer: int) -> table +``` +Converts an unsigned 4-bytes integer to bytes + +```lua +function bit_converter.int16_to_bytes(integer: int) -> table +``` +Converts a signed 2-bytes integer to bytes + +```lua +function bit_converter.int32_to_bytes(integer: int) -> table +``` +Converts a signed 4-bytes integer to bytes + +```lua +function bit_converter.int64_to_bytes(integer: int) -> table +``` +Converts a signed 8-bytes integer to bytes + +```lua +function bit_converter.bytes_to_string(table: bytes) -> string +``` +Converts a byte array to a string + +```lua +function bit_converter.byte_to_bool(integer: byte) -> boolean +``` +Converts a byte to a boolean value + +```lua +function bit_converter.bytes_to_single(table: bytes) -> number№ +``` +Converts a byte array to a single-precision float + +```lua +function bit_converter.bytes_to_double(table: bytes) -> number +``` +Converts a byte array to a double precision float + +```lua +function bit_converter.bytes_to_uint16(table: bytes) -> integer +``` +Converts a byte array to a 2-bytes unsigned number + +```lua +function bit_converter.bytes_to_uint32(table: bytes) -> integer +``` +Converts a byte array to a 4-bytes unsigned number + +```lua +function bit_converter.bytes_to_int16(table: bytes) -> integer +``` +Converts a byte array to a 2-bytes signed number + +```lua +function bit_converter.bytes_to_int32(table: bytes) -> integer +``` +Converts a byte array to a 4-bytes signed number + +```lua +function bit_converter.bytes_to_int64(table: bytes) -> integer +``` +Converts a byte array to an 8-bytes signed number diff --git a/doc/en/scripting/modules/core_data_buffer.md b/doc/en/scripting/modules/core_data_buffer.md new file mode 100644 index 00000000..fe383579 --- /dev/null +++ b/doc/en/scripting/modules/core_data_buffer.md @@ -0,0 +1,155 @@ +# Module core:data_buffer + +## Data buffer +### Stores an array of bytes and allows you to easily get or add different values + +```lua +function data_buffer(bytes) +``` +Creates a new data_buffer instance (the bytes parameter is optional) + +```lua +function data_buffer:put_byte(integer: byte) +``` +Writes a byte to the buffer + +```lua +function data_buffer:put_bytes(table: bytes) +``` +Writes bytes to the buffer + +```lua +function data_buffer:put_string(string: str) +``` +Converts a string to bytes and writes them to the buffer + +```lua +function data_buffer:put_bool(boolean: bool) +``` +Converts a boolean value to a byte and writes it to the buffer + +```lua +function data_buffer:put_single(number: single) +``` +Converts a single precision float to bytes and writes them to the buffer + +```lua +function data_buffer:put_double(number: double) +``` +Converts a double precision float to bytes and writes them to the buffer + +```lua +function data_buffer:put_uint16(integer: int) +``` +Converts an unsigned 2-bytes number to bytes and writes them to the buffer + +```lua +function data_buffer:put_uint32(integer: int) +``` +Converts an unsigned 4-bytes number to bytes and writes them to the buffer + +```lua +function data_buffer:put_int16(integer: int) +``` +Converts a signed 2-bytes number into bytes and writes them to the buffer + +```lua +function data_buffer:put_int32(integer: int) +``` +Converts a signed 4-bytes number into bytes and writes them to the buffer + +```lua +function data_buffer:put_int64(integer: int) +``` +Converts a signed 8-bytes number to bytes and writes them to the buffer + +```lua +function data_buffer:put_number(number: num) +``` +Converts any number into bytes and writes them to the buffer; + +The first byte is the value type: +```lua +zero = 0 +uint16 = 1 +uint32 = 2 +int16 = 3 +int32 = 4 +int64 = 5 +double = 6 +``` + +```lua +function data_buffer:get_byte() -> integer +``` +Returns the next byte from the buffer + +```lua +function data_buffer:get_bytes(n) -> table +``` +Returns the next n bytes, if n is nil or not specified, then an array of all bytes is returned + +```lua +function data_buffer:get_string() -> string +``` +Reads the next line from the buffer + +```lua +function data_buffer:get_bool() -> boolean +``` +Reads the next Boolean from the buffer + +```lua +function data_buffer:get_single() -> number +``` +Reads the next single precision floating number from the buffer + +```lua +function data_buffer:get_double() -> number +``` +Reads the next double precision floating number from the buffer + +```lua +function data_buffer:get_uint16() -> integer +``` +Reads the next 2-bytes unsigned integer from the buffer + +```lua +function data_buffer:get_uint32() -> integer +``` +Reads the next 4-bytes unsigned integer from the buffer + +```lua +function data_buffer:get_int16() -> integer +``` +Reads the next 2-bytes signed integer from the buffer + +```lua +function data_buffer:get_int32() -> integer +``` +Reads the next 4-bytes signed integer from the buffer + +```lua +function data_buffer:get_int64() -> integer +``` +Reads the next 8-bytes signed integer from the buffer + +```lua +function data_buffer:get_number() -> number +``` +Reads the next number (see data_buffer:put_number) + +```lua +function data_buffer:size() -> integer +``` +Returns the buffer size + +```lua +function data_buffer:set_position(integer: pos) +``` +Sets the current position in the buffer + +```lua +function data_buffer:set_bytes(table: bytes) +``` +Sets bytes into the buffer diff --git a/doc/en/scripting/modules/core_vector2_vector3.md b/doc/en/scripting/modules/core_vector2_vector3.md new file mode 100644 index 00000000..4c545739 --- /dev/null +++ b/doc/en/scripting/modules/core_vector2_vector3.md @@ -0,0 +1,191 @@ +# Modules core:vector2, core:vector3 + +## Vector2 +### Operations on vectors + + +```lua +function vector2:round(decimals: number) -> round[vec2] +``` +Rounding vector components + +```lua +function vector2:len() -> number +``` +Vector length + +```lua +function vector2:norm() -> number +``` +Vector normalization + +```lua +function vector2:abtw(vector: vec2) -> number +``` +Angle between two vectors in radians + +```lua +function vector2:proj(vector: vec2) -> vec2 +``` +Vector projection + +```lua +function vector2:dot(vector: vec2) -> number +``` +Vector (internal) product + +```lua +function vector2:lerp( + --Target vector + b:vec2, + --Interpolation coefficient (0 to 1) + t:number + ) -> vec2 +``` +Linear vector interpolation + +```lua +function vector2:dist(vector: vec2) -> number +``` +Distance between two vectors + +```lua +function vector2:cross(vector: vec2) -> number +``` +Vector (external) product + +```lua +function vector2:rot( + --The angle of rotation of the vector at a given angle (in radians) + angle: number->rad, + --Rotation of the vector relative to the axes ("x", "y", "z") + axis: str, + --If true, then the rotation angle is converted automatically from degrees to radians + convert2deg:bool + ) -> vec2 +``` +Rotate a vector + +### Operations with vectors + +```lua + local vec2 = require("core:vector2") + + local v1 = vec2(5, 10) + local v2 = vec2(10, 15) + + -- vec2 .. vec2 + sum_vectors = v1 + v2 -- (15, 25) + sub_vectors = v1 - v2 -- (-5, -5) + mul_vectors = v1 * v2 -- (50, 150) + div_vectors = v1 / v2 -- (0.5, 0.66667.) + pow_vectors = v1 ^ v2 -- (9765625, 1e+15) + + --vec2 .. scalar + sum_vec2_scalar = v1 + 10 -- (15, 25) + sub_vec2_scalar = v1 - 12 -- (-7, -2) + mul_vec2_scalar = v1 * 20 -- (100, 200) + div_vec2_scalar = v1 / 1 -- (5, 10) + pow_vec2_scalar= v1 ^ 2 -- (25, 100) +``` + + + +## Vector3 +### Operations on vectors + +```lua +function vector3:round(decimals: number) -> round[vec3] +``` +Rounding vector components +```lua +function vector3:len() -> number +``` +Vector length + +```lua +function vector3:norm() -> number +``` +Vector normalization + +```lua +function vector3:abtw(vector: vec3) -> number +``` +Angle between two vectors in radians + +```lua +function vector3:isParallel(vector: vec3) -> bool +``` +Parallelism of a vector to another vector + + +```lua +function vector3:proj(vector: vec3) -> vec3 +``` +Vector projection +... + +```lua +function vector3:dot(vector: vec3) -> number +``` +Vector (internal) product + +```lua +function vector3:lerp( + --Target vector + b:vec3, + --Interpolation coefficient (0 to 1) + t:number + ) -> vec3 +``` +Linear vector interpolation + +```lua +function vector3:dist(vector: vec3) -> number +``` +Distance between two vectors + +```lua +function vector3:dist2line(point1: vec3, point2: vec3) -> number +``` +Distance to line + +```lua +function vector3:cross(vector: vec3) -> number +``` +Vector (external) product + +```lua +function vector3:rot( + --The angle of rotation of the vector at a given angle (in radians) + angle: number->rad, + --Rotation of the vector relative to the axes ("x", "y", "z") + axis: str, + --If true, then the rotation angle is converted automatically from degrees to radians + convert2deg:bool + ) -> vec2 +``` +Rotate a vector + +### Operations with vectors + +```lua + +local vec3 = require("core:vector3") + +local v1 = vec3(1, 2, 3) +local v2 = vec3(4, 5, 6) + +--vec3..vec3 +local sum_vectors = v1 + v2 -- (5, 7, 9) +local sub_vectors = v1 - v2 -- (-3, -3, -3) +local mul_vectors = v1 * v2 -- (4, 10, 18) +local div_vectors = v1 / v2 -- (0.25, 0.4, 0.5) +local pow_vectors = v1 ^ v2 -- (1, 32, 216) + +--vec3..scalar +local scalar_vector = v1 * 2 -- (2, 4, 6) +local scalar_number = 2 * v1 -- (2, 4, 6) +-- ..etc + +``` diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md index e78a95ec..a6834591 100644 --- a/doc/ru/scripting.md +++ b/doc/ru/scripting.md @@ -8,7 +8,7 @@ - [Файловая система и сериализация](scripting/filesystem.md) - [Модуль core:bit_converter](scripting/modules/core_bit_converter.md) - [Модуль core:data_buffer](scripting/modules/core_data_buffer.md) -- [Модули core:Vector2, core:Vector3](scripting/modules/core_Vector2&&Vector3.md) +- [Модули core:vector2, core:vector3](scripting/modules/core_vector2_vector3.md) ```lua diff --git a/doc/ru/scripting/modules/core_bit_converter.md b/doc/ru/scripting/modules/core_bit_converter.md index cf2126c6..f9930560 100644 --- a/doc/ru/scripting/modules/core_bit_converter.md +++ b/doc/ru/scripting/modules/core_bit_converter.md @@ -1,3 +1,5 @@ +# Модуль core:bit_converter + ## Конвертация значений в байты и обратно ```lua @@ -23,27 +25,27 @@ function bit_converter.double_to_bytes(number: double) -> table ```lua function bit_converter.uint16_to_bytes(integer: int) -> table ``` -Конвертирует беззнаковое 2-х битное целое число в байты +Конвертирует беззнаковое 2-х байтовое целое число в байты ```lua function bit_converter.uint32_to_bytes(integer: int) -> table ``` -Конвертирует беззнаковое 4-х битное целое число в байты +Конвертирует беззнаковое 4-х байтовое целое число в байты ```lua function bit_converter.int16_to_bytes(integer: int) -> table ``` -Конвертирует знаковое 2-х битное целое число в байты +Конвертирует знаковое 2-х байтовое целое число в байты ```lua function bit_converter.int32_to_bytes(integer: int) -> table ``` -Конвертирует знаковое 4-х битное целое число в байты +Конвертирует знаковое 4-х байтовое целое число в байты ```lua function bit_converter.int64_to_bytes(integer: int) -> table ``` -Конвертирует знаковое 8-и битное целое число в байты +Конвертирует знаковое 8-и байтовое целое число в байты ```lua function bit_converter.bytes_to_string(table: bytes) -> string @@ -68,24 +70,24 @@ function bit_converter.bytes_to_double(table: bytes) -> number ```lua function bit_converter.bytes_to_uint16(table: bytes) -> integer ``` -Конвертирует массив байтов в 2-х битное беззнаковое число +Конвертирует массив байтов в 2-х байтовое беззнаковое число ```lua function bit_converter.bytes_to_uint32(table: bytes) -> integer ``` -Конвертирует массив байтов в 4-х битное беззнаковое число +Конвертирует массив байтов в 4-х байтовое беззнаковое число ```lua function bit_converter.bytes_to_int16(table: bytes) -> integer ``` -Конвертирует массив байтов в 2-х битное знаковое число +Конвертирует массив байтов в 2-х байтовое знаковое число ```lua function bit_converter.bytes_to_int32(table: bytes) -> integer ``` -Конвертирует массив байтов в 4-х битное знаковое число +Конвертирует массив байтов в 4-х байтовое знаковое число ```lua function bit_converter.bytes_to_int64(table: bytes) -> integer ``` -Конвертирует массив байтов в 8-х битное знаковое число \ No newline at end of file +Конвертирует массив байтов в 8-х байтовое знаковое число diff --git a/doc/ru/scripting/modules/core_data_buffer.md b/doc/ru/scripting/modules/core_data_buffer.md index 4bbbacf6..60c36193 100644 --- a/doc/ru/scripting/modules/core_data_buffer.md +++ b/doc/ru/scripting/modules/core_data_buffer.md @@ -1,3 +1,5 @@ +# Модуль core:data_buffer + ## Буффер данных ### Хранит в себе массив байтов и позволяет легко получать или добавлять разные значения @@ -39,27 +41,27 @@ function data_buffer:put_double(number: double) ```lua function data_buffer:put_uint16(integer: int) ``` -Конвертирует беззнаковое 2-х битное число в байты и записывает их в буффер +Конвертирует беззнаковое 2-х байтовое число в байты и записывает их в буффер ```lua function data_buffer:put_uint32(integer: int) ``` -Конвертирует беззнаковое 4-х битное число в байты и записывает их в буффер +Конвертирует беззнаковое 4-х байтовое число в байты и записывает их в буффер ```lua function data_buffer:put_int16(integer: int) ``` -Конвертирует знаковое 2-х битное число в байты и записывает их в буффер +Конвертирует знаковое 2-х байтовое число в байты и записывает их в буффер ```lua function data_buffer:put_int32(integer: int) ``` -Конвертирует знаковое 4-х битное число в байты и записывает их в буффер +Конвертирует знаковое 4-х байтовое число в байты и записывает их в буффер ```lua function data_buffer:put_int64(integer: int) ``` -Конвертирует знаковое 8-и битное число в байты и записывает их в буффер +Конвертирует знаковое 8-и байтовое число в байты и записывает их в буффер ```lua function data_buffer:put_number(number: num) @@ -110,27 +112,27 @@ function data_buffer:get_double() -> number ```lua function data_buffer:get_uint16() -> integer ``` -Читает следующее 2-х битное беззнаковое целое число из буффера +Читает следующее 2-х байтовое беззнаковое целое число из буффера ```lua function data_buffer:get_uint32() -> integer ``` -Читает следующее 4-х битное беззнаковое целое число из буффера +Читает следующее 4-х байтовое беззнаковое целое число из буффера ```lua function data_buffer:get_int16() -> integer ``` -Читает следующее 2-х битное знаковое целое число из буффера +Читает следующее 2-х байтовое знаковое целое число из буффера ```lua function data_buffer:get_int32() -> integer ``` -Читает следующее 4-х битное знаковое целое число из буффера +Читает следующее 4-х байтовое знаковое целое число из буффера ```lua function data_buffer:get_int64() -> integer ``` -Читает следующее 8-х битное знаковое целое число из буффера +Читает следующее 8-х байтовое знаковое целое число из буффера ```lua function data_buffer:get_number() -> number @@ -150,4 +152,4 @@ function data_buffer:set_position(integer: pos) ```lua function data_buffer:set_bytes(table: bytes) ``` -Устанавливает байты в буффер \ No newline at end of file +Устанавливает байты в буффер diff --git a/doc/ru/scripting/modules/core_Vector2&&Vector3.md b/doc/ru/scripting/modules/core_vector2_vector3.md similarity index 97% rename from doc/ru/scripting/modules/core_Vector2&&Vector3.md rename to doc/ru/scripting/modules/core_vector2_vector3.md index a1ea4d1c..349e5858 100644 --- a/doc/ru/scripting/modules/core_Vector2&&Vector3.md +++ b/doc/ru/scripting/modules/core_vector2_vector3.md @@ -1,4 +1,5 @@ -# Вектора +# Модули core:vector2, core:vector3 + ## Vector2 ### Операции над векторами @@ -7,6 +8,7 @@ function vector2:round(decimals: number) -> round[vec2] ``` Округление компонентов вектора + ```lua function vector2:len() -> number ``` @@ -68,7 +70,7 @@ function vector2:rot( ### Операции с векторами ```lua - local vec2 = require("res:vector2") + local vec2 = require("core:vector2") local v1 = vec2(5, 10) local v2 = vec2(10, 15) @@ -170,7 +172,7 @@ function vector3:rot( ```lua -local vec3 = require("res:vector3") +local vec3 = require("core:vector3") local v1 = vec3(1, 2, 3) local v2 = vec3(4, 5, 6) From ad5814060d8b209722c9351e8d1079f96cabd1f8 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 13 Jun 2024 23:37:29 +0300 Subject: [PATCH 14/14] update vignette calculation formula --- res/shaders/screen.glslf | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/res/shaders/screen.glslf b/res/shaders/screen.glslf index d654c5ec..00041cbc 100644 --- a/res/shaders/screen.glslf +++ b/res/shaders/screen.glslf @@ -5,21 +5,20 @@ uniform sampler2D u_texture0; uniform ivec2 u_screenSize; // Vignette -vec4 apply_vignette(vec4 color) -{ +vec4 apply_vignette(vec4 color) { vec2 position = (gl_FragCoord.xy / u_screenSize) - vec2(0.5); float dist = length(position); - float radius = 2.0; - float softness = 1.7; + float radius = 1.3; + float softness = 1.0; float vignette = smoothstep(radius, radius - softness, dist); - color.rgb = color.rgb - (1.0 - vignette); + color.rgb = color.rgb * vignette; return color; } -void main(){ +void main() { f_color = texture(u_texture0, v_coord); f_color = apply_vignette(f_color); }