Merge pull request #1072 from MihailRis/dev
Some checks are pending
x86-64 AppImage / build-appimage (ubuntu-22.04) (push) Waiting to run
Build / Build (push) Waiting to run
Macos Build / build-dmg (push) Waiting to run
Windows Build (CLang) / build-windows (clang, windows-latest) (push) Waiting to run
MSVC Build / build-windows (windows-2022) (push) Waiting to run

0.33 development
This commit is contained in:
MihailRis 2026-11-04 16:23:46 +03:00 • committed by GitHub
commit 97c790350d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
216 changed files with 6838 additions and 2590 deletions

View file

@ -11,6 +11,11 @@ on:
required: true
type: string
description: 'Build name passed as VC_BUILD_NAME define'
version_patch:
required: false
type: string
default: ''
description: 'Engine version patch number passed as VC_VERSION_PATCH define'
jobs:
build-appimage:
@ -35,14 +40,8 @@ jobs:
# fix luajit paths
sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua5.1.a
sudo ln -s /usr/include/luajit-2.1 /usr/include/lua
# install EnTT
git clone --branch v3.16.0 https://github.com/skypjack/entt.git
cd entt/build
cmake -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=on ..
sudo make install
cd ../..
- name: Configure
run: cmake -S . -B build -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1 -DVOXELENGINE_BUILD_TESTS=ON -DVC_BUILD_NAME="${{ inputs.build_name }}"
run: cmake -S . -B build -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1 -DVOXELENGINE_BUILD_TESTS=ON -DVC_BUILD_NAME="${{ inputs.build_name }}" -DVC_VERSION_PATCH="${{ inputs.version_patch }}"
- name: Build
run: cmake --build build -t install
- name: Run tests

View file

@ -43,12 +43,6 @@ jobs:
# fix luajit paths
sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua-5.1.a
sudo ln -s /usr/include/luajit-2.1 /usr/include/lua
# install EnTT
git clone --branch v3.16.0 https://github.com/skypjack/entt.git
cd entt/build
cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=on ..
sudo make install
cd ../..
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only

View file

@ -11,6 +11,11 @@ on:
required: true
type: string
description: 'Build name passed as VC_BUILD_NAME define'
version_patch:
required: false
type: string
default: ''
description: 'Engine version patch number passed as VC_VERSION_PATCH define'
jobs:
build-dmg:
@ -23,13 +28,13 @@ jobs:
- name: Install dependencies from brew
run: |
brew install glfw glew libpng openal-soft luajit libvorbis skypjack/entt/entt googletest glm freetype
brew install glfw glew libpng openal-soft luajit libvorbis googletest glm freetype
- name: Configure
run: |
cmake -DOPENAL_INCLUDE_DIR=$(brew --prefix openal-soft)/include \
-DOPENAL_LIBRARY=$(brew --prefix openal-soft)/lib/libopenal.dylib \
-S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOXELENGINE_BUILD_TESTS=ON -DVOXELENGINE_BUILD_APPDIR=1 -DVC_BUILD_NAME="${{ inputs.build_name }}"
-S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOXELENGINE_BUILD_TESTS=ON -DVOXELENGINE_BUILD_APPDIR=1 -DVC_BUILD_NAME="${{ inputs.build_name }}" -DVC_VERSION_PATCH="${{ inputs.version_patch }}"
- name: Build
run: |

View file

@ -13,24 +13,32 @@ jobs:
prepare:
runs-on: ubuntu-latest
steps:
- run: echo "exists just for outputs"
- id: version
run: |
if [[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.([0-9]+) ]]; then
echo "patch=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"
fi
outputs:
build_name: '${{ env.RELEASE_VERSION }}'
version_patch: '${{ steps.version.outputs.patch }}'
build_linux:
needs: [prepare]
uses: ./.github/workflows/appimage.yml
with:
build_name: '${{ needs.prepare.outputs.build_name }}'
version_patch: '${{ needs.prepare.outputs.version_patch }}'
build_macos:
needs: [prepare]
uses: ./.github/workflows/macos.yml
with:
build_name: '${{ needs.prepare.outputs.build_name }}'
version_patch: '${{ needs.prepare.outputs.version_patch }}'
build_windows:
needs: [prepare]
uses: ./.github/workflows/windows-clang.yml
with:
build_name: '${{ needs.prepare.outputs.build_name }}'
version_patch: '${{ needs.prepare.outputs.version_patch }}'
publish_release:
runs-on: ubuntu-latest
needs: [build_linux, build_macos, build_windows]

View file

@ -11,6 +11,11 @@ on:
required: true
type: string
description: 'Build name passed as VC_BUILD_NAME define'
version_patch:
required: false
type: string
default: ''
description: 'Engine version patch number passed as VC_VERSION_PATCH define'
jobs:
build-windows:
@ -53,7 +58,7 @@ jobs:
export VCPKG_ROOT=$(pwd)/vcpkg
mkdir build
cd build
cmake -G "MinGW Makefiles" -DVCPKG_TARGET_TRIPLET=x64-mingw-static -DVC_BUILD_NAME="${{ inputs.build_name }}" -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake ..
cmake -G "MinGW Makefiles" -DVCPKG_TARGET_TRIPLET=x64-mingw-static -DVC_BUILD_NAME="${{ inputs.build_name }}" -DVC_VERSION_PATCH="${{ inputs.version_patch }}" -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake ..
cmake --build . --config Release
- name: Package for Windows
run: |

View file

@ -12,6 +12,14 @@ option(VOXELENGINE_BUILD_TESTS "Build tests" OFF)
add_compile_definitions(VC_BUILD_NAME="${VC_BUILD_NAME}")
set(VC_VERSION_PATCH "" CACHE STRING "Engine version patch number")
if(NOT VC_VERSION_PATCH STREQUAL "")
if(NOT VC_VERSION_PATCH MATCHES "^[0-9]+$")
message(FATAL_ERROR "invalid VC_VERSION_PATCH: '${VC_VERSION_PATCH}'")
endif()
add_compile_definitions(VC_VERSION_PATCH=${VC_VERSION_PATCH})
endif()
# Need for static compilation on Windows with MSVC clang TODO: Make single build
# on Windows to avoid dependence on combinations of platforms and compilers and
# make it independent

View file

@ -38,15 +38,6 @@ RUN wget https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cm
./cmake-${CMAKE_VERSION}-linux-x86_64.sh --skip-license --prefix=/usr/local && \
rm cmake-${CMAKE_VERSION}-linux-x86_64.sh
# Install specific EnTT version (the latest version that supports C++17).
RUN git clone --branch v3.16.0 https://github.com/skypjack/entt.git && \
cd entt/build && \
cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=on .. && \
make install && \
cd ../.. && rm -rf entt
# CMake missing LUA_INCLUDE_DIR and LUA_LIBRARIES fix:
RUN ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua5.1.a \
&& ln -s /usr/include/luajit-2.1 /usr/include/lua

View file

@ -11,26 +11,11 @@
### Install libraries
#### Install EnTT
Installing last version that supports C++17.
```sh
git clone --branch v3.16.0 https://github.com/skypjack/entt.git
cd entt
mkdir -p build && cd build
cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=ON ..
sudo make install
```
> [!WARNING]
> If you are using ALT Linux, do **not** use this EnTT installation method.
#### ALT Linux based distros
```sh
su -
apt-get install entt-devel libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel
apt-get install libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel
```
#### Debian based distros
@ -80,7 +65,7 @@ cmake --build . --parallel
### Install libraries
```sh
brew install glfw glew glm libpng libvorbis lua luajit libcurl openal-soft skypjack/entt/entt freetype
brew install glfw glew glm libpng libvorbis lua luajit libcurl openal-soft freetype
```
> [!TIP]

27
dev/tests/hotbar.lua Normal file
View file

@ -0,0 +1,27 @@
local util = require "core:tests_util"
util.create_demo_world("core:default")
local pid = player.create("Xerxes")
local function selected_slot()
local _, slot = player.get_inventory(pid)
return slot
end
util.check_int(10, player.get_hotbar_size(pid), "default hotbar size")
player.set_selected_slot(pid, 12)
util.check_int(2, selected_slot(), "selected slot")
player.set_selected_slot(pid, 8)
player.set_hotbar_size(pid, 5)
util.check_int(5, player.get_hotbar_size(pid), "hotbar size")
util.check_int(4, selected_slot(), "clamped selected slot")
player.set_selected_slot(pid, 7)
util.check_int(2, selected_slot(), "selected slot")
player.set_hotbar_size(pid, 0)
util.check_int(1, player.get_hotbar_size(pid), "min hotbar size")
util.check_int(0, selected_slot(), "selected slot")

View file

