Update 0.27 docs (#484)

* update doc/*/scripting/builtins/libinventory.md

* add doc/*/scripting/builtins/libgfx-weather.md

* update doc/*/scripting/builtins/libfile.md

* update doc/*/item-properties & update doc/*/scripting/builtins/libinventory.md

* add inventory.decrement docs

* update doc/*/scripting/builtins/libinventory.md
This commit is contained in:
MihailRis 2025-03-16 20:10:41 +03:00 committed by GitHub
parent a74a4fcf53
commit b1e854a73c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 358 additions and 2 deletions

View File

@ -45,3 +45,16 @@ Examples:
### *stack-size*
Maximal number of an item units in one slot. Default - 64.
### Number of uses (durability) - `uses`
Property used via [inventory.use](scripting/builtins/libinventory.md).
Property status is displayed in the inventory interface. Display method is defined via `uses-display`.
### Display of uses - `uses-display`
- `none` - display disabled
- `number` - number
- `relation` - current value to initial value (x/y)
- `vbar` - vertical scale (used by default)

View File

@ -20,6 +20,7 @@ Subsections:
- [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md)
- [gfx.particles](particles.md#gfxparticles-library)
- [gfx.text3d](3d-text.md#gfxtext3d-library)
- [gfx.weather](scripting/builtins/libgfx-weather.md)
- [gui](scripting/builtins/libgui.md)
- [hud](scripting/builtins/libhud.md)
- [input](scripting/builtins/libinput.md)

View File

@ -144,3 +144,23 @@ file.prefix(path: str) --> str
```
Extracts the entry point (prefix) from the path. Example: `world:data/base/config.toml` -> `world`.
```lua
file.parent(path: str) --> str
```
Returns the path one level up. Example: `world:data/base/config.toml` -> `world:data/base`
```lua
file.path(path: str) --> str
```
Removes the entry point (prefix) from the path. Example: `world:data/base/config.toml` -> `data/base/config.toml`
```lua
file.join(directory: str, path: str) --> str
```
Joins the path. Example: `file.join("world:data", "base/config.toml)` -> `world:data/base/config.toml`.
You should use this function instead of concatenating with `/`, since `prefix:/path` is not valid.

View File

@ -0,0 +1,53 @@
# *gfx.weather* library
A library for managing audio/visual weather effects.
Weather settings:
| Property | Description | Default |
| ------------ | ------------------------------ | ------- |
| fall | Precipitation (see table 2) | {} |
| clouds | Cloudiness [0.0, 1.0] | 0.0 |
| fog_opacity | Maximum fog density [0.0, 1.0] | 0.0 |
| fog_dencity | Fog density | 1.0 |
| fog_curve | Fog curve | 1.0 |
| thunder_rate | Thunder rate [0.0, 1.0] | 0.0 |
Precipitation:
| Property | Description | Default |
| ------------- | -------------------------------------------- | ------- |
| texture | Precipitation texture | "" |
| noise | Precipitation noise | "" |
| vspeed | Precipitation vertical speed | 1.0 |
| hspeed | Maximum horizontal speed of precipitation | 0.1 |
| scale | Precipitation UV scale | 0.1 |
| min_opacity | Minimum alpha multiplier for precipitation | 0.0 |
| max_opacity | Maximum alpha multiplier for precipitation | 1.0 |
| max_intensity | Maximum precipitation intensity | 1.0 |
| opaque | Disable precipitation translucency | false |
| splash | Precipitation splash particle settings table | {} |
```lua
-- Smoothly switches weather
gfx.weather.change(
-- weather settings table
weather: table,
-- weather change duration in seconds
time: number,
-- weather preset name
[optional] name: str
)
-- Returns weather preset name
gfx.weather.get_current() -> str
-- Returns a copy of the weather settings table
gfx.weather.get_current_data() -> table
-- Returns the current precipitation intensity
gfx.weather.get_fall_intensity() -> number
-- Checks if weather is currently switching
gfx.weather.is_transition() -> bool
```

View File

@ -12,7 +12,7 @@ inventory.get(
) -> int, int
-- Returns item ID and count.
-- Set slot content.
-- Set slot content, deleting the data contained before.
inventory.set(
-- inventory ID
invid: int,
@ -24,6 +24,27 @@ inventory.set(
count: int
)
-- Sets the count of items in the slot without affecting the data if the argument is non-zero.
inventory.set_count(
-- inventory ID
invid: int,
-- slot index
slot: int,
-- item count
count: int
)
-- Checks for the presence of a local property by name without copying its value.
-- Preferably for tables, but not primitive types.
inventory.has_data(
-- inventory ID
invid: int,
-- slot index
slot: int,
-- property name
name: str
) -> bool
-- Returns inventory size (slots number).
-- Throws an exception if there's no inventory having specified ID.
inventory.size(invid: int) -> int
@ -63,6 +84,53 @@ inventory.remove(invid: int)
> [!WARNING]
> Unbound inventories will be deleted on world close.
Local properties of an item are data attached to the last item in the stack.
When splitting the stack (RMB), the data is not copied but moved to a new stack.
Properties can be of any serializable type, including tables.
Unlike block fields, property names do not need to be registered in the item definition.
The combination of
```lua
inventory.get(...)
inventory.get_all_data(...)
inventory.set(...)
inventory.set_all_data(...)
```
for moving is inefficient, use inventory.move or inventory.move_range.
```lua
-- Returns a copy of value of a local property of an item by name or nil.
inventory.get_data(
-- inventory ID
invid: int,
-- slot index
slot: int,
-- property name
name: str
) -> any
-- Sets the value of a local property of an item by name.
-- Nil value removes the property.
inventory.set_data(
-- inventory ID
invid: int,
-- slot index
slot: int,
-- property name
name: str
-- value
value: any
)
-- Returns a copy of the table of all local item properties.
inventory.get_all_data(
-- inventory ID
invid: int,
-- slot index
slot: int,
) -> table
```
```lua
-- Create inventory. Returns the created ID.
inventory.create(size: int) -> int
@ -87,4 +155,26 @@ inventory.move(
rangeBegin: int,
[optional] rangeEnd: int
)
-- Decreases the item count in the slot by 1.
inventory.decrement(
-- inventory id
invid: int,
-- slot index
slot: int,
-- count to subtract
[optional] count: int = 1
)
-- Decreases the remaining uses counter / durability of an item,
-- creating a local `uses` property if none.
-- Removes one item from the slot when the counter reaches zero.
-- Does nothing if the `uses` property is not specified in the item's JSON.
-- See [property `uses`](../../item-properties.md#number-of-uses-durability---uses)
inventory.use(
-- inventory id
invid: int,
-- slot index
slot: int
)
```

View File

@ -44,3 +44,16 @@
### Размер стопки (стека) - `stack-size`
Определяет максимальное количество предмета в одном слоте. Значение по-умолчанию - 64.
### Число использований (прочность) - `uses`
Свойство, используемое через [inventory.use](scripting/builtins/libinventory.md).
Статус свойства отображается в интерфейсе инвентаря. Способ отображения определяется через `uses-display`.
### Отображение использований - `uses-display`
- `none` - отображение отключено
- `number` - число
- `relation` - отношение текущего значения к изначальному (x/y)
- `vbar` - вертикальная шкала (используется по-умолчанию)

View File

@ -20,6 +20,7 @@
- [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md)
- [gfx.particles](particles.md#библиотека-gfxparticles)
- [gfx.text3d](3d-text.md#библиотека-gfxtext3d)
- [gfx.weather](scripting/builtins/libgfx-weather.md)
- [gui](scripting/builtins/libgui.md)
- [hud](scripting/builtins/libhud.md)
- [input](scripting/builtins/libinput.md)

View File

@ -144,3 +144,24 @@ file.prefix(путь: str) --> str
```
Извлекает точку входа (префикс) из пути. Пример: `world:data/base/config.toml` -> `world`.
```lua
file.parent(путь: str) --> str
```
Возвращает путь на уровень выше. Пример: `world:data/base/config.toml` -> `world:data/base`
```lua
file.path(путь: str) --> str
```
Убирает точку входа (префикс) из пути. Пример: `world:data/base/config.toml` -> `data/base/config.toml`
```lua
file.join(директория: str, путь: str) --> str
```
Соединяет путь. Пример: `file.join("world:data", "base/config.toml)` -> `world:data/base/config.toml`.
Следует использовать данную функцию вместо конкатенации с `/`, так как `префикс:/путь` не является валидным.

View File

@ -0,0 +1,53 @@
# Библиотека gfx.weather
Библиотека для управления аудио/визуальными погодными эффектами.
Настройки погоды:
| Свойство | Описание | По-умолчанию |
| ------------ | ---------------------------------------- | ------------ |
| fall | Осадки (см. таблица 2) | {} |
| clouds | Облачность [0.0, 1.0] | 0.0 |
| fog_opacity | Максимальная плотность тумана [0.0, 1.0] | 0.0 |
| fog_dencity | Плотность тумана | 1.0 |
| fog_curve | Кривая тумана | 1.0 |
| thunder_rate | Частота грома [0.0, 1.0] | 0.0 |
Осадки:
| Свойство | Описание | По-умолчанию |
| ------------- | -------------------------------------------- | ------------ |
| texture | Текстура осадков | "" |
| noise | Шум осадков | "" |
| vspeed | Вертикальная скорость осадков | 1.0 |
| hspeed | Максимальная горизонтальная скорость осадков | 0.1 |
| scale | Масштаб UV развертки осадков | 0.1 |
| min_opacity | Минимальный множитель alpha-канала осадков | 0.0 |
| max_opacity | Максимальный множитель alpha-канала осадков | 1.0 |
| max_intensity | Масимальная интенсивность осадков | 1.0 |
| opaque | Отключение полупрозрачности осадков | false |
| splash | Таблица настроек частиц всплесков от осадков | {} |
```lua
-- Плавно переключает погоду
gfx.weather.change(
-- таблица настроек погоды
weather: table,
-- длительность изменения погоды в секундах
time: number,
-- название пресета погоды
[опционально] name: str
)
-- Возвращает имя пресета погоды
gfx.weather.get_current() -> str
-- Возвращает копию таблицы настроек погоды
gfx.weather.get_current_data() -> table
-- Возвращает текущую интенсивность осадков
gfx.weather.get_fall_intensity() -> number
-- Проверяет, происходит ли в данный момент переключение погоды
gfx.weather.is_transition() -> bool
```

View File

@ -11,7 +11,7 @@ inventory.get(
slot: int
) -> int, int
-- Устанавливает содержимое слота.
-- Устанавливает содержимое слота, удаляя содержащиеся данные.
inventory.set(
-- id инвентаря
invid: int,
@ -23,6 +23,16 @@ inventory.set(
count: int
)
-- Устанавливает количество предмета в слоте не затрагивая данные при ненулевом значении аргумента.
inventory.set_count(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
-- количество предмета
count: int
)
-- Возвращает размер инвентаря (число слотов).
-- Если указанного инвентаря не существует, бросает исключение.
inventory.size(invid: int) -> int
@ -70,6 +80,65 @@ inventory.remove(invid: int)
> [!WARNING]
> Инвентари, не привязанные ни к одному из блоков, удаляются при выходе из мира.
Локальные свойства предмета - данные прикреплённые к последнему предмету в стеке.
При разделении стека (ПКМ) данные не копируются а перемемещаются в новый стек.
Свойства могут иметь любой сериализуемый тип, включая таблицы.
В отличие от полей блоков имена свойств не требуется регистрировать в определении предмета.
Сочетание
```lua
inventory.get(...)
inventory.get_all_data(...)
inventory.set(...)
inventory.set_all_data(...)
```
для перемещения вляется неэффективным, используйте inventory.move или inventory.move_range.
```lua
-- Проверяет наличие локального свойства по имени без копирования его значения.
-- Предпочтительно для таблиц, но не примитивных типов.
inventory.has_data(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
-- имя свойства
name: str
) -> bool
-- Возвращает копию значения локального свойства предмета по имени или nil.
inventory.get_data(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
-- имя свойства
name: str
) -> any
-- Устанавливает значение локального свойства предмета по имени.
-- Значение nil удаляет свойство.
inventory.set_data(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
-- имя свойства
name: str
-- значение
value: any
)
-- Возвращает копию таблицы всех локальных свойств предмета.
inventory.get_all_data(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
) -> table
```
```lua
-- Создаёт инвентарь и возвращает id.
inventory.create(size: int) -> int
@ -97,4 +166,26 @@ inventory.move_range(
rangeBegin: int,
[опционально] rangeEnd: int
)
-- Уменьшает количество предмета в слоте на 1.
inventory.decrement(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
-- вычитаемое количество
[опционально] count: int = 1
)
-- Уменьшает счётчик оставшихся использований / прочность предмета,
-- создавая локальное свойство `uses` при отсутствии.
-- Удаляет один предмет из слота при достижении нулевого значения счётчика.
-- При отсутствии в JSON предмета свойства `uses` ничего не делает.
-- См. [свойство `uses`](../../item-properties.md#число-использований-прочность---uses)
inventory.use(
-- id инвентаря
invid: int,
-- индекс слота
slot: int
)
```