@ -1,34 +1,385 @@
local device = file.create_memory_device()
file.write(device..":test.txt", "Hello\nWorld")
file.write_bytes(device..":test.bin", Bytearray({20, 30, 100, 200, 255}))
local stream = file.open(device..":test.txt", 'r')
local function path(name) return device .. ":" .. name end
local line1 = stream:read_line()
local line2 = stream:read_line()
local function eq_list(actual, expected, msg)
asserts.equals(#actual, #expected, (msg or "list") .. " length")
for i = 1, #expected do
asserts.equals(actual[i], expected[i], (msg or "list") .. "[" .. i .. "]")
end
end
assert(line1 == "Hello")
assert(line2 == "World")
file.write(path("test.txt"), "Hello\nWorld")
file.write_bytes(path("test.bin"), Bytearray({20, 30, 100, 200, 255}))
local stream2 = file.open(device..":test.bin", 'rb')
local data = stream2:read(5)
assert(data[1] == 20)
assert(data[2] == 30)
assert(data[3] == 100)
assert(data[4] == 200)
assert(data[5] == 255)
do
local stream = file.open(path("test.txt"), 'r')
asserts.equals(stream:read_line(), "Hello")
asserts.equals(stream:read_line(), "World")
stream:close()
end
local stream3 = file.open(device..":test.txt", 'r')
assert(stream3:is_alive())
stream3:close()
assert(not stream3:is_alive())
do
local stream = file.open(path("test.bin"), 'rb')
local data = stream:read(5)
asserts.equals(data[1], 20); asserts.equals(data[2], 30); asserts.equals(data[3], 100); asserts.equals(data[4], 200); asserts
.equals(data[5], 255)
stream:close()
end
local stream4 = file.open(device..":test.txt", 'r')
stream4:seek('b', 6)
local line = stream4:read_line()
assert(line == "World")
do
local stream = file.open(path("test.txt"), 'r')
assert(stream:is_alive())
assert(not stream:is_closed())
stream:close()
assert(not stream:is_alive())
assert(stream:is_closed())
end
local stream5 = file.open(device..":test.txt", 'r')
stream5:seek('e', 0)
local pos = stream5:tell()
assert(pos == 11)
do
local stream = file.open(path("test.txt"), 'r')
stream:seek('b', 6)
asserts.equals(stream:read_line(), "World")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
stream:seek('e', 0)
asserts.equals(stream:tell(), 11)
stream:close()
end
-------------------------------------------------------------------------------
-- text: line endings and end of stream
-------------------------------------------------------------------------------
do
local stream = file.open(path("test.txt"), 'r')
stream:read_line(); stream:read_line()
asserts.equals(stream:read_line(), nil, "after last line")
asserts.equals(stream:read_line(), nil, "after last line, again")
stream:close()
end
do
file.write(path("empty.txt"), "")
local stream = file.open(path("empty.txt"), 'r')
asserts.equals(stream:read_line(), nil, "empty file")
stream:close()
end
do
file.write(path("crlf.txt"), "a\r\nb\rc\nd\r")
local stream = file.open(path("crlf.txt"), 'r')
asserts.equals(stream:read_line(), "a", "CRLF")
asserts.equals(stream:read_line(), "b\rc", "lone CR is kept")
asserts.equals(stream:read_line(), "d\r", "CR at end of stream")
asserts.equals(stream:read_line(), nil)
stream:close()
end
-------------------------------------------------------------------------------
-- text: read(count) and read_fully
-------------------------------------------------------------------------------
do
file.write(path("blank.txt"), "\n\nA\nB\n\n")
local stream = file.open(path("blank.txt"), 'r')
eq_list(stream:read(10), {"A", "B"}, "trimmed")
stream:close()
end
do
local stream = file.open(path("blank.txt"), 'r')
eq_list(stream:read(10, false), {"", "", "A", "B", ""}, "untrimmed")
stream:close()
end
do
file.write(path("only_blank.txt"), "\n\n\n")
local stream = file.open(path("only_blank.txt"), 'r')
eq_list(stream:read(5), {}, "only empty lines")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
eq_list(stream:read(5), {"Hello", "World"}, "past end of stream")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
assert(not pcall(stream.read, stream, -1), "negative count must fail")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
asserts.equals(stream:read(), "Hello")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
asserts.equals(stream:read_fully(), "Hello\nWorld", "read_fully as string")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
eq_list(stream:read_fully(true), {"Hello", "World"}, "read_fully as lines")
stream:close()
end
-------------------------------------------------------------------------------
-- text: writing
-------------------------------------------------------------------------------
do
local stream = file.open(path("out.txt"), 'w')
stream:write("one")
stream:write({"two", "three"})
stream:write_line("four")
stream:close()
asserts.equals(file.read(path("out.txt")), "one\ntwo\nthree\nfour\n", "text write")
end
do
local stream = file.open(path("out.txt"), 'w')
assert(not pcall(stream.write, stream, 42), "writing a number in text mode must fail")
stream:close()
end
-------------------------------------------------------------------------------
-- binary
-------------------------------------------------------------------------------
do
local stream = file.open(path("test.bin"), 'rb')
eq_list(stream:read(5, true), {20, 30, 100, 200, 255}, "read as table")
stream:close()
end
do
local stream = file.open(path("test.bin"), 'rb')
stream:read(3)
asserts.equals(#stream:read(10), 2, "short read")
asserts.equals(#stream:read(10), 0, "read at end of stream")
stream:close()
end
do
local stream = file.open(path("test.bin"), 'rb')
local data = stream:read_fully()
asserts.equals(#data, 5); asserts.equals(data[1], 20); asserts.equals(data[5], 255)
stream:close()
end
do
local stream = file.open(path("test.bin"), 'rb')
eq_list(stream:read_fully(true), {20, 30, 100, 200, 255}, "read_fully as table")
stream:close()
end
do
local stream = file.open(path("out.bin"), 'wb')
stream:write({1, 2, 3})
stream:write(Bytearray({4, 5}))
stream:close()
local data = file.read_bytes(path("out.bin"))
asserts.equals(#data, 5, "binary write length")
for i = 1, 5 do asserts.equals(data[i], i, "binary write byte " .. i) end
end
do
local stream = file.open(path("fmt.bin"), 'wb')
stream:write("<iH", -5, 1000)
stream:close()
stream = file.open(path("fmt.bin"), 'rb')
local a, b = stream:read("<iH")
asserts.equals(a, -5, "packed int")
asserts.equals(b, 1000, "packed ushort")
stream:close()
end
do
local stream = file.open(path("test.bin"), 'rb')
assert(not pcall(stream.read, stream), "binary read without args must fail")
assert(not pcall(stream.read, stream, true), "binary read with boolean must fail")
stream:close()
end
-------------------------------------------------------------------------------
-- settings
-------------------------------------------------------------------------------
do
local stream = file.open(path("test.txt"), 'r')
stream:set_binary_mode(true)
assert(stream:is_binary_mode())
stream:set_binary_mode(false)
assert(not stream:is_binary_mode(), "set_binary_mode(false)")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'rb')
asserts.equals(stream:read_line(), "Hello")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
asserts.equals(stream:get_mode(), "default")
asserts.equals(stream:get_flush_mode(), "all")
assert(not pcall(stream.set_mode, stream, "nope"), "invalid mode must fail")
assert(not pcall(stream.set_flush_mode, stream, "nope"), "invalid flush mode must fail")
asserts.equals(stream:get_mode(), "default", "mode unchanged after error")
stream:close()
end
-------------------------------------------------------------------------------
-- buffered mode
-------------------------------------------------------------------------------
do
local stream = file.open(path("test.txt"), 'r')
stream:set_mode("buffered")
asserts.equals(stream:read_line(), "Hello")
asserts.equals(stream:read_line(), "World")
asserts.equals(stream:read_line(), nil)
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
stream:set_mode("buffered")
stream:read_line()
asserts.equals(stream:available(), 5, "available")
assert(stream:available(5))
assert(not stream:available(6))
asserts.equals(stream:tell(), 6, "tell after buffered read")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
stream:set_mode("buffered")
stream:read_line()
stream:seek('c', 1)
asserts.equals(stream:read_line(), "orld", "seek 'c' in buffered mode")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
stream:set_mode("buffered")
stream:read_line()
stream:seek('b', 0)
asserts.equals(stream:read_line(), "Hello", "seek 'b' in buffered mode")
stream:close()
end
do
local stream = file.open(path("test.txt"), 'r')
stream:set_mode("buffered")
stream:set_max_buffer_size(2)
asserts.equals(stream:get_max_buffer_size(), 2)
eq_list(stream:read_fully(true), {"Hello", "World"}, "tiny buffer")
stream:close()
end
do
local stream = file.open(path("buf.bin"), 'wb')
stream:set_mode("buffered")
stream:write({1, 2, 3})
asserts.equals(stream:tell(), 3, "tell with pending writes")
stream:close()
end
do
local stream = file.open(path("buf.txt"), 'w')
stream:set_mode("buffered")
stream:write("abc")
stream:close()
asserts.equals(file.read(path("buf.txt")), "abc\n", "close flushes")
end
do
local stream = file.open(path("buf.txt"), 'w')
stream:set_mode("buffered")
stream:write("abc")
stream:set_mode("default")
stream:write("def")
stream:close()
asserts.equals(file.read(path("buf.txt")), "abc\ndef\n", "set_mode flushes")
end
do
local stream = file.open(path("big.bin"), 'wb')
stream:set_mode("buffered")
stream:set_max_buffer_size(4)
stream:write({1, 2})
stream:write({3, 4, 5, 6, 7, 8, 9, 10, 11, 12})
stream:write({13})
stream:close()
local data = file.read_bytes(path("big.bin"))
asserts.equals(#data, 13, "big write length")
for i = 1, 13 do asserts.equals(data[i], i, "big write byte " .. i) end
end
do
for _, flush_mode in ipairs({"all", "buffer"}) do
local stream = file.open(path("flush.txt"), 'w')
stream:set_mode("buffered")
stream:set_flush_mode(flush_mode)
stream:write("x")
stream:flush()
asserts.equals(file.read(path("flush.txt")), "x\n", "flush mode " .. flush_mode)
stream:close()
end
end
-------------------------------------------------------------------------------
-- yield mode
-------------------------------------------------------------------------------
do
local stream = file.open(path("test.txt"), 'r')
stream:set_mode("yield")
local co = coroutine.create(function()
return stream:read_line(), stream:read_fully()
end)
local ok, line, rest = coroutine.resume(co)
assert(ok, line)
asserts.equals(coroutine.status(co), "dead", "yield mode read_fully must not hang")
asserts.equals(line, "Hello")
asserts.equals(rest, "World")
stream:close()
end
do
local stream = file.open(path("test.bin"), 'rb')
stream:set_mode("yield")
local co = coroutine.create(function() return stream:read(100) end)
local ok, err = coroutine.resume(co)
assert(ok, err)
asserts.equals(coroutine.status(co), "suspended", "short read must yield")
stream:close()
local ok2, data = coroutine.resume(co)
assert(ok2, data)
asserts.equals(coroutine.status(co), "dead", "closed stream ends the wait")
asserts.equals(#data, 5, "bytes read before close")
end

View file

@ -0,0 +1,31 @@
app.create_memory_device("memtest")
local script_path = "config:subprocess.lua"
local log_path = "config:subprocess.log"
file.write(script_path, [[
debug.log("hello from sub-instance")
sleep(1)
]])
local handle = app.start_background_instance(script_path, log_path)
assert(handle >= 0)
local stdin = app.get_stdin_stream(handle)
assert(stdin ~= nil)
stdin:write_line("sub_instance_test")
stdin:flush()
app.sleep_until(function() return not app.is_instance_alive(handle) end)
assert(not app.is_instance_alive(handle))
local stdout = app.get_stdout_stream(handle)
assert(stdout ~= nil)
local output = table.concat(table.map(stdout:read(1e6), function(_, line) return "<sub>"..line end), '\n')
print(output)
assert(output and output:find("hello from sub-instance", 1, true) ~= nil)
assert(output and output:find('stdin-cmd] unknown command "sub_instance_test"', 1, true) ~= nil)
stdout:close()
file.remove(script_path)
assert(not app.terminate_instance(handle))

View file

@ -38,6 +38,48 @@ Additional load settings example:
]
}
```
## Patterns
An asset name may contain `*` to include multiple assets at once. The `*` matches any sequence of characters within a single path segment.
Pattern matching is performed within the pack containing `preload.json`, specifically within the folder corresponding to the asset type (e.g., `textures/`, `sounds/`, etc.).
The resulting asset names are the same as if each discovered asset had been specified explicitly.
```json
{
"textures": [
"gui/*",
"mobs/*/skin-*"
],
"sounds": [
"steps/*"
]
}
```
> [!NOTE]
> Sound variations (such as `grass_0.ogg`, `grass_1.ogg`, etc.) are added as a single sound entry (e.g., `steps/grass`).
A pattern ending in `/` matches directories rather than individual files. This is used for atlases:
```json
{
"atlases": [
"smth/*/other-*/*/"
]
}
```
Entry parameters apply to all matched assets. The `path` parameter cannot be used in conjunction with a pattern:
```json
{
"sounds": [
{
"name": "ambient/*",
"keep-pcm": true
}
]
}
```
*preload.json* example from `core:` package (`res/preload.json`):
```json

View file

@ -71,6 +71,13 @@ Rotation profile (set of available block rotations and behaviour of placing bloc
- "stairs" - "pane" + flipped variants
- "ladder" - like a "pipe", but on horizontal surfaces it is installed like "pane"
### *uv-lock*
Keeps custom model textures aligned to world axes when the block is rotated,
so textures of rotated blocks join seamlessly with neighbours.
Applies to axis-aligned faces of `custom` models with named textures.
Leave it off for directional textures (doors, arrows, wood). `false` by default.
### *particles*
Particles are specified as a JSON object. Property names can be found [in the particles section](particles.md).
@ -112,6 +119,8 @@ Properties available for variance:
- model-name
- texture
- texture-faces
- hitbox
- hitboxes
- model-primitives (deprecated)
Variants are managed via `block.set_variant(x, y, z, index)`.
@ -142,6 +151,26 @@ In this example:
- Variant 1 = `stairs_left` (from variants[0])
- Variant 2 = `stairs_right` (from variants[1])
### Hitbox variants
A variant can override `hitbox` or `hitboxes`. Variants without them inherit the root hitboxes. Collisions, raycasts, block selection and `aabb` models use the hitboxes of the current variant.
```json
{
"model": "aabb",
"hitbox": [0.0, 0.0, 0.0, 1.0, 0.5, 1.0],
"rotation": "pipe",
"state-based": {
"bits": 1,
"variants": [
{ "hitbox": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] }
]
}
}
```
For extended blocks the variant is taken from the origin segment.
## Lighting
### *emission*

View file

@ -1,5 +1,17 @@
# Entity properties
## User properties
Access to custom entity properties is provided through the table `entities.properties[id]["property"]`, where `id` is the entity definition index.
Custom properties follow the same pack inheritance and override rules as block and item properties, and must be declared in `pack:config/user-props.toml`:
```toml
"pack:property_name" = {}
```
This makes the property available in Lua scripts as `entities.properties[entities.def_index("pack:entity")]["property"]`.
## Logic
### *components*
@ -132,6 +144,14 @@ The default value is the same as the entity name. Determines which skeleton will
- *bone-based* - lighting is calculated for each skeletal bone separately.
- *solid* - lighting is calculated for the entire entity.
### *translucent*
Enables translucency support in the entity textures (semi-transparent parts).
Should only be used when needed, as it impacts performance.
Not required for full transparency (cutout parts) and for fading the entity out with the skeleton tint alpha.
Default value: *false*.
## Saving/Loading
In addition to custom components, the engine automatically saves data from the built-in ones: transform, rigidbody, skeleton.

View file

@ -72,6 +72,45 @@ Property status is displayed in the inventory interface. Display method is defin
Defines the name of the script containing the item's event handlers. By default, equals to the item's string id (name).
Allows you to reuse a single script for multiple items.
## User properties
Access to custom item properties is provided through the table `item.properties[id]["property"]`, where `id` is the numeric item index.
User properties must be declared in `pack:config/user-props.toml`:
```toml
"pack:property_name" = {}
```
### Example usage in Lua - `base_survival:tool`
```lua
local tool = item.properties[itemid]["base_survival:tool"]
if tool then
local stone_material = tool.materials['base:stone']
if stone_material then
print(tool.type, stone_material.speed)
end
end
```
Definition in item JSON:
```json
{
"base_survival:tool": {
"type": "breaker",
"materials": {
"base:stone": {
"speed": 15.0
}
}
}
}
```
Custom property tables follow the same inheritance and override rules as block properties.
## Tags
Tags allow you to designate general properties of items. Names should be formatted as `prefix:tag_name`.

View file

@ -1,5 +1,9 @@
# Documentation
>![WARNING]
> This branch is used for VoxelCore 0.33 development, API is unstable.
> [Proceed to VoxelCore 0.32 documentation](https://github.com/MihailRis/voxelcore/blob/release-0.32/doc/en/main-page.md)
## Sections
- [Assets preloading](assets-preload.md)

View file

@ -119,7 +119,8 @@ app.close_world(
```lua
-- Returns the major and minor versions of the engine.
app.get_version() -> int, int
-- If a patch number is available, it also returns it.
app.get_version() -> int, int, int | nil
-- Returns the value of a setting.
-- Throws an exception if the setting does not exist.
@ -183,4 +184,10 @@ app.is_instance_alive(handle: int) -> boolean
-- Stops the engine sub-instance.
-- Returns true if the instance was alive at the time of the call.
app.terminate_instance(handle: int) -> boolean
-- Returns the input stream of the engine sub-instance.
app.get_stdin_stream(handle: int) -> stream
-- Returns the output stream of the engine sub-instance.
app.get_stdout_stream(handle: int) -> stream
```

View file

@ -25,10 +25,10 @@ assets.load_texture(
-- Parses and loads a 3D model
assets.parse_model(
-- Model file format (xml / vcm)
-- Model file format (xml / vcm / obj / vec3)
format: str,
-- Contents of the model file
content: str,
content: str | Bytearray (.vec3),
-- Model name after loading
name: str,
-- The skeleton name after loading. May be the same as the model name.
@ -37,6 +37,16 @@ assets.parse_model(
skeleton_name: string
)
-- Parses and loads a skeleton definition
assets.parse_skeleton(
-- Skeleton file format (json / vcm / xml)
format: str,
-- Contents of the skeleton file
content: str,
-- Skeleton name after loading
name: str
)
-- Parses and loads animation
assets.parse_animation(
-- Animation file format (vca)

View file

@ -177,7 +177,12 @@ block.get_textures(id: int, [optional] variant_index: int = 0) -> string table
-- returns array of two vectors (arrays of 3 numbers):
-- 1. Minimum point of the hitbox
-- 2. Hitbox size
block.get_hitbox(id: int, rotation_index: int, [optional] hitbox_index: int = 0) -> {vec3, vec3}
block.get_hitbox(
id: int,
rotation_index: int,
[optional] hitbox_index: int = 0,
[optional] variant_index: int = 0
) -> {vec3, vec3}
```
## Data fields

View file

@ -41,6 +41,11 @@ entities.defs_count() -> int
```
```lua
-- Table of custom entity properties (see ../../entity-properties.md)
entities.properties: table<int, table<string, object>>
```
> [!NOTE]
> The following functions for retrieving multiple entities return tables with integer keys (uid).
> For iteration, use `pairs`, and for calculating the table size, use `table.count_pairs`.

View file

@ -26,6 +26,10 @@ skeleton:get_matrix(index: int) -> mat4
-- Sets the transformation matrix of the bone with the specified index
skeleton:set_matrix(index: int, matrix: mat4)
-- Returns the offset of the bone with the specified index relative to its parent
-- (as defined in the skeleton config)
skeleton:get_bone_offset(index: int) -> vec3
-- Returns the texture by key (dynamically assigned textures - '$name')
skeleton:get_texture(key: str) -> str

View file

@ -82,6 +82,12 @@ hud.is_player_inventory_open() -> boolean
-- Sets whether to allow pausing. If false, the pause menu will not pause the game.
hud.set_allow_pause(flag: bool)
-- Returns true if the hotbar is not hidden with hud.set_hotbar_visible.
hud.is_hotbar_visible() -> bool
-- Shows or hides the hotbar. Selecting a slot with the mouse wheel and number keys keeps working.
hud.set_hotbar_visible(flag: bool)
-- Function that controls the named skeleton 'hand' (see gfx.skeletons)
hud.hand_controller: function()
```

View file

@ -55,6 +55,12 @@ pathfinding.pull_route(agent: int) --> table<vec3> or nil
--- Set the maximum number of visited blocks for the agent. Used to limit the amount of work of the pathfinding algorithm.
pathfinding.set_max_visited(agent: int, max_visited: int)
--- Sets the agent's width in blocks. Defaults to 0.6
pathfinding.set_width(agent: int, width: number)
--- Sets the agent's height in blocks. Defaults to 2
pathfinding.set_height(agent: int, height: int)
--- Adding an avoided blocks tag
pathfinding.avoid_tag(
agent: int,

View file

@ -142,7 +142,14 @@ Switches the player's camera. See [cameras](libcameras.md).
player.set_selected_slot(playerid: int, slotid: int)
```
Sets the selected slot index
Sets the selected slot index. The index wraps around the hotbar size.
```lua
player.get_hotbar_size(playerid: int) -> int
player.set_hotbar_size(playerid: int, size: int)
```
Hotbar size getter and setter: the number of first player inventory slots that can be selected. `player.set_selected_slot` wraps the index by it, and the selected slot is moved into the range when the size decreases. Default value is `hotbar-size` from `config/defaults.toml` (10); the value is not saved with the world. On the client these slots are shown in the hotbar and selected with the mouse wheel and number keys.
```lua
player.get_selected_block(playerid: int) -> x,y,z

View file

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

View file

@ -172,6 +172,9 @@ rig:get_matrix(index: int) -> mat4
-- Sets the bone transformation matrix at the specified index
rig:set_matrix(index: int, matrix: mat4)
-- Returns the bone offset relative to its parent (from the skeleton config)
rig:get_bone_offset(index: int) -> vec3
-- Returns the texture by key (dynamically assigned textures - '$name')
rig:get_texture(key: str) -> str

View file

@ -14,6 +14,26 @@ function on_placed(x, y, z, playerid)
Called on block placed by player
```lua
function can_be_placed(x, y, z, playerid, rotation) -> bool
```
Called before a player places the block, after the built-in checks
(replaceability, `grounded`, intersection with entities).
The block is placed only if the function returns `true`.
`rotation` is the rotation index the block will be placed with
(see `block.get_rotation`).
Example: a sapling that can only be planted on dirt.
```lua
function can_be_placed(x, y, z, playerid, rotation)
return block.name(block.get(x, y - 1, z)) == "base:dirt"
end
```
The event is not called when the block is placed with `block.place` or `block.set`.
```lua
function on_broken(x, y, z, playerid)
```
@ -117,10 +137,10 @@ function on_world_save()
Called before world save.
```lua
function on_world_tick()
function on_world_tick(tps)
```
Called 20 times per second
Called *tps* times per second
```lua
function on_world_quit()
@ -225,6 +245,12 @@ function on_content_loaded()
Called after the content pack has been fully loaded
```lua
function on_assets_loading()
```
Called on assets loading start
## HUD events
Callbacks specified in *hud.lua* script.

View file

@ -78,7 +78,8 @@ Common methods:
| clear() | clears content |
| add(xml) | adds an element, creating it using xml code. Example: `container:add("<image src='test'/>")` |
| add(xml, data) | overload with table, which in events declared in xml will be available as DATA |
| setInterval(interval, callback) | assigns a function to be executed repeatedly at an interval specified in milliseconds |
| setInterval(interval, callback) | assigns a function to be executed repeatedly at an interval specified in milliseconds, returns interval id |
| clearInterval(id) | cancels an interval created with setInterval |
## Textbox

View file

@ -28,6 +28,9 @@ Two kinds of curve definitions are currently available, each producing a value `
- `@scale` - scales an object/bone (multiplier)
- `@zoom` - camera zoom (multiplier)
- `@texture` - change of a dynamically assigned texture (see [skeleton:set_texture](scripting/ecs.md#skeleton))
- `@model` - bone model replacement (see [skeleton:set_model](scripting/ecs.md#skeleton))
- `@show` - visibility of a bone or the entire skeleton/object (if no bone is specified)
- `@color` - color of a bone or the entire skeleton/object (if no bone is specified) (RGBA)
## Metadata
@ -96,6 +99,23 @@ If you do not wish to limit the animation duration via `configure` but want to l
}
```
Example of using flag directives like `show`:
```vcd
# Specific bone
@show bone head period 20 {
@key frame 0 value on
@key frame 10 value off
}
# Entire skeleton
@show period 30 {
@key frame 0 value on
@key frame 10 value off
}
```
## Expression curves
The attribute describes a function `f(t) = x`, where t is time in seconds.

View file

@ -218,6 +218,8 @@ Element is a container. Does not have specific attributes.
> [!WARNING]
> Slots not linked to an inventory will not be displayed. "Linked to an inventory" refers to the association between an inventory UI element and an inventory via an ID. This link can be explicitly established using `inventory_ui.inventory = inventory_id`. [(see ui.md)](scripting/ui.md#inventory)
A pack can replace the player inventory screen and the hotbar with its own layouts using `inventory-layout` (`"core:inventory"` by default) and `hotbar-layout` in `config/defaults.toml`. The root element of such a layout must be `inventory`, it is bound to the player inventory. The hotbar layout is placed at the bottom center of the screen unless it has `position-func`.
## *slot*
Element must be a direct sub-element of *inventory*.

View file

@ -39,6 +39,49 @@
```
## Шаблоны
Имя ассета может содержать `*` для добавления сразу нескольких ассетов. `*` соответствует любой последовательности символов в пределах одного сегмента пути.
Поиск по шаблону производится в паке, содержащем `preload.json`, в папке типа ассетов (`textures/`, `sounds/`, ...).
Имена ассетов получаются такими же, как если бы каждый найденный ассет был указан явно.
```json
{
"textures": [
"gui/*",
"mobs/*/skin-*"
],
"sounds": [
"steps/*"
]
}
```
> [!NOTE]
> Вариации звука (`grass_0.ogg`, `grass_1.ogg`, ...) добавляются как один звук (`steps/grass`).
Шаблон, оканчивающийся на `/`, соответствует папкам, а не файлам. Используется для атласов:
```json
{
"atlases": [
"smth/*/other-*/*/"
]
}
```
Параметры записи применяются ко всем найденным ассетам. Параметр `path` нельзя использовать вместе с шаблоном:
```json
{
"sounds": [
{
"name": "ambient/*",
"keep-pcm": true
}
]
}
```
Пример файла из пакета `core:` (`res/preload.json`):
```json
{

View file

@ -72,6 +72,13 @@
- "stairs" - профиль "ступеньки" ("pane" + перевернутые варианты)
- "ladder" - профиль "лестница" (как "pipe", но на горизонтальных поверхностях как "pane")
### Блокировка UV - *uv-lock*
Сохраняет ориентацию текстур кастомной модели относительно мировых осей при вращении блока,
чтобы текстуры повёрнутых блоков бесшовно стыковались с соседними.
Работает для выровненных по осям граней `custom`-моделей с именованными текстурами.
Не включайте для направленных текстур (двери, стрелки, бревна). По умолчанию `false`.
### Испускаемые частицы - *particles*
Частицы указываются в виде JSON объекта. Имена свойств можно найти [в разделе, посвященном частицам](particles.md).
@ -113,6 +120,8 @@
- model-name
- texture
- texture-faces
- hitbox
- hitboxes
- model-primitives (устарело)
Управление состоянием производится через `block.set_variant(x, y, z, index)`.
@ -143,6 +152,26 @@
- Вариант 1 = `stairs_left` (из variants[0])
- Вариант 2 = `stairs_right` (из variants[1])
### Хитбоксы по вариантам
Вариант может переопределять `hitbox` или `hitboxes`. Варианты без них наследуют хитбоксы из корня. Коллизии, рейкасты, выделение блока и модели `aabb` используют хитбоксы текущего варианта.
```json
{
"model": "aabb",
"hitbox": [0.0, 0.0, 0.0, 1.0, 0.5, 1.0],
"rotation": "pipe",
"state-based": {
"bits": 1,
"variants": [
{ "hitbox": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] }
]
}
}
```
Для расширенных блоков вариант берётся из сегмента-источника.
## Освещение
### Излучение - *emission*:

View file

@ -1,5 +1,17 @@
# Свойства сущностей
## Пользовательские свойства
Доступ к пользовательским свойствам сущностей осуществляется через таблицу `entities.properties[id]["свойство"]`, где `id` - индекс определения сущности.
Пользовательские свойства следуют тем же правилам наследования и переопределения пакетов, что и свойства блоков и предметов, и должны быть объявлены в `pack:config/user-props.toml`:
```toml
"pack:property_name" = {}
```
Это делает свойство доступным в Lua-скриптах как `entities.properties[entities.def_index("pack:entity")]["свойство"]`.
## Логика
### Список компонентов - *components*
@ -132,6 +144,14 @@
- *bone-based* - освещение рассчитывается для каждой кости скелета отдельно.
- *solid* - освещение рассчитывается для всей сущности в целом.
### Полупрозрачность - *translucent*
Включает поддержку полупрозрачности в текстурах сущности.
Следует использовать только при необходимости, так как влияет на производительность.
Не требуется для полной прозрачности (вырезанных частей) и для затухания сущности через альфа-канал оттенка скелета.
Значение по-умолчанию: *false*.
## Сохранение/загрузка
Кроме данных пользовательских компонентов, движок автоматически сохраняет данные встроенных: transform, rigidbody, skeleton.

View file

@ -71,6 +71,45 @@
Определяет имя скрипта, содержащего обработчики событий предмета. По умолчанию соответствует строковому id (имени) предмета.
Свойство обеспечивает возможность использования одного скрипта для нескольких предметов.
## Пользовательские свойства
Доступ к пользовательским свойствам предметов осуществляется через таблицу `item.properties[id]["свойство"]`, где `id` — числовой индекс предмета.
Пользовательские свойства должны быть объявлены в файле `пак:config/user-props.toml`:
```toml
"пак:имя_свойства" = {}
```
### Пример использования в Lua - `base_survival:tool`
```lua
local tool = item.properties[itemid]["base_survival:tool"]
if tool then
local stone_material = tool.materials['base:stone']
if stone_material then
print(tool.type, stone_material.speed)
end
end
```
Описание в JSON предмета:
```json
{
"base_survival:tool": {
"type": "breaker",
"materials": {
"base:stone": {
"speed": 15.0
}
}
}
}
```
Пользовательские свойства следуют тем же правилам наследования и переопределения, что и свойства блоков.
## Теги - *tags*
Теги позволяют обозначать обобщённые свойства предметов. Названия следует формировать как `префикс:имя_тега`.

View file

@ -1,5 +1,9 @@
# Документация
>![WARNING]
> В этой ветке ведётся разработка VoxelCore 0.33, API нестабилен.
> [Перейти к документации VoxelCore 0.32](https://github.com/MihailRis/voxelcore/blob/release-0.32/doc/ru/main-page.md)
## Разделы
- [XML разметка интерфейса](xml-ui-layouts.md)

View file

@ -116,7 +116,8 @@ app.close_world(
```lua
-- Возвращает мажорную и минорную версии движка.
app.get_version() -> int, int
-- При наличии номера патча возвращает и его.
app.get_version() -> int, int, int | nil
-- Возвращает значение настройки.
-- Бросает исключение, если настройки не существует.
@ -173,4 +174,10 @@ app.is_instance_alive(handle: int) -> boolean
-- Останавливает под-экземпляр движка.
-- Возвращает true если экземпляр был жив в момент вызова.
app.terminate_instance(handle: int) -> boolean
-- Возвращает поток ввода под-экземпляра движка.
app.get_stdin_stream(handle: int) -> stream
-- Возвращает поток вывода под-экземпляра движка.
app.get_stdout_stream(handle: int) -> stream
```

View file

@ -26,10 +26,10 @@ assets.load_texture(
-- Парсит и загружает 3D модель
assets.parse_model(
-- Формат файла модели (xml / vcm)
-- Формат файла модели (xml / vcm / obj / vec3)
format: string,
-- Содержимое файла модели
content: string,
content: string | Bytearray (.vec3),
-- Имя модели после загрузки
name: string,
-- Имя скелета после загрузки. Может совпадать с именем модели.
@ -38,6 +38,16 @@ assets.parse_model(
skeleton_name: string
)
-- Парсит и загружает определение скелета
assets.parse_skeleton(
-- Формат файла скелета (json / vcm / xml)
format: string,
-- Содержимое файла скелета
content: string,
-- Имя скелета после загрузки
name: string
)
-- Парсит и загружает анимацию
assets.parse_animation(
-- Формат файла анимации (vca)

View file

@ -177,7 +177,13 @@ block.get_textures(id: int, [опционально] variant_index: int = 0) ->
-- 2. Размер хитбокса
-- rotation_index - индекс поворота блока
-- hitbox_index - индекс хитбокса
block.get_hitbox(id: int, rotation_index: int, [опционально] hitbox_index: int = 0) -> {vec3, vec3}
-- variant_index - индекс варианта
block.get_hitbox(
id: int,
rotation_index: int,
[опционально] hitbox_index: int = 0,
[опционально] variant_index: int = 0
) -> {vec3, vec3}
```
## Данные блоков

View file

@ -40,6 +40,11 @@ entities.def_index(name: string) -> int
entities.defs_count() -> int
```
```lua
-- Таблица пользовательских свойств сущностей (см. ../../entity-properties.md)
entities.properties: table<int, table<string, object>>
```
> [!NOTE]
> Следующие функции для получения нескольких сущностей возвращают таблицы с целочисленными ключами (uid).
> Для итерации нужно использовать pairs, для подсчёта размера таблицы - table.count_pairs.

View file

@ -27,6 +27,10 @@ skeleton:get_matrix(index: int) -> mat4
-- Устанавливает матрицу трансформации кости с указанным индексом
skeleton:set_matrix(index: int, matrix: mat4)
-- Возвращает смещение кости с указанным индексом относительно родительской
-- (как задано в конфиге скелета)
skeleton:get_bone_offset(index: int) -> vec3
-- Возвращает текстуру по ключу (динамически назначаемые текстуры - '$имя')
skeleton:get_texture(key: string) -> string

View file

@ -84,6 +84,12 @@ hud.is_player_inventory_open() -> boolean
-- Устанавливает разрешение на паузу. При значении false меню паузы не приостанавливает игру.
hud.set_allow_pause(flag: boolean)
-- Возвращает true, если хотбар не скрыт через hud.set_hotbar_visible.
hud.is_hotbar_visible() -> boolean
-- Показывает или скрывает хотбар. Выбор слота колесом мыши и цифровыми клавишами продолжает работать.
hud.set_hotbar_visible(flag: boolean)
-- Функция, управляющая именованным скелетом 'hand' (см. gfx.skeletons)
hud.hand_controller: function()
```

View file

@ -55,6 +55,12 @@ pathfinding.pull_route(agent: int) -> table<vec3> или nil
--- Установка максимального количества посещенных блоков для агента. Используется для ограничения объема работы алгоритма поиска пути.
pathfinding.set_max_visited(agent: int, max_visited: int)
--- Установка ширины агента в блоках. По-умолчанию 0.6
pathfinding.set_width(agent: int, width: number)
--- Установка высоты агента в блоках. По-умолчанию 2
pathfinding.set_height(agent: int, width: int)
--- Добавление тега избегаемых блоков
pathfinding.avoid_tag(
agent: int,
@ -63,4 +69,4 @@ pathfinding.avoid_tag(
-- стоимость пересечения блока
cost: int = 10
)
```
```

View file

@ -95,9 +95,17 @@ player.get_interaction_distance(playerid: int) -> number
-- Возвращает ID инвентаря и индекс выбранного слота
player.get_inventory(playerid: int) -> int, int
-- Устанавливает выбранный слот
-- Устанавливает выбранный слот (индекс берётся по модулю размера хотбара)
player.set_selected_slot(playerid: int, slotid: int)
-- Возвращает / устанавливает размер хотбара - число первых слотов инвентаря игрока,
-- доступных для выбора. player.set_selected_slot берёт индекс по модулю этого числа,
-- а при уменьшении размера выбранный слот сдвигается в допустимый диапазон.
-- По умолчанию - `hotbar-size` из `config/defaults.toml` (10), в мире не сохраняется.
-- На клиенте эти слоты показывает хотбар, они выбираются колесом мыши и цифровыми клавишами.
player.get_hotbar_size(playerid: int) -> int
player.set_hotbar_size(playerid: int, size: int)
-- Возвращает позицию выбранного блока
player.get_selected_block(playerid: int) -> x,y,z

View file

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

View file

@ -161,6 +161,9 @@ rig:get_matrix(index: int) -> mat4
-- Устанавливает матрицу трансформации кости с указанным индексом
rig:set_matrix(index: int, matrix: mat4)
-- Возвращает смещение кости относительно родительской (из конфига скелета)
rig:get_bone_offset(index: int) -> vec3
-- Возвращает текстуру по ключу (динамически назначаемые текстуры - '$имя')
rig:get_texture(key: str) -> str

View file

@ -24,6 +24,26 @@ function on_placed(x, y, z, playerid)
Вызывается после установки блока игроком
```lua
function can_be_placed(x, y, z, playerid, rotation) -> bool
```
Вызывается перед установкой блока игроком, после встроенных проверок
(заменяемость, `grounded`, пересечение с сущностями).
Блок устанавливается, только если функция возвращает `true`.
`rotation` - индекс поворота, с которым будет установлен блок
(см. `block.get_rotation`).
Пример: саженец, который можно посадить только на землю.
```lua
function can_be_placed(x, y, z, playerid, rotation)
return block.name(block.get(x, y - 1, z)) == "base:dirt"
end
```
Событие не вызывается при установке блока через `block.place` и `block.set`.
```lua
function on_broken(x, y, z, playerid)
```
@ -104,7 +124,7 @@ function on_block_break_by(x: int, y: int, z: int, playerid: int)
Вызывается при нажатии ЛКМ на блок (в т.ч неразрушимый). Предотвращает разрушение блока, если возвращает `true`
## События мира
## События мира
События мира для контент-пака прописываются в `scripts/world.lua`
@ -121,10 +141,10 @@ function on_world_save()
Вызывается перед сохранением мира
```lua
function on_world_tick()
function on_world_tick(tps)
```
Вызывается 20 раз в секунду
Вызывается *tps* раз в секунду
```lua
function on_world_quit()
@ -236,6 +256,12 @@ function on_content_loaded()
Вызывается после того, как контент-пак был полностью загружен
```lua
function on_assets_loading()
```
Вызывается в начале загрузки ассетов
## События HUD
События связанные с игровым интерфейсом прописываются в файле `scripts/hud.lua`

View file

@ -78,7 +78,8 @@ document["worlds-panel"]:clear()
| clear() | очищает контент |
| add(xml) | добавляет элемент, создавая его по xml коду. Пример: `container:add("<image src='test'/>")` |
| add(xml, data) | перегрузка с передачей таблицы, которая в событиях, объявленных в xml будет доступна как DATA |
| setInterval(interval, callback) | назначает функцию на повторяющееся выполнение с заданным в миллисекундах интервалом |
| setInterval(interval, callback) | назначает функцию на повторяющееся выполнение с заданным в миллисекундах интервалом, возвращает id интервала |
| clearInterval(id) | отменяет интервал, созданный через setInterval |
## Текстовое поле (textbox)

View file

@ -28,6 +28,9 @@ VCA файл состоит из набора директив, порядок
- `@scale` - масштабирование объекта/кости (множитель)
- `@zoom` - масштаб камеры (множитель)
- `@texture` - смена динамически-назначаемой текстуры (см. [skeleton:set_texture](scripting/ecs.md#skeleton))
- `@model` - назначение замены модели кости (см. [skeleton:set_model](scripting/ecs.md#skeleton))
- `@show` - видимость кости или всего скелета / объекта (если не указана кость)
- `@color` - цвет кости или всего скелета / объекта (если не указана кость) (RGBA)
## Мета-информация
@ -96,6 +99,23 @@ VCA файл состоит из набора директив, порядок
}
```
Пример использования директив-флагов, таких как `show`:
```vcd
# Конкретная кость
@show bone head period 20 {
@key frame 0 value on
@key frame 10 value off
}
# Весь скелет
@show period 30 {
@key frame 0 value on
@key frame 10 value off
}
```
## Кривые через выражения
Через атрибут описывается функция `f(t) = x` где t - время в секундах.

View file

@ -219,6 +219,8 @@
> [!WARNING]
> Слоты без привязки к инвентарю не будут отображаться. Под привязкой к инвентарю понимается связь UI элемента inventory с инвентарём по id. Которая может быть явно создана через `inventory_ui.inventory = inventory_id`. [(см ui.md)](scripting/ui.md#инвентарь-inventory)
Пак может заменить экран инвентаря игрока и хотбар своими макетами через ключи `inventory-layout` (по умолчанию `"core:inventory"`) и `hotbar-layout` в `config/defaults.toml`. Корневой элемент такого макета - `inventory`, он привязывается к инвентарю игрока. Макет хотбара ставится внизу по центру экрана, если у него нет `position-func`.
## Одиночный слот - *slot*
Элемент должен находиться внутри `inventory` элемента, без посредников.

View file

@ -38,7 +38,6 @@
luajit
curl
openssl
entt
mesa
freeglut
];
@ -47,11 +46,6 @@
glfw
mesa
freeglut
entt
];
cmakeFlags = [
"-DCMAKE_PREFIX_PATH=${pkgs.entt}"
"-DCMAKE_INCLUDE_PATH=${pkgs.entt}/include"
];
installPhase = ''

View file

@ -1,2 +1,4 @@
generator = "core:default"
player-entity = ""
hotbar-size = 10
inventory-layout = "core:inventory"

View file

@ -1,6 +1,6 @@
{
"id": "base",
"title": "Base",
"version": "0.32",
"version": "0.33",
"description": "basic content package"
}

View file

@ -3,5 +3,6 @@
<panel id='content_panel' size='480,100' color='#00000080' scrollable='true' max-length='400'>
<!-- content is generated in script -->
</panel>
<button onclick="delete_content(report)" context="world">@Delete Content</button>
<button onclick='menu:back()'>@Back to Main Menu</button>
</panel>

View file

@ -1,4 +1,18 @@
content_report = nil
function delete_content()
local units = {}
for i, entry in ipairs(content_report.content) do
table.insert(units, entry.name)
end
local request = {
units = units
}
app.delete_world_content(content_report.world, request, true)
end
function on_open(report)
content_report = report
for i, entry in ipairs(report.content) do
document.content_panel:add(gui.template("content_entry", entry))
end

View file

@ -39,12 +39,15 @@ local function bezier_interpolation(k0, k1, t)
return bezier(k0.value, k0.ry + k0.value, k1.ly + k1.value, k1.value, u)
end
local this = {
local M = {
CH_TRANSLATE = 1,
CH_ROTATE = 2,
CH_SCALE = 3,
CH_ZOOM = 4,
CH_TEXTURE = 5,
CH_SHOW = 6,
CH_MODEL = 7,
CH_COLOR = 8,
INT_CONST = 1,
INT_LINEAR = 2,
@ -67,14 +70,14 @@ function internals.store_animation(name, track)
loaded_tracks[name] = track
end
function this.get_track(identifier)
function M.get_track(identifier)
return loaded_tracks[identifier]
end
local running_actions = {}
local playing_tracks = {}
function this.action(func)
function M.action(func)
table.insert(running_actions, coroutine.create(func))
end
@ -98,7 +101,7 @@ local PlayingTrack = {
}
}
function this.play(name, target)
function M.play(name, target)
if target and target.reset_pose then
target:reset_pose()
end
@ -156,4 +159,4 @@ function internals.restore_animation_backup()
loaded_tracks, backup_tracks = backup_tracks, {}
end
return this
return M

View file

@ -18,7 +18,7 @@ local exclude_patters = {
}
-- TODO: replace with actual expression -> lua translator
local function process_expression(src, memoised, mode)
local function process_expression(src, mode)
if mode == 'mul' then
src = string.format("(%s) * intensity + (1.0 - intensity)", src)
elseif mode == "add" then
@ -33,7 +33,6 @@ local function process_expression(src, memoised, mode)
for i, pattern in ipairs(patterns) do
local pattern_safe = string.pattern_safe(pattern.pattern)
if src:find(pattern_safe) then
memoised[pattern.name] = pattern.pattern
src = src:gsub(pattern_safe, pattern.name)
end
end
@ -79,7 +78,7 @@ local env = {
return keys[left].value
end
left = keys[left]
if interp == INT_CONST then
if not interp or interp == INT_CONST then
return left.value
end
right = keys[right]
@ -119,8 +118,8 @@ local env = {
if target.set_rot then
target:set_rot(rot)
end
if target.set_scale then
target:set_scale(scale)
if target.set_size then
target:set_size(scale)
end
end
end,
@ -141,42 +140,48 @@ local is_multiplier = {
[animation.CH_ZOOM] = true,
}
local function codegen_track(raw_track, lineset, memoised, keysets, use_tsf)
local function codegen_line(raw_track, lineset, line, index, keysets)
if line.expression then
return "(" .. process_expression(line.expression,
is_multiplier[line.channel] and "mul" or "add") .. ")"
elseif line.keys then
local target_keysets = keysets[lineset.target_name]
if not target_keysets then
target_keysets = {}
keysets[lineset.target_name] = target_keysets
end
target_keysets[index] = line.keys
if line.curve_func then
local valueat = string.format("curves[%s]", string.escape(line.curve_func))
return string.format("value_at_custom(keysets['%s'][%d], t * %s %% %s, %s)",
lineset.target_name, index, raw_track.fps, line.period, valueat)
elseif line.channel == animation.CH_TEXTURE then
return string.format("string_at(keysets['%s'][%d], t * %s %% %s)",
lineset.target_name, index, raw_track.fps, line.period)
else
return string.format("value_at(keysets['%s'][%d], t * %s %% %s, %s)",
lineset.target_name, index, raw_track.fps, line.period, line.interp)
end
end
end
local function codegen_track(raw_track, lineset, keysets, use_tsf, target_type)
if lineset.target_type ~= target_type then
return ""
end
local lines = lineset.lines
local code = ""
local has_tsf = false
local translation = {false, false, false}
local rotation = {false, false, false}
local scale = {false, false, false}
local color = {false, false, false, false}
for i, line in ipairs(lines) do
if line.expression then
code = code .. "\n local l" .. i .. " = (" ..
process_expression(line.expression, memoised,
is_multiplier[line.channel] and "mul" or "add") .. ")"
elseif line.keys then
local target_keysets = keysets[lineset.target_name]
if not target_keysets then
target_keysets = {}
keysets[lineset.target_name] = target_keysets
end
target_keysets[i] = line.keys
if line.curve_func then
local valueat = string.format("curves[%s]", string.escape(line.curve_func))
code = code .. string.format(
"\n local l%d = value_at_custom(keysets['%s'][%d], t * %s %% %s, %s)",
i, lineset.target_name, i, raw_track.fps, line.period, valueat)
elseif line.channel == animation.CH_TEXTURE then
code = code .. string.format(
"\n local l%d = string_at(keysets['%s'][%d], t * %s %% %s)",
i, lineset.target_name, i, raw_track.fps, line.period)
else
code = code .. string.format(
"\n local l%d = value_at(keysets['%s'][%d], t * %s %% %s, %s)",
i, lineset.target_name, i, raw_track.fps, line.period, line.interp)
end
end
code = code .. string.format("\n local l%d = ", i)
.. codegen_line(raw_track, lineset, line, i, keysets)
if line.channel == animation.CH_TRANSLATE then
translation[line.axis] = i
@ -190,7 +195,31 @@ local function codegen_track(raw_track, lineset, memoised, keysets, use_tsf)
elseif line.channel == animation.CH_ZOOM then
code = code .. "\n zoom = l" .. i
elseif line.channel == animation.CH_TEXTURE then
code = code .. string.format("\n target:set_texture(%s, %s)", lineset.target_name:escape(), "l"..i)
code = code .. string.format("\n target:set_texture(%s, l%d)",
lineset.target_name:escape(), i)
elseif line.channel == animation.CH_MODEL then
code = code .. string.format("\n target:set_model(bone_index, l%d)", i)
elseif line.channel == animation.CH_SHOW then
if target_type == "bone" then
code = code .. string.format("\n target:set_visible(bone_index, l%d)", i)
else
code = code .. string.format("\n target:set_visible(l%d)", i)
end
elseif line.channel == animation.CH_COLOR then
color[line.axis] = i
end
end
if color[1] or color[2] or color[3] or color[4] then
local color_vector = "{" ..
(color[1] and ("l" .. color[1]) or '1').. ", " ..
(color[2] and ("l" .. color[2]) or '1').. ", " ..
(color[3] and ("l" .. color[3]) or '1').. ", " ..
(color[4] and ("l" .. color[4]) or '1').. "}"
if target_type == "bone" then
code = code .. "\n target:set_color(" .. color_vector .. ", bone_index)"
else
code = code .. "\n target:set_color(" .. color_vector .. ")"
end
end
@ -230,17 +259,18 @@ end
local function codegen_rig_target(raw_track, context)
local code = "\n if target.set_matrix and target.index then\n"
for bone, lineset in pairs(raw_track.linesets) do
if lineset.target_type ~= "bone" and lineset.target_type ~= "texture" then
if lineset.target_type ~= "bone" then
goto continue
end
local lineset_code = codegen_track(
raw_track, lineset, context.memoised, context.keysets, true)
local lineset_code = codegen_track(raw_track, lineset, context.keysets, true, "bone")
code = code .. string.format("\n local bone_index = target:index(%s)", string.escape(bone))
if context.has_tsf then
code = code .. "\n local dst = target:get_matrix(bone_index)"
end
code = code
.. string.format("\n local bone_index = target:index(%s)"
.. "\n local dst = target:get_matrix(bone_index)", string.escape(bone))
.. "\n do" .. lineset_code .. "\n end\n"
if lineset.target_type == "bone" then
if context.has_tsf then
code = code ..
" target:set_matrix(bone_index, dst)\n"
end
@ -279,14 +309,14 @@ local function codegen_native_rig_target(raw_track, context, track_name)
end
for bone, lineset in pairs(raw_track.linesets) do
if lineset.target_type ~= "bone" and lineset.target_type ~= "texture" then
if lineset.target_type ~= "bone" then
goto continue
end
local lineset_code = codegen_track(
raw_track, lineset, context.memoised, context.keysets, false)
raw_track, lineset, context.keysets, false, "bone")
local exported = {}
local entry = {name = bone}
if lineset.target_type == "bone" then
do
local channels = {
[animation.CH_TRANSLATE] = {},
[animation.CH_ROTATE] = {},
@ -351,18 +381,35 @@ local function codegen_native_rig_target(raw_track, context, track_name)
return "\n if target.__native_rig then" .. code
end
local function codegen_object_target(raw_track, context)
local code = "\n if target.set_pos then\n"
code = code .. " local dst = mat4.idt()\n"
local lineset = raw_track.linesets[""]
if not lineset then
local function codegen_texture_target(raw_track, context)
local code = ""
for _, lineset in pairs(raw_track.linesets) do
if lineset.target_type == "texture" then
code = code .. "\n do"
.. codegen_track(raw_track, lineset, context.keysets, false, "texture")
.. "\n end\n"
end
end
if #code == 0 then
return ""
end
local lineset_code = codegen_track(
raw_track, lineset, context.memoised, context.keysets, true)
code = code .. "\n do" .. lineset_code .. "\n end\n"
.. " set_matrix(target, dst)\n"
return code .. " end"
return "\n if target.set_texture then" .. code .. " end\n"
end
local function codegen_object_target(raw_track, context)
local code = codegen_texture_target(raw_track, context)
local lineset = raw_track.linesets[""]
if not lineset then
return code
end
local lineset_code = codegen_track(raw_track, lineset, context.keysets, true)
code = code .. " local dst = mat4.idt()\n"
.. "\n do" .. lineset_code .. "\n end\n"
if context.has_tsf then
code = code .. " set_matrix(target, dst)\n"
end
return code
end
local function codegen_camera_target(raw_track, context)
@ -372,25 +419,37 @@ local function codegen_camera_target(raw_track, context)
if not lineset then
return ""
end
local lineset_code = codegen_track(
raw_track, lineset, context.memoised, context.keysets, false)
local lineset_code = codegen_track(raw_track, lineset, context.keysets, false, "camera")
code = code .. "\n do" .. lineset_code .. "\n end\n"
.. " target:set_zoom(zoom)\n"
return code .. " end"
end
local function has_transform_directive(raw_track)
for _, lineset in pairs(raw_track.linesets) do
for _, line in ipairs(lineset.lines) do
if line.channel == animation.CH_TRANSLATE or
line.channel == animation.CH_ROTATE or
line.channel == animation.CH_SCALE then
return true
end
end
end
return false
end
function internals.compile_animation_track(raw_track, track_name)
local code = ""
local context = {
memoised = {},
keysets = {},
curves = {},
has_tsf = has_transform_directive(raw_track),
}
for name, curve in pairs(raw_track.curves) do
context.curves[name] = load(string.format(
"return function(kl, kr, t) return %s end",
process_expression(curve.func, context.memoised, "curve")
process_expression(curve.func, "curve")
), "<curve>", "t", env)()
end
@ -403,17 +462,8 @@ function internals.compile_animation_track(raw_track, track_name)
code = code .. codegen_object_target(raw_track, context)
code = code .. codegen_camera_target(raw_track, context)
local memoised_code = ""
for name, expression in pairs(context.memoised) do
memoised_code = memoised_code .. "\n local " .. name .. " = "
.. expression
end
if #memoised_code > 0 then
code = memoised_code .. "\n" .. code
end
local src = "return function(target, t, intensity, m)\n m = m or 1\n intensity = intensity or 1.0\n"
local src = "return function(target, t, intensity, m)\n"
.. " m = m or 1\n intensity = intensity or 1.0\n"
.. code .. "\nend"
if animation.TRACE_CODEGEN then

View file

@ -8,6 +8,9 @@ local action_to_channel = {
scale = animation.CH_SCALE,
zoom = animation.CH_ZOOM,
texture = animation.CH_TEXTURE,
show = animation.CH_SHOW,
model = animation.CH_MODEL,
color = animation.CH_COLOR,
}
local curve_to_interp = {
@ -16,6 +19,10 @@ local curve_to_interp = {
bezier = animation.INT_BEZIER,
}
local boolean_actions = {
show = true
}
local function parse_configure(raw_track, node)
if node.fps then
raw_track.fps = tonumber(node.fps)
@ -62,6 +69,70 @@ local function parse_simple_frames(line, node)
end
end
local function parse_boolean_frames(line, node)
line.keys = {}
for j, key_node in ipairs(node) do
local keyframe = {
frame = tonumber(key_node.frame),
value = key_node.value == "on",
}
table.insert(line.keys, keyframe)
end
end
local function parse_directive(node, raw_track)
local linesets = raw_track.linesets
local tag = node['#']
if tag == "configure" then
parse_configure(raw_track, node)
return
elseif tag == "curve" then
raw_track.curves[node.name] = node
return
end
local target_type = nil
if node.bone then
target_type = "bone"
elseif node.zoom then
target_type = "camera"
elseif tag == "texture" then
target_type = "texture"
end
local target_name = node.bone or node.name or ""
local lineset = linesets[target_name]
if not lineset then
lineset = {
lines = {},
target_type = target_type,
target_name = target_name,
flag = node.flag,
}
linesets[target_name] = lineset
end
local channel = action_to_channel[tag]
if not channel then
error("unknown directive " .. tag:escape())
end
local line = {
axis = node.by and (("xyz"):find(node.by) or ("rgba"):find(node.by)) or "",
channel = channel,
period = node.period or animation.MAX_FRAMES
}
if node.func then
line.expression = node.func
elseif node.curve then
parse_curve(line, node)
elseif boolean_actions[tag] then
parse_boolean_frames(line, node)
else
parse_simple_frames(line, node)
end
table.insert(lineset.lines, line)
end
local function parse_track(root)
local raw_track = {
duration = math.huge,
@ -69,56 +140,10 @@ local function parse_track(root)
linesets = {},
curves = {},
}
local linesets = raw_track.linesets
for i, node in ipairs(root) do
if type(node) == "string" then
goto continue
if type(node) == 'table' then
parse_directive(node, raw_track)
end
local tag = node['#']
if tag == "configure" then
parse_configure(raw_track, node)
goto continue
elseif tag == "curve" then
raw_track.curves[node.name] = node
goto continue
end
local target_type = nil
if node.bone then
target_type = "bone"
elseif tag == "texture" then
target_type = "texture"
end
local target_name = node.bone or node.name or ""
local lineset = linesets[target_name]
if not lineset then
lineset = {
lines = {},
target_type = target_type,
target_name = target_name
}
linesets[target_name] = lineset
end
local channel = action_to_channel[tag]
if not channel then
error("unknown directive " .. tag:escape())
end
local line = {
axis = node.by and ("xyz"):find(node.by) or "",
channel = channel,
period = node.period or animation.MAX_FRAMES
}
if node.func then
line.expression = node.func
elseif node.curve then
parse_curve(line, node)
else
parse_simple_frames(line, node)
end
table.insert(lineset.lines, line)
::continue::
end
return raw_track
end

View file

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

View file

@ -53,6 +53,7 @@ local Skeleton = {__index={
set_model=function(self, i, s) return __skeleton.set_model(self.eid, i, s) end,
get_matrix=function(self, i, ...) return __skeleton.get_matrix(self.eid, i, ...) end,
set_matrix=function(self, i, m) return __skeleton.set_matrix(self.eid, i, m) end,
get_bone_offset=function(self, i) return __skeleton.get_bone_offset(self.eid, i) end,
reset_pose=function(self) return __skeleton.reset_pose(self.eid) end,
get_texture=function(self, s) return __skeleton.get_texture(self.eid, s) end,
set_texture=function(self, s, s2) return __skeleton.set_texture(self.eid, s, s2) end,

View file

@ -0,0 +1,72 @@
local binary = {}
binary.__index = binary
local DEFAULT_CHUNK = 8192
function binary.new(stream)
return setmetatable({ stream = stream }, binary)
end
local function to_table(bytes)
local t = {}
for i = 1, #bytes do
t[i] = bytes[i]
end
return t
end
function binary.read_all(stream)
local result = Bytearray()
local avail = stream:available()
local chunk = avail > 0 and avail or DEFAULT_CHUNK
while true do
local part = stream:read_some(chunk)
if #part == 0 then break end
result:append(part)
end
return result
end
function binary:read(arg, as_table)
local t = type(arg)
if t == "number" then
local bytes = self.stream:read(arg)
return as_table and to_table(bytes) or bytes
elseif t == "string" then
local size = byteutil.get_size(arg)
local bytes = self.stream:read(size)
if #bytes < size then
error(string.format(
"unexpected end of stream: format %q needs %d bytes, got %d",
arg, size, #bytes), 2)
end
return byteutil.unpack(arg, bytes)
elseif t == "nil" then
error("in binary mode the first argument must be a byteutil format string"
.. " or the number of bytes to read")
else
error("unknown argument type: " .. t)
end
end
function binary:write(arg, ...)
local t = type(arg)
if t == "string" then
self.stream:write(byteutil.pack(arg, ...))
elseif t == "table" then
self.stream:write(Bytearray(arg))
else
self.stream:write(arg)
end
end
function binary:read_fully(as_table)
local bytes = binary.read_all(self.stream)
return as_table and to_table(bytes) or bytes
end
return binary

View file

@ -0,0 +1,19 @@
local wrapper = require "internal/stream/wrapper"
local blocking = wrapper.extend({})
function blocking.new(inner)
return setmetatable({ inner = inner }, blocking)
end
function blocking:read(n)
local result = self.inner:read(n)
while #result < n do
coroutine.yield()
if not self.inner:is_alive() then break end
result:append(self.inner:read(n - #result))
end
return result
end
return blocking

View file

@ -0,0 +1,90 @@
local wrapper = require "internal/stream/wrapper"
local buffered = wrapper.extend({})
buffered.DEFAULT_SIZE = 8192
function buffered.new(inner, size, flush_inner)
return setmetatable({
inner = inner,
size = size or buffered.DEFAULT_SIZE,
flush_inner = flush_inner ~= false,
rbuf = Bytearray(),
wbuf = Bytearray(),
}, buffered)
end
function buffered:_take(n)
local buf = self.rbuf
if n >= #buf then
self.rbuf = Bytearray()
return buf
end
local part = buf:slice(1, n)
buf:remove(1, n)
return part
end
function buffered:flush_buffer()
if #self.wbuf > 0 then
local data = self.wbuf
self.wbuf = Bytearray()
self.inner:write(data)
end
end
function buffered:read(n)
local have = #self.rbuf
if have < n then
if have == 0 and n >= self.size then
return self.inner:read(n)
end
self.rbuf:append(self.inner:read(self.size - have))
end
return self:_take(n)
end
buffered.read_some = buffered.read
function buffered:write(data)
if #self.wbuf + #data > self.size then
self:flush_buffer()
end
if #data >= self.size then
self.inner:write(data)
else
self.wbuf:append(data)
end
end
function buffered:flush()
self:flush_buffer()
if self.flush_inner then
self.inner:flush()
end
end
function buffered:available()
return self.inner:available() + #self.rbuf
end
function buffered:seek(mode, offset)
self:flush_buffer()
if mode == "c" then
offset = offset - #self.rbuf
end
self.rbuf = Bytearray()
self.inner:seek(mode, offset)
end
function buffered:tell()
return self.inner:tell() - #self.rbuf + #self.wbuf
end
function buffered:close()
self:flush_buffer()
self.rbuf = Bytearray()
return self.inner:close()
end
return buffered

View file

@ -0,0 +1,49 @@
local raw = {}
raw.__index = raw
function raw.new(descriptor, io_lib)
return setmetatable({ descriptor = descriptor, io_lib = io_lib }, raw)
end
function raw:read(n)
return self.io_lib.read(self.descriptor, n)
end
raw.read_some = raw.read
function raw:write(data)
self.io_lib.write(self.descriptor, data)
end
function raw:flush()
if self.io_lib.flush then
self.io_lib.flush(self.descriptor)
elseif not self:is_alive() then
error("stream is closed")
end
end
function raw:available()
local f = self.io_lib.available
return f and f(self.descriptor) or 0
end
function raw:seek(mode, offset)
if not self.io_lib.seek then error("cannot seek this stream") end
self.io_lib.seek(self.descriptor, mode, offset)
end
function raw:tell()
if not self.io_lib.tell then error("cannot tell this stream") end
return self.io_lib.tell(self.descriptor)
end
function raw:is_alive()
return self.io_lib.is_alive(self.descriptor)
end
function raw:close()
return self.io_lib.close(self.descriptor)
end
return raw

View file

@ -0,0 +1,102 @@
local binary = require "internal/stream/binary"
local text = {}
text.__index = text
local CR = string.byte('\r')
local LF = string.byte('\n')
function text.new(stream)
return setmetatable({stream = stream}, text)
end
function text:_read_byte()
return self.stream:read(1)[1]
end
function text:read_line()
local line = Bytearray()
local got_any = false
while true do
local b = self:_read_byte()
if b == nil then break end
got_any = true
if b == LF then
break
elseif b == CR then
local nb = self:_read_byte()
if nb == LF then break end
line:append(CR)
if nb == nil then break end
line:append(nb)
else
line:append(b)
end
end
if not got_any then return nil end
return utf8.tostring(line)
end
local function trim_empty(lines)
while #lines > 0 and lines[#lines] == "" do
lines[#lines] = nil
end
while #lines > 0 and lines[1] == "" do
table.remove(lines, 1)
end
end
function text:read_lines(count, trim)
if count < 0 then error("count of lines to read must be positive") end
local lines = {}
for i = 1, count do
local line = self:read_line()
if line == nil then break end
lines[i] = line
end
if trim ~= false then trim_empty(lines) end
return lines
end
function text:read(count, trim)
if count == nil then
return self:read_line()
end
return self:read_lines(count, trim)
end
function text:read_fully(as_lines)
if as_lines then
local lines = {}
for line in self.read_line, self do
lines[#lines + 1] = line
end
return lines
end
return utf8.tostring(binary.read_all(self.stream))
end
function text:write_line(str)
self.stream:write(utf8.tobytes(str .. "\n"))
end
-- write(string) | write({ lines... })
function text:write(arg)
local t = type(arg)
if t == "string" then
self:write_line(arg)
elseif t == "table" then
for i = 1, #arg do
self:write_line(arg[i])
end
else
error("unknown argument type: " .. t)
end
end
return text

View file

@ -0,0 +1,26 @@
local wrapper = {}
wrapper.__index = wrapper
function wrapper.extend(cls)
cls.__index = cls
return setmetatable(cls, { __index = wrapper })
end
function wrapper:read(n) return self.inner:read(n) end
function wrapper:read_some(n) return self.inner:read_some(n) end
function wrapper:write(data) return self.inner:write(data) end
function wrapper:flush() return self.inner:flush() end
function wrapper:available() return self.inner:available() end
function wrapper:seek(mode, off) return self.inner:seek(mode, off) end
function wrapper:tell() return self.inner:tell() end
function wrapper:is_alive() return self.inner:is_alive() end
function wrapper:close() return self.inner:close() end
return wrapper

View file

@ -2,7 +2,9 @@ local M = {}
function M.share_default_func(invid, slotid)
local blockinv = hud.get_block_inventory()
local playerinv = player.get_inventory(hud.get_player())
local pid = hud.get_player()
local playerinv = player.get_inventory(pid)
local hotbar_size = player.get_hotbar_size(pid)
if blockinv ~= 0 then
if invid == blockinv then
inventory.move(blockinv, slotid, playerinv)
@ -11,10 +13,10 @@ function M.share_default_func(invid, slotid)
end
elseif rules.get("allow-content-access") then
inventory.set(invid, slotid, 0, 0)
elseif slotid < 10 then
inventory.move_range(invid, slotid, invid, 10)
elseif slotid < hotbar_size then
inventory.move_range(invid, slotid, invid, hotbar_size)
else
inventory.move_range(invid, slotid, invid, 0, 9)
inventory.move_range(invid, slotid, invid, 0, hotbar_size - 1)
end
end

View file

@ -1,444 +1,108 @@
local io_stream = { }
local raw = require "internal/stream/raw"
local buffered = require "internal/stream/buffered"
local blocking = require "internal/stream/blocking"
local binary = require "internal/stream/binary"
local text = require "internal/stream/text"
local io_stream = {}
io_stream.__index = io_stream
local MAX_BUFFER_SIZE = 8192
local DEFAULT_MODE = "default"
local BUFFERED_MODE = "buffered"
local YIELD_MODE = "yield"
local ALL_MODES = {
DEFAULT_MODE,
BUFFERED_MODE,
YIELD_MODE
}
local FLUSH_MODE_ALL = "all"
local FLUSH_MODE_ONLY_BUFFER = "buffer"
local ALL_FLUSH_MODES = {
FLUSH_MODE_ALL,
FLUSH_MODE_ONLY_BUFFER
}
local CR = string.byte('\r')
local LF = string.byte('\n')
local function read_fully(result, read_func)
local isTable = type(result) == "table"
local buf
repeat
buf = read_func(MAX_BUFFER_SIZE)
if isTable then
for i = 1, #buf do
result[#result + 1] = buf[i]
end
else result:append(buf) end
until #buf == 0
end
--[[
descriptor - descriptor of stream for provided I/O library
binaryMode - if enabled, most methods will expect bytes instead of strings
ioLib - I/O library. Should include the following functions:
read(descriptor: int, length: int) -> Bytearray
May return bytearray with a smaller size if bytes have not arrived yet or have run out
May throw error if descriptor isn't readable
write(descriptor: int, data: Bytearray)
May throw error if descriptor isn't writeable
[optional] seek(descriptor: int, mode: string, offset: int)
Mode may be 'b' (relative begin), 'c' (relative current), 'e' (relative end + 1)
[optional] tell(descriptor: int) -> int
[optional] flush(descriptor: int)
[optional] available(descriptor: int) -> int
is_alive(descriptor: int) -> bool
close(descriptor: int)
--]]
local MODES = { default = true, buffered = true, yield = true }
local FLUSH_MODES = { all = true, buffer = true }
function io_stream.new(descriptor, binary_mode, io_lib, mode, flush_mode)
mode = mode or DEFAULT_MODE
flush_mode = flush_mode or FLUSH_MODE_ALL
local self = setmetatable({}, io_stream)
self.descriptor = descriptor
self.binary_mode = binary_mode
self.max_buffer_size = MAX_BUFFER_SIZE
self.io_lib = io_lib
self:set_mode(mode)
self:set_flush_mode(flush_mode)
local self = setmetatable({
descriptor = descriptor,
io_lib = io_lib,
binary_mode = binary_mode and true or false,
max_buffer_size = buffered.DEFAULT_SIZE,
}, io_stream)
self:set_flush_mode(flush_mode or "all")
self:set_mode(mode or "default")
return self
end
function io_stream:is_binary_mode()
return self.binary_mode
function io_stream:_rebuild()
local old = self.stream
if old and old.flush_buffer and old:is_alive() then
old:flush_buffer()
end
local s = raw.new(self.descriptor, self.io_lib)
if self.mode == "buffered" then
s = buffered.new(s, self.max_buffer_size, self.flush_mode == "all")
elseif self.mode == "yield" then
s = blocking.new(s)
end
self.stream = s
self.text = text.new(s)
self.binary = binary.new(s)
end
function io_stream:set_binary_mode(binary_mode)
self.binary_mode = binary_mode ~= nil
function io_stream:_format()
return self.binary_mode and self.binary or self.text
end
function io_stream:get_mode()
return self.mode
end
function io_stream:is_binary_mode() return self.binary_mode end
function io_stream:set_binary_mode(v) self.binary_mode = v and true or false end
function io_stream:get_mode() return self.mode end
function io_stream:set_mode(mode)
if not table.has(ALL_MODES, mode) then
error("invalid stream mode: "..mode)
end
if self.write_buffer then
self.write_buffer:clear()
self.write_buffer = nil
end
if self.read_buffer then
self.read_buffer:clear()
self.read_buffer = nil
end
if mode == BUFFERED_MODE then
self.write_buffer = Bytearray(self.max_buffer_size)
self.read_buffer = Bytearray(self.max_buffer_size)
end
if not MODES[mode] then error("invalid stream mode: " .. tostring(mode)) end
self.mode = mode
self:_rebuild()
end
function io_stream:get_flush_mode()
return self.flush_mode
end
function io_stream:get_flush_mode() return self.flush_mode end
function io_stream:set_flush_mode(flush_mode)
if not table.has(ALL_FLUSH_MODES, flush_mode) then
error("invalid flush mode: " .. flush_mode)
if not FLUSH_MODES[flush_mode] then
error("invalid flush mode: " .. tostring(flush_mode))
end
self.flush_mode = flush_mode
if self.mode == "buffered" then
self.stream.flush_inner = flush_mode == "all"
end
end
function io_stream:get_max_buffer_size()
return self.max_buffer_size
function io_stream:get_max_buffer_size() return self.max_buffer_size end
function io_stream:set_max_buffer_size(size)
self.max_buffer_size = size
if self.mode == "buffered" then self:_rebuild() end
end
function io_stream:set_max_buffer_size(max_buffer_size)
self.max_buffer_size = max_buffer_size
function io_stream:read(arg, use_table) return self:_format():read(arg, use_table) end
self.write_buffer = Bytearray(self.max_buffer_size)
self.read_buffer = Bytearray(self.max_buffer_size)
end
function io_stream:write(arg, ...) return self:_format():write(arg, ...) end
function io_stream:read_fully(use_table) return self:_format():read_fully(use_table) end
function io_stream:read_line() return self.text:read_line() end
function io_stream:write_line(str) return self.text:write_line(str) end
function io_stream:available(length)
local available = self.io_lib.available and self.io_lib.available(self.descriptor) or 0
if self.mode == BUFFERED_MODE then
available = available + #self.read_buffer
end
if not length then
return available
else
return available >= length
end
local n = self.stream:available()
if length then return n >= length end
return n
end
function io_stream:__read(length, from_read_fully)
if self.mode == YIELD_MODE then
if from_read_fully then
return self.io_lib.read(self.descriptor, length)
end
function io_stream:seek(mode, offset) return self.stream:seek(mode, offset) end
local buffer = Bytearray()
function io_stream:tell() return self.stream:tell() end
while #buffer < length do
buffer:append(self.io_lib.read(self.descriptor, length - #buffer))
function io_stream:is_alive() return self.stream:is_alive() end
if #buffer < length then coroutine.yield() end
end
function io_stream:is_closed() return not self.stream:is_alive() end
return buffer
elseif self.mode == BUFFERED_MODE then
local buf_len = #self.read_buffer
if buf_len < length then
self.read_buffer:append(
self.io_lib.read(self.descriptor, self.max_buffer_size - buf_len)
)
end
buf_len = #self.read_buffer
length = math.min(buf_len, length)
local copy = self.read_buffer:slice(1, length)
if buf_len == length then
self.read_buffer:clear()
else
self.read_buffer:remove(1, length)
end
return copy
elseif self.mode == DEFAULT_MODE then
return self.io_lib.read(self.descriptor, length)
end
end
function io_stream:__write(data)
if self.mode == BUFFERED_MODE then
local data_length = #data
if #self.write_buffer + data_length > self.max_buffer_size then
self:flush()
end
if data_length > self.max_buffer_size then
local to_write = math.floor(data_length / self.max_buffer_size) * self.max_buffer_size
local to_save = data_length - to_write
self.io_lib.write(self.descriptor, data:slice(1, to_write))
self:flush()
self.write_buffer = data:slice(to_write + 1, to_save)
else self.write_buffer:append(data) end
elseif self.mode == DEFAULT_MODE or self.mode == YIELD_MODE then
return self.io_lib.write(self.descriptor, data)
end
end
function io_stream:read_fully(use_table)
if self.binary_mode then
local result = use_table and { } or Bytearray()
local avail = self:available()
if avail == 0 then
avail = self.max_buffer_size
end
read_fully(result, function() return self:__read(avail, true) end)
return result
else
if use_table then
local lines = { }
local line
repeat
line = self:read_line()
lines[#lines + 1] = line
until not line
return lines
else
local result = Bytearray()
read_fully(result, function() return self:__read(self.max_buffer_size) end)
return utf8.tostring(result)
end
end
end
function io_stream:read_line()
local result = Bytearray()
local first = true
while true do
local char = self:__read(1)
if #char == 0 then
if first then return else break end
end
char = char[1]
if char == LF then break
elseif char == CR then
char = self:__read(1)
if char[1] == LF then break
else
result:append(CR)
result:append(char[1])
end
else result:append(char) end
first = false
end
return utf8.tostring(result)
end
function io_stream:write_line(str)
self:__write(utf8.tobytes(str .. "\n"))
end
function io_stream:read(arg, use_table)
local arg_type = type(arg)
if self.binary_mode then
local byte_arr
if arg_type == "number" then
-- using 'arg' as length
byte_arr = self:__read(arg)
if use_table == true then
local t = { }
for i = 1, #byte_arr do
t[i] = byte_arr[i]
end
return t
else
return byte_arr
end
elseif arg_type == "string" then
return byteutil.unpack(
arg,
self:__read(byteutil.get_size(arg))
)
elseif arg_type == "nil" then
error(
"in binary mode the first argument must be a string data format"..
" for the library \"byteutil\" or the number of bytes to read"
)
else
error("unknown argument type: "..arg_type)
end
else
if not arg then
return self:read_line()
else
local lines_count = arg
local trim_last_empty_lines = use_table
if use_table == nil then
trim_last_empty_lines = true
end
if lines_count < 0 then error "count of lines to read must be positive" end
local result = { }
for i = 1, lines_count do
result[i] = self:read_line()
end
if trim_last_empty_lines then
local i = #result
while i >= 0 do
local length = utf8.length(result[i])
if length > 0 then break
else result[i] = nil end
i = i - 1
end
local i = 1
while #result > 0 do
local length = utf8.length(result[i])
if length > 0 then break
else table.remove(result, i) end
end
end
return result
end
end
end
function io_stream:write(arg, ...)
local arg_type = type(arg)
if self.binary_mode then
local byte_arr
if arg_type ~= "string" then
-- using arg as bytes table/bytearray
if arg_type == "table" then
byte_arr = Bytearray(arg)
else
byte_arr = arg
end
else
byte_arr = byteutil.pack(arg, ...)
end
self:__write(byte_arr)
else
if arg_type == "string" then
self:write_line(arg)
elseif arg_type == "table" then
for i = 1, #arg do
self:write_line(arg[i])
end
else error("unknown argument type: "..arg_type) end
end
end
function io_stream:seek(mode, offset)
if not self.io_lib.seek then
error("cannot seek this stream")
end
self.io_lib.seek(self.descriptor, mode, offset)
end
function io_stream:tell()
if not self.io_lib.tell then
error("cannot tell this stream")
end
return self.io_lib.tell(self.descriptor)
end
function io_stream:is_alive()
return self.io_lib.is_alive(self.descriptor)
end
function io_stream:is_closed()
return not self:is_alive()
end
function io_stream:close()
if self.mode == BUFFERED_MODE then
self.read_buffer:clear()
self.write_buffer:clear()
end
return self.io_lib.close(self.descriptor)
end
function io_stream:close() return self.stream:close() end
function io_stream:flush()
if self.mode == BUFFERED_MODE and #self.write_buffer > 0 then
self.io_lib.write(self.descriptor, self.write_buffer)
self.write_buffer:clear()
end
if self.flush_mode ~= FLUSH_MODE_ONLY_BUFFER then
if self.io_lib.flush then
self.io_lib.flush(self.descriptor)
elseif self:is_closed() then error("stream is closed") end
end
if self.mode ~= "buffered" and self.flush_mode == "buffer" then return end
self.stream:flush()
end
return io_stream
return io_stream

View file

@ -5,7 +5,9 @@
"main",
"lines",
"entity",
"model",
"translucent",
"translucent_composite",
"background",
"skybox_gen",
"shadows",
@ -23,37 +25,11 @@
}
],
"textures": [
"gui/menubg",
"gui/delete_icon",
"gui/no_icon",
"gui/no_world_icon",
"gui/warning",
"gui/error",
"gui/cross",
"gui/refresh",
"gui/folder_icon",
"gui/settings_icon",
"misc/rain",
"misc/snow",
"gui/check_mark",
"gui/left_arrow",
"gui/right_arrow",
"gui/lock",
"gui/save",
"gui/block",
"gui/item",
"gui/file",
"gui/module",
"gui/play",
"gui/info",
"gui/world",
"gui/hud",
"gui/entity",
"gui/half_block",
{
"name": "",
"path": "textures/misc/blank"
}
},
"gui/*"
],
"fonts": [
{

View file

@ -5,8 +5,11 @@ local started
local tsf = entity.transform
local body = entity.rigidbody
local size = body:get_size()
agent = pathfinding.create_agent()
pathfinding.set_max_visited(agent, 1e3)
pathfinding.set_width(agent, math.max(size[1], size[3]))
pathfinding.set_height(agent, math.ceil(size[2]))
pathfinding.avoid_tag(agent, "core:liquid", 8)
function set_target(new_target)

View file

@ -43,7 +43,8 @@ function on_hud_open()
end
local id = block.get_picking_item(block.get(x, y, z))
local inv, cur_slot = player.get_inventory(pid)
local slot = inventory.find_by_item(inv, id, 0, 9)
local hotbar_size = player.get_hotbar_size(pid)
local slot = inventory.find_by_item(inv, id, 0, hotbar_size)
if slot then
player.set_selected_slot(pid, slot)
return
@ -51,7 +52,7 @@ function on_hud_open()
if not rules.get("allow-content-access") then
return
end
slot = inventory.find_by_item(inv, 0, 0, 9)
slot = inventory.find_by_item(inv, 0, 0, hotbar_size)
if slot then
cur_slot = slot
end

View file

@ -16,14 +16,16 @@ local Skeleton = {__index={
index=function(self, s) return gfx.skeletons.index(self.name, s) end,
get_model=function(self, i) return gfx.skeletons.get_model(self.name, i) end,
set_model=function(self, i, s) return gfx.skeletons.set_model(self.name, i, s) end,
get_matrix=function(self, i) return gfx.skeletons.get_matrix(self.name, i) end,
get_matrix=function(self, i, ...) return gfx.skeletons.get_matrix(self.name, i, ...) end,
reset_pose=function(self, ...) return gfx.skeletons.reset_pose(self.name, ...) end,
set_matrix=function(self, i, m) return gfx.skeletons.set_matrix(self.name, i, m) end,
get_bone_offset=function(self, i) return gfx.skeletons.get_bone_offset(self.name, i) end,
get_texture=function(self, i) return gfx.skeletons.get_texture(self.name, i) end,
set_texture=function(self, i, s) return gfx.skeletons.set_texture(self.name, i, s) end,
is_visible=function(self, i) return gfx.skeletons.is_visible(self.name, i) end,
set_visible=function(self, i, b) return gfx.skeletons.set_visible(self.name, i, b) end,
get_color=function(self, i) return gfx.skeletons.get_color(self.name, i) end,
set_color=function(self, i, c) return gfx.skeletons.set_color(self.name, i, c) end,
is_visible=function(self, ...) return gfx.skeletons.is_visible(self.name, ...) end,
set_visible=function(self, ...) return gfx.skeletons.set_visible(self.name, ...) end,
get_color=function(self, ...) return gfx.skeletons.get_color(self.name, ...) end,
set_color=function(self, ...) return gfx.skeletons.set_color(self.name, ...) end,
}}
gfx.text3d.new = function(pos, text, preset, extension)

View file

@ -2,7 +2,7 @@ local app = __vc_app
local internals = __vc_internals
local user_props = file.read_combined_object("config/user-props.toml")
local names = {
local core_names = {
"parent", "caption", "texture", "texture-faces", "model", "model-name",
"model-primitives", "material", "rotation", "hitboxes", "hitbox", "emission",
"size", "obstacle", "replaceable", "light-passing", "sky-light-passing",
@ -10,35 +10,61 @@ local names = {
"hidden", "draw-group", "picking-item", "surface-replacement", "script-name",
"ui-layout", "inventory-size", "tick-interval", "overlay-texture",
"translucent", "fields", "particles", "icon-type", "icon", "placing-block",
"stack-size", "name", "script-file", "culling", "solid"
"stack-size", "name", "script-file", "culling", "solid",
"components", "sensors", "body-type", "save", "save-skeleton-pose",
"save-skeleton-textures", "save-body-velocity", "save-body-settings",
"skeleton-name", "lighting-mode", "mass", "elasticity", "step-height",
"blocking", "material", "translucent", "uv-lock"
}
for name, _ in pairs(user_props) do
table.insert(names, name)
table.insert(core_names, name)
end
local function get_parent_props(lib, props)
if not props.parent then
return {}
end
if lib == entities then
local parent_id = entities.def_index(props.parent)
if parent_id == nil then
return {}
end
return entities.properties[parent_id] or {}
end
if lib.index == nil then
return {}
end
local parent_id = lib.index(props.parent)
if parent_id == nil then
return {}
end
return lib.properties[parent_id] or {}
end
-- remove undefined properties and build tags set
local function process_properties(lib)
for id, props in pairs(lib.properties) do
if props.parent then
local parent_props = lib.properties[block.index(props.parent)] or {}
for propname, value in pairs(parent_props) do
if not props[propname] then
props[propname] = value
end
local parent_props = get_parent_props(lib, props)
for propname, value in pairs(parent_props) do
if not props[propname] then
props[propname] = value
end
end
for propname, _ in pairs(props) do
if not table.has(names, propname) then
if not table.has(core_names, propname) then
props[propname] = nil
end
end
props.tags_set = lib.__get_tags(id)
if lib.__get_tags then
props.tags_set = lib.__get_tags(id)
end
end
end
process_properties(block)
process_properties(item)
process_properties(entities)
local function make_read_only(t)
setmetatable(t, {
@ -53,6 +79,16 @@ for k,v in pairs(block.properties) do
make_read_only(v)
end
make_read_only(item.properties)
for k,v in pairs(item.properties) do
make_read_only(v)
end
make_read_only(entities.properties)
for k,v in pairs(entities.properties) do
make_read_only(v)
end
local function cache_names(library)
local indices = {}
local names = {}
@ -87,6 +123,26 @@ end
cache_names(block)
cache_names(item)
local function cache_entity_names()
local indices = {}
local names = {}
for id=0, entities.defs_count() - 1 do
local name = entities.properties[id].name
indices[name] = id
names[id] = name
end
function entities.name(id)
return names[id]
end
function entities.index(name)
return indices[name]
end
end
cache_entity_names()
__vc_scripts_registry.build_registry()
local packs = app.get_content()

View file

@ -27,6 +27,7 @@ local function tb_frame_tostring(frame)
end
local __vc__app_script_coroutine
local __vc_process_streams = { stdin = {}, stdout = {} }
local function complete_app_lib(app)
local tick_required = true
@ -39,6 +40,45 @@ local function complete_app_lib(app)
end
local __app_set_setting = app.set_setting
local __app_quit = app.quit
local __app_get_stdout_stream = app.get_stdout_stream
local __app_get_stdin_stream = app.get_stdin_stream
local io_stream = require "core:io_stream"
local stdio_stream_lib = {
read = file.__read_descriptor,
write = file.__write_descriptor,
seek = file.__seek_descriptor,
tell = file.__tell_descriptor,
flush = file.__flush_descriptor,
available = file.__available_descriptor,
is_alive = file.__has_descriptor,
close = file.__close_descriptor,
}
local function get_process_stream(kind, handle, getter)
local cache = __vc_process_streams[kind]
local stream = cache[handle]
if stream and stream:is_alive() then
return stream
end
cache[handle] = nil
local descriptor = getter(handle)
if descriptor == nil then
return nil
end
stream = io_stream.new(descriptor, false, stdio_stream_lib)
cache[handle] = stream
return stream
end
app.get_stdout_stream = function(handle)
return get_process_stream("stdout", handle, __app_get_stdout_stream)
end
app.get_stdin_stream = function(handle)
return get_process_stream("stdin", handle, __app_get_stdin_stream)
end
app.sleep = sleep
app.script = __VC_SCRIPT_NAME

View file

@ -1,24 +1,28 @@
#include <shadows>
#include <deferred_light>
#include <fog>
#define CLOUDS_FOG_FACTOR_MUL 0.3f
#define CLOUDS_FOG_CURVE_MUL 0.4f
#define COLOR_TEMPERATURE_COMPENSATION 1.12f
vec4 effect() {
vec4 pos = texture(u_position, v_uv);
float light = 1.0;
float ao = 1.0;
#ifdef ENABLE_SSAO
light = 0.0;
float z = pos.z;
for (int y = -2; y <= 2; y++) {
for (int x = -2; x <= 2; x++) {
vec2 offset = vec2(x, y) / u_screenSize;
light += texture(u_ssao, v_uv + offset * 2.0).r;
vec2 texel = 2.0 / u_screenSize;
float centerZ = pos.z;
float sum = 0.0;
float wsum = 0.0;
for (int y = -2; y < 2; y++) {
for (int x = -2; x < 2; x++) {
vec2 uv = v_uv + vec2(x, y) * texel;
float z = texture(u_position, uv).z;
float w = exp(-abs(centerZ - z) / (abs(centerZ) * 0.05 + 0.001));
sum += texture(u_ssao, uv).r * w;
wsum += w;
}
}
light /= 24.0;
ao = sum / wsum;
#endif // ENABLE_SSAO
vec4 modelpos = u_inverseView * pos;
@ -26,18 +30,7 @@ vec4 effect() {
vec3 dir = modelpos.xyz - u_cameraPos;
float emission = texture(u_emission, v_uv).r;
float rg = 1.0;
#ifdef ENABLE_SHADOWS
float shadow_mul = calc_shadow(modelpos, normal, length(pos));
light *= shadow_mul;
rg *= min(1.0, shadow_mul + emission) * COLOR_TEMPERATURE_COMPENSATION;
light *= 2.0;
#endif
light = max(light, emission);
light = pow(light, u_gamma);
vec3 light = calc_deferred_light(modelpos, normal, length(pos), emission, ao);
vec3 fogColor = texture(u_skybox, dir).rgb;
float fog = calc_fog(
@ -45,5 +38,5 @@ vec4 effect() {
mix(1.0, CLOUDS_FOG_FACTOR_MUL, emission),
mix(1.0, CLOUDS_FOG_CURVE_MUL, emission)
);
return vec4(mix(texture(u_screen, v_uv).rgb * mix(1.0, light, 1.0) * vec3(rg, 0.5 + rg * 0.5, 1.0), fogColor, fog), 1.0);
return vec4(mix(texture(u_screen, v_uv).rgb * light, fogColor, fog), 1.0);
}

View file

@ -1,63 +1 @@
layout (location = 0) out vec4 f_color;
layout (location = 1) out vec4 f_position;
layout (location = 2) out vec4 f_normal;
layout (location = 3) out vec4 f_emission;
#include <world_fragment_header>
in vec4 a_color;
uniform sampler2D u_texture0;
uniform vec3 u_fogColor;
uniform float u_fogFactor;
uniform float u_fogCurve;
uniform bool u_alphaClip;
uniform bool u_dithering;
uniform vec3 u_sunDir;
const float BAYER_MATRIX[64] = float[](
0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0,
48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0,
12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0,
60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0,
3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0,
51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0,
15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0,
63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0
);
float calc_bayer(vec2 pos){
ivec2 p = ivec2(mod(pos, 8.0));
return BAYER_MATRIX[p.y * 8 + p.x] / 64.0;
}
void main() {
vec4 texColor = texture(u_texture0, a_texCoord);
float alpha = a_color.a * texColor.a;
// anyway it's any alpha-test alternative required
if (u_dithering) {
if (u_alphaClip) {
float bayer = calc_bayer(gl_FragCoord.xy);
if (alpha - bayer < 0.01f) {
discard;
}
alpha = 1.0;
} else if (alpha < 0.05f) {
discard;
}
} else if (alpha < (u_alphaClip ? 0.5f : 0.15f)) {
discard;
}
f_color = a_color * texColor;
#ifndef ADVANCED_RENDER
vec3 fogColor = texture(u_skybox, a_dir).rgb;
f_color = mix(f_color, vec4(fogColor, 1.0), a_fog);
#endif
f_color.a = alpha;
f_position = vec4(a_position, 1.0);
f_normal = vec4(a_normal, 1.0);
f_emission = vec4(vec3(a_emission), 1.0);
}
#include <entity_fragment>

View file

@ -8,8 +8,8 @@
#define CURVATURE_FACTOR 0.002
// lighting
#define SKY_LIGHT_MUL 2.5
#define SKY_LIGHT_TINT (vec3(1.0, 0.75, 0.6) * 2.0)
#define SKY_LIGHT_MUL 4.0
#define SKY_LIGHT_TINT (vec3(1.0, 0.2, 0.2) * 2.0)
// fog
#define FOG_POS_SCALE vec3(1.0, 0.2, 1.0)

View file

@ -0,0 +1,24 @@
#ifndef DEFERRED_LIGHT_GLSL_
#define DEFERRED_LIGHT_GLSL_
#include <shadows>
#define COLOR_TEMPERATURE_COMPENSATION 1.14f
vec3 calc_deferred_light(
vec4 modelpos, vec3 normal, float distance, float emission, float ao
) {
float light = ao;
float rg = 1.0;
#ifdef ENABLE_SHADOWS
float shadow_mul = calc_shadow(modelpos, normal, distance);
light *= shadow_mul;
rg *= min(1.0, shadow_mul + emission) * COLOR_TEMPERATURE_COMPENSATION;
light *= 2.0;
#endif
light = max(light, emission);
light = pow(light, u_gamma);
return light * vec3(rg, 0.5 + rg * 0.5, 1.0);
}
#endif // DEFERRED_LIGHT_GLSL_

View file

@ -0,0 +1,71 @@
layout (location = 0) out vec4 f_color;
layout (location = 1) out vec4 f_position;
layout (location = 2) out vec4 f_normal;
layout (location = 3) out vec4 f_emission;
uniform vec3 u_sunDir;
#include <world_fragment_header>
#include <deferred_light>
in vec4 a_color;
uniform sampler2D u_texture0;
uniform float u_alphaThreshold;
uniform bool u_opaque;
uniform bool u_forward;
uniform bool u_forwardLight;
uniform bool u_alphaClip;
const float BAYER_MATRIX[64] = float[](
0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0,
48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0,
12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0,
60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0,
3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0,
51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0,
15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0,
63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0
);
float calc_bayer(vec2 pos){
ivec2 p = ivec2(mod(pos, 8.0));
return BAYER_MATRIX[p.y * 8 + p.x] / 64.0;
}
void main() {
vec4 texColor = texture(u_texture0, a_texCoord);
float alpha = a_color.a * texColor.a;
if (u_opaque) {
float bayer = calc_bayer(gl_FragCoord.xy);
if (alpha - bayer < 0.01) {
discard;
}
alpha = 1.0;
} else {
if (alpha < u_alphaThreshold) {
discard;
}
}
f_color = a_color * texColor;
#ifdef ADVANCED_RENDER
if (u_forward) {
if (u_forwardLight) {
f_color.rgb *= calc_deferred_light(
a_modelpos, a_realnormal, length(a_position), a_emission, 1.0
);
}
vec3 fogColor = texture(u_skybox, a_dir).rgb;
f_color.rgb = mix(f_color.rgb, fogColor, a_fog);
}
#else
vec3 fogColor = texture(u_skybox, a_dir).rgb;
f_color.rgb = mix(f_color.rgb, fogColor, a_fog);
#endif
f_color.a = u_opaque ? 1.0 : alpha;
f_position = vec4(a_position, 1.0);
f_normal = vec4(a_normal, 1.0);
f_emission = vec4(vec3(a_emission), 1.0);
}

View file

@ -19,24 +19,22 @@ float calc_shadow(
float bias
) {
float step = 1.0 / float(u_shadowsRes);
vec4 mpos = shadowMatrix * vec4(modelPos.xyz + normalOffset, 1.0);
vec4 mpos = shadowMatrix * vec4(modelPos.xyz + normalOffset * 2.0, 1.0);
vec3 projCoords = mpos.xyz / mpos.w;
projCoords = projCoords * 0.5 + 0.5;
projCoords.z -= 0.00001 / u_shadowsRes + bias;
float shadow = 0.0;
if (dot(realnormal, u_sunDir) < 0.0) {
// 3x3 kernel
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
vec3 offset = vec3(x, y, -(abs(x) + abs(y)) * 0.8) * step * 1.0 * u_shadowsSoftness;
shadow += texture(shadowsMap, projCoords + offset);
}
// 3x3 kernel
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
vec3 offset = vec3(x, y, -(abs(x) + abs(y)) * 0.1) * step * 1.0 * u_shadowsSoftness;
shadow += texture(shadowsMap, projCoords + offset);
}
shadow /= 9.0;
} else {
shadow = 0.0;
}
shadow /= 9.0;
shadow *= max(0.0, sqrt(-dot(realnormal, u_sunDir)));
return shadow;
}

View file

@ -4,7 +4,7 @@
#include <constants>
vec3 pick_sky_color(samplerCube cubemap, float dayTime, vec3 minSkyLight) {
float elevation = sin(dayTime * PI2) * 0.2;
float elevation = -sin(dayTime * PI2) * 0.1;
vec3 skyLightColor = texture(cubemap, vec3(0.0f, elevation, -0.4f)).rgb;
skyLightColor *= SKY_LIGHT_TINT;
skyLightColor = min(vec3(1.0f), skyLightColor * SKY_LIGHT_MUL);

1
res/shaders/model.glslf Normal file
View file

@ -0,0 +1 @@
#include <entity_fragment>

58
res/shaders/model.glslv Normal file
View file

@ -0,0 +1,58 @@
#include <commons>
layout (location = 0) in vec3 v_position;
layout (location = 1) in vec2 v_texCoord;
layout (location = 2) in vec3 v_normal;
layout (location = 3) in mat4 i_model;
layout (location = 7) in vec4 i_tint;
layout (location = 8) in vec4 i_light;
layout (location = 9) in vec4 i_uvRegion;
layout (location = 10) in vec4 i_params;
#include <world_vertex_header>
#include <lighting>
#include <fog>
#include <sky>
out vec4 a_color;
uniform float u_dayTime;
const vec3 SUN_VECTOR = vec3(0.411934, 0.863868, -0.279161);
void main() {
a_modelpos = i_model * vec4(v_position, 1.0);
vec3 pos3d = a_modelpos.xyz - u_cameraPos;
vec3 normal = mat3(i_model) * v_normal;
float normalLength = length(normal);
normal = normalLength > 1e-6 ? normal / normalLength : v_normal;
bool shading = i_params.x > 0.5;
vec4 light = i_light;
if (shading) {
light *= 0.8 + dot(normal, SUN_VECTOR) * 0.2;
}
a_realnormal = normal;
a_normal = calc_screen_normal(a_realnormal);
a_color = vec4(calc_torch_light(
light.rgb, a_realnormal, a_modelpos.xyz, u_torchlightColor, u_gamma
), 1.0);
a_texCoord = v_texCoord * i_uvRegion.zw + i_uvRegion.xy;
a_dir = a_modelpos.xyz - u_cameraPos;
vec3 skyLightColor = pick_sky_color(u_skybox, u_dayTime, u_minSkyLight);
a_color.rgb = max(a_color.rgb, skyLightColor.rgb * light.a) * i_tint.rgb;
a_color.a = u_opacity * i_tint.a;
mat4 viewmodel = u_view * u_model;
a_distance = length(viewmodel * vec4(pos3d, 0.0));
a_fog = calc_fog(length(viewmodel * vec4(pos3d * FOG_POS_SCALE, 0.0)) / 256.0);
a_emission = shading ? 0.0 : 1.0;
vec4 viewmodelpos = u_view * a_modelpos;
a_position = viewmodelpos.xyz;
gl_Position = u_proj * viewmodelpos;
}

View file

@ -33,7 +33,7 @@ SOFTWARE.
#define ABSORPTION_BETA vec3(2.04e-5, 4.97e-5, 1.95e-6) /* what color gets absorbed by the atmosphere (Due to things like ozone) */
#define G 0.9 /* mie scattering direction, or how big the blob around the sun is */
// and the heights (how far to go up before the scattering has no effect)
#define HEIGHT_RAY 8e3 /* rayleigh height */
#define HEIGHT_RAY 12e3 /* rayleigh height */
#define HEIGHT_MIE 1.2e3 /* and mie */
#define HEIGHT_ABSORPTION 30e3 /* at what height the absorption is at it's maximum */
#define ABSORPTION_FALLOFF 4e3 /* how much the absorption decreases the further away it gets from the maximum height */

View file

@ -0,0 +1,55 @@
in vec2 v_uv;
out vec4 f_color;
#define LAYERS_COUNT 3
uniform sampler2D u_layerColor0;
uniform sampler2D u_layerColor1;
uniform sampler2D u_layerColor2;
uniform sampler2D u_layerDepth0;
uniform sampler2D u_layerDepth1;
uniform sampler2D u_layerDepth2;
void main() {
vec4 colors[LAYERS_COUNT];
float depths[LAYERS_COUNT];
colors[0] = texture(u_layerColor0, v_uv);
colors[1] = texture(u_layerColor1, v_uv);
colors[2] = texture(u_layerColor2, v_uv);
depths[0] = texture(u_layerDepth0, v_uv).r;
depths[1] = texture(u_layerDepth1, v_uv).r;
depths[2] = texture(u_layerDepth2, v_uv).r;
vec4 layerColors[LAYERS_COUNT];
float layerDepths[LAYERS_COUNT];
int count = 0;
for (int i = 0; i < LAYERS_COUNT; i++) {
if (colors[i].a > 0.0) {
layerColors[count] = colors[i];
layerDepths[count] = depths[i];
count++;
}
}
if (count == 0) {
discard;
}
for (int i = 1; i < count; i++) {
vec4 color = layerColors[i];
float depth = layerDepths[i];
int j = i - 1;
while (j >= 0 && layerDepths[j] < depth) {
layerColors[j + 1] = layerColors[j];
layerDepths[j + 1] = layerDepths[j];
j--;
}
layerColors[j + 1] = color;
layerDepths[j + 1] = depth;
}
vec4 result = vec4(0.0);
for (int i = 0; i < count; i++) {
result = result * (1.0 - layerColors[i].a) + layerColors[i];
}
f_color = result;
}

View file

@ -0,0 +1,8 @@
layout (location = 0) in vec2 v_position;
out vec2 v_uv;
void main() {
v_uv = v_position * 0.5 + 0.5;
gl_Position = vec4(v_position, 0.0, 1.0);
}

View file

@ -11,6 +11,7 @@ error.dependency-version-not-met=Dependency pack version is not met.
world.delete-confirm=Do you want to delete world forever?
world.generators.default=Default
world.generators.flat=Flat
world.delete-content-confirm=Delete missing content from the world __**(irreversible)**__?
editor.info.tooltip=CTRL+S - Save\nCTRL+R - Run\nCTRL+Z - Undo\nCTRL+Y - Redo
devtools.traceback=Traceback (most recent call first)

View file

@ -81,6 +81,8 @@ world.upgrade-request=Формат мира устарел! Конвертиро
world.convert-with-loss=Конвертировать мир с потерями?
world.convert-block-layouts=Есть изменения в полях блоков! Конвертировать мир?
world.delete-confirm=Удалить мир безвозвратно?
world.Delete Content=Удалить контент
world.delete-content-confirm=Удалить отсутствующий контент из мира __**(безвозвратно)**__?
# Настройки
settings.Ambient=Фон

View file

@ -28,9 +28,6 @@ find_package(CURL REQUIRED)
find_package(OpenSSL 3.0 REQUIRED COMPONENTS Crypto)
find_package(glfw3 REQUIRED)
find_package(Freetype REQUIRED)
if(NOT APPLE)
find_package(EnTT REQUIRED)
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
find_package(vorbis REQUIRED)

View file

@ -88,6 +88,7 @@ void Skeleton::deserialize(const dv::value& root) {
dv::get_mat(posearr[i], pose.matrices[i]);
}
}
boundsDirty = true;
}
void Skeleton::setConfig(std::shared_ptr<const SkeletonConfig> rigConfig) {
@ -105,6 +106,7 @@ void Skeleton::setConfig(std::shared_ptr<const SkeletonConfig> rigConfig) {
for (size_t i = 0; i < bonesCount; i++) {
flags[i].visible = true;
}
boundsDirty = true;
}
static void get_all_nodes(std::vector<Bone*>& nodes, Bone* node) {
@ -160,17 +162,87 @@ void SkeletonConfig::update(
const glm::vec3& position,
const glm::vec3& scale
) const {
if (skeleton.interpolation.isEnabled()) {
const auto& interpolation = skeleton.interpolation;
update(
0,
skeleton,
root.get(),
build_matrix(rotation, interpolation.getCurrent(), scale)
);
} else {
update(0, skeleton, root.get(), build_matrix(rotation, position, scale));
glm::vec3 pos = position;
const auto& interpolation = skeleton.interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) {
pos = interpolation.getCurrent();
}
glm::mat3 rot = rotation;
const auto& rotationInterpolation = skeleton.rotationInterpolation;
if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) {
rot = glm::mat3_cast(rotationInterpolation.getCurrent());
}
update(0, skeleton, root.get(), build_matrix(rot, pos, scale));
}
static float max_component(const glm::vec3& v) {
return glm::max(glm::abs(v.x), glm::max(glm::abs(v.y), glm::abs(v.z)));
}
static float farthest_corner_distance(
const glm::mat4& matrix, const AABB& aabb, const glm::vec3& origin
) {
glm::vec3 center = glm::vec3(matrix * glm::vec4(aabb.center(), 1.0f));
glm::vec3 halfSize = aabb.size() * 0.5f;
glm::vec3 extent = glm::abs(glm::vec3(matrix[0])) * halfSize.x +
glm::abs(glm::vec3(matrix[1])) * halfSize.y +
glm::abs(glm::vec3(matrix[2])) * halfSize.z;
return glm::length(glm::abs(center - origin) + extent);
}
void SkeletonConfig::processModels(
const Assets& assets,
Skeleton& skeleton,
const glm::vec3& position,
const glm::vec3& scale,
ModelBatch* batch,
ModelLightingMode lightingMode,
bool translucent
) const {
float radius = 0.0f;
bool pending = false;
for (size_t i = 0; i < nodes.size(); i++) {
auto* node = nodes[i];
if (!skeleton.flags[i].visible) {
continue;
}
node->model.refresh(assets);
auto model = node->model.model.lock(); // TODO: cache model pointer during frame
auto& modelOverride = skeleton.modelOverrides.at(i);
if (modelOverride.updateFlag) {
modelOverride.refresh(assets);
}
if (auto foundOverride = modelOverride.model.lock()) {
model = std::move(foundOverride);
}
if (model == nullptr) {
if (!node->model.name.empty()) {
node->model.updateFlag = true;
pending = true;
}
continue;
}
const auto& matrix = skeleton.calculated.matrices[i];
radius = glm::max(
radius, farthest_corner_distance(matrix, model->getBounds(), position)
);
if (batch == nullptr) {
continue;
}
batch->draw(
matrix,
skeleton.tint * skeleton.boneTints[i],
lightingMode == ModelLightingMode::SOLID
? position - glm::vec3(matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f))
: glm::vec3(),
model,
&skeleton.textures,
translucent
);
}
float maxScale = max_component(scale);
skeleton.boundsRadius = maxScale > 0.0f ? radius / maxScale : radius;
skeleton.boundsDirty = pending;
}
void SkeletonConfig::render(
@ -180,7 +252,8 @@ void SkeletonConfig::render(
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
const glm::vec3& scale,
bool translucent
) const {
if (skeleton.config->root == nullptr) {
return;
@ -190,39 +263,31 @@ void SkeletonConfig::render(
if (!skeleton.visible) {
return;
}
for (size_t i = 0; i < nodes.size(); i++) {
auto* node = nodes[i];
if (!skeleton.flags[i].visible) {
continue;
}
node->model.refresh(assets);
auto model = node->model.model.lock().get(); // TODO: cache model pointer during frame
auto& modelOverride = skeleton.modelOverrides.at(i);
if (modelOverride.updateFlag) {
modelOverride.refresh(assets);
}
if (auto foundOverride = modelOverride.model.lock()) {
model = foundOverride.get();
}
if (model == nullptr) {
if (!node->model.name.empty()) {
node->model.updateFlag = true;
}
continue;
}
batch.draw(
skeleton.calculated.matrices[i],
skeleton.tint * skeleton.boneTints[i],
lightingMode == ModelLightingMode::SOLID
? position - glm::vec3(
skeleton.calculated.matrices[i] *
glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)
)
: glm::vec3(),
model,
&skeleton.textures
);
processModels(
assets, skeleton, position, scale, &batch, lightingMode, translucent
);
}
void SkeletonConfig::updateBounds(
const Assets& assets,
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
) const {
if (skeleton.config->root == nullptr) {
return;
}
update(skeleton, rotation, position, scale);
processModels(
assets,
skeleton,
position,
scale,
nullptr,
ModelLightingMode::SOLID,
false
);
}
const Bone* SkeletonConfig::find(std::string_view str) const {

View file

@ -97,10 +97,15 @@ namespace rigging {
std::vector<ModelReference> modelOverrides;
bool visible;
bool culled = false;
/// @brief Bounding radius of visible models around entity position,
/// divided by the largest scale component
float boundsRadius = 0.0f;
bool boundsDirty = true;
glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f};
std::vector<glm::vec4> boneTints;
util::VecInterpolation<3, float> interpolation {false};
util::RotationInterpolation rotationInterpolation {false};
Skeleton(std::shared_ptr<const SkeletonConfig> config);
@ -126,6 +131,16 @@ namespace rigging {
size_t update(
size_t index, Skeleton& skeleton, Bone* node, const glm::mat4& matrix
) const;
void processModels(
const Assets& assets,
Skeleton& skeleton,
const glm::vec3& position,
const glm::vec3& scale,
ModelBatch* batch,
ModelLightingMode lightingMode,
bool translucent
) const;
public:
SkeletonConfig(
const std::string& name,
@ -147,6 +162,15 @@ namespace rigging {
ModelLightingMode lightingMode,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale,
bool translucent = false
) const;
void updateBounds(
const Assets& assets,
Skeleton& skeleton,
const glm::mat3& rotation,
const glm::vec3& position,
const glm::vec3& scale
) const;

View file

@ -19,8 +19,14 @@
#include "util/ThreadPool.hpp"
#include "voxels/Block.hpp"
#include <algorithm>
#include <cctype>
#include <map>
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>
namespace fs = std::filesystem;
@ -151,24 +157,14 @@ static std::string assets_def_folder(AssetType tag) {
return "<error>";
}
void AssetsLoader::processPreload(
AssetType tag, const std::string& name, const dv::value& map
static std::shared_ptr<AssetCfg> create_preload_config(
AssetType tag, const dv::value& map
) {
std::string defFolder = assets_def_folder(tag);
std::string path = defFolder + "/" + name;
if (map == nullptr) {
add(tag, path, name, nullptr, true);
return;
}
std::shared_ptr<AssetCfg> config = nullptr;
map.at("path").get(path);
logger.debug() << "processing preload " << util::quote(name)
<< " path: " << util::quote(path);
switch (tag) {
case AssetType::SOUND: {
bool keepPCM = false;
config = std::make_shared<SoundCfg>(map.at("keep-pcm").get(keepPCM));
break;
map.at("keep-pcm").get(keepPCM);
return std::make_shared<SoundCfg>(keepPCM);
}
case AssetType::ATLAS: {
std::string typeName = "atlas";
@ -177,44 +173,295 @@ void AssetsLoader::processPreload(
if (typeName == "separate") {
type = AtlasType::SEPARATE;
}
config = std::make_shared<AtlasCfg>(type);
break;
return std::make_shared<AtlasCfg>(type);
}
case AssetType::POST_EFFECT: {
bool advanced = false;
map.at("advanced").get(advanced);
config = std::make_shared<PostEffectCfg>(advanced);
break;
return std::make_shared<PostEffectCfg>(advanced);
}
case AssetType::MODEL: {
bool squashed = false;
map.at("squash").get(squashed);
config = std::make_shared<ModelCfg>(squashed);
break;
return std::make_shared<ModelCfg>(squashed);
}
case AssetType::FONT: {
int size = DEFAULT_FONT_SIZE;
map.at("size").get(size);
config = std::make_unique<FontCfg>(size);
break;
return std::make_shared<FontCfg>(size);
}
default:
break;
return nullptr;
}
}
static bool is_pattern(const std::string& name) {
return name.find('*') != std::string::npos;
}
static bool match_wildcard(std::string_view pattern, std::string_view str) {
size_t p = 0;
size_t s = 0;
size_t starPos = std::string_view::npos;
size_t starMatch = 0;
while (s < str.length()) {
if (p < pattern.length() && pattern[p] == '*') {
starPos = p++;
starMatch = s;
} else if (p < pattern.length() && pattern[p] == str[s]) {
p++;
s++;
} else if (starPos != std::string_view::npos) {
p = starPos + 1;
s = ++starMatch;
} else {
return false;
}
}
while (p < pattern.length() && pattern[p] == '*') {
p++;
}
return p == pattern.length();
}
static std::vector<std::string> split_pattern(const std::string& pattern) {
if (pattern.find("**") != std::string::npos) {
throw std::runtime_error(
"'**' is not supported in preload pattern " + util::quote(pattern)
);
}
std::vector<std::string> segments;
size_t start = 0;
while (start < pattern.length()) {
size_t end = pattern.find('/', start);
if (end == std::string::npos) {
end = pattern.length();
}
if (end > start) {
auto segment = pattern.substr(start, end - start);
if (segment == "." || segment == "..") {
throw std::runtime_error(
"relative segments are not allowed in preload pattern " +
util::quote(pattern)
);
}
segments.push_back(std::move(segment));
}
start = end + 1;
}
return segments;
}
static void glob(
const io::path& folder,
const std::vector<std::string>& segments,
size_t index,
const std::string& relative,
bool directories,
std::vector<std::string>& out
) {
const auto& segment = segments[index];
bool last = index + 1 == segments.size();
auto visit = [&](const std::string& name) {
io::path path = folder / name;
std::string rel = relative.empty() ? name : relative + "/" + name;
if (!last) {
if (io::is_directory(path)) {
glob(path, segments, index + 1, rel, directories, out);
}
} else if (directories ? io::is_directory(path)
: io::is_regular_file(path)) {
out.push_back(std::move(rel));
}
};
if (!is_pattern(segment)) {
visit(segment);
return;
}
if (!io::is_directory(folder)) {
return;
}
for (const auto& entry : io::directory_iterator(folder)) {
auto name = entry.name();
if (match_wildcard(segment, name)) {
visit(name);
}
}
}
static std::vector<std::string> asset_search_folders(AssetType tag) {
if (tag == AssetType::ANIMATION) {
return {ANIMATION_FOLDER, ANIMATION_FOLDER_ALIAS};
}
return {assets_def_folder(tag)};
}
static std::vector<std::string> asset_extensions(AssetType tag) {
switch (tag) {
case AssetType::ANIMATION:
return {".vca"};
case AssetType::FONT:
return {".png", ".ttf", ".otf"};
case AssetType::MODEL:
return {".vec3", ".obj", ".xml", ".vcm"};
case AssetType::POST_EFFECT:
return {".glsl"};
case AssetType::SHADER:
return {".glslv", ".glslf"};
case AssetType::SKELETON:
return {".json"};
case AssetType::SOUND:
return {".ogg", ".wav"};
case AssetType::TEXTURE:
return {".png"};
default:
return {};
}
}
static std::optional<std::string> strip_index_suffix(const std::string& stem) {
size_t pos = stem.rfind('_');
if (pos == std::string::npos || pos + 1 == stem.length()) {
return std::nullopt;
}
for (size_t i = pos + 1; i < stem.length(); i++) {
if (!std::isdigit(static_cast<unsigned char>(stem[i]))) {
return std::nullopt;
}
}
return stem.substr(0, pos);
}
struct PreloadMatch {
std::string name;
std::string path;
};
/// @brief Resolve asset name for a file matched by preload pattern
/// @param folder asset type folder the file was found in
/// @param relative file path relative to the folder
/// @return std::nullopt if the file is not a loadable asset of the type
static std::optional<PreloadMatch> resolve_preload_file(
AssetType tag, const io::path& folder, const std::string& relative
) {
io::path file = relative;
std::string extension = file.extension();
const auto& extensions = asset_extensions(tag);
if (std::find(extensions.begin(), extensions.end(), extension) ==
extensions.end()) {
return std::nullopt;
}
std::string base = relative.substr(0, relative.length() - extension.length());
std::string defFolder = assets_def_folder(tag);
if (tag == AssetType::FONT) {
if (extension != ".png") {
return PreloadMatch {base, defFolder + "/" + relative};
}
auto fontName = strip_index_suffix(base);
if (!fontName || !io::exists(folder / (*fontName + "_0.png"))) {
return std::nullopt;
}
base = std::move(*fontName);
} else if (tag == AssetType::SOUND) {
auto soundName = strip_index_suffix(base);
if (soundName && (io::exists(folder / (*soundName + extension)) ||
io::exists(folder / (*soundName + "_0" + extension)))) {
base = std::move(*soundName);
}
}
return PreloadMatch {base, defFolder + "/" + base};
}
static std::vector<PreloadMatch> find_preload_matches(
AssetType tag, const io::path& packFolder, const std::string& pattern
) {
auto segments = split_pattern(pattern);
if (segments.empty()) {
return {};
}
bool directories = pattern.back() == '/' || tag == AssetType::ATLAS;
if (directories && tag != AssetType::ATLAS) {
throw std::runtime_error(
"directory pattern " + util::quote(pattern) +
" is not applicable to assets of type " + assets_def_folder(tag)
);
}
std::map<std::string, std::string> found;
for (const auto& searchFolder : asset_search_folders(tag)) {
io::path folder = packFolder / searchFolder;
std::vector<std::string> files;
glob(folder, segments, 0, "", directories, files);
for (const auto& relative : files) {
if (directories) {
found.try_emplace(relative, assets_def_folder(tag) + "/" + relative);
continue;
}
if (auto match = resolve_preload_file(tag, folder, relative)) {
found.try_emplace(std::move(match->name), std::move(match->path));
}
}
}
std::vector<PreloadMatch> matches;
matches.reserve(found.size());
for (auto& [name, path] : found) {
matches.push_back(PreloadMatch {name, std::move(path)});
}
return matches;
}
void AssetsLoader::processPreload(
AssetType tag,
const std::string& name,
const dv::value& map,
const io::path& packFolder
) {
std::shared_ptr<AssetCfg> config =
map == nullptr ? nullptr : create_preload_config(tag, map);
if (is_pattern(name)) {
if (map != nullptr && map.has("path")) {
throw std::runtime_error(
"'path' cannot be used with preload pattern " + util::quote(name)
);
}
auto matches = find_preload_matches(tag, packFolder, name);
if (matches.empty()) {
logger.warning() << "preload pattern " << util::quote(name)
<< " matches nothing in " << packFolder.string();
}
for (const auto& match : matches) {
logger.debug() << "processing preload " << util::quote(match.name)
<< " path: " << util::quote(match.path);
add(tag, match.path, match.name, config, true);
}
return;
}
std::string path = assets_def_folder(tag) + "/" + name;
if (map != nullptr) {
map.at("path").get(path);
logger.debug() << "processing preload " << util::quote(name)
<< " path: " << util::quote(path);
}
add(tag, path, name, std::move(config), true);
}
void AssetsLoader::processPreloadList(AssetType tag, const dv::value& list) {
void AssetsLoader::processPreloadList(
AssetType tag, const dv::value& list, const io::path& packFolder
) {
if (list == nullptr) {
return;
}
for (const auto& value : list) {
switch (value.getType()) {
case dv::value_type::string:
processPreload(tag, value.asString(), nullptr);
processPreload(tag, value.asString(), nullptr, packFolder);
break;
case dv::value_type::object:
processPreload(tag, value["name"].asString(), value);
processPreload(tag, value["name"].asString(), value, packFolder);
break;
default:
throw std::runtime_error("invalid entry type");
@ -224,15 +471,17 @@ void AssetsLoader::processPreloadList(AssetType tag, const dv::value& list) {
void AssetsLoader::processPreloadConfig(const io::path& file) {
auto root = io::read_json(file);
processPreloadList(AssetType::ANIMATION, root["animation"]);
processPreloadList(AssetType::ATLAS, root["atlases"]);
processPreloadList(AssetType::FONT, root["fonts"]);
processPreloadList(AssetType::MODEL, root["models"]);
processPreloadList(AssetType::POST_EFFECT, root["post-effects"]);
processPreloadList(AssetType::SHADER, root["shaders"]);
processPreloadList(AssetType::SKELETON, root["skeletons"]);
processPreloadList(AssetType::SOUND, root["sounds"]);
processPreloadList(AssetType::TEXTURE, root["textures"]);
io::path folder = file.parent();
processPreloadList(AssetType::ANIMATION, root["animations"], folder);
processPreloadList(AssetType::ANIMATION, root["animation"], folder);
processPreloadList(AssetType::ATLAS, root["atlases"], folder);
processPreloadList(AssetType::FONT, root["fonts"], folder);
processPreloadList(AssetType::MODEL, root["models"], folder);
processPreloadList(AssetType::POST_EFFECT, root["post-effects"], folder);
processPreloadList(AssetType::SHADER, root["shaders"], folder);
processPreloadList(AssetType::SKELETON, root["skeletons"], folder);
processPreloadList(AssetType::SOUND, root["sounds"], folder);
processPreloadList(AssetType::TEXTURE, root["textures"], folder);
// layouts are loaded automatically
}

View file

@ -149,9 +149,14 @@ private:
AssetsLoadInfo& assetsLoadInfo;
void processPreload(
AssetType tag, const std::string& name, const dv::value& map
AssetType tag,
const std::string& name,
const dv::value& map,
const io::path& packFolder
);
void processPreloadList(
AssetType tag, const dv::value& list, const io::path& packFolder
);
void processPreloadList(AssetType tag, const dv::value& list);
void processPreloadConfig(const io::path& file);
void processPreloadConfigs(const Content* content);
};

View file

@ -44,6 +44,18 @@ static bool load_animated_texture(
Atlas* dstAtlas
);
static io::path find_animation(const ResPaths& paths, const std::string& filename) {
auto path = paths.find(filename + ".vca");
const auto prefix = ANIMATION_FOLDER + "/";
if (io::is_regular_file(path) || filename.rfind(prefix, 0) != 0) {
return path;
}
auto alias = paths.find(
ANIMATION_FOLDER_ALIAS + "/" + filename.substr(prefix.length()) + ".vca"
);
return io::is_regular_file(alias) ? alias : path;
}
assetload::postfunc assetload::animation(
AssetsLoader& loader,
const ResPaths& paths,
@ -51,7 +63,7 @@ assetload::postfunc assetload::animation(
const std::string& name,
const std::shared_ptr<AssetCfg>&
) {
auto path = paths.find(filename + ".vca");
auto path = find_animation(paths, filename);
loader.attachToFile(path, {name, AssetType::ANIMATION});
if (io::is_regular_file(path)) {

View file

@ -262,6 +262,18 @@ std::unique_ptr<Sound> audio::create_sound(
}
std::unique_ptr<PCMStream> audio::open_PCM_stream(const io::path& file) {
if (!io::exists(file)) {
io::path candidate = file.string() + ".wav";
if (io::exists(candidate)) {
return wav::create_stream(candidate);
}
candidate = file.string() + ".ogg";
if (io::exists(candidate)) {
return ogg::create_stream(candidate);
}
throw std::runtime_error("file not found '" + file.string() + "'");
}
std::string ext = file.extension();
if (ext == ".wav" || ext == ".WAV") {
return wav::create_stream(file);

View file

@ -134,6 +134,7 @@ public:
auto model = std::make_unique<Model>();
buildMeshes(*model);
model->clean();
model->calcBounds();
return model;
}
};

View file

@ -469,6 +469,7 @@ static VcmModel load_model(const xmlelement& root) {
perform_element(*elem, builder, ctx);
}
model.calcBounds();
vcmModel.parts["root"] = std::move(model);
vcmModel.skeleton = SkeletonConfig(
"",

View file

@ -6,7 +6,12 @@
#include <string>
inline constexpr int ENGINE_VERSION_MAJOR = 0;
inline constexpr int ENGINE_VERSION_MINOR = 32;
inline constexpr int ENGINE_VERSION_MINOR = 33;
#ifdef VC_VERSION_PATCH
inline constexpr int ENGINE_VERSION_PATCH = VC_VERSION_PATCH;
#else
inline constexpr int ENGINE_VERSION_PATCH = 0;
#endif
#ifdef NDEBUG
inline constexpr bool ENGINE_DEBUG_BUILD = false;
@ -14,7 +19,13 @@ inline constexpr bool ENGINE_DEBUG_BUILD = false;
inline constexpr bool ENGINE_DEBUG_BUILD = true;
#endif // NDEBUG
inline const std::string ENGINE_VERSION_STRING = "0.32";
inline const std::string ENGINE_VERSION_STRING =
std::to_string(ENGINE_VERSION_MAJOR) + "." +
std::to_string(ENGINE_VERSION_MINOR)
#ifdef VC_VERSION_PATCH
+ "." + std::to_string(ENGINE_VERSION_PATCH)
#endif
;
inline constexpr uint MAX_SUBPROCESSES = 1;
inline constexpr uint MAX_SUBPROCESS_DEPTH = 2;
@ -75,7 +86,8 @@ inline constexpr int DEFAULT_FONT_SIZE = 16;
inline constexpr int DEFAULT_PRE_RENDER_FONT_PAGES = 1; // must be at least 1
inline const std::string ANIMATION_FOLDER = "animation";
inline const std::string ANIMATION_FOLDER = "animations";
inline const std::string ANIMATION_FOLDER_ALIAS = "animation";
inline const std::string FONTS_FOLDER = "fonts";
inline const std::string LAYOUTS_FOLDER = "layouts";
inline const std::string MODELS_FOLDER = "models";

View file

@ -1,5 +1,8 @@
#include "ContentBuilder.hpp"
#include "core_defs.hpp"
#include "util/stringutil.hpp"
ContentBuilder::~ContentBuilder() = default;
void ContentBuilder::add(std::unique_ptr<ContentPackRuntime> pack) {
@ -19,6 +22,11 @@ std::unique_ptr<Content> ContentBuilder::build() {
for (const std::string& name : blocks.names) {
Block& def = *blocks.defs[name];
// Filling auto fields
if (def.caption.empty()) {
def.caption = util::id_to_caption(def.name);
}
// Generating runtime info
def.rt.id = blockDefsIndices.size();
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
@ -31,39 +39,50 @@ std::unique_ptr<Content> ContentBuilder::build() {
variant.culling == CullingMode::OPTIONAL;
};
auto prepareHitboxes = [&def](Variant& variant) {
if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {
auto& rotated = variant.rt.hitboxes[i];
rotated.clear();
rotated.reserve(variant.hitboxes.size());
for (AABB aabb : variant.hitboxes) {
def.rotations.variants[i].transform(aabb);
aabb.fix();
rotated.push_back(aabb);
}
}
} else {
variant.rt.hitboxes[0] = variant.hitboxes;
}
};
const float EPSILON = 0.01f;
auto isFullHitbox = [&def, EPSILON](const Variant& variant) {
return !variant.hitboxes.empty() &&
glm::i8vec3(variant.hitboxes[0].size() + EPSILON) == def.size;
};
bool fullHitboxes;
if (def.variants) {
fullHitboxes = true;
for (auto& variant : def.variants->variants) {
variant.rt.solid = isSolid(variant) || def.explictlySolid;
prepareHitboxes(variant);
fullHitboxes = fullHitboxes && isFullHitbox(variant);
}
def.defaults = def.variants->variants.at(0);
} else {
def.defaults.rt.solid = isSolid(def.defaults) || def.explictlySolid;
prepareHitboxes(def.defaults);
fullHitboxes = isFullHitbox(def.defaults);
}
def.rt.solid = def.defaults.rt.solid;
const float EPSILON = 0.01f;
def.rt.solid = def.rt.solid &&
def.obstacle &&
(glm::i8vec3(def.hitboxes[0].size() + EPSILON) == def.size);
def.rt.solid = def.defaults.rt.solid && def.obstacle && fullHitboxes;
def.rt.extended = def.size.x > 1 || def.size.y > 1 || def.size.z > 1;
if (def.material.empty()) {
defaults.at("block-material").get(def.material);
}
if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {
def.rt.hitboxes[i].reserve(def.hitboxes.size());
for (AABB aabb : def.hitboxes) {
def.rotations.variants[i].transform(aabb);
aabb.fix();
def.rt.hitboxes[i].push_back(aabb);
}
}
} else {
def.rt.hitboxes[0] = def.hitboxes;
}
blockDefsIndices.push_back(&def);
groups->insert(def.defaults.drawGroup); // FIXME: variants
}
@ -72,6 +91,11 @@ std::unique_ptr<Content> ContentBuilder::build() {
for (const std::string& name : items.names) {
ItemDef& def = *items.defs[name];
// Filling auto fields
if (def.caption.empty()) {
def.caption = util::id_to_caption(def.name);
}
// Generating runtime info
def.rt.id = itemDefsIndices.size();
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
@ -105,8 +129,17 @@ std::unique_ptr<Content> ContentBuilder::build() {
// Now, it's time to resolve foreign keys
for (Block* def : blockDefsIndices) {
def->rt.pickingItem = content->items.require(def->pickingItem).rt.id;
def->rt.surfaceReplacement = content->blocks.require(def->surfaceReplacement).rt.id;
def->rt.pickingItem =
content->items
.require(
def->pickingItem.empty()
? (def->hidden ? CORE_EMPTY
: def->name + BLOCK_ITEM_SUFFIX)
: def->pickingItem
)
.rt.id;
def->rt.surfaceReplacement =
content->blocks.require(def->surfaceReplacement).rt.id;
if (def->properties == nullptr) {
def->properties = dv::object();
}
@ -123,6 +156,13 @@ std::unique_ptr<Content> ContentBuilder::build() {
def->properties["script-file"] = def->scriptFile;
}
for (EntityDef* def : entityDefsIndices) {
if (def->properties == nullptr) {
def->properties = dv::object();
}
def->properties["name"] = def->name;
}
for (auto& [name, def] : content->generators.getDefs()) {
def->prepare(content.get());
}

View file

@ -38,16 +38,21 @@ public:
T& create(const std::string& id, bool* created = nullptr) {
auto found = defs.find(id);
if (found != defs.end()) {
if (created) *created = false;
if (created) {
*created = false;
}
return *found->second;
}
if (created) *created = true;
if (created) {
*created = true;
}
checkIdentifier(id);
allNames[id] = type;
names.push_back(id);
defs[id] = std::make_unique<T>(id);
return *defs[id];
}
// Only fetch existing definition, return null otherwise.
T* get(const std::string& id) {
auto found = defs.find(id);

View file

@ -180,7 +180,8 @@ void ContentUnitLoader<DefT>::loadUnit(
auto configFile = folder / (defsDir + "/" + name + ".json");
if (io::exists(configFile)) {
try {
loadUnit(def, full, configFile);
dv::value root = io::read_json(configFile);
loadUnit(def, full, std::move(root));
} catch (const std::runtime_error& err) {
throw std::runtime_error(
"file " + util::quote(configFile.string()) + ": " +
@ -286,12 +287,15 @@ void ContentLoader::loadContent(const dv::value& root) {
};
ContentUnitLoader<Block>(*pack, builder.blocks, "blocks",
[this](Block& def) {
[this](const Block& def) {
if (!def.hidden) {
bool created;
auto& item = builder.items.create(def.name + BLOCK_ITEM_SUFFIX, &created);
auto& item = builder.items.create(
def.name + BLOCK_ITEM_SUFFIX, &created
);
item.generated = true;
item.caption = def.caption;
item.caption = def.caption.empty() ? util::id_to_caption(def.name)
: def.caption;
item.iconType = ItemIconType::BLOCK;
item.icon = def.name;
item.placingBlock = def.name;

Some files were not shown because too many files have changed in this diff Show more